import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import {
  Gamepad2, Globe, Sparkles, FileText, ChevronDown,
  Menu, X, Server, Bot,
} from "lucide-react";
import logo from "@/assets/lumenhost-logo.png.asset.json";
import { useCurrency, type Currency } from "@/lib/currency";
import { cn } from "@/lib/utils";

interface MenuLink { label: string; to: string; icon?: React.ComponentType<{ className?: string }>; }

const hostingServices: MenuLink[] = [
  { label: "VPS Hosting", to: "/vps-hosting", icon: Server },
  { label: "Bot Hosting", to: "/bot-hosting", icon: Bot },
];

const importantLinks: MenuLink[] = [
  { label: "About Us", to: "/about" },
  { label: "Contact Us", to: "/contact" },
  { label: "FAQs", to: "/faqs" },
  { label: "Infrastructure", to: "/infrastructure" },
  { label: "Commitment", to: "/commitment" },
  { label: "Partnership", to: "/partnership" },
];

const legalLinks: MenuLink[] = [
  { label: "Terms of Service", to: "/terms" },
  { label: "Privacy Policy", to: "/privacy" },
  { label: "Refund Policy", to: "/refund" },
  { label: "Acceptable Use Policy", to: "/aup" },
  { label: "Reseller Policy", to: "/reseller-policy" },
  { label: "Service Level Agreement", to: "/sla" },
];

const mobileDropdownCategories = [
  { id: "hosting", label: "Hosting Services", icon: Globe, links: hostingServices },
  { id: "important", label: "Important", icon: Sparkles, links: importantLinks },
  { id: "legal", label: "Legal", icon: FileText, links: legalLinks },
];

const currencySymbols: Record<Currency, string> = { INR: "₹", USD: "$", EUR: "€" };
const currencies: Currency[] = ["USD", "INR", "EUR"];

function Brand({ onClick }: { onClick?: () => void }) {
  return (
    <Link to="/" onClick={onClick} className="flex items-center gap-2.5 group">
      <img src={logo.url} alt="LumenHost" className="h-9 w-9 rounded-full bg-white object-contain p-0.5 ring-1 ring-white/10" />
      <span className="text-base font-semibold tracking-tight text-white">
        Lumen<span className="text-primary">Host</span>
      </span>
    </Link>
  );
}

