'use client';

import { useState, useEffect, useRef } from 'react';
import {
  Menu,
  Search,
  Heart,
  ShoppingBag,
  User,
  ChevronDown,
} from 'lucide-react';
import { useCartStore } from '@/store/cart-store';

/* ── Men dropdown links ──────────────────────────────────── */
const MEN_CATEGORIES = [
  'Panjabi',
  'Shirt',
  'T-Shirt',
  'Trouser',
  'Winter Wear',
];

/* ── Nav links (desktop) ─────────────────────────────────── */
const NAV_LINKS = [
  { label: 'Home', href: '#' },
  { label: 'Men', href: '#', hasDropdown: true },
  { label: 'New Arrivals', href: '#' },
  { label: 'Best Sellers', href: '#' },
  { label: 'Sale', href: '#', highlighted: true },
  { label: 'Contact', href: '#' },
];

/* ── Props ─────────────────────────────────────────────────── */
interface HeaderProps {
  mobileMenuOpen: boolean;
  setMobileMenuOpen: (open: boolean) => void;
}

export default function Header({ mobileMenuOpen, setMobileMenuOpen }: HeaderProps) {
  const [menDropdownOpen, setMenDropdownOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const dropdownTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);

  /* Cart & wishlist counts from Zustand store */
  const cartItems = useCartStore((s) => s.items);
  const wishlist = useCartStore((s) => s.wishlist);
  const openCart = useCartStore((s) => s.openCart);
  const totalCartItems = cartItems.reduce((sum, i) => sum + i.quantity, 0);
  const wishlistCount = wishlist.size;

  /* Shadow on scroll */
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  /* Close men dropdown after a short delay for UX */
  const handleMouseEnter = () => {
    if (dropdownTimeout.current) clearTimeout(dropdownTimeout.current);
    setMenDropdownOpen(true);
  };

  const handleMouseLeave = () => {
    dropdownTimeout.current = setTimeout(() => setMenDropdownOpen(false), 150);
  };

  return (
    <header
      className={`sticky top-0 z-40 bg-white/95 backdrop-blur-sm transition-shadow duration-300 ${
        scrolled ? 'shadow-md' : ''
      }`}
    >
      <div className="mx-auto flex h-16 max-w-7xl items-center gap-4 px-4 sm:px-6 lg:px-8">
        {/* Mobile hamburger */}
        <button
          className="lg:hidden p-2 -ml-2 text-gray-700 hover:text-brand transition-colors"
          onClick={() => setMobileMenuOpen(true)}
          aria-label="Open menu"
        >
          <Menu className="h-6 w-6" />
        </button>

        {/* Brand logo */}
        <a href="/" className="flex items-baseline gap-0">
          <span className="font-heading text-2xl font-bold tracking-tight text-brand">
            X
          </span>
          <span className="font-heading text-2xl font-bold tracking-tight text-gray-900">
            evon
          </span>
        </a>

        {/* Desktop search bar */}
        <div className="ml-6 hidden flex-1 sm:flex">
          <div className="relative w-full max-w-md">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              placeholder="Search for panjabi, shirt, trouser..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full rounded-full border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-700 outline-none transition-colors placeholder:text-gray-400 focus:border-brand focus:bg-white focus:ring-1 focus:ring-brand/20"
            />
          </div>
        </div>

        {/* Right-side action icons */}
        <div className="ml-auto flex items-center gap-1 lg:gap-3">
          {/* Mobile Search */}
          <button className="sm:hidden p-2 text-gray-700 hover:text-brand transition-colors" aria-label="Search">
            <Search className="h-5 w-5" />
          </button>

          {/* Wishlist */}
          <button className="relative p-2 text-gray-700 hover:text-brand transition-colors" aria-label="Wishlist">
            <Heart className="h-5 w-5" />
            {wishlistCount > 0 && (
              <span className="absolute -right-0.5 -top-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-brand text-[10px] font-bold text-white">
                {wishlistCount}
              </span>
            )}
          </button>

          {/* Cart */}
          <button
            onClick={openCart}
            className="relative p-2 text-gray-700 hover:text-brand transition-colors"
            aria-label="Cart"
          >
            <ShoppingBag className="h-5 w-5" />
            {totalCartItems > 0 && (
              <span className="absolute -right-0.5 -top-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-brand text-[10px] font-bold text-white">
                {totalCartItems}
              </span>
            )}
          </button>

          {/* User (desktop only) */}
          <button className="hidden p-2 lg:block text-gray-700 hover:text-brand transition-colors" aria-label="Account">
            <User className="h-5 w-5" />
          </button>
        </div>
      </div>

      {/* ── Desktop navigation bar ────────────────────────── */}
      <nav className="hidden border-t border-gray-100 lg:block">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <ul className="flex items-center gap-1">
            {NAV_LINKS.map((link) => (
              <li key={link.label}>
                {link.hasDropdown ? (
                  /* Men – with dropdown */
                  <div
                    className="relative"
                    onMouseEnter={handleMouseEnter}
                    onMouseLeave={handleMouseLeave}
                  >
                    <button className="flex items-center gap-1 px-3 py-2.5 text-sm font-medium text-gray-700 transition-colors hover:text-brand">
                      {link.label}
                      <ChevronDown
                        className={`h-3.5 w-3.5 transition-transform duration-200 ${
                          menDropdownOpen ? 'rotate-180' : ''
                        }`}
                      />
                    </button>

                    {/* Dropdown panel */}
                    {menDropdownOpen && (
                      <div className="absolute left-0 top-full z-30 min-w-[180px] rounded-b-lg border border-gray-100 bg-white py-2 shadow-lg">
                        {MEN_CATEGORIES.map((cat) => (
                          <a
                            key={cat}
                            href="#"
                            className="block px-4 py-2 text-sm text-gray-600 transition-colors hover:bg-gray-50 hover:text-brand"
                          >
                            {cat}
                          </a>
                        ))}
                      </div>
                    )}
                  </div>
                ) : link.highlighted ? (
                  /* Sale – highlighted tab */
                  <a
                    href={link.href}
                    className="block bg-brand/10 px-3 py-2.5 text-sm font-semibold text-brand transition-colors hover:bg-brand/20"
                  >
                    {link.label}
                  </a>
                ) : (
                  /* Regular nav link */
                  <a
                    href={link.href}
                    className="block px-3 py-2.5 text-sm font-medium text-gray-700 transition-colors hover:text-brand"
                  >
                    {link.label}
                  </a>
                )}
              </li>
            ))}
          </ul>
        </div>
      </nav>
    </header>
  );
}
