"use client";

import { useCart } from "@/hooks/useCart";
import { usePathname, useRouter } from "next/navigation";
import { useState, useEffect, useRef, useCallback, FormEvent } from "react";
import Link from "next/link";
import { apiCall } from "@/utils/callApi";
import { useIsMobile } from "@/hooks/use-mobile";

interface Subcategory {
  _id: string;
  name: string;
  slug: string;
  parent: string;
  level: number;
  image?: string;
}

interface Category {
  _id: string;
  name: string;
  slug: string;
  description?: string;
  parent: string | null;
  level: number;
  image?: string;
  isActive: boolean;
  isevent?: boolean;
  createdAt: string;
  updatedAt: string;
  subcategories: Subcategory[];
}

let cachedSettings: any = null;
let cachedSettingsPromise: any = null;
let cachedCategories: Category[] | null = null;
let cachedCategoriesPromise: Promise<Category[]> | null = null;

const TopBar = ({
  menuOpen,
  setMenuOpen,
  cartItemCount,
}: {
  menuOpen: boolean;
  setMenuOpen: (open: boolean) => void;
  cartItemCount: number;
}) => {
  const [isSticky, setIsSticky] = useState(false);
  const [settings, setSettings] = useState<any>({});
  const [categories, setCategories] = useState<Category[]>([]);
  const [mobileSubmenuOpen, setMobileSubmenuOpen] = useState<{
    [key: string]: boolean;
  }>({});
  const pathname = usePathname();
  const menuRef = useRef<HTMLUListElement>(null);

  const [generalsettings, setGeneralSettings] = useState<any>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [suggestions, setSuggestions] = useState<
    Array<{ _id: string; name: string; slug: string }>
  >([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const searchBoxRef = useRef<HTMLDivElement | null>(null);
  const router = useRouter();
  const [megaMenuOpen, setMegaMenuOpen] = useState<boolean>(false);
  const [active, setActive] = useState(false);

    useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        searchBoxRef.current &&
        !searchBoxRef.current.contains(event.target as Node)
      ) {
        setActive(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

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

  useEffect(() => {
    const settings =
      localStorage.getItem("Generalsettings") ||
      localStorage.getItem("general-settings");

    if (settings) {
      setGeneralSettings(JSON.parse(settings));
    }
  }, []);

  const fetchProductSuggestions = useCallback(async (query: string) => {
    if (!query.trim()) {
      setSuggestions([]);
      return [];
    }

    setIsSearching(true);

    try {
      const response = await apiCall<any>(
        `/clientapi/products?search=${encodeURIComponent(query)}&limit=5`,
        {
          method: "GET",
          cache: "no-store",
        },
      );

      const products =
        response.data?.data ??
        (Array.isArray(response.data) ? response.data : []);
      const productList = Array.isArray(products) ? products.slice(0, 5) : [];
      setSuggestions(productList);
      setShowSuggestions(true);
      return productList;
    } catch (error) {
      console.error("Product search error:", error);
      setSuggestions([]);
      return [];
    } finally {
      setIsSearching(false);
    }
  }, []);

  useEffect(() => {
    const handler = setTimeout(() => {
      if (searchTerm.trim()) {
        fetchProductSuggestions(searchTerm.trim());
      } else {
        setSuggestions([]);
        setShowSuggestions(false);
      }
    }, 250);

    return () => clearTimeout(handler);
  }, [searchTerm, fetchProductSuggestions]);

  // useEffect(() => {
  //   const handleClickOutside = (event: MouseEvent) => {
  //     if (
  //       searchBoxRef.current &&
  //       !searchBoxRef.current.contains(event.target as Node)
  //     ) {
  //       setShowSuggestions(false);
  //     }
  //   };

  //   document.addEventListener("mousedown", handleClickOutside);
  //   return () => document.removeEventListener("mousedown", handleClickOutside);
  // }, []);

  const redirectToProduct = (slug: string) => {
    if (!slug) return;
    setSearchTerm("");
    setSuggestions([]);
    setShowSuggestions(false);
    router.push(`/productdetails/${slug}`);
  };

  const handleSearchSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!searchTerm.trim()) return;

    if (suggestions.length > 0) {
      redirectToProduct(suggestions[0].slug);
      return;
    }

    const productList = await fetchProductSuggestions(searchTerm.trim());
    if (productList.length > 0) {
      redirectToProduct(productList[0].slug);
    }
  };

  const fetchGeneralSettings = useCallback(async () => {
    try {
      if (cachedSettings) {
        setSettings(cachedSettings);
        return;
      }

      if (!cachedSettingsPromise) {
        cachedSettingsPromise = apiCall<any>("/api/general-settings").then(
          (res) => {
            const stg = res.data?.data || [];
            cachedSettings = stg;
            localStorage.setItem("general-settings", JSON.stringify(stg));
            return stg;
          },
        );
      }

      const stg = await cachedSettingsPromise;
      setSettings(stg);
    } catch (error) {
      console.error("Error fetching settings:", error);
    }
  }, []);

  const fetchCategories = useCallback(async () => {
    try {
      if (cachedCategories) {
        setCategories(cachedCategories);
        return;
      }

      if (!cachedCategoriesPromise) {
        cachedCategoriesPromise = apiCall<any>("/clientapi/meghamenue").then(
          (res) => {
            // Handle different response structures
            let cats = [];
            if (res.data?.data && Array.isArray(res.data.data)) {
              cats = res.data.data;
            } else if (res.data && Array.isArray(res.data)) {
              cats = res.data;
            } else if (res && Array.isArray(res)) {
              cats = res;
            } else if (res.data?.success && Array.isArray(res.data.data)) {
              cats = res.data.data;
            } else {
              cats = [];
            }
            cachedCategories = cats;
            return cats;
          },
        );
      }

      const cats = await cachedCategoriesPromise;
      setCategories(Array.isArray(cats) ? cats : []);
    } catch (error) {
      console.error("Error fetching categories:", error);
      setCategories([]);
    }
  }, []);

  // Safely get categories array
  const getCategoriesArray = (): Category[] => {
    return Array.isArray(categories) ? categories : [];
  };

  // Group categories by type (Events vs Products)
  const categoriesArray = getCategoriesArray();
  const eventCategories = categoriesArray.filter((cat) => cat.isevent === true);
  const productCategories = categoriesArray;

  // Handle mega menu dropdown for desktop
  const setupMegaMenu = useCallback(() => {
    const menu = menuRef.current;
    if (!menu) return;

    // Add parent class to li elements that have child ul
    const listItems = menu.querySelectorAll("li");
    listItems.forEach((li) => {
      if (li.querySelector(":scope > ul")) {
        li.classList.add("parent");
      } else {
        li.classList.remove("parent");
      }
    });

    // Prepend slidedown span to parent items
    menu.querySelectorAll("li.parent").forEach((li) => {
      if (!li.querySelector(":scope > .slidedown")) {
        const span = document.createElement("span");
        span.className = "slidedown";
        li.prepend(span);
      }
    });
  }, []);

  // Handle mega menu click events
  const handleMegaMenuClick = useCallback((e: MouseEvent) => {
    const target = e.target as HTMLElement;
    if (!target.classList.contains("slidedown")) return;

    e.stopPropagation();
    const currentLi = target.closest("li");
    if (!currentLi) return;

    const childUl = currentLi.querySelector(
      ":scope > ul",
    ) as HTMLUListElement | null;
    if (childUl) {
      if (
        childUl.style.display === "none" ||
        getComputedStyle(childUl).display === "none"
      ) {
        childUl.style.display = "block";
        target.classList.add("slideup");
      } else {
        childUl.style.display = "none";
        target.classList.remove("slideup");
      }
    }

    // Close sibling menus
    const siblings = [...(currentLi.parentElement?.children || [])].filter(
      (el) => el !== currentLi,
    );
    siblings.forEach((sibling) => {
      sibling.querySelectorAll(".slidedown").forEach((btn: any) => {
        btn.classList.remove("slideup");
      });
      sibling.querySelectorAll("ul").forEach((ul: any) => {
        ul.style.display = "none";
      });
    });
  }, []);

  // Handle mobile submenu toggle
  const toggleMobileSubmenu = (key: string) => {
    setMobileSubmenuOpen((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  useEffect(() => {
    fetchGeneralSettings();
    fetchCategories();

    // Sticky header scroll handler
    const handleScroll = () => {
      const headerBtm = document.querySelector(".headerbtm") as HTMLElement;
      if (headerBtm) {
        const wScroll = window.scrollY;
        const headerBtmHeight = headerBtm.offsetHeight;

        if (wScroll > headerBtmHeight) {
          setIsSticky(true);
        } else {
          setIsSticky(false);
        }
      }
    };

    window.addEventListener("scroll", handleScroll);
    handleScroll();

    // Setup mega menu after component mounts
    // setTimeout(() => {
    //   setupMegaMenu();
    // }, 100);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [fetchGeneralSettings, fetchCategories]);

  // Add mega menu event listener
  useEffect(() => {
    const menu = menuRef.current;
    if (menu) {
      menu.addEventListener("click", handleMegaMenuClick);
      return () => {
        menu.removeEventListener("click", handleMegaMenuClick);
      };
    }
  }, [handleMegaMenuClick]);

  // Split categories into columns for mega menu (max 4 columns)
  const splitIntoColumns = (items: Category[], columns: number) => {
    if (!Array.isArray(items) || items.length === 0) return [];
    const result: Category[][] = [];
    const itemsPerColumn = Math.ceil(items.length / columns);
    for (let i = 0; i < items.length; i += itemsPerColumn) {
      result.push(items.slice(i, i + itemsPerColumn));
    }
    return result;
  };

  const categoriesWithSubcategories = productCategories.filter(
    (cat) => Array.isArray(cat.subcategories) && cat.subcategories.length > 0,
  );
  const categoriesWithoutSubcategories = productCategories.filter(
    (cat) =>
      !Array.isArray(cat.subcategories) || cat.subcategories.length === 0,
  );
  const productColumns = splitIntoColumns(
    categoriesWithSubcategories,
    Math.min(categoriesWithSubcategories.length, 4) || 1,
  );
  const eventColumns = splitIntoColumns(eventCategories, 4);

  return (
    <header className="headercontainer">
      {/* Top Bar */}
      <div className="headertp">
        <div className="container-xxl container px-3">
          <div className="headertpinner">
            <div className="headlocation">
              <i className="icon icon-globe"></i>
              <span>India</span>
            </div>
            <div className="offertetx">{settings.statementContent}</div>
            <ul>
              <li>
                <Link href="/appointments">Appointments</Link>
              </li>
              <li>
                <Link href="/store">Stores</Link>
              </li>
            </ul>
          </div>
        </div>
      </div>

      {/* Main Header */}
      <div className={`headerbtm ${isSticky ? "sticky" : ""}`}>
        <div className="container-xxl container px-3">
          <div className="headtoprow">
            {/* Navigation - Desktop */}
            <div className="navigation">
              <div className="navigationbox">
                <div className="navuser">
                  <Link className="userimg" href="/">
                    <img
                      alt=""
                      src={settings?.logo || "/images/logo-icon.png"}
                    />
                  </Link>
                  <div className="w-full">
                    <h3>
                      <Link href="/">
                        {settings?.siteName || "Dulhe Sahab"}
                      </Link>
                    </h3>
                  </div>
                </div>
                <ul className="sf-menu" ref={menuRef}>
                  <li key="home" className={pathname === "/" ? "active" : ""}>
                    <Link href="/">Home</Link>
                  </li>
                  <li
                    key="about-us"
                    className={pathname === "/about" ? "active" : ""}
                  >
                    <Link href="/about">About Us</Link>
                  </li>
                  <li
                    key="products"
                    onMouseEnter={() => setMegaMenuOpen(true)}
                    onMouseLeave={() => setMegaMenuOpen(false)}
                    className={`${pathname === "/products" ? "active" : ""} parent`}
                  >
                    <Link
                      href="/products"
                      onClick={() => setMegaMenuOpen(false)}
                    >
                      Products
                    </Link>
                    {megaMenuOpen && (
                      <ul className="megamenu">
                        <li>
                          <div className="container-xxl container !px-3">
                            <div className="-mx-2 flex flex-wrap">
                              <div className="flex w-full flex-col px-2 sm:w-9/12 md:w-9/12 lg:w-9/12 xl:w-9/12 2xl:w-9/12">
                                <div className="-mx-2 flex flex-grow flex-wrap">
                                  <div className="w-full px-2 sm:w-6/12 md:w-6/12 lg:w-2/12 xl:w-2/12 2xl:w-2/12">
                                    {categoriesWithoutSubcategories.length > 0 && (
                                    <ul className="child-category">
                                      {categoriesWithoutSubcategories.map(
                                        (cat) => (
                                          <li>
                                            <Link
                                              key={cat._id}
                                              href={`/products?category=${cat.slug}`}
                                              onClick={() =>
                                                setMegaMenuOpen(false)
                                              }
                                              className=""
                                            >
                                              {cat.name}
                                            </Link>
                                          </li>
                                        ),
                                      )}
                                    </ul>
                                    )}
                                  </div>
                                  <div className="w-full px-2 sm:w-6/12 md:w-6/12 lg:w-10/12 xl:w-10/12 2xl:w-10/12">
                                    <div className="-mx-2 flex flex-grow flex-wrap">
                                    {/* Shop By Collection - Dynamic Categories with subcategories */}
                                    {productColumns.length > 0
                                      ? productColumns.map((column, colIndex) => (
                                          <div
                                            key={colIndex}
                                            className="w-full px-2 sm:w-6/12 md:w-6/12 lg:w-4/12 xl:w-4/12 2xl:w-4/12 mb-4"
                                          >
                                            <ul>
                                              {column.map((cat) => (
                                                <li key={cat._id}>
                                                  <Link
                                                    href={`/products?category=${cat.slug}`}
                                                    onClick={() =>
                                                      setMegaMenuOpen(false)
                                                    }
                                                  >
                                                    Shop by {cat.name}
                                                  </Link>
                                                  {cat.subcategories &&
                                                    cat.subcategories.length >
                                                      0 && (
                                                      <ul>
                                                        {cat.subcategories.map(
                                                          (sub) => (
                                                            <li key={sub._id}>
                                                              <Link
                                                                href={`/products?subcategory=${sub.slug}`}
                                                                onClick={() =>
                                                                  setMegaMenuOpen(
                                                                    false,
                                                                  )
                                                                }
                                                              >
                                                                {sub.name}
                                                              </Link>
                                                            </li>
                                                          ),
                                                        )}
                                                      </ul>
                                                    )}
                                                </li>
                                              ))}
                                            </ul>
                                          </div>
                                        ))
                                      : categoriesWithoutSubcategories.length ===
                                          0 && (
                                          <div className="w-full px-2 sm:w-6/12 md:w-6/12 lg:w-4/12 xl:w-4/12 2xl:w-4/12">
                                            <ul>
                                              <li>
                                                <Link href="#">
                                                  No categories available
                                                </Link>
                                              </li>
                                            </ul>
                                          </div>
                                        )}
                                    </div>
                                  </div>
                                </div>
                                
                              </div>
                              <div className="w-full px-2 sm:w-6/12 md:w-6/12 lg:w-3/12 xl:w-3/12 2xl:w-3/12">
                                <img
                                  className="max-h-full w-full"
                                  src="https://quality-web-developer.com/dulhe_sahebimages/uploads/1779953245107_086ydoyze043.webp"
                                  alt="Mega Menu Banner"
                                />
                              </div>
                            </div>
                          </div>
                        </li>
                      </ul>
                    )}
                  </li>

                  <li
                    key="contact-us"
                    className={pathname === "/contact-us" ? "active" : ""}
                  >
                    <Link href="/contact-us">Contact Us</Link>
                  </li>
                </ul>
              </div>
            </div>

            {/* Logo */}
            <div className="logocontainer">
              <Link href="/">
                <img
                  src={generalsettings?.logo || "/images/logo.png"}
                  alt="Logo"
                />
              </Link>
            </div>

            {/* User Actions */}
            <div className="userbts">
              <div className={`searchbx ${active ? 'active' : ''}`} ref={searchBoxRef}>
                <div className="mx-auto w-full max-w-[1180px] px-3">
                  <div className="-mx-3 flex flex-wrap">
                    <div className="w-full px-3">
                      <div className="searchbxinner">
                        <form
                          className="formgroup relative"
                          onSubmit={handleSearchSubmit}
                        >
                          <input
                            className="form-control"
                            name="search"
                            placeholder="Search..."
                            type="text"
                            value={searchTerm}
                            onChange={(e) => {
                              setSearchTerm(e.target.value);
                              if (e.target.value.trim()) {
                                setShowSuggestions(true);
                              } else {
                                setShowSuggestions(false);
                              }
                            }}
                            onFocus={() => {
                              if (suggestions.length > 0) {
                                setShowSuggestions(true);
                              }
                            }}
                            autoComplete="off"
                          />
                          <button className="searchbutton" type="submit">
                            <i className="icon icon-search-o"></i>
                          </button>

                          {showSuggestions && suggestions.length > 0 && (
                            <ul className="absolute left-0 right-0 z-50 mt-9 max-h-72 overflow-auto rounded-2xl border border-slate-200 bg-white shadow-2xl">
                              {suggestions.map((product) => (
                                <li
                                  key={product._id}
                                  className="cursor-pointer border-b border-slate-100 px-4 py-3 hover:bg-slate-50"
                                  onMouseDown={(e) => {
                                    e.preventDefault();
                                    redirectToProduct(product.slug);
                                  }}
                                >
                                  <span className="font-medium text-slate-800">
                                    {product.name}
                                  </span>
                                </li>
                              ))}
                            </ul>
                          )}

                          {showSuggestions &&
                            suggestions.length === 0 &&
                            searchTerm.trim() &&
                            !isSearching && (
                              <div className="absolute left-0 right-0 z-50 mt-9 rounded-2xl border border-[#e6d5bc] bg-gradient-to-b from-[#fff9f5] to-[#f5e7d5] p-8 text-center shadow-2xl">
                                <div className="flex flex-col items-center gap-4">
                                  <div className="text-5xl text-[#d4a574]">
                                    💍
                                  </div>
                                  <h3 className="text-lg font-semibold text-[#7c5b39]">
                                    Oops! No Products Found
                                  </h3>
                                  <p className="max-w-xs text-sm text-[#9d7d63]">
                                    We couldn't find "{searchTerm}" in our
                                    collection. Try searching for different
                                    styles, colors, or occasions.
                                  </p>
                                  <Link
                                    href="/products"
                                    className="mt-3 inline-block rounded-full bg-[#c88a3c] px-6 py-2 text-sm font-medium text-white transition hover:bg-[#b7762f]"
                                    onClick={() => setShowSuggestions(false)}
                                  >
                                    Browse All Products
                                  </Link>
                                </div>
                              </div>
                            )}
                        </form>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="cartbtns">
                <div className="cartbtn searchbtn lg:hidden" onClick={() => setActive((prev) => !prev)}>
                  <i className="icon icon-search-o"></i>
                </div>
                <Link
                  className="cartbtn"
                  href="/cart"
                  style={{ position: "relative" }}
                >
                  <i className="icon icon-cart-bag"></i>
                  {cartItemCount > 0 && (
                    <span className="cart-badge">{cartItemCount}</span>
                  )}
                </Link>
              </div>
              {/* Hamburger Menu Button */}
              <button
                className="NavBar"
                onClick={() => setMenuOpen(!menuOpen)}
                aria-label="Toggle menu"
              >
                <i className="icon icon-segment"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Mobile Menu Overlay */}
      {menuOpen && (
        <>
          <div
            className="mobile-menu-overlay lg:hidden"
            onClick={() => setMenuOpen(false)}
          />
          <div className="mobile-menu lg:hidden">
            <div className="navigation">
              <div className="mobile-menu-header">
                <img
                  alt="Logo"
                  src="/images/logo.png"
                  style={{ height: "40px" }}
                />
                <button
                  onClick={() => setMenuOpen(false)}
                  className="mobile-menu-close"
                >
                  ✕
                </button>
              </div>
              <ul className="sf-menu !p-0">
                <li>
                  <Link href="/" onClick={() => setMenuOpen(false)}>
                    Home
                  </Link>
                </li>
                <li>
                  <Link href="/about" onClick={() => setMenuOpen(false)}>
                    About Us
                  </Link>
                </li>
                <li className="mobile-parent">
                  <Link href="/products" onClick={() => setMenuOpen(false)}>
                    Products
                  </Link>
                  <button
                    className="mobile-submenu-toggle"
                    onClick={() => toggleMobileSubmenu("products")}
                  >
                    <i
                      className={`icon icon-${mobileSubmenuOpen["products"] ? "minus" : "plus"}`}
                    ></i>
                  </button>

                  {mobileSubmenuOpen["products"] && (
                    <ul className="mobile-submenu">
                      {productCategories.map((cat) => (
                        <li key={cat._id}>
                          <Link
                            href={`/products?category=${cat.slug}`}
                            onClick={() => setMenuOpen(false)}
                          >
                            {cat.name}
                          </Link>
                          {cat.subcategories &&
                            cat.subcategories.length > 0 && (
                              <ul style={{ paddingLeft: "15px" }}>
                                {cat.subcategories.map((sub) => (
                                  <li key={sub._id}>
                                    <Link
                                      href={`/products?subcategory=${sub.slug}`}
                                      onClick={() => setMenuOpen(false)}
                                    >
                                      {sub.name}
                                    </Link>
                                  </li>
                                ))}
                              </ul>
                            )}
                        </li>
                      ))}
                    </ul>
                  )}
                </li>
                {/* {eventCategories.length > 0 && (
                  <li className="mobile-parent">
                    <Link href="/events" onClick={() => setMenuOpen(false)}>Events</Link>
                    <button
                      className="mobile-submenu-toggle"
                      onClick={() => toggleMobileSubmenu('events')}
                    >
                      <i className={`icon icon-${mobileSubmenuOpen['events'] ? 'minus' : 'plus'}`}></i>
                    </button>
                    {mobileSubmenuOpen['events'] && (
                      <ul className="mobile-submenu">
                        {eventCategories.map((event) => (
                          <li key={event._id}>
                            <Link href={`/products?event=${event.slug}`} onClick={() => setMenuOpen(false)}>
                              {event.name}
                            </Link>
                            {event.subcategories && event.subcategories.length > 0 && (
                              <ul>
                                {event.subcategories.map((sub) => (
                                  <li key={sub._id}>
                                    <Link href={`/products?subcategory=${sub.slug}`} onClick={() => setMenuOpen(false)}>
                                      {sub.name}
                                    </Link>
                                  </li>
                                ))}
                              </ul>
                            )}
                          </li>
                        ))}
                      </ul>
                    )}
                  </li>
                )} */}
                <li>
                  <Link href="/contact-us" onClick={() => setMenuOpen(false)}>
                    Contact Us
                  </Link>
                </li>
                {/* <li className="mobile-divider">
                  <Link href="/wishlist" onClick={() => setMenuOpen(false)}>
                    Wishlist
                  </Link>
                </li> */}
                <li>
                  <Link href="/appointments" onClick={() => setMenuOpen(false)}>
                    Appointments
                  </Link>
                </li>
                <li>
                  <Link href="/store" onClick={() => setMenuOpen(false)}>
                    Stores
                  </Link>
                </li>
              </ul>
            </div>
          </div>
        </>
      )}

      <style jsx>{`
        .cart-badge {
          position: absolute;
          top: -6px;
          right: -6px;
          background: red;
          color: white;
          border-radius: 50%;
          width: 18px;
          height: 18px;
          font-size: 11px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: bold;
        }

        .mobile-menu-overlay {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.5);
          z-index: 999;
        }

        .mobile-menu {
          position: fixed;
          top: 0;
          left: 0;
          bottom: 0;
          width: 280px;
          background-color: white;
          z-index: 1000;
          box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
          transform: ${menuOpen ? "translateX(0)" : "translateX(-100%)"};
          transition: transform 0.3s ease-in-out;
          overflow-y: auto;
        }

        .mobile-menu-header {
          display: flex;
          gap: 10px;
          width: 100%;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          padding: 20px;
          border-bottom: 1px solid #eee;
        }

        .mobile-menu-close {
          background: none;
          border: none;
          font-size: 24px;
          cursor: pointer;
          padding: 8px;
        }

        .mobile-menu-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .mobile-submenu-toggle {
          background: none;
          position: absolute;
          top: 10px;
          right: 5px;
          border: none;
          cursor: pointer;
          padding: 0px;
          display: inline-flex;
          justify-content: center;
          align-items: center;
          width: 26px;
          height: 26px;
          font-size: 24px;
        }

        .mobile-submenu {
          padding-left: 30px;
          margin-top: 0px;
        }

        .mobile-divider {
          border-top: 1px solid #eee;
        }
      `}</style>
    </header>
  );
};

const AppHeader = () => {
  const { cart } = useCart();
  const isMobile = useIsMobile()  
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    if (menuOpen && isMobile) {
      document.body.classList.add("mobile-menu");
    } else {
      document.body.classList.remove("mobile-menu");
    }

    // cleanup when component unmounts
    return () => {
      document.body.classList.remove("mobile-menu");
    };
  }, [menuOpen, isMobile]);

  return (
    <header className="sticky top-0 z-50 shadow-md">
      <TopBar
        menuOpen={menuOpen}
        setMenuOpen={setMenuOpen}
        cartItemCount={cart?.length || 0}
      />
    </header>
  );
};

export default AppHeader;
