"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import type { MegaMenuSection } from "@/lib/nav-mega-menu";

export function NavMegaMenu({
  section,
  active,
  onNavigateHomeGuest,
}: {
  section: MegaMenuSection;
  active?: boolean;
  onNavigateHomeGuest?: () => void;
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const clearClose = () => {
    if (closeTimer.current) {
      clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
  };

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

  useEffect(() => {
    return () => clearClose();
  }, []);

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

  return (
    <div
      ref={rootRef}
      className="relative"
      onMouseEnter={() => {
        clearClose();
        setOpen(true);
      }}
      onMouseLeave={scheduleClose}
    >
      <Link
        href={section.href}
        className={
          active || open
            ? "text-ot-gold border-b border-ot-gold pb-0.5"
            : "text-ot-ink/80 hover:text-ot-ink"
        }
        aria-expanded={open}
        aria-haspopup="true"
        onFocus={() => setOpen(true)}
      >
        {section.label}
      </Link>

      {open ? (
        <div className="absolute left-1/2 top-full z-[60] w-[min(92vw,860px)] -translate-x-1/2 pt-3">
          <div
            className="border border-black/10 bg-white shadow-[0_18px_40px_rgba(0,0,0,0.08)] animate-[ot-fade-up_0.25s_ease]"
            onMouseEnter={clearClose}
          >
            <div
              className={`grid gap-0 ${
                section.columns.length >= 3
                  ? "grid-cols-1 md:grid-cols-3"
                  : section.columns.length === 2
                    ? "grid-cols-1 md:grid-cols-2"
                    : "grid-cols-1"
              }`}
            >
              {section.columns.map((col) => (
                <div
                  key={col.id}
                  className="px-5 py-5 border-r border-black/5 last:border-r-0"
                >
                  <p className="text-[11px] tracking-[0.18em] uppercase font-medium text-ot-ink">
                    {col.title}
                  </p>
                  <span className="mt-2 mb-3 block h-px bg-black/10" />
                  <ul className="space-y-2.5">
                    {col.items.map((item) => (
                      <li key={`${col.id}-${item.label}`}>
                        <Link
                          href={item.href}
                          className="text-[13px] text-ot-ink/75 hover:text-ot-green transition-colors leading-snug"
                          onClick={() => {
                            setOpen(false);
                            if (item.href === "/") onNavigateHomeGuest?.();
                          }}
                        >
                          {item.label}
                          {item.soon ? (
                            <span className="ml-1 text-[10px] tracking-[0.12em] uppercase text-ot-gold">
                              pronto
                            </span>
                          ) : null}
                        </Link>
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
            <div className="border-t border-black/5 px-5 py-3 flex flex-wrap items-center justify-between gap-2 bg-ot-cream/40">
              <p className="text-[11px] tracking-[0.14em] uppercase text-ot-muted">
                Colección {section.label.toLowerCase()} · OLD TENNIS
              </p>
              <Link
                href={section.href}
                className="text-[11px] tracking-[0.14em] uppercase text-ot-green underline underline-offset-4"
                onClick={() => setOpen(false)}
              >
                Ver todo
              </Link>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
