"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";

type MenuGroup = {
  title: string;
  items: { href: string; label: string }[];
};

type CategoryMenu = {
  href: string;
  label: string;
  groups: MenuGroup[];
};

const categoryMenus: CategoryMenu[] = [
  {
    href: "/societes",
    label: "Sociétés",
    groups: [
      {
        title: "Création & cessation",
        items: [
          { href: "/societes/creation-de-societe", label: "Création de société" },
          { href: "/societes/dissolution-de-societe", label: "Dissolution" },
        ],
      },
      {
        title: "Modifications statutaires",
        items: [
          { href: "/societes/transfert-de-siege-social", label: "Transfert de siège" },
          {
            href: "/societes/changement-de-denomination-sociale",
            label: "Changement de dénomination",
          },
          {
            href: "/societes/modification-de-l-objet-social",
            label: "Objet social",
          },
          {
            href: "/societes/nomination-revocation-de-dirigeant",
            label: "Nomination ou révocation de dirigeant",
          },
          {
            href: "/societes/nomination-revocation-commissaire-aux-comptes",
            label: "Commissaire aux comptes",
          },
        ],
      },
      {
        title: "Obligations & actes",
        items: [
          { href: "/societes/depot-des-comptes", label: "Dépôt des comptes" },
          {
            href: "/societes/modification-des-beneficiaires-effectifs",
            label: "Bénéficiaires effectifs",
          },
          {
            href: "/societes/redaction-d-acte-isole",
            label: "Rédaction d'acte isolé",
          },
        ],
      },
    ],
  },
  {
    href: "/marques",
    label: "Marques",
    groups: [
      {
        title: "Protection",
        items: [
          { href: "/marques/depot-de-marques", label: "Dépôt de marque" },
        ],
      },
    ],
  },
];

const simpleLinks = [
  { href: "/", label: "Accueil" },
  { href: "/contact", label: "Contact" },
];

