﻿"use client";
import { useEffect, useState, useRef } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { Menu, X, ArrowUpRight } from "lucide-react";
import CommandPalette from "./CommandPalette";

const NAV = [
  { label: "Home", href: "/" },
  { label: "About", href: "/about" },
  { label: "Work", href: "/work" },
  { label: "Experience", href: "/experience" },
  { label: "Blog", href: "/blog" },
];
const MORE = [
  { label: "Zyphron Cloud", href: "/zyphron" },
  { label: "Skills", href: "/skills" },
  { label: "Uses", href: "/uses" },
  { label: "Now", href: "/now" },
  { label: "Resume", href: "/resume" },
];

const MEGA: Record<string, { label:string, href:string }[]> = {
  WORK: [
    { label:"Work", href:"/work" },
    { label:"Zyphron", href:"/zyphron" },
    { label:"FreeDash", href:"/work/freedash" },
  ],
  CONTENT: [
    { label:"Blog", href:"/blog" },
    { label:"Videos", href:"/videos" },
    { label:"Playlists", href:"/playlists" },
    { label:"Changelog", href:"/changelog" },
  ],
  ABOUT: [
    { label:"About", href:"/about" },
    { label:"Experience", href:"/experience" },
    { label:"Skills", href:"/skills" },
    { label:"Now", href:"/now" },
    { label:"Timeline", href:"/timeline" },
  ],
  EXPLORE: [
    { label:"Lab", href:"/lab" },
    { label:"Open Source", href:"/opensource" },
    { label:"Uses", href:"/uses" },
    { label:"Bookmarks", href:"/bookmarks" },
    { label:"Resources", href:"/resources" },
    { label:"Ecosystem", href:"/ecosystem" },
    { label:"Stats", href:"/stats" },
    { label:"Office", href:"/office" },
  ],
  SERVICES: [
    { label:"Services", href:"/services" },
    { label:"Hire", href:"/hire" },
  ],
  CONNECT: [
    { label:"Testimonials", href:"/testimonials" },
    { label:"Collaborations", href:"/collaborations" },
    { label:"Press", href:"/press" },
    { label:"Contact", href:"/contact" },
    { label:"Achievements", href:"/achievements" },
  ],
};

const ALL_MEGA = Object.values(MEGA).flat();

