"use client";

import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
  Menu,
  Search,
  ChevronDown,
  ChevronRight,
  X,
  Contact,
  LogIn,
  UserRound,
  LayoutGrid,
  LogOut,
} from "lucide-react";
import Image from "next/image";
import logo from "../../public/assets/logo/logo1.png";
import TopHeader from "./topHeader";
import Link from "next/link";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "./ui/button";
import { useRouter } from "next/navigation";
import { logoutUser } from "@/lib/api/auth";
import profileImg from '../../public/assets/profile/profileImage.png';

type MenuChild = {
  name: string;
  link: string;
};
type ProductItem = {
  name: string;
  link?: string;
  submenu?: MenuChild[];
};
type ProductMenu = {
  id: number;
  name: string;
  link: string;
  items?: ProductItem[];
};

type ChildSubcategory = {
  name: string;
  link: string;
};

type Subcategory = {
  name: string;
  link: string;
  childSubcategories: ChildSubcategory[];
};

type Category = {
  id: number;
  name: string;
  subcategories: Subcategory[];
};

const categories: Category[] = [
  {
    id: 1,
    name: "Electrical",
    subcategories: [
      {
        name: "Cables",
        link: "/price",
        childSubcategories: [
          { name: "Building Wire / Domestic", link: "/price?product=Cables&category=Building Wire/Domestic Cable" },
          { name: "Low Voltage Cables", link: "/price?product=Cables&category=Low Voltage Cables" },
          { name: "Medium Voltage Cables", link: "/price?product=Cables&category=Medium Voltage Cables" },
          { name: "Overhead Conductor & Cables", link: "/price?product=Cables&category=Overhead Conductor & Cables" },
          { name: "EV Cables", link: "/price?product=Cables&category=EV Cables" },
          { name: "Solar Cable", link: "/price?product=Cables&category=Solar Cable" },
          { name: "Communication Cables", link: "/price?product=Cables&category=Communication Cables" },
          { name: "Instrumentation Cables", link: "/price?product=Cables&category=Instrumentation Cables" },
          { name: "Fire Survival Cables", link: "/price?product=Cables&category=Fire Survival Cables" },
          { name: "Anti-rodent and Anti-termite Cables", link: "/price?product=Cables&category=Anti-rodent and Anti-termite Cables" },
          { name: "UV Resistance Cables", link: "/price?product=Cables&category=UV Resistance Cables" },
          { name: "Speaker Cable", link: "/price?product=Cables&category=Speaker Cable" },
        ],
      },
      {
        name: "Super Enamelled",
        link: "/price",
        childSubcategories: [
          { name: "Super Enamelled", link: "/price?product=Super Enamelled&category=Super Enamelled" },
        ],
      },
      {
        name: "Busbar",
        link: "/price",
        childSubcategories: [
          { name: "Copper", link: "/price?product=Busbar&category=Copper" },
          { name: "Aluminium", link: "/price?product=Busbar&category=Aluminium" },
        ],
      },
      {
        name: "LED Light",
        link: "/price",
        childSubcategories: [
          { name: "LED Bulb Emergency", link: "/price?product=Light&category=LED Bulb Emergency" },
          { name: "LED Bulbs", link: "/price?product=Light&category=LED Bulbs" },
          { name: "LED ECO Bulbs", link: "/price?product=Light&category=LED ECO Bulbs" },
          { name: "LED Floodlights", link: "/price?product=Light&category=LED Floodlights" },
          { name: "LED Panel", link: "/price?product=Light&category=LED Panel" },
          { name: "LED Smart Capsul Light", link: "/price?product=Light&category=LED Smart Capsul Light" },
          { name: "LED T Shape", link: "/price?product=Light&category=LED T Shape" },
          { name: "LED Tube", link: "/price?product=Light&category=LED Tube" },
          { name: "LED UFO Lights", link: "/price?product=Light&category=LED UFO Lights" },
          { name: "Mega Pro LED (Diamond Shape)", link: "/price?product=Light&category=Mega Pro LED (Diamond Shape)" },
          { name: "Solar DC LED", link: "/price?product=Light&category=Solar DC LED" },
          { name: "SQ-Color LED Bulb", link: "/price?product=Light&category=SQ-Color LED Bulb" },
        ],
      },
      {
        name: "Accessories",
        link: "/price",
        childSubcategories: [
          { name: "PC Items", link: "/price?product=Accessories&category=PC Items" },
          { name: "Piano", link: "/price?product=Accessories&category=Piano" },
          { name: "Premium - Engineer", link: "/price?product=Accessories&category=Premium - Engineer" },
          { name: "Premium - Mistiri", link: "/price?product=Accessories&category=Premium - Mistiri" },
          { name: "SQ IVORY SERIES", link: "/price?product=Accessories&category=SQ IVORY SERIES" },
          { name: "CCT Breaker", link: "/price?product=Accessories&category=CCT Breaker" },
          { name: "Ceiling Fan Capacitor", link: "/price?product=Accessories&category=Ceiling Fan Capacitor" },
        ],
      },
      {
        name: "Fan",
        link: "/price",
        childSubcategories: [
          { name: "Ceiling Fan", link: "/price?product=Fan&category=Ceiling Fan" },
          { name: "Rechargeable Fan", link: "/price?product=Fan&category=Rechargeable Fan" },
        ],
      },
      {
        name: "Meter",
        link: "/price",
        childSubcategories: [
          { name: "Single Phase Smart Pre-Payment Energy Meter", link: "/price?product=Meter&category=Single Phase Smart Pre-Payment Energy Meter" },
          { name: "Three Phase Smart Pre-Payment Energy Meter", link: "/price?product=Meter&category=Three Phase Smart Pre-Payment Energy Meter" },
          { name: "Single Phase Electronic Meter", link: "/price?product=Meter&category=Single Phase Electronic Meter" },
          { name: "Three Phase Electronic Meter", link: "/price?product=Meter&category=Three Phase Electronic Meter" },
          { name: "Meter Socket", link: "/price?product=Meter&category=Meter Socket" },
        ],
      },
      {
        name: "Transformer",
        link: "/price",
        childSubcategories: [
          { name: "Distribution Transformer", link: "/price?product=Transformer&category=Distribution Transformer" },
          { name: "Instrument Transformer (LT CTPT)", link: "/price?product=Transformer&category=INSTRUMENT TRANSFORMER (LT CTPT)" },
          { name: "Instrument Transformer (11kV CTPT)", link: "/price?product=Transformer&category=INSTRUMENT TRANSFORMER (11kV CTPT)" },
          { name: "Instrument Transformer (33kV CTPT)", link: "/price?product=Transformer&category=INSTRUMENT TRANSFORMER (33kV CTPT)" },
        ],
      },
      {
        name: "Switchgear",
        link: "/price",
        childSubcategories: [
          { name: "Air-Insulated Switchgear", link: "/price?product=Switchgear&category=Air-Insulated Switchgear" },
          { name: "Gas-Insulated Switchgear", link: "/price?product=Switchgear&category=Gas-Insulated Switchgear" },
          { name: "Vacuum Circuit Breaker", link: "/price?product=Switchgear&category=Vacuum Circuit Breaker" },
          { name: "Switchgear Components", link: "/price?product=Switchgear&category=Switchgear Components" },
          { name: "Protective Device", link: "/price?product=Switchgear&category=Protective Device" },
        ],
      },
      {
        name: "Sub Stations",
        link: "/price",
        childSubcategories: [
          { name: "AIS Sub-Station", link: "/price?product=Substation Information&category=AIS Sub-Station" },
          { name: "GIS Substation", link: "/price?product=Substation Information&category=GIS Sub-Station" },
          { name: "Switching Station", link: "/price?product=Substation Information&category=Switching Station" },
          { name: "Bay-Breaker Station", link: "/price?product=Substation Information&category=Bay-Breaker Extension" },
          { name: "Feeder Works at Grid Sub-Station", link: "/price?product=Substation Information&category=Feeder Works at Grid Sub-Station" },
        ],
      },
    ],
  },
];

