"use client";

import Link from "next/link";
import Image from "next/image";
import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import {
  motion,
  AnimatePresence,
  useScroll,
  useMotionValueEvent,
} from "framer-motion";
import { MaterialIcon } from "@/components/ui/MaterialIcon";

const EASE = [0.22, 1, 0.36, 1] as [number, number, number, number];

const NAV_LINKS = [
  { label: "Home", href: "/" },
  { label: "Nearle for Business", href: "/businesses" },
  { label: "Nearle for People", href: "/people" },
  { label: "About", href: "/about" },
  { label: "Contact", href: "/contact" },
];

const mobileMenuVariants = {
  hidden: { opacity: 0, height: 0 },
  visible: {
    opacity: 1,
    height: "auto",
    transition: { duration: 0.3, ease: EASE },
  },
  exit: {
    opacity: 0,
    height: 0,
    transition: { duration: 0.2, ease: "easeIn" as const },
  },
};

const mobileStagger = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.04, delayChildren: 0.06 } },
};

const mobileItemVariants = {
  hidden: { opacity: 0, x: -10 },
  visible: { opacity: 1, x: 0, transition: { duration: 0.22, ease: EASE } },
};

export function PremiumNavbar() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const pathname = usePathname();
  const { scrollY } = useScroll();

  useMotionValueEvent(scrollY, "change", (y) => {
    setScrolled(y > 20);
  });

  // Close mobile menu whenever the route changes (navbar no longer remounts on navigation)
  useEffect(() => {
    setMobileOpen(false);
  }, [pathname]);

  const isActiveLink = (href: string) => {
    if (href === "/") return pathname === "/";
    return pathname.startsWith(href);
  };

  return (
    <motion.header
      className={`sticky top-0 z-50 w-full text-white transition-[background-color,box-shadow,backdrop-filter] duration-300 ${
        scrolled
          ? "bg-[#83429f]/82 backdrop-blur-lg shadow-[0_6px_32px_rgba(0,0,0,0.35)] border-b border-white/15"
          : "bg-[#83429f] border-b border-white/10"
      }`}
      initial={{ opacity: 0, y: -8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4, ease: EASE }}
    >
      <div className="relative mx-auto flex h-16 w-full max-w-[1600px] items-center px-6 md:h-20 md:px-10 xl:px-16">
        {/* Logo */}
        <Link
          href="/"
          className="flex shrink-0 items-center transition-transform duration-200 hover:scale-[1.02] active:scale-95"
          aria-label="Nearle Home"
        >
          <Image
            src="/logo-light.png"
            alt="Nearle"
            width={180}
            height={45}
            className="h-7 w-auto object-contain md:h-8 xl:h-9"
            priority
          />
        </Link>

        {/* Desktop Navigation */}
        <nav className="absolute left-1/2 hidden -translate-x-1/2 items-center gap-6 lg:flex lg:gap-8 xl:gap-10">
          {NAV_LINKS.map((link) => {
            const isActive = isActiveLink(link.href);
            return (
              <motion.div
                key={link.label}
                className="relative py-2"
                initial="rest"
                whileHover="hover"
                animate="rest"
              >
                <Link
                  href={link.href}
                  className={`whitespace-nowrap text-sm font-bold transition-colors duration-200 ${
                    isActive ? "text-white" : "text-white/70 hover:text-white"
                  }`}
                >
                  {link.label}
                </Link>

                {/* Active underline: layoutId lets it slide between links on navigation */}
                {isActive && (
                  <motion.span
                    layoutId="activeNavUnderline"
                    className="absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-white"
                    transition={{ duration: 0.3, ease: EASE }}
                  />
                )}

                {/* Hover underline: grows from left on inactive links */}
                {!isActive && (
                  <motion.span
                    className="absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-white/40"
                    style={{ originX: 0 }}
                    variants={{ rest: { scaleX: 0 }, hover: { scaleX: 1 } }}
                    transition={{ duration: 0.2, ease: EASE }}
                  />
                )}
              </motion.div>
            );
          })}
        </nav>

        {/* Mobile Toggle */}
        <button
          type="button"
          className="ml-auto flex h-10 w-10 items-center justify-center rounded-full text-white transition-all duration-200 hover:bg-white/10 active:scale-90 lg:hidden"
          onClick={() => setMobileOpen((v) => !v)}
          aria-label={mobileOpen ? "Close menu" : "Open menu"}
          aria-expanded={mobileOpen}
        >
          <MaterialIcon icon={mobileOpen ? "close" : "menu"} size={24} />
        </button>
      </div>

      {/* Mobile Menu with enter/exit animation */}
      <AnimatePresence>
        {mobileOpen && (
          <motion.div
            key="mobile-menu"
            variants={mobileMenuVariants}
            initial="hidden"
            animate="visible"
            exit="exit"
            className="overflow-hidden border-t border-white/10 bg-[#30226F]/98 backdrop-blur-xl lg:hidden"
          >
            <motion.nav
              className="mx-auto flex w-full max-w-[1600px] flex-col gap-1 px-6 py-5 md:px-10"
              variants={mobileStagger}
              initial="hidden"
              animate="visible"
            >
              {NAV_LINKS.map((link) => {
                const isActive = isActiveLink(link.href);
                return (
                  <motion.div key={link.label} variants={mobileItemVariants}>
                    <Link
                      href={link.href}
                      onClick={() => setMobileOpen(false)}
                      className={`flex items-center justify-between rounded-xl px-4 py-3 text-sm font-bold transition-all duration-200 ${
                        isActive
                          ? "bg-white/15 text-white"
                          : "text-white/70 hover:bg-white/10 hover:text-white"
                      }`}
                    >
                      {link.label}
                      {isActive && (
                        <span className="h-2 w-2 rounded-full bg-white" />
                      )}
                    </Link>
                  </motion.div>
                );
              })}
            </motion.nav>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.header>
  );
}