export default function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [megaOpen, setMegaOpen] = useState(false);
  const [visible, setVisible] = useState(false);
  const [isHovering, setIsHovering] = useState(false);
  const pathname = usePathname();
  const hideRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  // Auto-hide: only on desktop with fine pointer
  useEffect(() => {
    const isCoarse = window.matchMedia("(pointer: coarse)").matches;
    const isDesktop = window.matchMedia("(min-width: 1024px)").matches;
    if (isCoarse || !isDesktop) {
      setVisible(true);
      return;
    }
    if (megaOpen) { setVisible(true); return; }
    setVisible(false);

    const TOP_REVEAL = 48;
    const TOP_KEEP = 110;

    const show = () => {
      if (hideRef.current) { clearTimeout(hideRef.current); hideRef.current = null; }
      setVisible(true);
    };
    const scheduleHide = () => {
      if (hideRef.current) clearTimeout(hideRef.current);
      hideRef.current = setTimeout(() => {
        setVisible(false);
      }, 160);
    };

    const onMouseMove = (e: MouseEvent) => {
      const hoveringNav = document.querySelector("header nav:hover") !== null;
      if (hoveringNav || open || megaOpen) {
        show();
        return;
      }
      if (e.clientY <= TOP_REVEAL) {
        show();
      } else if (e.clientY > TOP_KEEP) {
        scheduleHide();
      }
    };

    window.addEventListener("mousemove", onMouseMove, { passive: true });
    return () => {
      window.removeEventListener("mousemove", onMouseMove);
      if (hideRef.current) clearTimeout(hideRef.current);
    };
  }, [open, megaOpen]);

  // keep visible while hovering header (fallback sync with state)
  useEffect(() => {
    if (isHovering) {
      if (hideRef.current) { clearTimeout(hideRef.current); hideRef.current = null; }
      setVisible(true);
    }
  }, [isHovering]);

  useEffect(() => { setMegaOpen(false); }, [pathname]);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { setMegaOpen(false); setOpen(false); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const isActive = (href: string) => pathname === href || (href !== "/" && pathname.startsWith(href));

  return (
    <>
      <motion.header
        initial={{ y: -24, opacity: 0 }}
        animate={{ y: visible || open || megaOpen ? 0 : -96, opacity: visible || open || megaOpen ? 1 : 0 }}
        transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
        onMouseEnter={() => { setIsHovering(true); setVisible(true); if (hideRef.current) { clearTimeout(hideRef.current); hideRef.current = null; } }}
        onMouseLeave={() => {
          setIsHovering(false);
          const isCoarse = typeof window !== "undefined" && window.matchMedia("(pointer: coarse)").matches;
          const isDesktop = typeof window !== "undefined" && window.matchMedia("(min-width: 1024px)").matches;
          if (!isCoarse && isDesktop && !open && !megaOpen) {
            if (hideRef.current) clearTimeout(hideRef.current);
            hideRef.current = setTimeout(() => setVisible(false), 260);
          }
        }}
        className="fixed top-0 inset-x-0 z-50 flex justify-center px-4 sm:px-6 pt-4 sm:pt-5 pointer-events-none"
        style={{ willChange: "transform, opacity" }}
      >
        <nav className={`pointer-events-auto flex items-center justify-between gap-2 sm:gap-4 rounded-full px-2 py-2 transition-all duration-500 w-full max-w-[980px] ${scrolled ? "glass-strong shadow-[0_8px_32px_rgba(0,0,0,0.4)]" : "bg-white/[0.04] border border-white/[0.06] backdrop-blur-xl"}`}>
          <Link href="/" className="flex items-center gap-2.5 pl-3 shrink-0">
            <span className="w-8 h-8 rounded-full bg-white text-black grid place-items-center font-bold text-[13px] tracking-tighter">RB</span>
            <span className="hidden sm:block text-[13px] font-medium tracking-tight text-white/90">Ravneet Brar</span>
          </Link>

          <div className="hidden lg:flex items-center gap-1">
            {NAV.map(l => (
              <Link key={l.href} href={l.href} className={`px-3 py-1.5 rounded-full text-[13px] font-medium transition ${isActive(l.href) ? "bg-white text-black" : "text-white/60 hover:text-white hover:bg-white/10"}`}>{l.label}</Link>
            ))}
            <div className="w-px h-4 bg-white/10 mx-1" />
            {MORE.slice(0,3).map(l => (
              <Link key={l.href} href={l.href} className={`px-2.5 py-1.5 rounded-full text-[12px] font-medium ${isActive(l.href) ? "bg-white text-black" : "text-white/50 hover:text-white"}`}>{l.label}</Link>
            ))}
          </div>

          <div className="flex items-center gap-2 shrink-0">
            <div className="hidden sm:block"><CommandPalette /></div>
            <button
              onClick={() => setMegaOpen(!megaOpen)}
              aria-label={megaOpen ? "Close menu" : "Open all pages"}
              className={`hidden lg:grid place-items-center w-9 h-9 rounded-full border transition ${megaOpen ? "bg-white text-black border-white" : "bg-white/10 border-white/15 text-white/80 hover:bg-white hover:text-black"}`}
            >
              {megaOpen ? <X size={14} /> : <Menu size={14} />}
            </button>
            <Link href="/contact" className="hidden sm:inline-flex items-center gap-1.5 bg-[#2563eb] hover:bg-[#1d4ed8] text-white text-[13px] font-semibold px-5 py-[9px] rounded-full transition">Let&apos;s Talk <ArrowUpRight size={14} /></Link>
            <button aria-label={open ? "Close menu" : "Open menu"} onClick={() => setOpen(!open)} className="lg:hidden w-9 h-9 rounded-full bg-white text-black grid place-items-center">
              {open ? <X size={16} /> : <Menu size={16} />}
            </button>
          </div>
        </nav>
      </motion.header>

      {/* Desktop mega menu */}
      <AnimatePresence>
        {megaOpen && (
          <motion.div
            initial={{ opacity: 0, y: -12 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -12 }}
            transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
            className="hidden lg:block fixed top-[74px] inset-x-0 z-40 flex justify-center px-6 pointer-events-none"
            onMouseEnter={() => { setIsHovering(true); setVisible(true); }}
            onMouseLeave={() => setMegaOpen(false)}
          >
            <div className="pointer-events-auto w-full max-w-[980px] rounded-[24px] border border-white/10 bg-[#0a0d12]/95 backdrop-blur-2xl shadow-[0_20px_60px_rgba(0,0,0,0.5)] overflow-hidden">
              <div className="grid grid-cols-6 gap-6 p-6">
                {Object.entries(MEGA).map(([cat, links]) => (
                  <div key={cat}>
                    <p className="text-[11px] tracking-[0.14em] font-bold text-white/30 uppercase">{cat}</p>
                    <div className="mt-3 space-y-1">
                      {links.map(l => (
                        <Link
                          key={l.href}
                          href={l.href}
                          onClick={() => setMegaOpen(false)}
                          className={`block px-3 py-1.5 rounded-full text-[13px] font-medium transition ${isActive(l.href) ? "bg-white text-black" : "text-white/60 hover:text-white hover:bg-white/10"}`}
                        >
                          {l.label}
                        </Link>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
              <div className="flex justify-between items-center px-6 py-3 border-t border-white/10 bg-white/[0.02]">
                <span className="text-xs text-white/30">Every public page reachable â€” no hidden routes</span>
                <Link href="/sitemap.xml" onClick={() => setMegaOpen(false)} className="text-xs text-white/50 hover:text-white">Sitemap â†’</Link>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {open && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-40 bg-[#07080c]/95 backdrop-blur-2xl lg:hidden flex flex-col pt-[84px] px-6 pb-8 overflow-auto">
            <div className="flex flex-col gap-6 mt-2">
              {Object.entries(MEGA).map(([cat, links]) => (
                <div key={cat}>
                  <p className="text-[11px] tracking-[0.14em] font-bold text-white/30 uppercase">{cat}</p>
                  <div className="mt-2 grid grid-cols-1 gap-1">
                    {links.map(l => (
                      <Link key={l.href} href={l.href} onClick={() => setOpen(false)} className={`flex justify-between items-center py-2 text-[18px] font-semibold tracking-tight ${isActive(l.href) ? "text-white" : "text-white/70"}`}>
                        {l.label} <ArrowUpRight size={14} className="text-white/20" />
                      </Link>
                    ))}
                  </div>
                </div>
              ))}
              <div className="grid grid-cols-2 gap-3 mt-2">
                <Link href="/guestbook" onClick={() => setOpen(false)} className="rounded-full border border-white/10 py-3 text-center text-sm font-medium text-white/80">Guestbook</Link>
                <Link href="/links" onClick={() => setOpen(false)} className="rounded-full border border-white/10 py-3 text-center text-sm font-medium text-white/80">Links</Link>
              </div>
              <Link href="/contact" onClick={() => setOpen(false)} className="mt-2 bg-[#2563eb] text-white rounded-full py-4 text-center font-semibold flex items-center justify-center gap-2">Let&apos;s Talk <ArrowUpRight size={18} /></Link>
              <p className="text-center text-white/20 text-[11px] tracking-widest uppercase mt-2">ravneetbrar.in â€¢ 2026</p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
