"use client";

import * as React from "react";
import Image from "next/image";
import Link from "next/link";
import { useLocale, useTranslations } from "next-intl";
import { useRouter, usePathname } from "next/navigation";
import { Menu, FileText, ChevronDown, Globe, Check } from "lucide-react";
import { cn } from "@/lib/utils";
import { ButtonLink } from "@/components/ui/button";
import { Sheet } from "@/components/ui/sheet";
import { NAV_LINKS, CONTACT_INFO } from "@/data/site-data";

/* ── Language config ──────────────────────────────────── */
const LANGUAGES = [
  { code: "en", label: "English", short: "EN", flag: "EN" },
  { code: "id", label: "Bahasa Indonesia", short: "ID", flag: "ID" },
  { code: "zh", label: "中文", short: "CN", flag: "CN" },
] as const;

type LangCode = (typeof LANGUAGES)[number]["code"];

const navKeys: Record<string, string> = {
  "PRODUCTS": "products",
  "PROCESS": "process",
  "CERTIFICATIONS": "credentials",
  "RECOGNITION": "recognition",
  "SOHEALTHY": "sohealthy",
  "ABOUT US": "about",
};

// Map product href to message key for localized dropdown labels
const productItemKeys: Record<string, string> = {
  "/products/white-house-nest": "whiteHouseNest",
  "/products/golden-nest": "goldenNest",
  "/products/white-cup": "whiteCup",
  "/products/broken-nest": "brokenNest",
  "/products/nest-powder": "nestPowder",
};

