"use client";

import React, { useState, useRef, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import {
  Search,
  ArrowRight,
  User,
  ShoppingCart,
  ChevronDown,
  ClipboardList,
  Phone,
  Menu,
  X,
  ChevronRight,
  FlaskConical,
  TestTube2,
  Wrench,
  Sparkles,
  Sprout,
  Pipette,
} from "lucide-react";

interface SubCategoryItem {
  name: string;
  href: string;
}

interface MegaCategory {
  id: string;
  title: string;
  href: string;
  icon: React.ReactNode;
  activeHeader?: boolean;
  activeItem?: string;
  items: SubCategoryItem[];
  viewAllCount: number;
}

const megaCategories: MegaCategory[] = [
  {
    id: "affinity",
    title: "Affinity Products",
    href: "/products/affinity-products",
    icon: (
      <Image
        src="/images/icons/Affinity.png"
        alt="Affinity Products"
        width={20}
        height={20}
        className="w-9 h-9 object-contain"
      />
    ),
    activeHeader: true,
    activeItem: "96 Well Microplates",
    items: [
      { name: "96 Well Microplates", href: "/products/96-well-microplates" },
      { name: "Kits", href: "/products/kits" },
      { name: "MagneZoom(TM) Magnetic Microbeads", href: "/products/magnezoom-microbeads" },
      { name: "OnePASS(TM) Prepared Columns", href: "/products/onepass-columns" },
    ],
    viewAllCount: 2,
  },
  {
    id: "antibodies",
    title: "Antibodies & Serums",
    href: "/products/antibodies",
   icon: (
      <Image
        src="/images/icons/serum.png"
        alt="Affinity Products"
        width={20}
        height={20}
        className="w-9 h-9 object-contain"
      />
    ),
    items: [
      { name: "Antibody Kits", href: "/products/antibody-kits" },
      { name: "Conjugated Antibodies", href: "/products/conjugated-antibodies" },
      { name: "Primary Antibodies", href: "/products/primary-antibodies" },
      { name: "Secondary Antibodies", href: "/products/secondary-antibodies" },
    ],
    viewAllCount: 1,
  },
  {
    id: "buffers",
    title: "Buffers And Reagents",
    href: "/products/buffers",
   icon: (
      <Image
        src="/images/icons/buffer.png"
        alt="Affinity Products"
        width={20}
        height={20}
        className="w-9 h-9 object-contain"
      />
   ),
    items: [
      { name: "Blotting Buffers", href: "/products/blotting-buffers" },
      { name: "Cell Lysis Buffers", href: "/products/cell-lysis-buffers" },
      { name: "Electrophoresis Buffers", href: "/products/electrophoresis-buffers" },
      { name: "ELISA & Immunobiology Buffers", href: "/products/elisa-buffers" },
    ],
    viewAllCount: 6,
  },
  {
    id: "equipment",
    title: "Equipment & Tools",
    href: "/products/equipment",
   icon: (
      <Image
        src="/images/icons/tools.png"
        alt="Affinity Products"
        width={20}
        height={20}
        className="w-9 h-9 object-contain"
      />
   ),
    items: [
      { name: "A to Z", href: "/products/equipment-a-to-z" },
      { name: "Cell Scrapers, Spreaders & Lifters", href: "/products/cell-scrapers" },
      { name: "Forceps and Tweezers", href: "/products/forceps-tweezers" },
      { name: "Hybridization Bags", href: "/products/hybridization-bags" },
    ],
    viewAllCount: 4,
  },
  {
    id: "lectins",
    title: "Lectins, Proteins & Enzymes",
    href: "/products/enzymes",
     icon: (
      <Image
        src="/images/icons/protein.png"
        alt="Affinity Products"
        width={20}
        height={20}
        className="w-9 h-9 object-contain"
      />
   ),
    items: [
      { name: "BSA and Other Albumins", href: "/products/albumins" },
      { name: "Conjugates Lectins", href: "/products/conjugates-lectins" },
      { name: "Enzymes & Substrates", href: "/products/enzymes-substrates" },
      { name: "Lectin Resins and Agarose", href: "/products/lectin-resins" },
    ],
    viewAllCount: 3,
  },
  {
    id: "microbiology",
    title: "Microbiology",
    href: "/products/microbiology",
    icon: (
      <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 2v20M2 12h20M4.93 4.93l14.14 14.14M4.93 19.07l14.14-14.14" />
        <circle cx="12" cy="12" r="2" fill="currentColor" />
      </svg>
    ),
    items: [
      { name: "Agar Plates", href: "/products/agar-plates" },
      { name: "Consumables", href: "/products/microbiology-consumables" },
      { name: "Liquid Media", href: "/products/liquid-media" },
      { name: "Solid Media", href: "/products/solid-media" },
    ],
    viewAllCount: 0,
  },
  {
    id: "plant-media",
    title: "Plant Media",
    href: "/products/plant-media",
    icon: (
      <Image
        src="/images/icons/plant-media.png"
        alt="Affinity Products"
        width={20}
        height={20}
        className="w-9 h-9 object-contain"
      />
   ),
    items: [
      { name: "BioChemicals", href: "/products/plant-biochemicals" },
      { name: "Dehydrated Media", href: "/products/dehydrated-media" },
      { name: "Gelling Agents", href: "/products/gelling-agents" },
      { name: "Growth Hormones & Regulators", href: "/products/growth-hormones" },
    ],
    viewAllCount: 3,
  },
  {
    id: "chemicals",
    title: "Laboratory Chemicals & Antibiotics",
    href: "/products/chemicals",
     icon: (
      <Image
        src="/images/icons/lab-anti.png"
        alt="Affinity Products"
        width={20}
        height={20}
        className="w-9 h-9 object-contain"
      />
   ),
    items: [
      { name: "A to Z", href: "/products/chemicals-a-to-z" },
      { name: "Acids", href: "/products/acids" },
      { name: "Amino Acids", href: "/products/amino-acids" },
      { name: "Antibiotics", href: "/products/antibiotics" },
    ],
    viewAllCount: 11,
  },
];

export const Header: React.FC = () => {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [productsOpen, setProductsOpen] = useState(false);
  const [mobileProductsOpen, setMobileProductsOpen] = useState(false);
  const productsNavRef = useRef<HTMLDivElement>(null);

  // Close mega menu when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        productsNavRef.current &&
        !productsNavRef.current.contains(event.target as Node)
      ) {
        setProductsOpen(false);
      }
    };

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

  return (
    <header className="w-full bg-white select-none border-b-2 border-slate-100 relative z-50">
      <div className="w-full max-w-[1800px] mx-auto px-6 sm:px-10 lg:px-12">
        {/* ROW 1: Header Top Bar */}
        <div className="flex items-center justify-between h-[68px] sm:h-[88px] gap-2 sm:gap-3 lg:gap-6">
          {/* Mobile Left: Menu Toggle + Logo */}
          <div className="flex items-center gap-2 sm:gap-3">
            {/* Mobile Hamburger Menu Toggle on LEFT matching reference */}
            <button
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="p-1 -ml-1 text-slate-800 hover:text-[#0077b6] md:hidden focus:outline-none"
              aria-label="Toggle navigation menu"
            >
              {mobileMenuOpen ? <X className="w-6 h-6 stroke-[2.2]" /> : <Menu className="w-6 h-6 stroke-[2.2]" />}
            </button>

            {/* Logo */}
            <Link
              href="/"
              className="shrink-0 flex items-center"
              aria-label="bioWORLD Home"
            >
              <div className="relative h-[38px] w-[150px] xs:h-[42px] xs:w-[180px] sm:h-[57px] sm:w-[270px] shrink-0">
                <Image
                  src="/images/logo/bioworld-logo.png"
                  alt="bioWORLD - molecular tools and laboratory essentials"
                  fill
                  priority
                  className="object-contain object-left"
                />
              </div>
            </Link>
          </div>

          {/* Language Selector */}
          <div className="spacing hidden sm:flex items-center justify-center gap-1.5 h-[56px] px-4 border border-slate-200/90 rounded-md bg-white shrink-0 hover:bg-slate-50 transition-colors cursor-pointer">
            <span className="text-[18px] font-bold text-slate-800">US</span>
            <span className="text-[18px] font-bold text-[#0077b6]">EN</span>
            <ChevronDown className="w-3.5 h-3.5 text-slate-400 stroke-[2.2] ml-0.5" />
          </div>

          {/* Search Bar */}
          <div className="hidden md:flex flex-1 max-w-[650px] h-[56px] items-center border border-slate-200/90 rounded-md overflow-hidden bg-white mx-1 lg:mx-3">
            <div className="pl-3.5 pr-2.5 flex items-center justify-center text-slate-400">
              <Search className="w-5 h-5 text-slate-400 stroke-[2]" />
            </div>

            <input
              type="text"
              placeholder="Search"
              className="w-full text-base text-slate-700 placeholder-slate-400 bg-transparent focus:outline-none"
            />

            <button
              type="button"
              className="bg-[#0077b6] hover:bg-[#02699e] text-white w-[56px] h-full flex items-center justify-center shrink-0 transition-colors"
              aria-label="Search button"
            >
              <ArrowRight className="w-5 h-5 stroke-[2.8]" />
            </button>
          </div>

          {/* Right Section */}
          <div className="flex items-center gap-3 sm:gap-4 lg:gap-5 shrink-0">
            {/* Account: icon only on mobile, box on desktop/tablet */}
            <Link
              href="/account"
              className="flex sm:hidden p-1 text-slate-700 hover:text-[#0077b6]"
              aria-label="Account"
            >
              <User className="w-[22px] h-[22px] stroke-[1.8]" />
            </Link>

            {/* Desktop Account Box */}
            <div className="spacing-account hidden sm:flex items-center justify-between gap-2.5 h-[56px] px-4 border border-slate-200/90 rounded-md bg-white shrink-0 hover:bg-slate-50 transition-colors cursor-pointer">
              <User className="w-[20px] h-[20px] text-slate-600 stroke-[1.8]" />
              <div className="flex flex-col text-left justify-center">
                <span className="text-[12px] text-slate-400 leading-none mb-1 font-normal">
                  Account
                </span>
                <span className="text-[14px] font-regular text-[#0077b6] leading-none">
                  Sign In <span className="text-slate-300 font-normal mx-0.5">|</span> Register
                </span>
              </div>
              <ChevronDown className="w-3.5 h-3.5 text-slate-400 stroke-[2] ml-1" />
            </div>

            {/* Divider */}
            <div className="hidden lg:block h-[30px] w-[1px] bg-slate-200 shrink-0" />

            {/* Your Orders */}
            <Link
              href="/orders"
              className="hidden lg:flex items-center gap-2.5 shrink-0 hover:text-[#0077b6] transition-colors"
            >
              <ClipboardList className="w-[22px] h-[22px] text-slate-700 stroke-[1.5]" />
              <div className="flex flex-col text-left justify-center">
                <span className="text-[12px] text-slate-400 leading-none mb-0.5 font-normal">
                  Your
                </span>
                <span className="text-[16px] font-bold text-slate-900 leading-none">
                  Orders
                </span>
              </div>
            </Link>

            {/* Divider */}
            <div className="hidden lg:block h-[30px] w-[1px] bg-slate-200 shrink-0" />

            {/* Shopping Cart */}
            <Link
              href="/cart"
              className="flex items-center gap-2.5 shrink-0 hover:text-[#0077b6] transition-colors relative"
              aria-label="Shopping Cart with 0 items"
            >
              <div className="relative">
                <ShoppingCart className="w-[22px] h-[22px] text-slate-700 stroke-[1.5]" />
                {/* Mobile cart badge matching screenshot */}
                <span className="sm:hidden absolute -top-2 -right-2.5 bg-[#0077b6] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">
                  0
                </span>
              </div>
              <div className="hidden sm:flex flex-col text-left justify-center">
                <span className="text-[12px] text-slate-400 leading-none mb-0.5 font-normal">
                  Shopping Cart
                </span>
                <span className="text-[16px] font-bold text-slate-900 leading-none">
                  0 Items
                </span>
              </div>
            </Link>
          </div>
        </div>

        {/* Mobile Search Bar matching reference image with clean search icon */}
        <div className="md:hidden pb-3 pt-1 border-t border-slate-100">
          <div className="w-full h-[42px] flex items-center border border-slate-200 rounded-md px-3 bg-white">
            <Search className="w-4 h-4 text-slate-400 mr-2 shrink-0" />
            <input
              type="text"
              placeholder=""
              className="w-full text-sm text-slate-700 bg-transparent focus:outline-none"
            />
          </div>
        </div>
      </div>

      {/* ROW 2: Desktop Navigation Bar with relative container for Mega Menu */}
      <div 
        style={{ fontFamily: 'var(--font-roboto), "Roboto", sans-serif' }}
        className="hidden md:flex w-full items-center justify-center h-[72px] border-t-2 border-slate-100 relative"
      >
        <div className="w-full max-w-[1800px] mx-auto px-6 sm:px-10 lg:px-12 h-full relative">
          <div className="flex w-[85%] mx-auto items-center justify-between h-full">
            <span className="text-[18px] font-regular text-slate-800 hover:text-[#0077b6] whitespace-nowrap transition-colors cursor-pointer">
              Home
            </span>

            {/* Products trigger container */}
            <div ref={productsNavRef} className="h-full flex items-center">
              <button
                type="button"
                onClick={() => setProductsOpen((prev) => !prev)}
                className={`text-[18px] font-regular flex items-center gap-1.5 whitespace-nowrap transition-colors py-2 cursor-pointer relative h-full ${
                  productsOpen
                    ? "text-[#0077b6]"
                    : "text-slate-800 hover:text-[#0077b6]"
                }`}
                aria-expanded={productsOpen}
                aria-haspopup="true"
              >
                <span>Products</span>
                <ChevronDown
                  className={`w-4 h-4 text-slate-500 transition-transform duration-250 ${
                    productsOpen ? "rotate-180 text-[#0077b6]" : ""
                  }`}
                />
                {/* Active blue indicator on bottom border of navbar matching reference */}
                {productsOpen && (
                  <span className="absolute bottom-0 left-0 right-0 h-[3px] bg-[#0077b6]" />
                )}
              </button>
            </div>

            <span className="text-[18px] font-regular text-slate-800 hover:text-[#0077b6] whitespace-nowrap transition-colors cursor-pointer">
              Custom Order & Quotes
            </span>

            <div className="text-[18px] font-regular text-slate-800 hover:text-[#0077b6] flex items-center gap-1 whitespace-nowrap transition-colors cursor-pointer">
              <span>About</span>
              <ChevronDown className="w-3.5 h-3.5 text-slate-500" />
            </div>

            <span className="text-[18px] font-regular text-slate-800 hover:text-[#0077b6] whitespace-nowrap transition-colors cursor-pointer">
              Distributors
            </span>

            <span className="text-[18px] font-regular text-slate-800 hover:text-[#0077b6] whitespace-nowrap transition-colors cursor-pointer">
              FAQ
            </span>

            <button
              type="button"
              className="inline-flex items-center justify-center gap-2 h-[40px] px-5 bg-[#0077b6] hover:bg-[#02699e] text-white text-[16px] font-regular rounded-md whitespace-nowrap transition-colors cursor-pointer"
            >
              <Phone className="w-4 h-4 fill-white text-white" />
              Contact Us
            </button>
          </div>

          {/* FULLY FUNCTIONAL MEGA MENU DROPDOWN (Spans across the full header content width from logo to shopping cart) */}
          <div
            className={`absolute left-6 sm:left-10 lg:left-12 right-6 sm:right-10 lg:right-12 top-full z-50 transition-all duration-200 ease-out ${
              productsOpen
                ? "opacity-100 visible translate-y-0 pointer-events-auto"
                : "opacity-0 invisible -translate-y-2 pointer-events-none"
            }`}
          >
            <div className="bg-white rounded-b-xl shadow-2xl border border-slate-200 overflow-hidden">
              {/* 4-column x 2-row Mega Menu Grid */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 divide-y lg:divide-y-0">
                {megaCategories.map((category, index) => {
                  const isBottomRow = index >= 4;
                  const isLastCol = (index + 1) % 4 === 0;

                  return (
                    <div
                      key={category.id}
                      className={`flex flex-col p-5 bg-white transition-colors ${
                        !isLastCol ? "lg:border-r lg:border-slate-100" : ""
                      } ${isBottomRow ? "lg:border-t lg:border-slate-100" : ""}`}
                    >
                      {/* Category Header Card (using Roboto font-size 24px and font-weight semibold on desktop, scaled on mobile/tab) */}
                      <div
                        style={{ fontFamily: 'var(--font-roboto), "Roboto", sans-serif' }}
                        className={`group flex items-center justify-between px-3 sm:px-3.5 py-2 rounded-md transition-all duration-150 mb-3 cursor-pointer ${
                          category.activeHeader
                            ? "bg-[#0077b6] text-white"
                            : "hover:bg-[#0077b6] hover:text-white text-slate-900"
                        }`}
                      >
                        <div className="flex items-center gap-2 sm:gap-2.5 min-w-0">
                          {/* Icon badge */}
                          <div
                            className={`w-9 h-9 sm:w-9 sm:h-9 rounded flex items-center justify-center shrink-0 transition-colors ${
                              category.activeHeader
                                ? "text-white"
                                : "bg-[#eaf4fa] text-[#0077b6] group-hover:bg-white/20 group-hover:text-white"
                            }`}
                          >
                            {category.icon}
                          </div>
                          <span className="text-[17px] sm:text-[20px] lg:text-[24px] font-semibold tracking-tight truncate">
                            {category.title}
                          </span>
                        </div>
                        <ChevronRight
                          className={`w-4 h-4 sm:w-5 sm:h-5 shrink-0 transition-transform duration-150 ${
                            category.activeHeader
                              ? "text-white"
                              : "text-slate-800 group-hover:text-white group-hover:translate-x-0.5"
                          }`}
                        />
                      </div>

                      {/* Subcategories List (using Poppins font-size 16px and font-weight regular) */}
                      <ul 
                        style={{ fontFamily: 'var(--font-poppins), "Poppins", sans-serif' }}
                        className="space-y-1 flex-1 mb-2"
                      >
                        {category.items.map((subItem) => {
                          const isActiveItem =
                            category.activeItem === subItem.name;
                          return (
                            <li key={subItem.name}>
                              <div
                                className={`group/sub flex items-center justify-between px-2.5 sm:px-3 py-1.5 rounded text-[14px] sm:text-[15px] lg:text-[16px] transition-colors duration-150 cursor-pointer ${
                                  isActiveItem
                                    ? "bg-[#f0f8fd] text-[#0077b6] font-normal"
                                    : "text-slate-600 hover:text-[#0077b6] hover:bg-slate-50 font-normal"
                                }`}
                              >
                                <span className="truncate">{subItem.name}</span>
                                {isActiveItem && (
                                  <ArrowRight className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-[#0077b6] shrink-0" />
                                )}
                              </div>
                            </li>
                          );
                        })}
                      </ul>

                      {/* View All (Count) link (using Poppins font-size 16px) */}
                      <div 
                        style={{ fontFamily: 'var(--font-poppins), "Poppins", sans-serif' }}
                        className="pt-2 px-2.5 sm:px-3"
                      >
                        <span
                          className="inline-flex items-center gap-1 text-[14px] sm:text-[15px] lg:text-[16px] font-medium text-[#0077b6] hover:text-[#02699e] transition-colors cursor-pointer"
                        >
                          <span>
                            {category.viewAllCount > 0
                              ? `View All (${category.viewAllCount})`
                              : "View All"}
                          </span>
                        </span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Mobile Dropdown Menu */}
      {mobileMenuOpen && (
        <div 
          style={{ fontFamily: 'var(--font-roboto), "Roboto", sans-serif' }}
          className="md:hidden px-6 py-4 border-t border-slate-100 flex flex-col space-y-3 bg-white max-h-[80vh] overflow-y-auto"
        >
          <span
            onClick={() => setMobileMenuOpen(false)}
            className="text-sm font-regular text-slate-800 py-1 cursor-pointer"
          >
            Home
          </span>

          {/* Mobile Products Accordion */}
          <div>
            <button
              type="button"
              onClick={() => setMobileProductsOpen((prev) => !prev)}
              className="w-full flex items-center justify-between text-sm font-regular text-slate-800 py-1"
            >
              <span>Products</span>
              <ChevronDown
                className={`w-4 h-4 text-slate-500 transition-transform ${
                  mobileProductsOpen ? "rotate-180 text-[#0077b6]" : ""
                }`}
              />
            </button>

            {mobileProductsOpen && (
              <div className="pl-3 pt-2 pb-1 space-y-4 border-l-2 border-sky-100 ml-1">
                {megaCategories.map((category) => (
                  <div key={category.id} className="space-y-1.5">
                    <div
                      style={{ fontFamily: 'var(--font-roboto), "Roboto", sans-serif' }}
                      className="text-[17px] sm:text-[19px] font-regular text-[#0077b6] flex items-center justify-between pr-2 cursor-pointer"
                    >
                      <span>{category.title}</span>
                      <ChevronRight className="w-4 h-4 text-[#0077b6]" />
                    </div>
                    <ul 
                      style={{ fontFamily: 'var(--font-poppins), "Poppins", sans-serif' }}
                      className="pl-2 space-y-1.5"
                    >
                      {category.items.map((sub) => (
                        <li key={sub.name}>
                          <span
                            className="text-[14px] sm:text-[15px] text-slate-600 hover:text-[#0077b6] font-normal cursor-pointer block py-0.5"
                          >
                            {sub.name}
                          </span>
                        </li>
                      ))}
                    </ul>
                  </div>
                ))}
              </div>
            )}
          </div>

          <span
            onClick={() => setMobileMenuOpen(false)}
            className="text-sm font-regular text-slate-800 py-1 cursor-pointer"
          >
            Custom Order & Quotes
          </span>

          <span
            onClick={() => setMobileMenuOpen(false)}
            className="text-sm font-regular text-slate-800 py-1 cursor-pointer"
          >
            About
          </span>

          <span
            onClick={() => setMobileMenuOpen(false)}
            className="text-sm font-regular text-slate-800 py-1 cursor-pointer"
          >
            Distributors
          </span>

          <span
            onClick={() => setMobileMenuOpen(false)}
            className="text-sm font-regular text-slate-800 py-1 cursor-pointer"
          >
            FAQ
          </span>

          <div className="pt-2">
            <button
              type="button"
              onClick={() => setMobileMenuOpen(false)}
              className="inline-flex items-center justify-center gap-2 w-full py-2 bg-[#0077b6] text-white text-sm font-regular rounded-md"
            >
              <Phone className="w-4 h-4 fill-white" />
              <span>Contact Us</span>
            </button>
          </div>
        </div>
      )}
    </header>
  );
};