export default function Nav() {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const [openMenu, setOpenMenu] = useState<string | null>(null);
  const [mobileExpanded, setMobileExpanded] = useState<string | null>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const navRef = useRef<HTMLDivElement | null>(null);

  const isActive = (href: string) =>
    href === "/" ? pathname === "/" : pathname.startsWith(href);

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

  const scheduleClose = () => {
    cancelClose();
    closeTimer.current = setTimeout(() => setOpenMenu(null), 220);
  };

  const handleOpen = (href: string) => {
    cancelClose();
    setOpenMenu(href);
  };

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

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpenMenu(null);
    };
    const onClick = (e: MouseEvent) => {
      if (!navRef.current?.contains(e.target as Node)) setOpenMenu(null);
    };
    window.addEventListener("keydown", onKey);
    window.addEventListener("mousedown", onClick);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("mousedown", onClick);
    };
  }, []);

  return (
    <nav
      ref={navRef}
      className="fixed top-0 left-0 right-0 z-50 bg-white/90 backdrop-blur-md border-b border-outline-variant/40"
    >
      <div className="container-page flex justify-between items-center gap-4 py-5 md:py-6">
        <Link
          href="/"
          className="inline-flex items-center gap-2.5 font-serif font-bold text-xl md:text-2xl tracking-tighter text-primary shrink-0"
          aria-label="Socialex, retour à l'accueil"
        >
          <img
            src="/logo.png"
            alt=""
            aria-hidden="true"
            width="30"
            height="28"
            className="h-7 w-auto"
          />
          <span>Socialex</span>
        </Link>

        <div className="hidden md:flex items-center gap-6 lg:gap-12 min-w-0">
          <Link
            href="/"
            className={`font-serif text-sm tracking-wide uppercase pb-1 transition-colors duration-300 whitespace-nowrap ${
              isActive("/")
                ? "text-primary border-b border-primary"
                : "text-outline hover:text-primary"
            }`}
          >
            Accueil
          </Link>

          {categoryMenus.map((menu) => {
            const active = isActive(menu.href);
            const isOpen = openMenu === menu.href;
            return (
              <div
                key={menu.href}
                className="relative self-stretch flex items-center -my-5 md:-my-6 py-5 md:py-6"
                onMouseEnter={() => handleOpen(menu.href)}
                onMouseLeave={scheduleClose}
              >
                <Link
                  href={menu.href}
                  aria-haspopup="true"
                  aria-expanded={isOpen}
                  onFocus={() => handleOpen(menu.href)}
                  onClick={() => setOpenMenu(null)}
                  className={`group inline-flex items-center gap-1.5 font-serif text-sm tracking-wide uppercase pb-1 transition-colors duration-300 whitespace-nowrap ${
                    active
                      ? "text-primary border-b border-primary"
                      : "text-outline hover:text-primary"
                  }`}
                >
                  {menu.label}
                  <span
                    aria-hidden="true"
                    className={`material-symbols-outlined !text-[14px] transition-transform duration-300 ${
                      isOpen ? "rotate-180" : ""
                    }`}
                  >
                    expand_more
                  </span>
                </Link>
              </div>
            );
          })}

          <Link
            href="/contact"
            className={`font-serif text-sm tracking-wide uppercase pb-1 transition-colors duration-300 whitespace-nowrap ${
              isActive("/contact")
                ? "text-primary border-b border-primary"
                : "text-outline hover:text-primary"
            }`}
          >
            Contact
          </Link>
        </div>

        <Link
          href="/espace-client"
          className="hidden md:inline-flex btn btn-primary !py-3 !px-5 lg:!px-8 text-xs whitespace-nowrap shrink-0"
        >
          Espace client
        </Link>

        <button
          type="button"
          aria-label="Ouvrir le menu"
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
          className="md:hidden p-2 -mr-2 text-primary"
        >
          <span className="material-symbols-outlined">
            {open ? "close" : "menu"}
          </span>
        </button>
      </div>

      {/* Desktop dropdown panel */}
      {categoryMenus.map((menu) => {
        const isOpen = openMenu === menu.href;
        return (
          <div
            key={`panel-${menu.href}`}
            className={`hidden md:block absolute left-0 right-0 top-full bg-white border-b border-outline-variant/60 transition-all duration-200 ease-out ${
              isOpen
                ? "opacity-100 translate-y-0 pointer-events-auto"
                : "opacity-0 -translate-y-1 pointer-events-none"
            }`}
            onMouseEnter={() => handleOpen(menu.href)}
            onMouseLeave={scheduleClose}
            aria-hidden={!isOpen}
          >
            <div
              className={`container-page py-10 lg:py-12 ${
                menu.groups.length === 1
                  ? "flex justify-center"
                  : "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-10"
              }`}
            >
              {menu.groups.map((group) => (
                <div
                  key={group.title}
                  className={`flex flex-col gap-4 ${
                    menu.groups.length === 1
                      ? "items-center text-center min-w-[280px]"
                      : ""
                  }`}
                >
                  <span className="text-[0.7rem] tracking-[0.18em] uppercase text-outline font-semibold border-b border-outline-variant/60 pb-3 w-full">
                    {group.title}
                  </span>
                  <ul
                    className={`flex flex-col gap-3 ${
                      menu.groups.length === 1 ? "items-center" : ""
                    }`}
                  >
                    {group.items.map((item) => (
                      <li key={item.href}>
                        <Link
                          href={item.href}
                          className="group inline-flex items-start gap-2 font-serif text-[0.95rem] leading-snug text-primary hover:text-secondary transition-colors duration-200"
                        >
                          {menu.groups.length === 1 ? null : (
                            <span className="block w-3 h-px bg-outline-variant mt-[0.7em] group-hover:bg-secondary transition-colors duration-200" />
                          )}
                          <span>{item.label}</span>
                        </Link>
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </div>
        );
      })}

      {open && (
        <div className="md:hidden border-t border-outline-variant/40 bg-white max-h-[calc(100vh-80px)] overflow-y-auto">
          <div className="container-page py-6 flex flex-col gap-1">
            {simpleLinks.slice(0, 1).map((link) => (
              <Link
                key={link.href}
                href={link.href}
                onClick={() => setOpen(false)}
                className={`font-serif text-sm tracking-wide uppercase py-3 ${
                  isActive(link.href) ? "text-primary" : "text-outline"
                }`}
              >
                {link.label}
              </Link>
            ))}

            {categoryMenus.map((menu) => {
              const expanded = mobileExpanded === menu.href;
              return (
                <div
                  key={menu.href}
                  className="border-t border-outline-variant/40"
                >
                  <div className="flex items-center justify-between py-3">
                    <Link
                      href={menu.href}
                      onClick={() => setOpen(false)}
                      className={`font-serif text-sm tracking-wide uppercase ${
                        isActive(menu.href) ? "text-primary" : "text-outline"
                      }`}
                    >
                      {menu.label}
                    </Link>
                    <button
                      type="button"
                      aria-label={`${expanded ? "Replier" : "Déplier"} le menu ${menu.label}`}
                      aria-expanded={expanded}
                      onClick={() =>
                        setMobileExpanded((v) =>
                          v === menu.href ? null : menu.href
                        )
                      }
                      className="p-2 -mr-2 text-outline"
                    >
                      <span
                        className={`material-symbols-outlined transition-transform duration-300 ${
                          expanded ? "rotate-180" : ""
                        }`}
                      >
                        expand_more
                      </span>
                    </button>
                  </div>
                  {expanded && (
                    <div className="pb-4 pl-1 flex flex-col gap-5">
                      {menu.groups.map((group) => (
                        <div key={group.title} className="flex flex-col gap-2">
                          <span className="text-[0.65rem] tracking-[0.18em] uppercase text-outline font-semibold">
                            {group.title}
                          </span>
                          <ul className="flex flex-col gap-2">
                            {group.items.map((item) => (
                              <li key={item.href}>
                                <Link
                                  href={item.href}
                                  onClick={() => setOpen(false)}
                                  className="block font-serif text-[0.95rem] text-primary py-1"
                                >
                                  {item.label}
                                </Link>
                              </li>
                            ))}
                          </ul>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}

            <div className="border-t border-outline-variant/40 py-3">
              <Link
                href="/contact"
                onClick={() => setOpen(false)}
                className={`font-serif text-sm tracking-wide uppercase ${
                  isActive("/contact") ? "text-primary" : "text-outline"
                }`}
              >
                Contact
              </Link>
            </div>

            <Link
              href="/espace-client"
              onClick={() => setOpen(false)}
              className="btn btn-primary !py-3 mt-4 text-xs justify-center"
            >
              Espace client
            </Link>
          </div>
        </div>
      )}
    </nav>
  );
}
