"use client";
import Link from "next/link";
import { useMemo, useState } from "react";
import { usePathname } from "next/navigation";
import { ConstructionModal } from "./ConstructionModal";

export function Navigation() {
  const [expanded, setExpanded] = useState(false);
  const [expandedSubs, setExpandedSubs] = useState<string[]>([]);
  const [showConstructionModal, setShowConstructionModal] = useState(false);
  const pathname = usePathname();
  const locale = pathname.startsWith("/en") ? "en" : "pt";
  const base = `/${locale}`;
  const isActive = (href: string) => pathname.startsWith(href);

  const toggleSubmenu = (key: string) => {
    setExpandedSubs((prev) =>
      prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
    );
  };

  const closeMenu = () => {
    setExpanded(false);
    setExpandedSubs([]);
  };

  const sections = useMemo(() => [
    {
      key: "home",
      label: locale === "en" ? "Home" : "Início",
      path: base,
      items: [] as { label: string; href: string }[],
    },
    {
      key: "sobre",
      label: locale === "en" ? "About APP" : "Sobre a APP",
      path: `${base}/sobre`,
      items: [
        { label: locale === "en" ? "Quem Somos" : "Quem Somos", href: `${base}/sobre/quem-somos` },
        { label: locale === "en" ? "Contatos" : "Contatos", href: `${base}/sobre/contatos` },
      ],
    },
    {
      key: "competicoes",
      label: locale === "en" ? "Competitions" : "Competições",
      path: `${base}/competicoes`,
      items: [
        { label: locale === "en" ? "Calendar" : "Calendário", href: `${base}/competicoes/calendario` },
        { label: locale === "en" ? "Results" : "Resultados", href: `${base}/competicoes/resultados` },
        { label: locale === "en" ? "Photos" : "Fotos", href: `${base}/competicoes/fotos` },
      ],
    },
    {
      key: "regras",
      label: locale === "en" ? "Rules" : "Regras",
      path: `${base}/regras`,
      items: [
        { label: "Regras/Códigos/Info IPF", href: `${base}/regras/ipf-rule-book` },
        { label: locale === "en" ? "Anti-Doping" : "Anti-Doping", href: `${base}/regras/anti-doping` },
      ],
    },
    {
      key: "perguntas",
      label: locale === "en" ? "FAQ" : "Perguntas",
      path: `${base}/perguntas`,
      items: [] as { label: string; href: string }[],
    },
  ], [locale, base, pathname]);

  const currentSection = sections.find(
    (s) => s.key !== "home" && pathname.startsWith(s.path)
  );

  return (
    <>
      <nav aria-label="Principal" className="nav">
      <button
        className="nav-toggle"
        aria-expanded={expanded}
        aria-controls="primary-menu"
        onClick={() => setExpanded((e) => !e)}
      >
        <span className="sr-only">{expanded ? (locale === "en" ? "Close menu" : "Fechar menu") : (locale === "en" ? "Open menu" : "Abrir menu")}</span>
        ☰
      </button>
      <ul id="primary-menu" className="nav-list" data-expanded={expanded}>
        {sections.map((s) => (
          <li key={s.key} className={s.items.length ? "nav-item has-sub" : "nav-item"}>
            {s.items.length > 0 ? (
              <>
                <div className="nav-item-header">
                  <span className={isActive(s.path) ? "active nav-label" : "nav-label"}>{s.label}</span>
                  <button
                    className="nav-submenu-toggle"
                    aria-expanded={expandedSubs.includes(s.key) ? "true" : "false"}
                    onClick={(e) => {
                      e.preventDefault();
                      toggleSubmenu(s.key);
                    }}
                  >
                    <span className="sr-only">
                      {expandedSubs.includes(s.key)
                        ? (locale === "en" ? "Hide" : "Ocultar") + ` ${s.label}`
                        : (locale === "en" ? "Show" : "Mostrar") + ` ${s.label}`}
                    </span>
                  </button>
                </div>
                <ul className={`submenu ${expandedSubs.includes(s.key) ? "expanded" : ""}`} role="menu" aria-label={s.label}>
                  {s.items.map((it) => (
                    <li key={it.href} role="none">
                      <Link role="menuitem" href={it.href} className={isActive(it.href) ? "active" : ""} onClick={closeMenu}>{it.label}</Link>
                    </li>
                  ))}
                </ul>
              </>
            ) : (
              <Link className={isActive(s.path) ? "active" : ""} href={s.path} onClick={closeMenu}>{s.label}</Link>
            )}
          </li>
        ))}
        <li className="lang-switcher" role="group" aria-label={locale === "en" ? "Language" : "Idioma"}>
          <Link className={locale === "pt" ? "current" : ""} href="/pt">PT</Link>
          <button
            className={`lang-switcher-btn ${locale === "en" ? "current" : ""}`}
            onClick={() => setShowConstructionModal(true)}
          >
            EN
          </button>
        </li>
      </ul>
      </nav>
      <ConstructionModal isOpen={showConstructionModal} onClose={() => setShowConstructionModal(false)} />
    </>
  );
}
