"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ArrowRight, Menu, X, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { LanguageSwitcher } from "./LanguageSwitcher";
import { useTranslation, getServerTranslations } from "@/lib/i18n";
import { cn } from "@/lib/utils";

export function Header() {
  const pathname = usePathname();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const { t, locale, setLocale } = useTranslation();

  useEffect(() => {
    setMounted(true);

    // Auto detect language on first mount if not manually set
    const stored = localStorage.getItem("locale-storage");
    if (!stored) {
      const lang = navigator.language.toLowerCase();
      if (lang.includes("zh")) setLocale("zh");
    }
  }, [setLocale]);

  useEffect(() => {
    if (!mounted) return;
    document.documentElement.lang = locale;
  }, [locale, mounted]);

  // Prevent hydration mismatch by rendering a stable version initially
  const displayT = (key: string, params?: Record<string, string | number>) => {
    if (!mounted) return getServerTranslations("en").t(key, params);
    return t(key, params);
  };

  const navItems = useMemo(
    () => [
      { name: displayT("sidebar.videoToFrames"), href: "/tools/video-frames" },
      { name: displayT("sidebar.imageCompression"), href: "/tools/image-compress" },
      { name: displayT("sidebar.audioCompression"), href: "/tools/audio-compress" },
      { name: displayT("sidebar.textureAtlas"), href: "/tools/texture-atlas" },
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [mounted, locale]
  );

  return (
    <header className="sticky top-0 z-50 w-full border-b border-white/5 bg-background/70 backdrop-blur-xl supports-[backdrop-filter]:bg-background/50">
      <nav className="container flex h-16 items-center justify-between">
        <Link href="/" className="group flex items-center gap-2">
          <span className="relative grid h-9 w-9 place-items-center rounded-xl bg-primary text-primary-foreground shadow-[0_0_0_1px_rgba(255,255,255,0.1)]">
            <Sparkles className="h-5 w-5" />
            <span className="pointer-events-none absolute inset-0 rounded-xl opacity-0 transition-opacity duration-500 group-hover:opacity-100 bg-[radial-gradient(circle_at_50%_20%,rgba(255,255,255,0.35),transparent_60%)]" />
          </span>
          <span className="text-base font-semibold tracking-tight">{displayT("common.appName")}</span>
        </Link>

        <div className="hidden md:flex items-center gap-1">
          {navItems.map((item) => {
            const active = pathname === item.href || pathname?.startsWith(item.href + "/");
            return (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  "rounded-full px-3 py-1.5 text-sm font-medium transition-colors",
                  active
                    ? "bg-white/8 text-foreground"
                    : "text-muted-foreground hover:bg-white/5 hover:text-foreground"
                )}
              >
                {item.name}
              </Link>
            );
          })}
        </div>

        <div className="hidden md:flex items-center gap-2">
          {mounted && <LanguageSwitcher />}
          <Button asChild size="sm" className="rounded-full px-4">
            <Link href="/tools/image-compress">
              {displayT("common.startBuilding")} <ArrowRight className="ml-1 h-4 w-4" />
            </Link>
          </Button>
        </div>

        <button
          className="md:hidden rounded-full p-2 hover:bg-white/5"
          onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          aria-label={displayT("common.toggleMenu")}
        >
          {isMobileMenuOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </button>
      </nav>

      <AnimatePresence>
        {isMobileMenuOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.18 }}
            className="md:hidden border-t border-white/5"
          >
            <div className="container py-5">
              <div className="flex flex-col gap-2">
                {navItems.map((item) => (
                  <Link
                    key={item.href}
                    href={item.href}
                    onClick={() => setIsMobileMenuOpen(false)}
                    className={cn(
                      "rounded-xl px-3 py-2 text-sm font-medium transition-colors",
                      pathname === item.href
                        ? "bg-white/8 text-foreground"
                        : "text-muted-foreground hover:bg-white/5 hover:text-foreground"
                    )}
                  >
                    {item.name}
                  </Link>
                ))}
              </div>

              <div className="mt-4 flex items-center justify-between">
                {mounted && <LanguageSwitcher />}
                <Button asChild size="sm" className="rounded-full px-4">
                  <Link href="/tools/image-compress" onClick={() => setIsMobileMenuOpen(false)}>
                    {displayT("common.startBuilding")} <ArrowRight className="ml-1 h-4 w-4" />
                  </Link>
                </Button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </header>
  );
}