const productMenuItems2: ProductMenu[] = [
  { id: 1, name: "Home", link: "/" },
  { id: 2, name: "Catalogue", link: "/catalogue" },
  { id: 3, name: "Price", link: "/price" },
  { id: 4, name: "Sales Network", link: "/sales-network" },
];

const mainMenuItems = [
  {
    id: 1,
    name: "Plant(s)",
    items: [
      { name: "SQ Electricals LTD. NSEZ, Mirsarai", link: "/plants/sq-electricals-mirsarai" },
      { name: "TS Transformers, Gazipur", link: "/plants/ts-transformers-gazipur" },
    ],
  },
  {
    id: 2,
    name: "About",
    items: [
      { name: "Our Group", link: "/about-company" },
      { name: "Chairman Message", link: "/chairman-message" },
      { name: "Vision & Mission", link: "/vision-mission" },
      { name: "Leadership Team", link: "/leadership-team" },
      { name: "News", link: "/news" },
      { name: "Gallery", link: "/gallery" },
      { name: "Careers", link: "/careers" },
    ],
  },
  {
    id: 3,
    name: "Our Group",
    items: [
      { name: "Business Units", link: "/business-units" },
      { name: "Corporate Social Responsibility (CSR)", link: "/csr" },
      { name: "Research & Development (R&D)", link: "/r&d" },
    ],
  },
];

