"use client";

import { useState, useEffect, useRef } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ArrowRight, ArrowLeft } from "lucide-react";
import { Bag, User, UserCircle, ListChecks, SignOut, CaretDown, Check, Globe } from "@phosphor-icons/react";
import gsap from "gsap";
import { useCart } from "@/lib/cartStore";
import CartDrawer from "./CartDrawer";
import OrderStatusPoller from "./OrderStatusPoller";
import type { CustomerPayload } from "@/lib/customerAuth";
import { useLanguage } from "@/lib/i18n/context";
import type { Locale } from "@/lib/i18n/translations";

// Only the home page has a dark video behind the transparent navbar — white text looks good there.
// All other pages have light/amber backgrounds so need dark text even when not scrolled.
const HERO_PATHS    = ["/"];
const HERO_PREFIXES: string[] = [];

// Nav link labels are provided by the translation hook inside the component

const LANGUAGES: { code: Locale; label: string }[] = [
  { code: "fr", label: "Français" },
  { code: "en", label: "English"  },
  { code: "es", label: "Español"  },
  { code: "ar", label: "العربية"  },
];

export default function Navbar() {
  const [scrolled,     setScrolled]     = useState(false);
  const [menuOpen,     setMenuOpen]     = useState(false);
  const [profileOpen,  setProfileOpen]  = useState(false);
  const [langOpen,     setLangOpen]     = useState(false);
  const [explorerOpen, setExplorerOpen] = useState(false);
  const [customer,     setCustomer]     = useState<CustomerPayload | null>(null);
  const { locale, t, setLocale } = useLanguage();
  const [mounted,      setMounted]      = useState(false);

  const pathname     = usePathname();

  const LEFT_LINKS = [
    { label: t.nav.home,     href: "/"         },
    { label: t.nav.products, href: "/produits" },
  ];
  const EXPLORER_LINKS = [
    { label: t.nav.recipes, href: "/recettes"   },
    { label: t.nav.news,    href: "/actualites" },
  ];
  const RIGHT_LINKS = [
    { label: t.nav.about,   href: "/a-propos" },
    { label: t.nav.contact, href: "/contact"  },
  ];
  const navRef       = useRef<HTMLElement>(null);
  const profileRef   = useRef<HTMLDivElement>(null);
  const langRef      = useRef<HTMLDivElement>(null);
  const explorerRef  = useRef<HTMLLIElement>(null);
  const { openCart, count, clearCart } = useCart();

  useEffect(() => { setMounted(true); }, []);

  useEffect(() => {
    fetch("/api/customer/me").then(r => r.json()).then(setCustomer).catch(() => {});
  }, [pathname]);

  const [isHero, setIsHero] = useState(
    HERO_PATHS.includes(pathname ?? "/") || HERO_PREFIXES.some(p => (pathname ?? "/").startsWith(p))
  );
  useEffect(() => {
    const p = window.location.pathname;
    setIsHero(HERO_PATHS.includes(p) || HERO_PREFIXES.some(prefix => p.startsWith(prefix)));
  }, [pathname]);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (profileRef.current  && !profileRef.current.contains(e.target as Node))  setProfileOpen(false);
      if (langRef.current     && !langRef.current.contains(e.target as Node))      setLangOpen(false);
      if (explorerRef.current && !explorerRef.current.contains(e.target as Node))  setExplorerOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  useEffect(() => {
    if (!navRef.current) return;
    gsap.fromTo(navRef.current, { y: "-110%" }, { y: "0%", duration: 1.1, ease: "power3.out", delay: 0.15 });
  }, []);

  const logout = async () => {
    await fetch("/api/customer/logout", { method: "POST" });
    clearCart();
    setCustomer(null);
    setProfileOpen(false);
    setMenuOpen(false);
    window.location.href = "/";
  };

  const isDark = scrolled || !isHero;
  // White text only on the hero before scrolling (transparent over video); dark text everywhere else
  const useDarkText = scrolled || !isHero;

  const linkClass = `${locale === "ar" ? "text-[14px]" : "text-[11px]"} font-extrabold tracking-[0.12em] uppercase transition-colors duration-300 whitespace-nowrap ${
    useDarkText ? "text-brand-dark/80 hover:text-brand-dark" : "text-white hover:text-white/70"
  }`;

  const iconClass = `transition-colors duration-300 ${
    useDarkText ? "text-brand-dark/70 hover:text-brand-dark" : "text-white hover:text-white/70"
  }`;

  const dropdownClass = `absolute top-full mt-3 bg-white border border-brand-dark/8 rounded-2xl shadow-2xl overflow-hidden transition-all duration-200 origin-top`;

  return (
    <>
      <nav
        ref={navRef}
        style={{ transform: "translateY(-110%)" }}
        className={`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ${
          scrolled ? "bg-brand-off-white shadow-sm py-3" : "bg-transparent py-4"
        }`}
      >
        {/* ── Desktop ── */}
        <div className="hidden lg:grid grid-cols-3 items-center max-w-7xl mx-auto px-6">

          {/* Left */}
          <ul className="flex items-center gap-7">
            {LEFT_LINKS.map(({ label, href }) => (
              <li key={label}>
                <Link href={href} className={linkClass}>{label}</Link>
              </li>
            ))}

            {/* Explorer dropdown */}
            <li ref={explorerRef} className="relative">
              <button
                onClick={() => setExplorerOpen(o => !o)}
                className={`flex items-center gap-1 ${linkClass}`}
              >
                {t.nav.explore}
                <CaretDown size={10} weight="bold" className={`transition-transform duration-200 ${explorerOpen ? "rotate-180" : ""}`} />
              </button>
              <div className={`${dropdownClass} ${locale === "ar" ? "right-0" : "left-0"} w-44 ${explorerOpen ? "opacity-100 scale-100 pointer-events-auto" : "opacity-0 scale-95 pointer-events-none"}`}>
                {EXPLORER_LINKS.map(({ label, href }) => (
                  <Link
                    key={label}
                    href={href}
                    onClick={() => setExplorerOpen(false)}
                    className="block px-4 py-3 text-xs font-semibold text-brand-dark/60 hover:text-brand-dark hover:bg-brand-dark/5 transition-colors"
                  >
                    {label}
                  </Link>
                ))}
              </div>
            </li>
          </ul>

          {/* Center logo */}
          <div className="flex justify-center">
            <Link href="/">
              <Image
                src="/logo.png" alt="Asli Food" width={200} height={80}
                className={`h-20 w-auto object-contain transition-all duration-500 ${useDarkText ? "brightness-0" : "brightness-0 invert"}`}
                priority
              />
            </Link>
          </div>

          {/* Right */}
          <div className="flex items-center justify-end gap-6">
            {RIGHT_LINKS.map(({ label, href }) => (
              <Link key={label} href={href} className={linkClass}>{label}</Link>
            ))}

            {/* Language switcher */}
            <div ref={langRef} className="relative">
              <button
                onClick={() => setLangOpen(o => !o)}
                className={`flex items-center gap-1.5 ${linkClass}`}
              >
                <Globe size={11} weight="bold" />
                <span>{locale.toUpperCase()}</span>
                <CaretDown size={9} weight="bold" className={`transition-transform duration-200 ${langOpen ? "rotate-180" : ""}`} />
              </button>
              <div className={`${dropdownClass} ${locale === "ar" ? "left-0" : "right-0"} w-44 py-1.5 ${langOpen ? "opacity-100 scale-100 pointer-events-auto" : "opacity-0 scale-95 pointer-events-none"}`}>
                {LANGUAGES.map(({ code, label }) => (
                  <button
                    key={code}
                    onClick={() => { setLocale(code); setLangOpen(false); }}
                    className={`w-full flex items-center gap-3 px-4 py-2.5 text-xs font-bold transition-colors ${
                      locale === code
                        ? "text-brand-dark bg-brand-dark/8"
                        : "text-brand-dark/75 hover:text-brand-dark hover:bg-brand-dark/5"
                    }`}
                  >
                    <span className="flex-1">{label}</span>
                    {locale === code && <Check size={11} weight="bold" className="text-brand-yellow flex-shrink-0" />}
                  </button>
                ))}
              </div>
            </div>

            {/* Cart */}
            <button onClick={openCart} className={`relative ${iconClass}`} aria-label="Panier">
              <Bag size={22} />
              {mounted && count() > 0 && (
                <span className="absolute -top-1.5 -right-1.5 bg-brand-yellow text-brand-dark text-[9px] font-bold rounded-full w-4 h-4 flex items-center justify-center">
                  {count()}
                </span>
              )}
            </button>

            {/* Boutique / Profile */}
            {customer ? (
              <div ref={profileRef} className="relative">
                <button onClick={() => setProfileOpen(o => !o)} className={iconClass}>
                  <User size={22} />
                </button>
                <div className={`${dropdownClass} ${locale === "ar" ? "left-0" : "right-0"} w-52 ${profileOpen ? "opacity-100 scale-100 pointer-events-auto" : "opacity-0 scale-95 pointer-events-none"}`}>
                  <div className="px-4 py-3.5 border-b border-brand-dark/8">
                    <p className="text-brand-dark text-xs font-bold truncate" style={{ fontFamily: "var(--font-space, sans-serif)" }}>{customer.name}</p>
                    <p className="text-brand-dark/35 text-[11px] truncate mt-0.5">{customer.email}</p>
                  </div>
                  <div className="p-1.5 flex flex-col">
                    <Link href="/profil?tab=profil" onClick={() => setProfileOpen(false)}
                      className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-brand-dark/70 hover:bg-brand-dark/6 hover:text-brand-dark transition-colors text-xs font-semibold">
                      <UserCircle size={15} weight="bold" /> {t.nav.profile}
                    </Link>
                    <Link href="/suivi-commandes" onClick={() => setProfileOpen(false)}
                      className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-brand-dark/70 hover:bg-brand-dark/6 hover:text-brand-dark transition-colors text-xs font-semibold">
                      <ListChecks size={15} weight="bold" /> {t.nav.orders}
                    </Link>
                    <button onClick={logout}
                      className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-red-400/80 hover:bg-red-500/10 hover:text-red-400 transition-colors text-xs font-semibold w-full">
                      <SignOut size={15} weight="bold" /> {t.nav.logout}
                    </button>
                  </div>
                </div>
              </div>
            ) : (
              <Link
                href="/login"
                className="group inline-flex items-center gap-2 bg-brand-yellow text-brand-dark font-bold px-5 py-2 rounded-full text-[11px] tracking-widest uppercase transition-all duration-300 hover:bg-brand-dark hover:text-brand-yellow hover:scale-105 border-2 border-brand-yellow"
              >
                {t.nav.shop}
                {locale === "ar"
                  ? <ArrowLeft  size={13} strokeWidth={2.5} className="transition-transform duration-300 group-hover:-translate-x-1" />
                  : <ArrowRight size={13} strokeWidth={2.5} className="transition-transform duration-300 group-hover:translate-x-1" />}
              </Link>
            )}
          </div>
        </div>

        {/* ── Mobile ── */}
        <div className="lg:hidden flex items-center justify-between px-5">
          <div className="w-10" />
          <Link href="/">
            <Image
              src="/logo.png" alt="Asli Food" width={160} height={64}
              className={`h-16 w-auto object-contain transition-all duration-500 ${useDarkText ? "brightness-0" : "brightness-0 invert"}`}
              priority
            />
          </Link>
          <div className="flex items-center gap-3">
            <button onClick={openCart} className={`relative ${iconClass}`} aria-label="Panier">
              <Bag size={22} />
              {mounted && count() > 0 && (
                <span className="absolute -top-1.5 -right-1.5 bg-brand-yellow text-brand-dark text-[9px] font-bold rounded-full w-4 h-4 flex items-center justify-center">
                  {count()}
                </span>
              )}
            </button>
            <button
              onClick={() => setMenuOpen(o => !o)}
              className={`flex flex-col justify-center gap-1.5 w-6 h-6 ${useDarkText ? "text-brand-dark" : "text-white"}`}
            >
              <span className={`block h-0.5 w-full bg-current rounded-full transition-all duration-300 origin-center ${menuOpen ? "rotate-45 translate-y-2" : ""}`} />
              <span className={`block h-0.5 w-full bg-current rounded-full transition-all duration-300 ${menuOpen ? "opacity-0 scale-x-0" : ""}`} />
              <span className={`block h-0.5 w-full bg-current rounded-full transition-all duration-300 origin-center ${menuOpen ? "-rotate-45 -translate-y-2" : ""}`} />
            </button>
          </div>
        </div>

        {/* ── Mobile drawer ── */}
        <div className={`lg:hidden overflow-hidden transition-all duration-500 bg-brand-section ${menuOpen ? "max-h-[40rem]" : "max-h-0"}`}>
          <div className="px-6 py-6 flex flex-col gap-4">
            {[...LEFT_LINKS, ...EXPLORER_LINKS, ...RIGHT_LINKS].map(({ label, href }) => (
              <Link key={label} href={href}
                className="text-brand-section-accent text-xs font-extrabold tracking-[0.15em] uppercase hover:text-brand-section-accent/60 transition-colors"
                onClick={() => setMenuOpen(false)}
              >
                {label}
              </Link>
            ))}

            {/* Language pills */}
            <div className="border-t border-brand-section-accent/15 pt-4 flex items-center gap-2 flex-wrap">
              {LANGUAGES.map(({ code }) => (
                <button key={code} onClick={() => setLocale(code)}
                  className={`text-[11px] font-bold px-3 py-1.5 rounded-full border transition-colors ${
                    locale === code
                      ? "bg-brand-yellow text-brand-dark border-brand-yellow"
                      : "text-brand-section-accent/50 border-brand-section-accent/20 hover:text-brand-section-accent hover:border-brand-section-accent/40"
                  }`}
                >
                  {code.toUpperCase()}
                </button>
              ))}
            </div>

            {customer ? (
              <>
                <div className="flex items-center gap-3 border-t border-brand-section-accent/15 pt-4">
                  <User size={24} weight="bold" className="text-brand-section-accent flex-shrink-0" />
                  <div className="min-w-0">
                    <p className="text-brand-section-accent text-xs font-bold truncate">{customer.name}</p>
                    <p className="text-brand-section-accent/50 text-[10px] truncate">{customer.email}</p>
                  </div>
                </div>
                <Link href="/profil?tab=profil" onClick={() => setMenuOpen(false)}
                  className="flex items-center gap-2.5 text-brand-section-accent/70 text-xs font-bold tracking-[0.2em] uppercase hover:text-brand-section-accent transition-colors">
                  <UserCircle size={13} weight="bold" /> {t.nav.profile}
                </Link>
                <Link href="/suivi-commandes" onClick={() => setMenuOpen(false)}
                  className="flex items-center gap-2.5 text-brand-section-accent/70 text-xs font-bold tracking-[0.2em] uppercase hover:text-brand-section-accent transition-colors">
                  <ListChecks size={13} weight="bold" /> {t.nav.orders}
                </Link>
                <button onClick={logout}
                  className="flex items-center gap-2.5 text-red-300/80 text-xs font-bold tracking-[0.2em] uppercase hover:text-red-300 transition-colors">
                  <SignOut size={13} weight="bold" /> {t.nav.logout}
                </button>
              </>
            ) : (
              <Link href="/login" onClick={() => setMenuOpen(false)}
                className="border-t border-brand-dark/10 pt-4 bg-brand-yellow text-brand-dark font-bold px-6 py-3 rounded-full text-xs tracking-widest uppercase text-center flex items-center justify-center gap-2">
                {t.nav.shop}
                {locale === "ar" ? <ArrowLeft size={14} strokeWidth={2.5} /> : <ArrowRight size={14} strokeWidth={2.5} />}
              </Link>
            )}
          </div>
        </div>
      </nav>

      <CartDrawer />
      <OrderStatusPoller customer={customer} />
    </>
  );
}