function NavCurrencySelector() {
  const { currency, setCurrency, symbol } = useCurrency();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const h = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  return (
    <div ref={ref} className="relative ml-1">
      <button
        onClick={() => setOpen(v => !v)}
        className="inline-flex h-9 items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 text-xs font-medium text-foreground/90 hover:bg-white/10"
      >
        <span className="text-primary font-bold">{symbol}</span>
        {currency}
        <ChevronDown className={cn("h-3 w-3 opacity-60 transition", open && "rotate-180")} />
      </button>
      {open && (
        <div className="absolute right-0 mt-2 w-44 overflow-hidden rounded-xl border border-white/10 bg-popover/95 backdrop-blur-xl p-1.5 shadow-2xl">
          {currencies.map(c => (
            <button
              key={c}
              onClick={() => { setCurrency(c); setOpen(false); }}
              className={cn("flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm transition",
                currency === c ? "bg-white/10 text-foreground" : "text-muted-foreground hover:bg-white/5 hover:text-foreground")}
            >
              <span className="flex h-7 w-7 items-center justify-center rounded-md bg-white/5 text-xs font-bold">
                {currencySymbols[c]}
              </span>
              <span className="font-medium">{c}</span>
              {currency === c && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-primary" />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function MobileCurrencyCard() {
  const { currency, setCurrency } = useCurrency();
  const [open, setOpen] = useState(false);
  return (
    <div className="rounded-2xl bg-white/[0.02] ring-1 ring-white/[0.06] p-4">
      <div className="flex items-center justify-between">
        <span className="text-sm text-zinc-500">Currency</span>
        <button onClick={() => setOpen(!open)}
          className={cn("flex items-center gap-2 px-3 py-1.5 rounded-xl text-sm font-medium transition",
            open ? "bg-white/[0.04] text-foreground" : "text-zinc-400 hover:text-foreground")}>
          <span className="text-primary font-bold">{currencySymbols[currency]}</span>
          <span>{currency}</span>
          <ChevronDown className={cn("w-4 h-4 transition", open && "rotate-180")} />
        </button>
      </div>
      {open && (
        <div className="mt-3 rounded-xl bg-black/50 ring-1 ring-white/[0.08] overflow-hidden">
          {currencies.map(c => (
            <button key={c} onClick={() => { setCurrency(c); setOpen(false); }}
              className={cn("flex items-center gap-3 w-full px-4 py-3 text-sm transition-colors",
                currency === c ? "text-foreground bg-white/[0.04]" : "text-zinc-400 hover:text-foreground hover:bg-white/[0.02]")}>
              <span className={cn("w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold",
                currency === c ? "bg-primary/20 text-primary" : "bg-white/[0.02] text-zinc-500")}>{currencySymbols[c]}</span>
              <span className="font-medium">{c}</span>
              {currency === c && <div className="ml-auto w-2 h-2 rounded-full bg-primary" />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = mobileMenuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileMenuOpen]);

  useEffect(() => {
    setMobileMenuOpen(false);
    setOpenDropdown(null);
  }, [location.pathname]);

  const isActive = (p: string) => location.pathname === p;
  const closeMobile = () => setMobileMenuOpen(false);
  const handleMobileLink = (href: string) => { closeMobile(); navigate({ to: href }); };

  return (
    <>
      <nav className={cn(
        "fixed top-0 left-0 right-0 z-50 transition-all duration-500",
        scrolled
          ? "bg-black/40 backdrop-blur-3xl ring-1 ring-white/[0.06] shadow-[0_8px_32px_rgba(0,0,0,0.4)]"
          : "bg-black/20 backdrop-blur-md"
      )}>
        <div className="container mx-auto px-4">
          <div className="flex items-center justify-between h-16">
            <Brand onClick={closeMobile} />

            <div className="hidden lg:flex items-center gap-1">
              <Link to="/game-hosting" className={cn(
                "flex items-center gap-2 px-3.5 py-2 text-xs font-medium transition-colors rounded-xl uppercase tracking-[0.15em]",
                isActive("/game-hosting") ? "text-white" : "text-zinc-400 hover:text-white"
              )}>
                <Gamepad2 className="w-3.5 h-3.5" /> Games
              </Link>

              {[
                { label: "Hosting", icon: Globe, links: hostingServices },
                { label: "Company", icon: Sparkles, links: importantLinks },
                { label: "Legal", icon: FileText, links: legalLinks },
              ].map(menu => (
                <div key={menu.label} className="relative group">
                  <button className="flex items-center gap-1.5 px-3.5 py-2 text-xs font-medium transition-colors rounded-xl text-zinc-400 hover:text-white uppercase tracking-[0.15em]">
                    {menu.label}
                    <ChevronDown className="w-3 h-3 transition-transform duration-200 group-hover:rotate-180" />
                  </button>
                  <div className="absolute top-full left-0 pt-2 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 translate-y-1 group-hover:translate-y-0">
                    <div className="p-2 min-w-[220px] rounded-2xl bg-black/70 backdrop-blur-3xl ring-1 ring-white/[0.08] shadow-[0_20px_40px_rgba(0,0,0,0.6)]">
                      {menu.links.map(link => (
                        <Link key={link.to} to={link.to}
                          className={cn("flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm transition-colors",
                            isActive(link.to) ? "bg-white/[0.06] text-white" : "text-zinc-400 hover:text-white hover:bg-white/[0.04]")}>
                          {link.icon && <link.icon className="w-4 h-4 text-primary/80" />}
                          {link.label}
                        </Link>
                      ))}
                    </div>
                  </div>
                </div>
              ))}
              <NavCurrencySelector />
            </div>

            <div className="hidden lg:flex items-center gap-2">
              <a href="https://zyrocloud.com/client/index.php?rp=/login" target="_blank" rel="noreferrer"
                className="px-5 py-2 rounded-xl bg-white text-black text-xs uppercase tracking-[0.1em] font-bold hover:bg-primary hover:text-primary-foreground hover:shadow-[0_0_20px_hsl(var(--uv-bright)/0.5)] transition-all duration-300">
                Login
              </a>
            </div>

            <button onClick={() => setMobileMenuOpen(v => !v)}
              className="lg:hidden p-2 text-foreground rounded-xl hover:bg-white/[0.04] transition-colors" aria-label="Toggle menu">
              {mobileMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
            </button>
          </div>
        </div>
      </nav>

      {/* spacer */}
      <div className="h-16" aria-hidden />

      {mobileMenuOpen && (
        <div className="lg:hidden fixed inset-0 z-[60] bg-[oklch(0.1_0.01_240)] flex flex-col">
          <div className="flex items-center justify-between px-5 h-16 border-b border-white/[0.04] shrink-0">
            <Brand onClick={closeMobile} />
            <button onClick={closeMobile} className="p-2 text-foreground hover:bg-white/[0.04] rounded-xl transition-colors" aria-label="Close menu">
              <X className="w-6 h-6" />
            </button>
          </div>

          <div className="flex-1 overflow-y-auto px-5 pt-5 pb-6">
            <div className="space-y-3">
              <MobileCurrencyCard />
              <button onClick={() => handleMobileLink("/game-hosting")}
                className="w-full rounded-2xl bg-white/[0.02] ring-1 ring-white/[0.06] p-4 flex items-center gap-3 active:bg-white/[0.04] transition-colors text-left">
                <Gamepad2 className="w-5 h-5 text-primary" />
                <span className="text-base font-medium text-foreground">Game Hosting</span>
              </button>
              {mobileDropdownCategories.map(cat => (
                <div key={cat.id} className="rounded-2xl bg-white/[0.02] ring-1 ring-white/[0.06] overflow-hidden">
                  <button onClick={() => setOpenDropdown(openDropdown === cat.id ? null : cat.id)}
                    className="w-full p-4 flex items-center justify-between active:bg-white/[0.02] transition-colors">
                    <div className="flex items-center gap-3">
                      <cat.icon className="w-5 h-5 text-primary" />
                      <span className="text-base font-medium text-foreground">{cat.label}</span>
                    </div>
                    <ChevronDown className={cn("w-5 h-5 text-zinc-500 transition-transform duration-300", openDropdown === cat.id && "rotate-180")} />
                  </button>
                  <div className={cn("overflow-hidden transition-all duration-300 ease-in-out", openDropdown === cat.id ? "max-h-[600px] opacity-100" : "max-h-0 opacity-0")}>
                    <div className="px-4 pb-4 pt-1 space-y-0.5">
                      {cat.links.map(link => (
                        <button key={link.to} onClick={() => handleMobileLink(link.to)}
                          className={cn("block w-full text-left py-2.5 pl-8 text-sm transition-colors rounded-xl",
                            isActive(link.to) ? "text-primary font-medium" : "text-zinc-400 active:text-foreground")}>
                          {link.label}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="border-t border-white/[0.04] px-5 py-4 shrink-0">
            <a href="https://zyrocloud.com/client/index.php?rp=/login" target="_blank" rel="noreferrer"
              className="block w-full text-center py-3 rounded-xl bg-white text-black font-bold text-sm uppercase tracking-wider">
              Login
            </a>
          </div>
        </div>
      )}
    </>
  );
}
