"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { AnimatePresence, motion } from "motion/react";
import {
  ChevronDown,
  Layers,
  FileSignature,
  GraduationCap,
  School,
  ShoppingBag,
  FlaskConical,
} from "lucide-react";
import { products, type Product } from "@/lib/site-config";

const productIcons: Record<string, React.ReactNode> = {
  atlas: <Layers size={18} strokeWidth={1.75} aria-hidden="true" />,
  consentiq: <FileSignature size={18} strokeWidth={1.75} aria-hidden="true" />,
  orthoprep: <GraduationCap size={18} strokeWidth={1.75} aria-hidden="true" />,
  academy: <School size={18} strokeWidth={1.75} aria-hidden="true" />,
  store: <ShoppingBag size={18} strokeWidth={1.75} aria-hidden="true" />,
  research: <FlaskConical size={18} strokeWidth={1.75} aria-hidden="true" />,
};

export function ProductsMegaMenu() {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();
  const router = useRouter();
  const closeTimer = useRef<number | null>(null);

  useEffect(() => {
    setOpen(false);
  }, [pathname]);

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

  const openMenu = () => {
    if (closeTimer.current) {
      window.clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
    setOpen(true);
  };

  const scheduleClose = () => {
    if (closeTimer.current) window.clearTimeout(closeTimer.current);
    closeTimer.current = window.setTimeout(() => setOpen(false), 120);
  };

  const isActive = pathname?.startsWith("/products");

  return (
    <div
      className="relative"
      onMouseEnter={openMenu}
      onMouseLeave={scheduleClose}
      onFocus={openMenu}
      onBlur={scheduleClose}
    >
      <button
        type="button"
        aria-haspopup="true"
        aria-expanded={open}
        onClick={() => {
          // Hover already opens the mega menu on desktop; a deliberate
          // click/tap (or keyboard Enter) should navigate to the products
          // overview anchor on the homepage rather than toggling the
          // hover-opened menu shut. There is no /products index route.
          router.push("/#products");
        }}
        className={`relative inline-flex items-center gap-1 py-2 transition-colors after:absolute after:left-0 after:-bottom-1 after:h-px after:w-full after:origin-left after:bg-[var(--color-blue)] after:transition-transform after:duration-300 after:ease-out ${
          open || isActive
            ? "text-[var(--color-blue)] after:scale-x-100"
            : "text-[var(--color-slate)] after:scale-x-0 hover:text-[var(--color-blue)] hover:after:scale-x-100"
        }`}
      >
        Initiatives
        <ChevronDown
          size={14}
          strokeWidth={1.75}
          aria-hidden="true"
          className={`transition-transform duration-200 ${open ? "rotate-180" : ""}`}
        />
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            key="mega"
            initial={{ opacity: 0, y: -6 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -6 }}
            transition={{ duration: 0.18, ease: "easeOut" }}
            className="absolute left-1/2 top-full z-50 mt-3 w-[min(720px,90vw)] -translate-x-1/2"
          >
            <div className="overflow-hidden rounded-xl border border-[var(--color-line)] bg-white shadow-[0_20px_60px_-20px_rgba(11,18,32,0.25)]">
              <div className="grid grid-cols-2 gap-1 p-3">
                {products.map((p: Product) => (
                  <Link
                    key={p.slug}
                    href={p.href}
                    className="group flex gap-3 rounded-lg p-3 transition-colors hover:bg-[#f4f6fc]"
                  >
                    <span className="mt-0.5 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-[var(--color-line)] bg-white text-[var(--color-blue)] transition-colors group-hover:border-[var(--color-blue)]">
                      {productIcons[p.slug]}
                    </span>
                    <span className="min-w-0">
                      <span className="block text-[14px] font-semibold text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                        {p.name}
                      </span>
                      <span className="mt-0.5 block truncate text-[12px] leading-snug text-[var(--color-slate)]">
                        {p.tagline}
                      </span>
                    </span>
                  </Link>
                ))}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
