import { personalInfo } from "@/lib/data/index";
import LanguageSwitcher from "./LanguageSwitcher";
import ThemeToggle from "./ui/theme-toggle";
import Container from "./ui/Container.tsx";
import { useTranslations, getLocalizedPath } from "@/i18n/utils";
import type { Lang } from "@/types/i18n";
import { useState, useEffect } from "react";
import { Menu, X, Home, Rocket, PenTool, User, Briefcase, Clock3 } from "lucide-react";
import { defaultLang } from "@/i18n/ui";
import { type GlassHeaderProps } from "@/types";
import { cn } from "@/lib/utils";

export default function GlassHeader({ lang: propLang }: GlassHeaderProps) {
  const [lang, setLang] = useState<Lang>(propLang || defaultLang);
  const [currentPath, setCurrentPath] = useState("");

  const normalizePath = (path: string) => {
    const clean = path.split("#")[0].split("?")[0];
    if (!clean) return "/";
    if (clean === "/") return "/";
    return clean.endsWith("/") ? clean.slice(0, -1) : clean;
  };
  
  useEffect(() => {
    const updatePath = () => setCurrentPath(normalizePath(window.location.pathname));
    updatePath();

    const syncLang = () => {
      const htmlLang = document.documentElement.lang as Lang;
      if (htmlLang && (!propLang || htmlLang !== lang)) {
        setLang(htmlLang);
      }
    };
    syncLang();

    const originalPushState = history.pushState.bind(history);
    const originalReplaceState = history.replaceState.bind(history);

    history.pushState = function (...args) {
      originalPushState(...args);
      window.dispatchEvent(new Event("locationchange"));
    };
    history.replaceState = function (...args) {
      originalReplaceState(...args);
      window.dispatchEvent(new Event("locationchange"));
    };

    window.addEventListener("popstate", updatePath);
    window.addEventListener("locationchange", updatePath);
    document.addEventListener("astro:after-swap", updatePath as EventListener);
    document.addEventListener("astro:page-load", updatePath as EventListener);
    document.addEventListener("astro:page-load", syncLang as EventListener);

    return () => {
      history.pushState = originalPushState;
      history.replaceState = originalReplaceState;
      window.removeEventListener("popstate", updatePath);
      window.removeEventListener("locationchange", updatePath);
      document.removeEventListener("astro:after-swap", updatePath as EventListener);
      document.removeEventListener("astro:page-load", updatePath as EventListener);
      document.removeEventListener("astro:page-load", syncLang as EventListener);
    };
  }, [propLang, lang]);

  const t = useTranslations(lang);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 0);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const toggleMenu = () => setIsMenuOpen(!isMenuOpen);

  const navItems = [
    { key: 'nav.home', icon: Home, href: getLocalizedPath('/', lang) },
    { key: 'nav.about', icon: User, href: getLocalizedPath('/about', lang) },
    { key: 'nav.projects', icon: Rocket, href: getLocalizedPath('/projects', lang) },
    { key: 'nav.blog', icon: PenTool, href: getLocalizedPath('/blog', lang) },
    { key: 'nav.now', icon: Clock3, href: getLocalizedPath('/now', lang) },
    { key: 'nav.hire', icon: Briefcase, href: getLocalizedPath('/hire', lang) },
  ];

  const isActive = (path: string) => {
    const normalizedPath = normalizePath(path);

    if (normalizedPath === '/' || normalizedPath === '/zh') {
      return currentPath === normalizedPath;
    }

    return currentPath === normalizedPath || currentPath.startsWith(`${normalizedPath}/`);
  };

  return (
    <header
      className={`fixed top-0 z-50 w-full transition-all duration-300 ${
        isScrolled
          ? 'backdrop-blur-xl backdrop-saturate-150 bg-white/70 dark:bg-black/70 border-b border-border/50 shadow-lg shadow-black/5 dark:shadow-primary/5'
          : 'bg-transparent'
      }`}
    >
      <Container className="p-4 flex justify-between items-center">
        <a
          className="flex items-center text-lg font-medium transition-colors duration-150 hover:text-foreground/80 hover:scale-105 active:scale-95"
          href={getLocalizedPath('/', lang)}
        >
          <div className="w-6 h-6 mr-2 flex items-center justify-center">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" className="w-full h-full">
              <path d="M9 6L3 12L9 18" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-primary" />
              <path d="M15 6L21 12L15 18" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-accent" />
            </svg>
          </div>
          <span className="gradient-text font-bold">{personalInfo.name}</span>
        </a>

        {/* Desktop Navigation */}
        <nav className="hidden md:flex items-center space-x-6 text-sm font-medium">
          {navItems.map((item) => {
            const active = isActive(item.href);
            return (
              <a
                key={item.key}
                href={item.href}
                className={cn(
                  "flex items-center gap-2 transition-colors duration-150 px-3 py-2 rounded-md hover:bg-primary/5",
                  active
                    ? "text-primary bg-primary/5 font-semibold"
                    : "text-foreground/70 hover:text-primary"
                )}
              >
                <item.icon size={16} />
                {t(item.key as any)}
              </a>
            );
          })}
        </nav>

        <div className="flex items-center space-x-3">
          {/* Language Switcher added here */}
          <div>
            <LanguageSwitcher lang={lang} />
          </div>

          <div>
            <ThemeToggle />
          </div>

          {/* Mobile Menu Button */}
          <button
            className="md:hidden p-2 text-foreground transition-all duration-150 hover:bg-foreground/10 active:bg-foreground/20 rounded-md active:scale-90"
            onClick={toggleMenu}
            aria-label="Toggle menu"
          >
            {isMenuOpen ? <X size={24} /> : <Menu size={24} />}
          </button>
        </div>
      </Container>

      {/* Mobile Navigation */}
      <div className={`md:hidden overflow-hidden transition-all duration-300 ease-out ${
        isMenuOpen ? 'max-h-80 opacity-100' : 'max-h-0 opacity-0'
      }`}>
        <div className={`py-4 px-4 border-t border-border/10 glass-effect shadow-xl ${
          isScrolled
            ? 'bg-white/90 dark:bg-black/80'
            : 'bg-white/95 dark:bg-black/85'
        }`}>
          <nav className="flex flex-col space-y-3 text-sm font-medium">
            {navItems.map((item) => {
              const active = isActive(item.href);
              return (
                <a
                  key={item.key}
                  href={item.href}
                  className={cn(
                    "flex items-center gap-2 transition-colors duration-150 py-2 px-3 block rounded-md",
                    active
                      ? "text-primary bg-primary/5 font-semibold"
                      : "text-foreground/60 hover:text-foreground/80 hover:bg-foreground/5"
                  )}
                  onClick={toggleMenu}
                >
                  <item.icon size={18} />
                  {t(item.key as any)}
                </a>
              );
            })}
          </nav>
        </div>
      </div>
    </header>
  );
}
