"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Menu, X, Sparkles } from "lucide-react";
// import { Button } from "@/components/ui/button"; // TODO: Uncomment when adding login/register buttons
import { LanguageSwitcher } from "./LanguageSwitcher";
import { useTranslation, getServerTranslations } from "@/lib/i18n";
import { cn } from "@/lib/utils";

function useNavItems() {
  const { t } = useTranslation();
  return [
    { name: t("nav.tools"), href: "/tools/image-compress" },
    { name: t("nav.pricing"), href: "/tools/video-frames" },
    { name: t("nav.docs"), href: "/tools/audio-compress" },
    // Note: Temporarily redirecting to existing tool pages
    // TODO: Create dedicated pages for pricing, docs, about
  ];
}

export function Header() {
  const pathname = usePathname();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const navItems = useNavItems();
  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) {
      document.documentElement.lang = locale;
    }
  }, [locale, mounted]);

  // Prevent hydration mismatch by rendering a stable version initially
  const displayT = (key: string, params?: any) => {
    if (!mounted) return getServerTranslations("en").t(key, params);
    return t(key, params);
  };
  
  const currentNavItems = mounted ? navItems : [
    { name: "Tools", href: "/tools/image-compress" },
    { name: "Pricing", href: "/tools/video-frames" },
    { name: "Docs", href: "/tools/audio-compress" },
  ];

  return (
    <header className="sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
      <nav className="container flex h-16 items-center justify-between">
        {/* Logo */}
        <Link href="/" className="flex items-center space-x-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary">
            <Sparkles className="h-5 w-5 text-primary-foreground" />
          </div>
          <span className="text-xl font-bold">{displayT("common.appName")}</span>
        </Link>

        {/* Desktop Navigation */}
        <div className="hidden md:flex md:items-center md:space-x-6">
          {currentNavItems.map((item) => (
            <Link
              key={item.name}
              href={item.href}
              className={cn(
                "text-sm font-medium transition-colors hover:text-primary",
                pathname === item.href ? "text-primary" : "text-muted-foreground"
              )}
            >
              {item.name}
            </Link>
          ))}
        </div>

        {/* CTA Buttons */}
        <div className="hidden md:flex md:items-center md:space-x-4">
          {mounted && <LanguageSwitcher />}
          {/* TODO: Create login/register pages
          <Button variant="ghost" size="sm" asChild>
            <Link href="/login">{displayT("common.signIn")}</Link>
          </Button>
          <Button size="sm" asChild>
            <Link href="/register">{displayT("common.getStarted")}</Link>
          </Button>
          */}
        </div>

        {/* Mobile Menu Button */}
        <button
          className="md:hidden"
          onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          aria-label={displayT("common.toggleMenu")}
        >
          {isMobileMenuOpen ? (
            <X className="h-6 w-6" />
          ) : (
            <Menu className="h-6 w-6" />
          )}
        </button>
      </nav>

      {/* Mobile Menu */}
      <AnimatePresence>
        {isMobileMenuOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.2 }}
            className="md:hidden border-t border-border/40"
          >
            <div className="container space-y-4 py-6">
              {currentNavItems.map((item) => (
                <Link
                  key={item.name}
                  href={item.href}
                  onClick={() => setIsMobileMenuOpen(false)}
                  className={cn(
                    "block text-sm font-medium transition-colors hover:text-primary",
                    pathname === item.href ? "text-primary" : "text-muted-foreground"
                  )}
                >
                  {item.name}
                </Link>
              ))}
              <div className="flex flex-col space-y-2 pt-4">
                {mounted && <LanguageSwitcher />}
                {/* TODO: Create login/register pages
                <Button variant="ghost" size="sm" asChild className="w-full">
                  <Link href="/login">{displayT("common.signIn")}</Link>
                </Button>
                <Button size="sm" asChild className="w-full">
                  <Link href="/register">{displayT("common.getStarted")}</Link>
                </Button>
                */}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </header>
  );
}
