"use client";

import { useState, useEffect, useCallback } from "react";
import NextLink from "next/link";
import { Link, useLocale, usePathname, useRouter, useTranslation } from "@/app/digital/i18n/navigation";
import { getStoredUserEmail } from "@/app/digital/lib/pocketbase";
import { useCrossSiteUrls } from "@/app/digital/lib/useCrossSiteUrls";
import AuthModal from "./AuthModal";
import ThemeToggle from "./ThemeToggle";
import UserAvatar from "./UserAvatar";

type NavItem =
  | { labelKey: "roadmap" | "tools" | "resources"; href: string; hash: string }
  | { labelKey: "community"; href: string; external: true };

export default function Header() {
  const { t } = useTranslation("common");
  const { t: tNav } = useTranslation("nav");
  const locale = useLocale();
  const pathname = usePathname();
  const router = useRouter();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [authOpen, setAuthOpen] = useState(false);
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [vip, setVip] = useState(false);
  const { vipUrl } = useCrossSiteUrls();

  const navLinks: NavItem[] = [
    { labelKey: "roadmap", href: "/#roadmap", hash: "roadmap" },
    { labelKey: "tools", href: "/#tools", hash: "tools" },
    { labelKey: "resources", href: "/#resources", hash: "resources" },
    { labelKey: "community", href: vipUrl, external: true },
  ];

  const fetchAuthAndVip = useCallback(async () => {
    try {
      const meRes = await fetch("/api/digital/auth/me", { credentials: "include" });
      const meData = await meRes.json();
      if (meData?.user && meData?.token) {
        const { pbSaveAuth } = await import("@/app/digital/lib/pocketbase");
        pbSaveAuth(meData.token, { id: meData.user.id, email: meData.user.email });
        setUserEmail(meData.user.email);
        const vipRes = await fetch(
          `/api/digital/vip/check?email=${encodeURIComponent(meData.user.email)}`,
          { credentials: "include" }
        );
        const vipData = await vipRes.json();
        setVip(vipData?.vip === true);
      } else {
        setUserEmail(getStoredUserEmail());
        setVip(false);
      }
    } catch {
      /* ignore */
    }
  }, []);

  useEffect(() => {
    fetchAuthAndVip();
  }, [fetchAuthAndVip]);

  useEffect(() => {
    const onVipUpdated = () => fetchAuthAndVip();
    const onAuthSuccess = () => fetchAuthAndVip();
    const onAuthUpdated = () => fetchAuthAndVip();
    window.addEventListener("vip:updated", onVipUpdated);
    window.addEventListener("auth:success", onAuthSuccess);
    window.addEventListener("auth:updated", onAuthUpdated);
    return () => {
      window.removeEventListener("vip:updated", onVipUpdated);
      window.removeEventListener("auth:success", onAuthSuccess);
      window.removeEventListener("auth:updated", onAuthUpdated);
    };
  }, [fetchAuthAndVip]);

  const isGuideHome = pathname === "/";

  const navClass = (active: boolean) =>
    `flex items-center gap-1.5 px-3 py-2 rounded-full text-sm font-medium transition-colors whitespace-nowrap shrink-0 ${
      active
        ? "text-gray-900 dark:text-gray-100 bg-gray-100 dark:bg-gray-800"
        : "text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-50 dark:hover:bg-gray-800"
    }`;

  return (
    <header className="dn-header sticky top-0 z-50 bg-white/80 dark:bg-gray-900/80 backdrop-blur-lg border-b border-gray-100 dark:border-gray-800">
      <div className="max-w-[1600px] mx-auto px-4 sm:px-6 h-16 flex items-center justify-between gap-2">
        <div className="flex min-w-0 items-center gap-2 sm:gap-3">
          <NextLink
            href={`/${locale}`}
            className="flex shrink-0 items-center gap-2 text-gray-900 transition-colors hover:text-[#ff4d4f] dark:text-gray-100"
            title={tNav("mainSite")}
          >
            <span className="text-2xl">🌏</span>
            <span className="hidden text-lg font-bold tracking-tight sm:inline">
              {t("parentSiteName")}
            </span>
          </NextLink>
          <span className="hidden text-gray-300 dark:text-gray-600 sm:inline" aria-hidden>
            /
          </span>
          <Link
            href="/"
            className={`truncate text-sm font-semibold sm:text-base ${
              isGuideHome
                ? "text-[#ff4d4f]"
                : "text-gray-600 hover:text-[#ff4d4f] dark:text-gray-400"
            }`}
          >
            {t("siteName")}
          </Link>
        </div>

        <nav className="hidden md:flex items-center gap-1 overflow-x-auto max-w-[calc(100vw-420px)] hide-scrollbar">
          {navLinks.map((link) =>
            "external" in link && link.external ? (
              <a
                key={link.href}
                href={link.href}
                target="_blank"
                rel="noopener noreferrer"
                className={navClass(false)}
              >
                {tNav(link.labelKey)}
              </a>
            ) : (
              <Link key={link.href} href={link.href} className={navClass(false)}>
                {tNav(link.labelKey)}
              </Link>
            )
          )}
        </nav>

        <div className="flex shrink-0 items-center gap-1 sm:gap-2">
          {userEmail ? (
            <UserAvatar
              email={userEmail}
              vip={vip}
              onLogout={() => {
                setUserEmail(null);
                setVip(false);
                router.replace("/");
              }}
            />
          ) : (
            <button
              type="button"
              onClick={() => setAuthOpen(true)}
              className="hidden sm:inline-flex shrink-0 items-center justify-center rounded-full border border-gray-200 dark:border-gray-700 px-3 py-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
            >
              {t("loginRegister")}
            </button>
          )}
          <button
            type="button"
            onClick={() => router.replace(pathname, { locale: locale === "zh" ? "en" : "zh" })}
            className="inline-flex shrink-0 items-center justify-center rounded-lg p-2 text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
            aria-label={locale === "zh" ? "Switch to English" : "切换到中文"}
            title={locale === "zh" ? "EN" : "中文"}
          >
            {locale === "zh" ? "EN" : "中文"}
          </button>
          <ThemeToggle />
          <Link
            href="/#roadmap"
            className="dn-button-primary hidden text-xs sm:text-sm text-white px-3 sm:px-4 py-2 rounded-full font-medium whitespace-nowrap sm:inline-flex"
          >
            {t("explore")}
          </Link>
          <button
            type="button"
            className="md:hidden p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800"
            onClick={() => setMobileOpen(!mobileOpen)}
            aria-label={t("toggleMenu")}
          >
            {mobileOpen ? (
              <svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path d="M6 18L18 6M6 6l12 12" />
              </svg>
            ) : (
              <svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            )}
          </button>
        </div>
      </div>

      {mobileOpen && (
        <div className="md:hidden border-t border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900 px-4 py-3 space-y-1">
          <NextLink
            href={`/${locale}`}
            onClick={() => setMobileOpen(false)}
            className="flex items-center gap-2 px-4 py-3 rounded-xl text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800"
          >
            <span className="text-lg">🌏</span>
            <span>{tNav("mainSite")}</span>
          </NextLink>
          {navLinks.map((link) =>
            "external" in link && link.external ? (
              <a
                key={link.href}
                href={link.href}
                target="_blank"
                rel="noopener noreferrer"
                onClick={() => setMobileOpen(false)}
                className="flex items-center gap-2 px-4 py-3 rounded-xl text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800"
              >
                {tNav(link.labelKey)}
              </a>
            ) : (
              <Link
                key={link.href}
                href={link.href}
                onClick={() => setMobileOpen(false)}
                className="flex items-center gap-2 px-4 py-3 rounded-xl text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800"
              >
                {tNav(link.labelKey)}
              </Link>
            )
          )}
          {userEmail ? (
            <div className="pt-2 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between px-4 py-2.5 rounded-lg bg-gray-50 dark:bg-gray-800">
              <UserAvatar
                email={userEmail}
                vip={vip}
                onLogout={() => {
                  setUserEmail(null);
                  setVip(false);
                  setMobileOpen(false);
                  router.replace("/");
                }}
              />
              <span className="truncate text-sm text-gray-600 dark:text-gray-400">{userEmail}</span>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => {
                setMobileOpen(false);
                setAuthOpen(true);
              }}
              className="block w-full text-left px-4 py-3 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
            >
              {t("loginRegister")}
            </button>
          )}
        </div>
      )}

      <AuthModal
        isOpen={authOpen}
        onClose={() => setAuthOpen(false)}
        onSuccess={() => fetchAuthAndVip()}
      />
    </header>
  );
}
