"use client";

import { useState, useEffect } from "react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { usePathname } from "next/navigation";
import Image from "next/image";
import { Menu, X, ChevronDown } from "lucide-react";
import { NAV_LINKS } from "@/lib/constants";
import AuthMenu from "./AuthMenu";
import HeaderSearch from "./HeaderSearch";
import NotificationBell from "@/components/notifications/NotificationBell";
import { useAuth } from "@/lib/auth/AuthContext";
import SafeImage from "@/components/ui/SafeImage";
import { catalogApi } from "@/lib/api/catalog";
import type { ApiCategory } from "@/lib/api/types";

/**
 * The Firebase messaging SDK is ~100 KB and is only ever exercised for signed-in
 * users who grant notification permission. A static import would place it in the
 * shared layout chunk — i.e. downloaded by every anonymous visitor on every
 * marketing page. The `isAuthenticated` guard below gates rendering; this gates
 * the bytes to match.
 */
const FCMRegister = dynamic(() => import("@/components/notifications/FCMRegister"), {
  ssr: false,
});

const FALLBACK_CATEGORIES = [
  "#1a73e8",
  "#f59e0b",
  "#8b5cf6",
  "#10b981",
  "#f97316",
  "#6366f1",
  "#22c55e",
  "#ec4899",
];