export default function Navbar() {
  const [isMounted, setIsMounted] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [selectedSubcategory, setSelectedSubcategory] = useState<string | null>(null);
  const [activeDropdownOne, setActiveDropdownOne] = useState<number | null>(null);
  const [activeDropdown, setActiveDropdown] = useState<number | null>(null);
  const [activeSubmenu, setActiveSubmenu] = useState<string | null>(null);

  const [hoverMenu, setHoverMenu] = useState(false);

  
  // Mobile states
  const [mobileCategoryOpen, setMobileCategoryOpen] = useState(false);
  const [mobileSelectedCategory, setMobileSelectedCategory] = useState<number | null>(null);
  const [mobileSelectedSubcategory, setMobileSelectedSubcategory] = useState<string | null>(null);
  const [mobileActiveDropdownOne, setMobileActiveDropdownOne] = useState<number | null>(null);
  const [mobileActiveDropdown, setMobileActiveDropdown] = useState<number | null>(null);
  const [mobileSubmenu, setMobileSubmenu] = useState<string | null>(null);
  const [isProductsHover, setIsProductsHover] = useState(false);


  const mobileMenuRef = useRef<HTMLDivElement>(null);

  // user hooks call
  const { user, isAuthenticated, isLoading } = useAuth();

  // Logout function 
  const [loggingOut, setLoggingOut] = useState(false);
  const [error, setError] = useState("");
  const router = useRouter();

  async function handleLogout(){
    if(loggingOut) return;
    setLoggingOut(true)
    setError('')
    window.location.href = "/"; 
    try{
      await logoutUser();
       setHoverMenu(false);
       router.replace("/");
       router.refresh();
    } catch (logoutError) {
      setError(
        logoutError instanceof Error
        ? logoutError.message
        : "Unable to log Out. Please Try again",
      );
      setLoggingOut(false);
    }
  }

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsMounted(true);
    }, 0);
    return () => clearTimeout(timer);
  }, []);

  // Close mobile menu on outside click
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      if (mobileMenuRef.current && !mobileMenuRef.current.contains(event.target as Node)) {
        setIsMobileMenuOpen(false);
      }
    };

    if (isMobileMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('touchstart', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, [isMobileMenuOpen]);

  // Prevent body scroll when mobile menu is open
  useEffect(() => {
    if (isMobileMenuOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isMobileMenuOpen]);

  const selectedCategoryData = categories.find((cat) => cat.id === selectedCategory);
  const selectedSubcategoryData = selectedCategoryData?.subcategories.find(
    (sub) => sub.name === selectedSubcategory
  );

  // Mobile toggle functions
  const toggleMobileCategory = (categoryId: number) => {
    setMobileSelectedCategory(mobileSelectedCategory === categoryId ? null : categoryId);
    setMobileSelectedSubcategory(null);
  };

  const toggleMobileSubcategory = (subcategoryName: string) => {
    setMobileSelectedSubcategory(
      mobileSelectedSubcategory === subcategoryName ? null : subcategoryName
    );
  };

  const toggleMobileDropdownOne = (menuId: number) => {
    setMobileActiveDropdownOne(mobileActiveDropdownOne === menuId ? null : menuId);
    setMobileSubmenu(null);
  };

  const toggleMobileDropdown = (menuId: number) => {
    setMobileActiveDropdown(mobileActiveDropdown === menuId ? null : menuId);
  };

  const toggleMobileSubmenu = (itemName: string) => {
    setMobileSubmenu(mobileSubmenu === itemName ? null : itemName);
  };

  const closeMobileMenu = () => {
    setIsMobileMenuOpen(false);
  };

  return (
    <div className="bg-gray-50" suppressHydrationWarning>
      <header className="bg-background text-white relative z-40">
        <div className="fixed top-0 lg:px-8 px-4 lg:py-3 py-2 flex items-center justify-between gap-4 bg-background z-50 w-full border-b border-green-700">
          <button
            onClick={() => setIsMobileMenuOpen(true)}
            className="lg:hidden"
            aria-label="Open menu"
          >
            <Menu className="w-6 h-6" />
          </button>

          <Link href="/">
            <Image
              src={logo}
              alt="logo"
              width={170}
              height={170}
              className="lg:w-[170px] w-[110px] h-auto"
              priority
            />
          </Link>

          <div className="hidden md:flex flex-1 max-w-xl bg-white rounded-full">
            <div className="relative w-full">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="What can we help you find today?"
                className="w-full pl-10 pr-4 py-3 text-gray-900 rounded-full focus:outline-none"
              />
            </div>
          </div>

    
          {/* <div className="flex items-center justify-end gap-1 py-2">
            {isAuthenticated && user ? (
              <div className="relative">
                <h2
                  onMouseEnter={() => setHoverMenu(true)}
                  onMouseLeave={() => setHoverMenu(false)}
                  className="flex items-center gap-1.5 rounded-sm px-3 py-1.5 text-base text-white transition-colors hover:bg-white/10 hover:text-gray-300 cursor-pointer"
                >
                  <UserRound className="h-3.5 w-3.5" />
                  <span>{user.name}</span>
                </h2>

                {hoverMenu && (
                  <div
                    onMouseEnter={() => setHoverMenu(true)}
                    onMouseLeave={() => setHoverMenu(false)}
                    className="absolute right-0 top-full z-50 w-48 rounded-xl bg-gray-100 shadow-lg"
                  >
                      <Link
                        href="/dashboard"
                        className="flex items-center gap-2 rounded-t-xl border-b border-gray-200 px-4 py-3 text-sm text-gray-800 hover:bg-green-700 hover:text-white"
                      >
                        <LayoutGrid className="h-4 w-4" />
                        Dashboard
                      </Link>

                      <button
                        onClick={handleLogout}
                        className="flex w-full items-center gap-2 cursor-pointer rounded-b-xl px-4 py-3 text-left text-sm text-gray-800 hover:bg-green-700 hover:text-white"
                      >
                        <LogOut className="h-4 w-4" />
                        Logout
                      </button>
                    </div>
                  )}
                </div>
                    ) : (
                    <>
                      <Link
                        href="/signup"
                        className="flex items-center gap-1.5 rounded-sm px-3 py-1.5 text-base text-white transition-colors hover:bg-white/10 hover:text-gray-300"
                      >
                        <UserRound className="h-3.5 w-3.5" />
                        <span>Sign Up</span>
                      </Link>

                      <Link
                        href="/signin"
                        className="flex items-center gap-1.5 rounded-sm px-3 py-1.5 text-base text-white transition-colors hover:bg-white/10 hover:text-gray-300"
                      >
                        <LogIn className="h-3.5 w-3.5" />
                        <span>Login</span>
                      </Link>
                    </>
                  )}
          </div> */}
          <div className="flex items-center justify-end py-2">
          {isLoading ? (
            <div className="flex gap-1.5 items-center">
              <div className="h-8 w-8 rounded-full bg-green-700/20" />
              <div className="h-8 w-33 animate-pulse rounded-md bg-green-700/20"></div>
            </div>
          ) : isAuthenticated && user ? (
            <div className="relative">
              <h2
                onMouseEnter={() => setHoverMenu(true)}
                onMouseLeave={() => setHoverMenu(false)}
                className="flex items-center gap-1.5 rounded-sm px-4 py-1.5 text-base text-white transition-colors hover:bg-white/10 hover:text-gray-300 cursor-pointer"
              >
                <Image src={profileImg.src} alt="SQ User" width={100} height={100} className="w-6 h-6 rounded-full"></Image>
                <span>{user.name}</span>
              </h2>

              {hoverMenu && (
                <div
                  onMouseEnter={() => setHoverMenu(true)}
                  onMouseLeave={() => setHoverMenu(false)}
                  className="absolute right-0 top-full z-50 w-48 rounded-lg bg-gray-100 shadow-lg"
                >
                  <Link
                    href="/dashboard"
                    className="flex items-center gap-2 rounded-t-lg border-b border-gray-200 px-4 py-3 text-sm text-gray-800 hover:bg-green-700 hover:text-white"
                  >
                    <LayoutGrid className="h-4 w-4" />
                    Dashboard
                  </Link>

                  <button
                    onClick={handleLogout}
                    className="flex w-full items-center gap-2 cursor-pointer rounded-b-lg px-4 py-3 text-left text-sm text-gray-800 hover:bg-green-700 hover:text-white"
                  >
                    <LogOut className="h-4 w-4" />
                    Logout
                  </button>
                </div>
              )}
            </div>
          ) : (
            <>
              <Link
                href="/signup"
                className="flex items-center gap-1.5 rounded-sm px-3 py-1.5 text-base text-white transition-colors hover:bg-white/10 hover:text-gray-300"
              >
                <UserRound className="h-3.5 w-3.5" />
                <span>Sign Up</span>
              </Link>

              <Link
                href="/signin"
                className="flex items-center gap-1.5 rounded-sm px-3 py-1.5 text-base text-white transition-colors hover:bg-white/10 hover:text-gray-300"
              >
                <LogIn className="h-3.5 w-3.5" />
                <span>Login</span>
              </Link>
            </>
          )}
        </div>
        </div>

        <div className="md:hidden fixed top-[56px] left-0 right-0 px-4 py-2 bg-background z-40 border-b border-green-700">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="Search..."
              className="w-full pl-10 pr-4 py-2 bg-white rounded-full text-gray-800 focus:outline-none"
            />
          </div>
        </div>

        <div className="hidden lg:flex fixed top-[83px] w-full bg-background border-t border-[#00704D] z-40 pr-8 items-center justify-between">
          <div className="flex items-center gap-6">
            <div
              onMouseEnter={() => setIsProductsHover(true)}
              onMouseLeave={() => {
                setIsProductsHover(false);
                setSelectedCategory(null);
                setSelectedSubcategory(null);
              }}
            >
              <button
                className="flex items-center gap-2 bg-green-800 py-3 pl-8 pr-8 text-white font-medium"
                aria-label="Products"
              >
                <Menu className="w-5 h-5" />
                Products
              </button>

              <AnimatePresence>
                {isProductsHover && isMounted && (
                  <>
                    <motion.div
                      initial={{ x: "-100%" }}
                      animate={{ x: 0 }}
                      exit={{ x: "-100%" }}
                      transition={{
                        type: "spring",
                        damping: 25,
                        stiffness: 200,
                      }}
                      className="fixed left-0 top-32 bottom-0 z-40 flex"
                    >
                      <div className="w-80 bg-white shadow-2xl overflow-y-auto">
                        {categories.map((category) => (
                          <div key={category.id} className="border-b border-gray-200">
                            <button
                              onMouseEnter={() => {
                                setSelectedCategory(category.id);
                                setSelectedSubcategory(null);
                              }}
                              className={`w-full px-4 py-3 flex items-center justify-between ${
                                selectedCategory === category.id ? "bg-gray-100" : "hover:bg-gray-50"
                              }`}
                              aria-label={`View ${category.name} products`}
                            >
                              <span className="text-gray-700">{category.name}</span>
                              <ChevronRight className="w-5 h-5 text-gray-400" />
                            </button>
                          </div>
                        ))}
                      </div>

                      <AnimatePresence>
                        {selectedCategory && selectedCategoryData && (
                          <motion.div
                            initial={{ x: -320, opacity: 0 }}
                            animate={{ x: 0, opacity: 1 }}
                            exit={{ x: -320, opacity: 0 }}
                            className="w-80 bg-white border-l border-gray-200 overflow-y-auto"
                          >
                            <div className="p-4 border-b sticky top-0 bg-white">
                              <h3 className="font-bold text-background border-b-2 border-green-600 inline pb-1">
                                {selectedCategoryData.name}
                              </h3>
                            </div>

                            {selectedCategoryData.subcategories.map((subcategory, index) => (
                              <div key={index}>
                                <button
                                  onMouseEnter={() => {
                                    setSelectedSubcategory(subcategory.name);
                                  }}
                                  className={`w-full text-left px-4 py-3 flex items-center justify-between ${
                                    selectedSubcategory === subcategory.name
                                      ? "bg-gray-100"
                                      : "hover:bg-gray-50"
                                  } border-b border-gray-100`}
                                  aria-label={`View ${subcategory.name}`}
                                >
                                  <span className="text-gray-700">{subcategory.name}</span>
                                  {subcategory.childSubcategories &&
                                    subcategory.childSubcategories.length > 0 && (
                                      <ChevronRight className="w-5 h-5 text-gray-400" />
                                    )}
                                </button>
                              </div>
                            ))}
                          </motion.div>
                        )}
                      </AnimatePresence>

                      <AnimatePresence>
                        {selectedSubcategory && selectedSubcategoryData && selectedSubcategoryData.childSubcategories && (
                          <motion.div
                            initial={{ x: -320, opacity: 0 }}
                            animate={{ x: 0, opacity: 1 }}
                            exit={{ x: -320, opacity: 0 }}
                            className="w-80 bg-white border-l border-gray-200 overflow-y-auto"
                          >
                            <div className="p-4 border-b sticky top-0 bg-white">
                              <h3 className="font-bold text-background border-b-2 border-green-600 inline pb-1">
                                {selectedSubcategory}
                              </h3>
                            </div>

                            {selectedSubcategoryData.childSubcategories.map((childItem, index) => (
                              <Link
                                key={index}
                                href={childItem.link}
                                onClick={() => {
                                  setIsProductsHover(false);
                                  setSelectedCategory(null);
                                  setSelectedSubcategory(null);
                                }}
                                className="w-full text-left block px-4 py-3 text-gray-700 hover:bg-gray-50 border-b border-gray-100"
                                aria-label={`View ${childItem.name}`}
                              >
                                {childItem.name}
                              </Link>
                            ))}
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </motion.div>
                  </>
                )}
              </AnimatePresence>
            </div>

            <div className="flex items-center gap-1">
              {productMenuItems2.map((menuItem) => (
                <div
                  key={menuItem.id}
                  className="relative"
                  onMouseEnter={() =>
                    menuItem.items && menuItem.items.length > 0
                      ? setActiveDropdownOne(menuItem.id)
                      : setActiveDropdownOne(null)
                  }
                  onMouseLeave={() => {
                    setActiveDropdownOne(null);
                    setActiveSubmenu(null);
                  }}
                >
                  <Link
                    href={menuItem?.link}
                    className="text-sm px-3 py-2 rounded hover:bg-white/10 flex items-center gap-1"
                  >
                    {menuItem?.name}
                    {(menuItem.items?.length ?? 0) > 0 && (
                      <ChevronDown
                        className={`w-4 h-4 transition-transform ${
                          activeDropdownOne === menuItem.id ? "rotate-180" : ""
                        }`}
                      />
                    )}
                  </Link>

                  <AnimatePresence>
                    {activeDropdownOne === menuItem.id &&
                      menuItem.items &&
                      menuItem.items.length > 0 && (
                        <motion.div
                          initial={{ opacity: 0, y: -10 }}
                          animate={{ opacity: 1, y: 0 }}
                          exit={{ opacity: 0, y: -10 }}
                          transition={{ duration: 0.2 }}
                          className="absolute top-full left-0 mt-2 bg-white rounded-lg shadow-xl flex z-40"
                        >
                          <div className="w-64 border-r border-gray-200">
                            {menuItem.items.map((item, index) => (
                              <div
                                key={index}
                                onMouseEnter={() =>
                                  setActiveSubmenu(item.submenu ? item.name : null)
                                }
                              >
                                <button className="w-full text-left px-4 py-3 text-sm text-background hover:bg-background hover:text-white flex items-center justify-between border-b border-gray-100">
                                  <span>{item.name}</span>
                                  {item.submenu && <ChevronRight className="w-4 h-4" />}
                                </button>
                              </div>
                            ))}
                          </div>

                          <AnimatePresence mode="wait">
                            {(() => {
                              const activeSubmenuItem = menuItem.items?.find(
                                (item) => item.submenu && activeSubmenu === item.name
                              );

                              return activeSubmenuItem ? (
                                <motion.div
                                  key={activeSubmenuItem.name}
                                  initial={{ opacity: 0, x: -10 }}
                                  animate={{ opacity: 1, x: 0 }}
                                  exit={{ opacity: 0, x: -10 }}
                                  className="w-64 bg-gray-50"
                                >
                                  <div className="p-3 border-b bg-white font-semibold text-background">
                                    {activeSubmenuItem.name}
                                  </div>

                                  {activeSubmenuItem.submenu?.map((child, childIndex) => (
                                    <button
                                      key={childIndex}
                                      className="w-full text-left px-4 py-3 text-sm text-gray-700 hover:bg-background hover:text-white border-b border-gray-200"
                                    >
                                      {child.name}
                                    </button>
                                  ))}
                                </motion.div>
                              ) : null;
                            })()}
                          </AnimatePresence>
                        </motion.div>
                      )}
                  </AnimatePresence>
                </div>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-4">
            {mainMenuItems.map((menuItem) => (
              <div
                key={menuItem.id}
                className="relative"
                onMouseEnter={() => setActiveDropdown(menuItem.id)}
                onMouseLeave={() => setActiveDropdown(null)}
              >
                <button className="text-sm px-3 py-2 rounded bg-white/10 hover:bg-white/20 flex items-center gap-1">
                  {menuItem.name}
                  <ChevronDown
                    className={`w-4 h-4 transition-transform ${
                      activeDropdown === menuItem.id ? "rotate-180" : ""
                    }`}
                  />
                </button>

                <AnimatePresence>
                  {activeDropdown === menuItem.id && (
                    <motion.div
                      initial={{ opacity: 0, y: -10 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -10 }}
                      className="absolute top-full right-0 mt-2 w-64 bg-white rounded-lg shadow-xl overflow-hidden"
                    >
                      {menuItem.items.map((item, index) => (
                        <Link href={item.link} key={index}>
                          <div className="w-full text-left px-4 py-3 text-sm text-background hover:bg-background hover:text-white border-b border-gray-100">
                            {item.name}
                          </div>
                        </Link>
                      ))}
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            ))}
          </div>
        </div>
      </header>

      {/* ================= MOBILE MENU - COMPLETELY REWRITTEN ================= */}
      <AnimatePresence>
        {isMobileMenuOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={closeMobileMenu}
              className="fixed inset-0 bg-black/50 z-50"
            />

            <motion.div
              ref={mobileMenuRef}
              initial={{ x: "-100%" }}
              animate={{ x: 0 }}
              exit={{ x: "-100%" }}
              transition={{
                type: "spring",
                damping: 25,
                stiffness: 200,
              }}
              className="fixed left-0 top-0 bottom-0 w-80 bg-white z-50 overflow-y-auto"
            >
              <div className="bg-background text-white p-4 flex items-center justify-between sticky top-0 z-10">
                <h2 className="text-lg font-bold">Main Menu</h2>
                <button onClick={closeMobileMenu} aria-label="Close menu" className="p-1">
                  <X className="w-6 h-6" />
                </button>
              </div>

              <div className="divide-y divide-gray-200">
                <div>
                  <button
                    onClick={() => setMobileCategoryOpen(!mobileCategoryOpen)}
                    className="w-full px-4 py-4 flex items-center justify-between bg-gray-50 hover:bg-gray-100"
                  >
                    <span className="font-medium text-gray-900 flex items-center gap-2">
                      <Menu className="w-5 h-5" />
                      Products
                    </span>
                    <ChevronDown
                      className={`w-5 h-5 transition-transform duration-200 ${
                        mobileCategoryOpen ? "rotate-180" : ""
                      }`}
                    />
                  </button>

                  {mobileCategoryOpen && (
                    <div className="bg-white">
                      {categories.map((category) => (
                        <div key={category.id} className="border-t border-gray-100">
                          <button
                            onClick={() => toggleMobileCategory(category.id)}
                            className="w-full text-left px-8 py-3 flex items-center justify-between hover:bg-gray-50"
                          >
                            <span className="text-gray-700">{category.name}</span>
                            <ChevronDown
                              className={`w-4 h-4 transition-transform duration-200 ${
                                mobileSelectedCategory === category.id ? "rotate-180" : ""
                              }`}
                            />
                          </button>

                          {mobileSelectedCategory === category.id && (
                            <div className="bg-gray-50">
                              {category.subcategories.map((sub, index) => (
                                <div key={index} className="border-t border-gray-200">
                                  <button
                                    onClick={() => toggleMobileSubcategory(sub.name)}
                                    className="w-full text-left px-12 py-2.5 flex items-center justify-between hover:bg-gray-100"
                                  >
                                    <span className="text-sm text-gray-600">{sub.name}</span>
                                    {sub.childSubcategories && sub.childSubcategories.length > 0 && (
                                      <ChevronDown
                                        className={`w-4 h-4 transition-transform duration-200 ${
                                          mobileSelectedSubcategory === sub.name ? "rotate-180" : ""
                                        }`}
                                      />
                                    )}
                                  </button>

                                  {mobileSelectedSubcategory === sub.name && sub.childSubcategories && (
                                    <div className="bg-white">
                                      {sub.childSubcategories.map((child, childIdx) => (
                                        <Link
                                          key={childIdx}
                                          href={child.link}
                                          onClick={closeMobileMenu}
                                          className="w-full text-left block px-16 py-2.5 text-sm text-gray-600 hover:bg-gray-100 border-t border-gray-100"
                                        >
                                          {child.name}
                                        </Link>
                                      ))}
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {productMenuItems2.map((menuItem) => {
                  const hasItems = (menuItem.items?.length ?? 0) > 0;

                  return (
                    <div key={menuItem.id}>
                      <div className="flex items-center">
                        <Link
                          href={menuItem.link}
                          onClick={() => {
                            if (!hasItems) {
                              closeMobileMenu();
                            }
                          }}
                          className={`flex-1 px-4 py-4 font-medium text-gray-900 hover:bg-gray-50 ${
                            hasItems ? "border-r border-gray-200" : ""
                          }`}
                        >
                          {menuItem.name}
                        </Link>

                        {hasItems && (
                          <button
                            onClick={() => toggleMobileDropdownOne(menuItem.id)}
                            className="px-4 py-4 hover:bg-gray-50"
                          >
                            <ChevronDown
                              className={`w-5 h-5 transition-transform duration-200 ${
                                mobileActiveDropdownOne === menuItem.id ? "rotate-180" : ""
                              }`}
                            />
                          </button>
                        )}
                      </div>

                      {mobileActiveDropdownOne === menuItem.id && hasItems && (
                        <div className="bg-gray-50">
                          {menuItem.items?.map((item, index) => {
                            const hasSubmenu = item.submenu && item.submenu.length > 0;

                            return (
                              <div key={index} className="border-t border-gray-200">
                                <div className="flex items-center">
                                  <Link
                                    href={item.link || "#"}
                                    onClick={closeMobileMenu}
                                    className={`flex-1 px-8 py-3 text-gray-600 hover:bg-gray-100 ${
                                      hasSubmenu ? "border-r border-gray-200" : ""
                                    }`}
                                  >
                                    {item.name}
                                  </Link>

                                  {hasSubmenu && (
                                    <button
                                      onClick={() => toggleMobileSubmenu(item.name)}
                                      className="px-4 py-3 hover:bg-gray-100"
                                    >
                                      <ChevronDown
                                        className={`w-4 h-4 transition-transform duration-200 ${
                                          mobileSubmenu === item.name ? "rotate-180" : ""
                                        }`}
                                      />
                                    </button>
                                  )}
                                </div>

                                {mobileSubmenu === item.name && hasSubmenu && (
                                  <div className="bg-white">
                                    {item.submenu?.map((subItem, subIndex) => (
                                      <Link
                                        key={subIndex}
                                        href={subItem.link || "#"}
                                        onClick={closeMobileMenu}
                                        className="w-full text-left block px-12 py-3 text-sm text-gray-600 hover:bg-gray-100 border-t border-gray-100"
                                      >
                                        {subItem.name}
                                      </Link>
                                    ))}
                                  </div>
                                )}
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                })}

                {mainMenuItems.map((menuItem) => (
                  <div key={menuItem.id}>
                    <button
                      onClick={() => toggleMobileDropdown(menuItem.id)}
                      className="w-full px-4 py-4 flex items-center justify-between hover:bg-gray-50"
                    >
                      <span className="font-medium text-gray-900">{menuItem.name}</span>
                      <ChevronDown
                        className={`w-5 h-5 transition-transform duration-200 ${
                          mobileActiveDropdown === menuItem.id ? "rotate-180" : ""
                        }`}
                      />
                    </button>

                    {mobileActiveDropdown === menuItem.id && (
                      <div className="bg-gray-50">
                        {menuItem.items.map((item, index) => (
                          <Link
                            key={index}
                            href={item.link}
                            onClick={closeMobileMenu}
                            className="w-full text-left block px-8 py-3 text-gray-600 hover:bg-gray-100 border-t border-gray-200"
                          >
                            {item.name}
                          </Link>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      <TopHeader />
    </div>
  );
}