/* ── Language Switcher ────────────────────────────────── */
function LanguageSwitcher({ mobile = false }: { mobile?: boolean }) {
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef<HTMLDivElement>(null);

  const current = LANGUAGES.find((l) => l.code === locale) ?? LANGUAGES[0];
  const langLabel = locale === "id" ? "Bahasa" : locale === "zh" ? "语言" : "Language";

  // Switch locale by replacing the locale prefix in the URL
  const switchLocale = (code: LangCode) => {
    // pathname looks like /en/about or /en — replace locale segment
    const segments = pathname.split("/");
    segments[1] = code; // index 1 is the locale
    router.push(segments.join("/") || "/");
    setOpen(false);
  };

  // Close on outside click
  React.useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  if (mobile) {
    return (
      <div className="border-t border-black/5 pt-4">
        <p className="mb-2 text-[10px] font-bold uppercase tracking-widest text-muted">
          {langLabel}
        </p>
        <div className="flex flex-col gap-1">
          {LANGUAGES.map((lang) => (
            <button
              key={lang.code}
              onClick={() => switchLocale(lang.code)}
              className={cn(
                "flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-semibold transition-colors",
                locale === lang.code
                  ? "bg-gold/10 text-gold"
                  : "text-ink hover:bg-black/5"
              )}
            >
              <span className="text-base">{lang.flag}</span>
              {lang.label}
              {locale === lang.code && (
                <Check className="ml-auto h-3.5 w-3.5 text-gold" />
              )}
            </button>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        className="flex items-center gap-1.5 text-xs font-bold tracking-widest text-ink transition-colors hover:text-gold"
        aria-label="Select language"
        aria-expanded={open}
      >
        <Globe className="h-4 w-4" />
        {current.short}
        <ChevronDown
          className={cn(
            "h-3 w-3 transition-transform duration-200",
            open && "rotate-180"
          )}
        />
      </button>

      {open && (
        <div className="absolute right-0 mt-3 w-52 overflow-hidden rounded-xl border border-black/5 bg-white shadow-xl">
          {LANGUAGES.map((lang, i) => (
            <button
              key={lang.code}
              onClick={() => switchLocale(lang.code)}
              className={cn(
                "flex w-full items-center gap-3 px-4 py-3.5 text-sm transition-colors hover:bg-gold/5",
                i !== LANGUAGES.length - 1 && "border-b border-black/5",
                locale === lang.code ? "text-gold" : "text-ink"
              )}
            >
              <span className="text-base">{lang.flag}</span>
              <span className="font-medium">{lang.label}</span>
              {locale === lang.code && (
                <Check className="ml-auto h-3.5 w-3.5 text-gold" />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ── Floating WhatsApp Widget ─────────────────────────── */
function WhatsAppWidget() {
  const [hovered, setHovered] = React.useState(false);
  const locale = useLocale();
  const label = locale === "id" ? "Hubungi Kami" : locale === "zh" ? "联系我们" : "Chat with Us";

  return (
    <a
      href={CONTACT_INFO.whatsapp}
      target="_blank"
      rel="noopener noreferrer"
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      aria-label="Chat with us on WhatsApp"
      className="fixed bottom-6 right-6 z-50 flex items-center gap-3 rounded-full bg-[#25D366] shadow-lg transition-all duration-300 hover:shadow-xl"
      style={{ padding: hovered ? "12px 20px 12px 16px" : "14px" }}
    >
      <svg className="h-6 w-6 shrink-0 text-white" viewBox="0 0 24 24" fill="currentColor">
        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
      </svg>
      <span
        className={cn(
          "overflow-hidden whitespace-nowrap text-xs font-bold tracking-wide text-white transition-all duration-300",
          hovered ? "max-w-[120px] opacity-100" : "max-w-0 opacity-0"
        )}
      >
        {label}
      </span>
    </a>
  );
}

/* ── Header ───────────────────────────────────────────── */
function Header() {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const locale = useLocale();
  const t = useTranslations("nav");

  // Helper to prefix links with locale
  const l = (href: string) => `/${locale}${href === "/" ? "" : href}`;

  React.useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <>
      <header
        className={cn(
          "sticky top-0 z-50 border-b border-black/5 bg-white transition-shadow duration-300",
          scrolled && "shadow-md"
        )}
      >
        <div className="mx-auto flex max-w-[1400px] items-center justify-between px-4 py-3.5 sm:px-6 lg:px-8">

          {/* Brand Logo & Company Info */}
          <Link href={l("/")} className="flex shrink-0 items-center gap-2 sm:gap-3">
            <Image
              src="/images/logo-original-nest.png"
              alt="PT Ori Ginalnest Indonesia"
              width={48}
              height={48}
              className="h-10 w-auto max-h-[40px] sm:h-12 sm:max-h-[48px] object-contain"
              priority
            />
            <div className="flex flex-col justify-center">
              <span className="font-serif text-[13px] font-bold tracking-tight text-ink sm:text-[17px] leading-tight">
                PT Ori Ginalnest Indonesia
              </span>
              <div className="mt-[2px] flex flex-col text-[9px] text-gray-500 font-medium sm:text-[10px] leading-[1.2]">
                <span>Registration No. : 014</span>
                <span>China Registration No. : CIDN03011808010009</span>
              </div>
            </div>
          </Link>

          {/* Desktop Nav */}
          <nav className="hidden items-center gap-3 text-[11px] font-bold tracking-widest text-ink xl:flex xl:gap-6 2xl:gap-8 xl:text-xs">
            {NAV_LINKS.map((link: any) =>
              "children" in link && link.children ? (
                <div key={link.label} className="group relative">
                  <button className="flex items-center gap-1 transition-colors hover:text-gold animate-none">
                    {t(navKeys[link.label] || link.label)}
                    <ChevronDown className="h-2.5 w-2.5" />
                  </button>
                  <div className="invisible absolute left-0 mt-2 w-52 rounded border border-black/5 bg-white py-2 opacity-0 shadow-lg transition-all duration-200 group-hover:visible group-hover:opacity-100">
                    <Link
                      href={l("/products")}
                      className="block border-b border-black/5 px-4 py-2 text-left font-bold text-gold transition-colors hover:bg-gold/10"
                    >
                      {t("viewAllProducts")}
                    </Link>
                    {link.children.map((child: any) => (
                      <Link
                        key={child.label}
                        href={l(child.href)}
                        className="block px-4 py-2 text-left transition-colors hover:bg-gold/10 hover:text-gold"
                      >
                        {productItemKeys[child.href]
                          ? t(`productItems.${productItemKeys[child.href]}`)
                          : child.label}
                      </Link>
                    ))}
                  </div>
                </div>
              ) : (
                <Link
                  key={link.label}
                  href={l(link.href)}
                  className="transition-colors hover:text-gold"
                >
                  {t(navKeys[link.label] || link.label)}
                </Link>
              )
            )}
          </nav>

          {/* Right side: Lang switcher + CTA */}
          <div className="hidden items-center gap-3 xl:flex xl:gap-4">
            <LanguageSwitcher />
            <ButtonLink
              href="/Company-Profile.pdf"
              target="_blank"
              rel="noopener noreferrer"
              size="sm"
            >
              <FileText className="h-3.5 w-3.5" />
              {locale === "zh" ? "公司简介" : locale === "id" ? "Profil Perusahaan" : "Company Profile"}
            </ButtonLink>
          </div>

          {/* Mobile Menu Toggle */}
          <button
            className="text-ink transition-colors hover:text-gold focus:outline-none xl:hidden"
            onClick={() => setMobileOpen(true)}
            aria-label="Open menu"
          >
            <Menu className="h-6 w-6" />
          </button>
        </div>

        {/* Mobile Sheet */}
        <Sheet open={mobileOpen} onClose={() => setMobileOpen(false)}>
          <nav className="flex flex-col space-y-4">
            <Link
              href={l("/")}
              className="text-sm font-bold tracking-wide text-ink transition-colors hover:text-gold"
              onClick={() => setMobileOpen(false)}
            >
              {t("home")}
            </Link>
            {NAV_LINKS.map((link: any) => (
              <Link
                key={link.label}
                href={l(link.href)}
                className="text-sm font-bold tracking-wide text-ink transition-colors hover:text-gold"
                onClick={() => setMobileOpen(false)}
              >
                {t(navKeys[link.label] || link.label)}
              </Link>
            ))}
            <div className="flex flex-col gap-3 border-t border-black/5 pt-4">
              <ButtonLink
                href="/Company-Profile.pdf"
                target="_blank"
                rel="noopener noreferrer"
                className="w-full justify-center"
              >
                <FileText className="h-4 w-4" />
                {locale === "zh" ? "公司简介" : locale === "id" ? "Profil Perusahaan" : "Company Profile"}
              </ButtonLink>
              <a
                href={CONTACT_INFO.whatsapp}
                target="_blank"
                rel="noopener noreferrer"
                onClick={() => setMobileOpen(false)}
                className="flex w-full items-center justify-center gap-2 rounded-full border border-[#25D366] py-2.5 text-xs font-bold tracking-widest text-[#25D366] transition-colors hover:bg-[#25D366] hover:text-white"
              >
                <svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                </svg>
                {t("chatWhatsApp")}
              </a>
            </div>
            {/* Language switcher in mobile */}
            <LanguageSwitcher mobile />
          </nav>
        </Sheet>
      </header>

      {/* Floating WhatsApp Widget */}
      <WhatsAppWidget />
    </>
  );
}

export { Header };
