"use client";

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

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 [scrolled, setScrolled] = useState(false);
  const [authOpen, setAuthOpen] = useState(false);
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const { vipUrl } = useCrossSiteUrls();
  const navLinks = [
    { labelKey: "roadmap" as const, href: "#roadmap" },
    { labelKey: "tools" as const, href: "#tools" },
    { labelKey: "community" as const, href: vipUrl, external: true },
    { labelKey: "resources" as const, href: "#resources" },
  ];

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const res = await fetch("/api/auth/me", { credentials: "include" });
        const data = await res.json();
        if (!mounted) return;
        if (data?.user && data?.token) {
          const { pbSaveAuth } = await import("@/app/lib/pocketbase");
          pbSaveAuth(data.token, { id: data.user.id, email: data.user.email });
          setUserEmail(data.user.email);
          return;
        }
      } catch {
        /* ignore */
      }
      if (mounted) setUserEmail(getStoredUserEmail());
    })();
    return () => { mounted = false; };
  }, []);

  return (
    <header
      className={`fixed top-0 left-0 right-0 z-50 w-full max-w-[100vw] transition-all duration-300 ${
        scrolled
          ? "bg-white/80 backdrop-blur-lg shadow-sm dark:bg-slate-900/80 dark:shadow-slate-950/50"
          : "bg-transparent"
      }`}
    >
      <div className="mx-auto flex h-16 w-full min-w-0 max-w-7xl items-center justify-between gap-2 pl-[max(1rem,env(safe-area-inset-left))] pr-[max(1rem,env(safe-area-inset-right))] sm:pl-[max(1.5rem,env(safe-area-inset-left))] sm:pr-[max(1.5rem,env(safe-area-inset-right))] lg:pl-[max(2rem,env(safe-area-inset-left))] lg:pr-[max(2rem,env(safe-area-inset-right))]">
          <Link href="/" className="flex min-w-0 shrink items-center gap-2 text-lg font-bold text-slate-900 dark:text-slate-100">
            <span className="text-2xl">🌍</span>
            <span className="hidden sm:inline">{t("siteName")}</span>
            <span className="sm:hidden">{t("siteNameShort")}</span>
          </Link>

          <nav className="hidden items-center gap-1 md:flex">
            {navLinks.map((link) => (
              <a
                key={link.href}
                href={link.href}
                target={"external" in link && link.external ? "_blank" : undefined}
                rel={"external" in link && link.external ? "noopener noreferrer" : undefined}
                className="rounded-lg px-3 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-100"
              >
                {tNav(link.labelKey)}
              </a>
            ))}
          </nav>

          <div className="flex shrink-0 items-center gap-1 sm:gap-3">
            {userEmail ? (
              <UserAvatar email={userEmail} onLogout={() => setUserEmail(null)} />
            ) : (
              <button
                onClick={() => setAuthOpen(true)}
                className="hidden rounded-full border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-400 dark:hover:bg-slate-800 sm:inline-flex"
              >
                {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-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
              aria-label={locale === "zh" ? "Switch to English" : "切换到中文"}
              title={locale === "zh" ? "EN" : "中文"}
            >
              {locale === "zh" ? "EN" : "中文"}
            </button>
            <ThemeToggle />
            <button
              onClick={() => setMobileOpen(!mobileOpen)}
              className="inline-flex shrink-0 items-center justify-center rounded-lg p-2 text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800 md:hidden"
              aria-label={t("toggleMenu")}
            >
              {mobileOpen ? (
                <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              ) : (
                <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                </svg>
              )}
            </button>
            <a
              href="#roadmap"
              className="hidden rounded-full bg-sky-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-sky-600 dark:bg-sky-600 dark:hover:bg-sky-500 sm:inline-flex"
            >
              {t("explore")}
            </a>
          </div>
        </div>

      {mobileOpen && (
        <div className="overflow-x-hidden border-t border-slate-100 bg-white/95 backdrop-blur-lg dark:border-slate-800 dark:bg-slate-900/95 md:hidden">
          <nav className="mx-auto w-full max-w-7xl space-y-1 px-4 py-3 pr-[max(1rem,env(safe-area-inset-right))]">
            {navLinks.map((link) => (
              <a
                key={link.href}
                href={link.href}
                target={"external" in link && link.external ? "_blank" : undefined}
                rel={"external" in link && link.external ? "noopener noreferrer" : undefined}
                onClick={() => setMobileOpen(false)}
                className="block rounded-lg px-3 py-2.5 text-base font-medium text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-100"
              >
                {tNav(link.labelKey)}
              </a>
            ))}
            <button
              type="button"
              onClick={() => {
                setMobileOpen(false);
                router.replace(pathname, { locale: locale === "zh" ? "en" : "zh" });
              }}
              className="block w-full rounded-lg px-3 py-2.5 text-left text-base font-medium text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-100"
            >
              {locale === "zh" ? "EN" : "中文"}
            </button>
            {userEmail ? (
              <div className="mt-2 flex items-center gap-3 rounded-lg border border-slate-100 bg-slate-50 px-4 py-2.5 dark:border-slate-700 dark:bg-slate-800">
                <UserAvatar email={userEmail} onLogout={() => { setUserEmail(null); setMobileOpen(false); }} />
                <span className="truncate text-sm text-slate-600 dark:text-slate-400">{userEmail}</span>
              </div>
            ) : (
              <button
                onClick={() => {
                  setMobileOpen(false);
                  setAuthOpen(true);
                }}
                className="mt-2 block w-full rounded-full border border-slate-200 px-4 py-2.5 text-center text-base font-medium text-slate-600 dark:border-slate-700 dark:text-slate-400"
              >
                {t("loginRegister")}
              </button>
            )}
            <a
              href="#roadmap"
              onClick={() => setMobileOpen(false)}
              className="mt-2 block rounded-full bg-sky-500 px-4 py-2.5 text-center text-base font-medium text-white transition-colors hover:bg-sky-600 dark:bg-sky-600 dark:hover:bg-sky-500"
            >
              {t("explore")}
            </a>
          </nav>
        </div>
      )}

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