"use client";

import Image from "next/image";
import Link from "next/link";
import { siteConfig } from "@/lib/config/site";
import { cn } from "@/lib/utils";
import {
  ChevronDown,
  Menu,
  X,
  Server,
  Cpu,
  AppWindow,
  Network,
  HelpCircle,
  Activity,
  Info,
  Zap,
  LogIn,
  LayoutDashboard,
  Gamepad2,
  Terminal,
  Globe,
  Sun,
  Moon,
  Monitor,
} from "lucide-react";
import React, { useState, useRef, useEffect } from "react";
import { useTheme } from "@/components/ThemeProvider";
import { motion, AnimatePresence } from "motion/react";
import { navFeaturedGames } from "@/lib/data/product-config";

type NavItem = {
  label: string;
  href: string;
  icon: React.ReactNode;
  description: string;
  image?: string;
  badge?: string;
};

function useDropdown() {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent | TouchEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    document.addEventListener("touchstart", handler);
    return () => {
      document.removeEventListener("mousedown", handler);
      document.removeEventListener("touchstart", handler);
    };
  }, []);

  return { open, setOpen, ref };
}

function DropdownMenu({ label, items, align = "left" }: { label: string; items: NavItem[]; align?: "left" | "right" }) {
  const { open, setOpen, ref } = useDropdown();

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1 px-3 py-2 text-sm font-medium text-content-dim hover:text-white transition-colors duration-200"
      >
        {label}
        <ChevronDown size={14} className={cn("transition-transform duration-200", open && "rotate-180")} />
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -4 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -4 }}
            transition={{ duration: 0.15 }}
            className={cn("absolute top-full mt-2 w-72 z-50", align === "right" ? "right-0" : "left-0")}
          >
            <div className="bg-surface border border-border/80 rounded-xl shadow-2xl p-2 space-y-0.5">
              {items.map((item) => (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setOpen(false)}
                  className="group/item flex gap-3 p-3 rounded-lg hover:bg-zinc-800/60 transition-colors duration-150"
                >
                  {item.image ? (
                    <img
                      src={item.image}
                      alt=""
                      className="shrink-0 h-9 w-9 object-contain transition-transform duration-300 group-hover/item:scale-110"
                    />
                  ) : (
                    <div className="shrink-0 w-9 h-9 rounded-lg bg-accent-hover/10 border border-accent-hover/20 flex items-center justify-center text-accent-text">
                      {item.icon}
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-semibold text-white group-hover/item:text-accent-text/80 transition-colors duration-150 leading-snug">
                        {item.label}
                      </p>
                      {item.badge && (
                        <span className="px-1.5 py-0.5 rounded text-[9px] uppercase font-bold tracking-wide bg-accent/15 text-accent-text">
                          {item.badge}
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-content-muted mt-0.5">{item.description}</p>
                  </div>
                </Link>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

function LoginDropdown({ items }: { items: NavItem[] }) {
  const { open, setOpen, ref } = useDropdown();

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium text-content-dim hover:text-white border border-border/80 hover:border-border-hover bg-transparent hover:bg-zinc-800/40 transition-all duration-200"
      >
        <LogIn size={14} />
        Login
        <ChevronDown size={13} className={cn("transition-transform duration-200", open && "rotate-180")} />
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -4 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -4 }}
            transition={{ duration: 0.15 }}
            className="absolute right-0 top-full mt-2 w-64 z-50"
          >
            <div className="bg-surface border border-border/80 rounded-xl shadow-2xl p-2 space-y-0.5">
              {items.map((item) => (
                <Link
                  key={item.label}
                  href={item.href}
                  onClick={() => setOpen(false)}
                  className="group/item flex gap-3 p-3 rounded-lg hover:bg-zinc-800/60 transition-colors duration-150"
                >
                  <div className="shrink-0 w-8 h-8 rounded-lg bg-zinc-800/80 border border-border-hover/50 flex items-center justify-center text-content-dim group-hover/item:text-accent-text group-hover/item:border-accent-hover/30 group-hover/item:bg-accent-hover/10 transition-all duration-150">
                    {item.icon}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-white group-hover/item:text-accent-text/80 transition-colors duration-150 leading-snug">
                      {item.label}
                    </p>
                    <p className="text-xs text-content-muted mt-0.5">{item.description}</p>
                  </div>
                </Link>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

const THEME_OPTIONS = [
  { value: "auto",  Icon: Monitor },
  { value: "light", Icon: Sun     },
  { value: "dark",  Icon: Moon    },
] as const;

function ThemeSegmented() {
  const { theme, setTheme } = useTheme();
  return (
    <div className="flex items-center gap-1 p-1 rounded-lg bg-elevated border border-border">
      {THEME_OPTIONS.map(({ value, Icon }) => (
        <button
          key={value}
          onClick={() => setTheme(value)}
          aria-label={value}
          className={cn(
            "p-1.5 rounded-md transition-all duration-150",
            theme === value
              ? "bg-accent text-white shadow-sm"
              : "text-content-muted hover:text-content"
          )}
        >
          <Icon size={14} />
        </button>
      ))}
    </div>
  );
}

function ThemeToggle() {
  const { theme, setTheme } = useTheme();

  const cycle = () => {
    if (theme === "auto") setTheme("light");
    else if (theme === "light") setTheme("dark");
    else setTheme("auto");
  };

  const Icon = theme === "light" ? Sun : theme === "dark" ? Moon : Monitor;
  const label = theme === "light" ? "Light" : theme === "dark" ? "Dark" : "Auto";

  return (
    <button
      onClick={cycle}
      title={`Theme: ${label}`}
      aria-label={`Switch theme (currently ${label})`}
      className="flex items-center gap-1.5 p-2 rounded-full text-sm text-content-dim hover:text-content hover:bg-elevated border border-transparent hover:border-border transition-all duration-200"
    >
      <Icon size={15} />
    </button>
  );
}

export default function Navbar() {
  const [mobileOpen, setMobileOpen]   = useState(false);
  const [openSection, setOpenSection] = useState<string | null>(null);
  const [scrolled, setScrolled]       = useState(false);
  const [bannerVisible, setBannerVisible] = useState(true);
  const navRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (localStorage.getItem("banner-dismissed")) setBannerVisible(false);
  }, []);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const onClickOutside = (e: MouseEvent) => {
      if (navRef.current && !navRef.current.contains(e.target as Node)) {
        setMobileOpen(false);
      }
    };
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, []);

  const hostingItems: NavItem[] = [
    { label: "App Hosting",  href: "/app-host",  icon: <AppWindow size={16} />, description: "Deploy bots, APIs, and web apps in seconds" },
    { label: "VPS",          href: "/vps",        icon: <Cpu size={16} />,       description: "Full root access, bare metal performance" },
    { label: "Private Node", href: "/nodes",      icon: <Network size={16} />,   description: "Dedicated infrastructure for your community" },
    { label: "Domains",      href: "/domain",     icon: <Globe size={16} />,     description: "Register, transfer, and manage your domains" },
    { label: "Web Hosting",  href: "/web-host",   icon: <Server size={16} />,    description: "LiteSpeed hosting for websites and email" },
  ];

  const gameItems: NavItem[] = navFeaturedGames.map((game) => ({
    label: game.label,
    href: game.href,
    image: game.image,
    icon: <Gamepad2 size={16} />,
    description:
      game.label === "Minecraft"
        ? "SMP, modpacks, Paper, Fabric, and Forge"
        : game.label === "Hytale"
          ? "Prepared Hytale themed packages"
          : "FiveM RP city hosting packages",
  }));

  const companyItems: NavItem[] = [
    { label: "About",   href: "/about",   icon: <Info size={16} />,        description: "Who we are and why we built this" },
    { label: "Status",  href: "/status",  icon: <Activity size={16} />,    description: "Live uptime and incident reports" },
    { label: "Support", href: "/support", icon: <HelpCircle size={16} />,  description: "Tickets, live chat, and knowledge base" },
  ];

  const loginItems: NavItem[] = [
    { label: "Client Area",  href: "/billing", icon: <LayoutDashboard size={15} />, description: "Billing, invoices, and account settings" },
    { label: "Game Panel",   href: "/panel",   icon: <Gamepad2 size={15} />,        description: "Manage and control your game servers" },
    { label: "VPS Panel",    href: "/billing", icon: <Terminal size={15} />,         description: "SSH access and VPS management" },
  ];

  return (
    <nav ref={navRef} className="fixed top-0 left-0 right-0 z-50">
      {siteConfig.nav.banner.enabled && bannerVisible && (
        <div className={cn("text-white text-xs sm:text-sm", {
          "bg-accent":        siteConfig.nav.banner.color === "accent",
          "bg-emerald-600":   siteConfig.nav.banner.color === "emerald",
          "bg-amber-600":     siteConfig.nav.banner.color === "amber",
          "bg-rose-600":      siteConfig.nav.banner.color === "rose",
        })}>
          <div className="max-w-7xl mx-auto px-4 sm:px-6 py-2 flex items-center justify-between gap-4">
            <div className="flex-1 flex items-center justify-center gap-2">
              <Zap size={13} className="shrink-0" />
              <span className="text-center">
                {siteConfig.nav.banner.text}{" "}
                <Link href={siteConfig.nav.banner.link} className="font-semibold underline underline-offset-2 hover:text-white/70 transition-colors">{siteConfig.nav.banner.linkText}</Link>
              </span>
            </div>
            <button
              onClick={() => { setBannerVisible(false); localStorage.setItem("banner-dismissed", "1"); }}
              className="shrink-0 p-1 rounded text-white/60 hover:text-white transition-colors"
              aria-label="Dismiss"
            >
              <X size={13} />
            </button>
          </div>
        </div>
      )}

      <div
        className={`transition-all duration-300 ${
          scrolled
            ? "bg-surface/50 backdrop-blur-xl border-b border-border/80 shadow-sm shadow-black/30"
            : "bg-transparent"
        }`}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="flex items-center justify-between h-16 relative">

            <Link href="/" className="shrink-0 flex items-center gap-2 group">
              <div className="relative w-8 h-8">
                <Image src={siteConfig.logo} alt={siteConfig.name} width={32} height={32} className="object-contain" />
              </div>
              <span className="font-bold text-white hidden sm:inline-block tracking-tight">{siteConfig.name}</span>
            </Link>

            <div className="hidden md:flex items-center gap-1 absolute left-1/2 -translate-x-1/2">
              <Link href="/" className="px-3 py-2 text-sm font-medium text-content-dim hover:text-white transition-colors duration-200">
                Home
              </Link>
              <DropdownMenu label="Game Hosting" items={gameItems} />
              <DropdownMenu label="Hosting" items={hostingItems} />
              <DropdownMenu label="Company" items={companyItems} />
            </div>

            <div className="hidden md:flex items-center gap-2">
              <ThemeToggle />
              <LoginDropdown items={loginItems} />
              <Link
                href="/game-host/minecraft"
                className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-semibold text-white bg-accent hover:bg-accent-hover shadow-[0_3px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)] hover:shadow-[0_4px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)] hover:-translate-y-px active:translate-y-0.5 active:shadow-none transition-all duration-150"
              >
                <Zap size={14} />
                Get Started
              </Link>
            </div>

            <button
              onClick={() => setMobileOpen(!mobileOpen)}
              className="md:hidden inline-flex items-center justify-center p-2 rounded-lg text-content-dim hover:text-white hover:bg-zinc-800/60 transition-all duration-200"
              aria-label="Toggle menu"
            >
              {mobileOpen ? <X size={22} /> : <Menu size={22} />}
            </button>
          </div>
        </div>

        <AnimatePresence>
        {mobileOpen && (
          <motion.div
            initial={{ opacity: 0, y: -6 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -6 }}
            transition={{ duration: 0.18, ease: "easeOut" }}
            className={`md:hidden border-t border-border/80 ${!scrolled && "bg-surface/95 backdrop-blur-xl rounded-b-xl border border-t-0 border-border/80"}`}
          >
            <div className="px-4 pt-3 pb-5 space-y-1 max-w-7xl mx-auto">
              <Link
                href="/"
                onClick={() => setMobileOpen(false)}
                className="block px-3 py-2.5 text-sm font-medium text-zinc-300 hover:text-white hover:bg-zinc-800/50 rounded-lg transition-all duration-200"
              >
                Home
              </Link>

              <div>
                <button
                  onClick={() => setOpenSection(openSection === "games" ? null : "games")}
                  className="w-full flex items-center justify-between px-3 py-2.5 text-sm font-medium text-zinc-300 hover:text-white hover:bg-zinc-800/50 rounded-lg transition-all duration-200"
                >
                  Game Hosting
                  <ChevronDown size={15} className={`transition-transform duration-200 ${openSection === "games" ? "rotate-180" : ""}`} />
                </button>
                {openSection === "games" && (
                  <div className="pl-3 mt-1 space-y-0.5">
                    {gameItems.map((item) => (
                      <Link
                        key={item.href}
                        href={item.href}
                        onClick={() => setMobileOpen(false)}
                        className="flex gap-3 px-3 py-2.5 rounded-lg text-content-dim hover:text-white hover:bg-zinc-800/50 transition-all duration-200"
                      >
                        {item.image ? (
                          <img src={item.image} alt="" className="shrink-0 h-8 w-8 object-contain" />
                        ) : (
                          <div className="shrink-0 text-accent-text mt-0.5">{item.icon}</div>
                        )}
                        <div className="min-w-0">
                          <p className="text-sm font-medium text-zinc-300">{item.label}</p>
                          <p className="text-xs text-content-subtle">{item.description}</p>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </div>

              <div>
                <button
                  onClick={() => setOpenSection(openSection === "hosting" ? null : "hosting")}
                  className="w-full flex items-center justify-between px-3 py-2.5 text-sm font-medium text-zinc-300 hover:text-white hover:bg-zinc-800/50 rounded-lg transition-all duration-200"
                >
                  Hosting
                  <ChevronDown size={15} className={`transition-transform duration-200 ${openSection === "hosting" ? "rotate-180" : ""}`} />
                </button>
                {openSection === "hosting" && (
                  <div className="pl-3 mt-1 space-y-0.5">
                    {hostingItems.map((item) => (
                      <Link
                        key={item.href}
                        href={item.href}
                        onClick={() => setMobileOpen(false)}
                        className="flex gap-3 px-3 py-2.5 rounded-lg text-content-dim hover:text-white hover:bg-zinc-800/50 transition-all duration-200"
                      >
                        {item.image ? (
                          <img src={item.image} alt="" className="shrink-0 h-8 w-8 object-contain" />
                        ) : (
                          <div className="shrink-0 text-accent-text mt-0.5">{item.icon}</div>
                        )}
                        <div className="min-w-0">
                          <div className="flex items-center gap-2">
                            <p className="text-sm font-medium text-zinc-300">{item.label}</p>
                            {item.badge && (
                              <span className="px-1.5 py-0.5 rounded text-[9px] uppercase font-bold tracking-wide bg-accent/15 text-accent-text">
                                {item.badge}
                              </span>
                            )}
                          </div>
                          <p className="text-xs text-content-subtle">{item.description}</p>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </div>

              <div>
                <button
                  onClick={() => setOpenSection(openSection === "company" ? null : "company")}
                  className="w-full flex items-center justify-between px-3 py-2.5 text-sm font-medium text-zinc-300 hover:text-white hover:bg-zinc-800/50 rounded-lg transition-all duration-200"
                >
                  Company
                  <ChevronDown size={15} className={`transition-transform duration-200 ${openSection === "company" ? "rotate-180" : ""}`} />
                </button>
                {openSection === "company" && (
                  <div className="pl-3 mt-1 space-y-0.5">
                    {companyItems.map((item) => (
                      <Link
                        key={item.href}
                        href={item.href}
                        onClick={() => setMobileOpen(false)}
                        className="flex gap-3 px-3 py-2.5 rounded-lg text-content-dim hover:text-white hover:bg-zinc-800/50 transition-all duration-200"
                      >
                        <div className="shrink-0 text-accent-text mt-0.5">{item.icon}</div>
                        <div className="min-w-0">
                          <p className="text-sm font-medium text-zinc-300">{item.label}</p>
                          <p className="text-xs text-content-subtle">{item.description}</p>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </div>

              <div>
                <button
                  onClick={() => setOpenSection(openSection === "login" ? null : "login")}
                  className="w-full flex items-center justify-between px-3 py-2.5 text-sm font-medium text-zinc-300 hover:text-white hover:bg-zinc-800/50 rounded-lg transition-all duration-200"
                >
                  <span className="flex items-center gap-2">
                    <LogIn size={15} />
                    Login
                  </span>
                  <ChevronDown size={15} className={`transition-transform duration-200 ${openSection === "login" ? "rotate-180" : ""}`} />
                </button>
                {openSection === "login" && (
                  <div className="pl-3 mt-1 space-y-0.5">
                    {loginItems.map((item) => (
                      <Link
                        key={item.label}
                        href={item.href}
                        onClick={() => setMobileOpen(false)}
                        className="flex gap-3 px-3 py-2.5 rounded-lg text-content-dim hover:text-white hover:bg-zinc-800/50 transition-all duration-200"
                      >
                        <div className="shrink-0 text-accent-text mt-0.5">{item.icon}</div>
                        <div className="min-w-0">
                          <p className="text-sm font-medium text-zinc-300">{item.label}</p>
                          <p className="text-xs text-content-subtle">{item.description}</p>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </div>

              <div className="pt-3 mt-3 border-t border-border/80 space-y-2">
                <div className="flex items-center justify-between px-1">
                  <span className="text-xs text-content-muted px-2">Appearance</span>
                  <ThemeSegmented />
                </div>
                <Link
                  href="/game-host/minecraft"
                  onClick={() => setMobileOpen(false)}
                  className="flex items-center justify-center gap-1.5 px-4 py-2.5 rounded-lg text-sm font-semibold text-white bg-accent hover:bg-accent-hover shadow-[0_4px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)] hover:shadow-[0_6px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)] hover:-translate-y-0.5 active:translate-y-1 active:shadow-none transition-all duration-150"
                >
                  <Zap size={14} />
                  Get Started
                </Link>
              </div>
            </div>
          </motion.div>
        )}
        </AnimatePresence>
      </div>
    </nav>
  );
}