export default function Header() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [categoryOpen, setCategoryOpen] = useState(false);
  const [categories, setCategories] = useState<ApiCategory[]>([]);
  const { isAuthenticated } = useAuth();
  const pathname = usePathname();

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 10);
    // Passive: the handler never calls preventDefault, and saying so lets the
    // browser keep scrolling on the compositor instead of waiting on main.
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  // Close the mobile menu whenever the route changes.
  useEffect(() => {
    setMobileOpen(false);
  }, [pathname]);

  // Lock body scroll while the mobile menu is open.
  useEffect(() => {
    if (!mobileOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [mobileOpen]);

  useEffect(() => {
    let active = true;

    async function loadCategories() {
      try {
        const res = await catalogApi.categories(
          { per_page: 12, with_products: true },
          { next: { revalidate: 120 } }
        );
        if (active) setCategories(res.data);
      } catch {
        if (active) setCategories([]);
      }
    }

    loadCategories();

    return () => {
      active = false;
    };
  }, []);

  return (
    <>
      {/* Top announcement bar */}
      <div className="bg-[#CC1414] text-white text-center text-xs py-2 px-4 font-medium tracking-wide">
        🚀 Get Best Rates on Raw Materials — &nbsp;
        <Link href="/contact" className="underline underline-offset-2 hover:text-yellow-200 transition-colors">
          Tell Us Your Requirements →
        </Link>
      </div>

      <header
        className={`sticky top-0 z-50 bg-white transition-all duration-300 ${
          scrolled ? "shadow-md" : "shadow-sm"
        }`}
      >
        <div className="relative z-50 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 bg-white">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <Link href="/" className="flex items-center gap-2 shrink-0">
              <Image
                src="/favicon.png"
                alt="Biznie icon"
                width={36}
                height={36}
                className="h-9 w-9 sm:hidden"
                priority
              />
              <Image
                src="/logo.png"
                alt="Biznie"
                width={180}
                height={48}
                className="hidden sm:block h-9 w-auto"
                priority
              />
            </Link>

            {/* Categories Dropdown */}
            <div className="relative hidden lg:block ml-4">
              <button
                onMouseEnter={() => setCategoryOpen(true)}
                onMouseLeave={() => setCategoryOpen(false)}
                className="flex items-center gap-1 text-sm font-semibold text-gray-700 hover:text-[#CC1414] transition-colors border border-gray-200 rounded-lg px-3 py-2"
              >
                All Categories <ChevronDown size={14} />
              </button>
              {categoryOpen && (
                <div
                  onMouseEnter={() => setCategoryOpen(true)}
                  onMouseLeave={() => setCategoryOpen(false)}
                  className="absolute top-full left-0 mt-1 w-64 max-h-[70vh] overflow-y-auto bg-white border border-gray-100 rounded-xl shadow-2xl py-2 z-50"
                >
                  {categories.length > 0 ? (
                    categories.map((cat, index) => {
                      const color = FALLBACK_CATEGORIES[index % FALLBACK_CATEGORIES.length];
                      const imageSrc = cat.thumbnail || cat.icon || "/logo.png";

                      return (
                        <Link
                          key={cat.id}
                          href={`/categories/${cat.slug}`}
                          className="flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-red-50 hover:text-[#CC1414] transition-colors"
                          onClick={() => setCategoryOpen(false)}
                        >
                          <div
                            className="relative w-9 h-9 rounded-lg overflow-hidden shrink-0"
                            style={{ background: `${color}15`, border: `1px solid ${color}20` }}
                          >
                            <SafeImage
                              src={imageSrc}
                              alt={cat.name}
                              fill
                              sizes="36px"
                              className="object-contain p-1.5"
                            />
                          </div>
                          <div className="min-w-0">
                            <div className="font-medium truncate">{cat.name}</div>
                            <div className="text-xs text-gray-400 line-clamp-1">
                              {cat.meta.description || `Browse ${cat.name}`}
                            </div>
                          </div>
                        </Link>
                      );
                    })
                  ) : (
                    <div className="px-4 py-3 text-sm text-gray-500">Loading categories...</div>
                  )}
                </div>
              )}
            </div>

            {/* Search Bar */}
            <div className="hidden md:flex flex-1 max-w-md mx-4">
              <HeaderSearch />
            </div>

            {/* Desktop Nav */}
            <nav className="hidden lg:flex items-center gap-1">
              {NAV_LINKS.slice(1).map((link) => (
                <Link
                  key={link.href}
                  href={link.href}
                  className="text-sm font-medium text-gray-700 hover:text-[#CC1414] px-3 py-2 rounded-lg hover:bg-red-50 transition-all"
                >
                  {link.label}
                </Link>
              ))}
            </nav>

            {/* Right actions */}
            <div className="flex items-center gap-2">
              {isAuthenticated && <NotificationBell />}
              {/* Always visible: on mobile this collapses to an avatar / compact
                  Login pill so it never depends on opening the burger menu. */}
              <AuthMenu />
              {isAuthenticated && <FCMRegister />}
              <button
                onClick={() => setMobileOpen(!mobileOpen)}
                className="lg:hidden p-2 text-gray-600 hover:text-[#CC1414] transition-colors"
                aria-label="Toggle menu"
              >
                {mobileOpen ? <X size={22} /> : <Menu size={22} />}
              </button>
            </div>
          </div>
        </div>

        {/* Mobile Menu */}
        {mobileOpen && (
          <>
            <div
              className="lg:hidden fixed inset-0 top-0 z-40 bg-black/40"
              onClick={() => setMobileOpen(false)}
              aria-hidden
            />
            {/* dvh, not vh: on iOS Safari `100vh` is the *large* viewport, which
                ignores the bottom toolbar and pushed the Login button below the
                fold. dvh tracks the visible area as the toolbar shows/hides. */}
            <div className="lg:hidden relative z-50 max-h-[calc(100dvh-9rem)] overflow-y-auto overscroll-contain bg-white border-t border-gray-100 shadow-xl">
            <div className="px-4 py-3 pb-[calc(1rem+env(safe-area-inset-bottom))]">
              <HeaderSearch
                placeholder="Search products..."
                className="mb-3"
                inputClassName="py-2.5"
                onNavigate={() => setMobileOpen(false)}
              />
              {NAV_LINKS.map((link) => (
                <Link
                  key={link.href}
                  href={link.href}
                  onClick={() => setMobileOpen(false)}
                  className="block py-2.5 text-sm font-medium text-gray-700 hover:text-[#CC1414] border-b border-gray-50 last:border-none"
                >
                  {link.label}
                </Link>
              ))}
              <div className="mt-3 pt-3 border-t border-gray-100">
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">
                  Categories
                </p>
                <div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
                  {categories.slice(0, 8).map((cat, index) => {
                    const color = FALLBACK_CATEGORIES[index % FALLBACK_CATEGORIES.length];
                    const imageSrc = cat.thumbnail || cat.icon || "/logo.png";

                    return (
                      <Link
                        key={cat.id}
                        href={`/categories/${cat.slug}`}
                        onClick={() => setMobileOpen(false)}
                        className="flex flex-col items-center gap-1 p-2 rounded-lg hover:bg-red-50 transition-colors text-center"
                      >
                        <div
                          className="relative w-10 h-10 rounded-lg overflow-hidden shrink-0"
                          style={{ background: `${color}15`, border: `1px solid ${color}20` }}
                        >
                          <SafeImage
                            src={imageSrc}
                            alt={cat.name}
                            fill
                            sizes="40px"
                            className="object-contain p-1.5"
                          />
                        </div>
                        <span className="text-xs text-gray-600 line-clamp-2">{cat.name}</span>
                      </Link>
                    );
                  })}
                </div>
              </div>
              {/* No account block here — AuthMenu is now always visible in the
                  header bar itself, so repeating it inside the menu duplicated
                  the signed-in user on every mobile screen. */}
            </div>
            </div>
          </>
        )}
      </header>
    </>
  );
}
