All files / src/components/layout/Header index.tsx

5.68% Statements 22/387
100% Branches 0/0
0% Functions 0/1
5.68% Lines 22/387

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 3881x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1x 1x  
"use client";
import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Select } from "@/components/ui/Select";
import { menuData } from "@/config/menuData";
import Dropdown from "./Dropdown";
import { useSelector } from "react-redux";
import { selectTotalPrice, selectTotalItemCount } from "@/redux/features/cartSlice";
import { useCartModalContext } from "@/contexts";
import { BrandLogo } from "../../shared";
import ThemeToggle from "../../shared/ThemeToggle";
import { CartIcon, HeartIcon, SearchIcon, UserIcon } from "../../ui/icons";
import { useSession, signOut } from "next-auth/react";
import { Button } from "@/components/ui";
import { formatCurrency } from "@/lib/core";
import { NotificationBell } from "@/components/features/notifications";
import { useAppSelector } from "@/redux/store";
 
const Header = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [searchCategory, setSearchCategory] = useState("0");
  const [navigationOpen, setNavigationOpen] = useState(false);
  const [stickyMenu, setStickyMenu] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const userMenuRef = useRef<HTMLDivElement>(null);
  const router = useRouter();
  const { openCartModal } = useCartModalContext();
  const { data: session } = useSession();

  const totalPrice = useSelector(selectTotalPrice);
  const totalItemCount = useSelector(selectTotalItemCount);
  const wishlistItemCount = useAppSelector((state) => state.wishlistReducer.items?.length ?? 0);

  // Check if user is admin
  const isAdmin = session?.user?.role === "ADMIN";

  // Get admin menu item for the dropdown
  const adminMenuItem = menuData.find((item) => item.adminOnly);

  const handleSignOut = async () => {
    await signOut({ callbackUrl: "/" });
  };

  const handleOpenCartModal = () => {
    openCartModal();
  };

  // Handle search form submission - navigate to shop page with query
  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const trimmedQuery = searchQuery.trim();
    if (trimmedQuery.length >= 2) {
      router.push(`/shop?query=${encodeURIComponent(trimmedQuery)}`);
      setSearchQuery("");
    }
  };

  // Handle search input change
  const handleSearchInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
  };

  // Handle clicking outside user menu
  const handleClickOutside = (event: MouseEvent) => {
    if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
      setDropdownOpen(false);
    }
  };

  // Sticky menu
  const handleStickyMenu = () => {
    if (window.scrollY >= 80) {
      setStickyMenu(true);
    } else {
      setStickyMenu(false);
    }
  };

  useEffect(() => {
    window.addEventListener("scroll", handleStickyMenu);
    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      window.removeEventListener("scroll", handleStickyMenu);
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const options = [
    { label: "All Categories", value: "0" },
    { label: "Desktop", value: "1" },
    { label: "Laptop", value: "2" },
    { label: "Monitor", value: "3" },
    { label: "Phone", value: "4" },
    { label: "Watch", value: "5" },
    { label: "Mouse", value: "6" },
    { label: "Tablet", value: "7" },
  ];

  return (
    <header
      role="banner"
      className={`fixed left-0 top-0 w-full z-9999 bg-white dark:bg-gray-900 transition-all ease-in-out duration-300 ${stickyMenu && "shadow dark:shadow-gray-800"
        }`}
    >
      <div className="max-w-[1400px] mx-auto px-4 sm:px-7.5 xl:px-0">
        {/* <!-- header top start --> */}
        <div
          className={`flex flex-col lg:flex-row gap-5 items-end lg:items-center xl:justify-between ease-out duration-200 ${stickyMenu ? "py-4" : "py-6"
            }`}
        >
          {/* <!-- header top left --> */}
          <div className="xl:w-auto flex-col sm:flex-row w-full flex sm:justify-between sm:items-center gap-5 sm:gap-10">
            <Link className="flex-shrink-0" href="/">
              <BrandLogo />
            </Link>

            <div className="max-w-[550px] w-full">
              <form role="search" aria-label="Site search" onSubmit={handleSearchSubmit}>
                <div className="flex items-center">
                  <Select
                    options={options}
                    value={searchCategory}
                    onChange={(value) => setSearchCategory(value)}
                    label="Search category"
                    hideLabel
                    variant="header"
                    className="flex-shrink-0"
                  />

                  <div className="relative max-w-[400px] sm:min-w-[350px] w-full">
                    {/* <!-- divider --> */}
                    <span className="absolute left-0 top-1/2 -translate-y-1/2 inline-block w-px h-5.5 bg-gray-4 dark:bg-gray-600" aria-hidden="true"></span>
                    <label htmlFor="search" className="sr-only">Search products</label>
                    <input
                      onChange={handleSearchInputChange}
                      value={searchQuery}
                      type="search"
                      name="search"
                      id="search"
                      placeholder="I am shopping for..."
                      autoComplete="off"
                      aria-describedby="search-hint"
                      className="custom-search w-full rounded-r-[5px] bg-gray-1 dark:bg-gray-800 !border-l-0 border border-gray-3 dark:border-gray-600 py-2.5 pl-4 pr-10 outline-none ease-in duration-200 dark:text-gray-200 dark:placeholder-gray-400"
                    />
                    <span id="search-hint" className="sr-only">Enter keywords to search products, press Enter to search</span>

                    <Button
                      id="search-btn"
                      aria-label="Search"
                      type="submit"
                      variant="ghost"
                      size="sm"
                      className="absolute right-3 top-1/2 -translate-y-1/2"
                    >
                      <SearchIcon />
                    </Button>
                  </div>
                </div>
              </form>
            </div>
          </div>

          {/* <!-- header top right --> */}
          <div className="flex w-full lg:w-auto items-center gap-7.5">
            {/* <div className="hidden xl:flex items-center gap-3.5">
              <PhoneIcon />

              <div>
                <span className="block text-2xs text-dark-4 dark:text-gray-400 uppercase">
                  24/7 SUPPORT
                </span>
                <p className="font-medium text-custom-sm text-dark dark:text-gray-200">
                  (+965) 7492-3477
                </p>
              </div>
            </div> */}

            {/* <!-- divider --> */}
            <span className="hidden xl:block w-px h-7.5 bg-gray-4 dark:bg-gray-600"></span>

            <div className="flex w-full lg:w-auto justify-between items-center gap-5">
              <div className="flex items-center gap-5">
                {/* Admin Dropdown - Only visible for admin users on desktop */}
                {isAdmin && adminMenuItem && (
                  <div className="hidden xl:block">
                    <Dropdown
                      menuItem={adminMenuItem}
                      stickyMenu={stickyMenu}
                    />
                  </div>
                )}

                {session ? (
                  <>
                    <div className="relative" ref={userMenuRef}>
                      <Button
                        onClick={() => setDropdownOpen(!dropdownOpen)}
                        variant="ghost"
                        size="sm"
                        className="gap-2.5"
                      >
                        <UserIcon />

                        <div>
                          <span className="block text-2xs text-dark-4 dark:text-gray-400 uppercase">
                            account
                          </span>
                          <p className="font-medium text-custom-sm text-dark dark:text-gray-200 truncate max-w-[80px]">
                            {session.user?.name || "User"}
                          </p>
                        </div>
                      </Button>

                      {dropdownOpen && (
                        <div className="absolute right-0 mt-2 bg-white dark:bg-gray-800 border border-gray-3 dark:border-gray-600 rounded-lg shadow-lg z-50">
                          <Link
                            href="/my-account"
                            onClick={() => setDropdownOpen(false)}
                            className="block px-4 py-2 text-dark dark:text-gray-200 hover:bg-gray-1 dark:hover:bg-gray-700 border-b border-gray-3 dark:border-gray-600 text-custom-sm"
                          >
                            My Account
                          </Link>
                          <Link
                            href="/account/orders"
                            onClick={() => setDropdownOpen(false)}
                            className="block px-4 py-2 text-dark dark:text-gray-200 hover:bg-gray-1 dark:hover:bg-gray-700 border-b border-gray-3 dark:border-gray-600 text-custom-sm"
                          >
                            Orders
                          </Link>
                          <Link
                            href="/my-account?tab=loyalty"
                            onClick={() => setDropdownOpen(false)}
                            className="block px-4 py-2 text-dark dark:text-gray-200 hover:bg-gray-1 dark:hover:bg-gray-700 border-b border-gray-3 dark:border-gray-600 text-custom-sm"
                          >
                            Rewards
                          </Link>
                          <Button
                            onClick={() => {
                              setDropdownOpen(false);
                              handleSignOut();
                            }}
                            variant="ghost"
                            size="sm"
                            className="w-full text-left px-4 py-2 dark:text-gray-200 dark:hover:bg-gray-700"
                          >
                            Sign Out
                          </Button>
                        </div>
                      )}
                    </div>

                    {/* Notification Bell - Only visible for logged-in users */}
                    <NotificationBell />
                  </>
                ) : (
                  <Link href="/signin" className="flex items-center gap-2.5">
                    <UserIcon />

                    <div>
                      <span className="block text-2xs text-dark-4 dark:text-gray-400 uppercase">
                        account
                      </span>
                      <p className="font-medium text-custom-sm text-dark dark:text-gray-200">
                        Sign In
                      </p>
                    </div>
                  </Link>
                )}

                {/* Wishlist Icon */}
                <Link
                  href="/wishlist"
                  className="relative p-2 text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white transition-colors rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800"
                  aria-label={`Wishlist${wishlistItemCount > 0 ? ` (${wishlistItemCount} items)` : ''}`}
                >
                  <HeartIcon className="w-5 h-5" />
                  {wishlistItemCount > 0 && (
                    <span className="flex items-center justify-center font-medium text-2xs absolute -right-0.5 -top-0.5 bg-blue w-4.5 h-4.5 rounded-full text-white">
                      {wishlistItemCount > 99 ? '99+' : wishlistItemCount}
                    </span>
                  )}
                </Link>

                <Button
                  onClick={handleOpenCartModal}
                  variant="ghost"
                  size="sm"
                  className="gap-2.5"
                  data-testid="cart-button"
                  aria-label={`Shopping cart with ${totalItemCount} items`}
                >
                  <span className="inline-block relative">
                    <CartIcon />

                    <span className="flex items-center justify-center font-medium text-2xs absolute -right-2 -top-2.5 bg-blue w-4.5 h-4.5 rounded-full text-white">
                      {totalItemCount}
                    </span>
                  </span>

                  <div>
                    <span className="block text-2xs text-dark-4 dark:text-gray-400 uppercase">
                      cart
                    </span>
                    <p className="font-medium text-custom-sm text-dark dark:text-gray-200">
                      {formatCurrency(totalPrice)}
                    </p>
                  </div>
                </Button>

                {/* Theme Toggle - visible on all screen sizes */}
                <ThemeToggle size="sm" />
              </div>

              {/* <!-- Hamburger Toggle BTN - Only for admin users to access admin menu on mobile --> */}
              {isAdmin && (
                <Button
                  id="Toggle"
                  aria-label="Toggle admin menu"
                  data-testid="mobile-menu-toggle"
                  variant="ghost"
                  size="sm"
                  className="xl:hidden block"
                  onClick={() => setNavigationOpen(!navigationOpen)}
                >
                <span className="block relative cursor-pointer w-5.5 h-5.5">
                  <span className="du-block absolute right-0 w-full h-full">
                    <span
                      className={`block relative top-0 left-0 bg-dark dark:bg-gray-200 rounded-sm w-0 h-0.5 my-1 ease-in-out duration-200 delay-[0] ${!navigationOpen && "!w-full delay-300"
                        }`}
                    ></span>
                    <span
                      className={`block relative top-0 left-0 bg-dark dark:bg-gray-200 rounded-sm w-0 h-0.5 my-1 ease-in-out duration-200 delay-150 ${!navigationOpen && "!w-full delay-400"
                        }`}
                    ></span>
                    <span
                      className={`block relative top-0 left-0 bg-dark dark:bg-gray-200 rounded-sm w-0 h-0.5 my-1 ease-in-out duration-200 delay-200 ${!navigationOpen && "!w-full delay-500"
                        }`}
                    ></span>
                  </span>

                  <span className="block absolute right-0 w-full h-full rotate-45">
                    <span
                      className={`block bg-dark dark:bg-gray-200 rounded-sm ease-in-out duration-200 delay-300 absolute left-2.5 top-0 w-0.5 h-full ${!navigationOpen && "!h-0 delay-[0] "
                        }`}
                    ></span>
                    <span
                      className={`block bg-dark dark:bg-gray-200 rounded-sm ease-in-out duration-200 delay-400 absolute left-0 top-2.5 w-full h-0.5 ${!navigationOpen && "!h-0 dealy-200"
                        }`}
                    ></span>
                  </span>
                </span>
              </Button>
              )}
              {/* //   <!-- Hamburger Toggle BTN --> */}
            </div>
          </div>
        </div>
        {/* <!-- header top end --> */}
      </div>

      {/* Mobile menu - only shows Admin dropdown for admin users */}
      {isAdmin && navigationOpen && (
        <div className="border-t border-gray-3 dark:border-gray-700 xl:hidden">
          <div className="max-w-[1400px] mx-auto px-4 sm:px-7.5">
            <div
              data-testid="mobile-menu"
              className="bg-white dark:bg-gray-800 shadow-lg border border-gray-3 dark:border-gray-600 rounded-md p-5 my-2"
            >
              <nav aria-label="Admin navigation">
                {adminMenuItem && (
                  <Dropdown
                    menuItem={adminMenuItem}
                    stickyMenu={stickyMenu}
                  />
                )}
              </nav>
            </div>
          </div>
        </div>
      )}
    </header>
  );
};
 
export default Header;