/* Nav — top header with editorial dropdowns on Proyectos and Talento.
 *
 * Each dropdown opens on hover/focus and contains either:
 *   · Proyectos → the 6 sector entries (route to /sector/:id)
 *   · Talento   → Opportunities (/talento) + Life at Aguilera (/vida)
 *
 * Clicking the parent label itself still goes to the parent route as a
 * fallback (so Proyectos → /proyectos, Talento → /talento). On mobile
 * (≤900px) the row nav collapses into a fullscreen overlay where sub-
 * entries are surfaced inline because there's no hover affordance.
 */
const Nav = ({ route, realRoute, sectorId, setRoute }) => {
  const { t } = useLang();
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  /* Which top-level nav item currently has its dropdown open. Tracked on
     hover (mouseenter/leave) AND focus (keyboard tab). */
  const [openMenu, setOpenMenu] = React.useState(null);
  React.useEffect(() => { setOpenMenu(null); }, [route]);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const go = (id) => { setRoute(id); setOpen(false); setOpenMenu(null); window.scrollTo({top:0,behavior:"smooth"}); };
  const goSector = (sectorId) => {
    setRoute({route: "sector", sectorId});
    setOpen(false);
    setOpenMenu(null);
    window.scrollTo({top:0, behavior:"smooth"});
  };

  const sectors = t.sectors || [];
  const talentoSubnav = (t.talento && t.talento.subnav) || [];

  /* Resolve a nav item to its dropdown config (items list + the
     header label that links to the parent), or null for flat items.
     This keeps the navItem renderer agnostic of which entry it's
     rendering — both Proyectos and Talento flow through the same
     JSX path. */
  const dropdownFor = (id) => {
    if (id === "proyectos" && sectors.length > 0) {
      return {
        allLabel: t.proyectos && t.proyectos.navAll,
        items: sectors.map(s => ({
          key: s.id,
          label: s.label,
          onClick: () => goSector(s.id),
        })),
      };
    }
    if (id === "talento" && talentoSubnav.length > 0) {
      return {
        /* Talento dropdown has no "All" header — there's no parent
           overview page distinct from the first item, so the parent
           label click is enough. */
        allLabel: null,
        items: talentoSubnav.map(s => ({
          key: s.id,
          label: s.label,
          primary: !!s.primary,
          onClick: () => go(s.route),
        })),
      };
    }
    return null;
  };

  /* Keep the parent underline lit while the user is on a sub-route
     of that parent (sector / project under Proyectos; vida under
     Talento). Matches the article→newsletter convention. */
  const isActiveParent = (id) =>
    route === id ||
    (id === "proyectos" && (route === "sector" || route === "project")) ||
    (id === "talento"   && route === "vida");

  const navItem = (n) => {
    const drop = dropdownFor(n.id);
    if (!drop) {
      return (
        <li key={n.id}>
          <a className={"ai-nav__link " + (route === n.id ? "is-active" : "")} onClick={() => go(n.id)}>
            {n.label}
          </a>
        </li>
      );
    }
    const isOpen = openMenu === n.id;
    return (
      <li key={n.id}
          className={"ai-nav__has-menu " + (isOpen ? "is-open" : "")}
          onMouseEnter={() => setOpenMenu(n.id)}
          onMouseLeave={() => setOpenMenu(null)}>
        <a className={"ai-nav__link " + (isActiveParent(n.id) ? "is-active" : "")}
           onClick={() => go(n.id)}
           onFocus={() => setOpenMenu(n.id)}>
          {n.label}
        </a>
        <div className="ai-nav__menu" role="menu" onMouseEnter={() => setOpenMenu(n.id)}>
          <div className="ai-nav__menu-inner">
            {drop.allLabel && (
              <a className="ai-nav__menu-all" onClick={() => go(n.id)}>
                {drop.allLabel}
                <span className="ai-nav__menu-arrow">→</span>
              </a>
            )}
            <ul className="ai-nav__menu-list">
              {drop.items.map(it => (
                <li key={it.key} className={it.primary ? "is-primary" : ""}>
                  <a onClick={it.onClick}>
                    <span className="ai-nav__menu-label">{it.label}</span>
                    <span className="ai-nav__menu-arrow">→</span>
                  </a>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </li>
    );
  };

  return (
    <>
      {/* Transparent-at-top decision:
            - home / proyectos / personas / newsletter / contacto qualify —
              all open with a full-bleed dark hero (image, video stage, or
              dark section) that gives the nav the contrast it needs.
            - sector landings qualify ONLY when the active sector has
              heroVariant === "stage" (Data Centers, Singular Buildings).
              Sectors with framed split heros (Farma / Hos / Fab / Sos)
              keep the nav solid since their hero panel doesn't reach the
              top edge of the viewport.
            - everything else (about, careers, article) stays solid. */}
      <nav className={
        "ai-nav " +
        (() => {
          if (scrolled) return "ai-nav--solid";
          const TRANSPARENT_AT_TOP = ["home", "quienes", "proyectos", "personas", "talento", "newsletter", "contacto"];
          if (TRANSPARENT_AT_TOP.includes(realRoute)) return "";
          if (realRoute === "sector" && sectorId) {
            const active = (t.sectors || []).find(s => s.id === sectorId);
            if (active && (active.heroVariant === "stage" || active.heroVariant === "deck")) return "";
          }
          return "ai-nav--solid";
        })()
      }>
        <div className="ai-nav__inner">
          <a className="ai-nav__logo" onClick={() => go("home")}>
            <Logo dark={true} size={34} />
          </a>
          <ul className="ai-nav__links" onMouseLeave={() => setOpenMenu(null)}>
            {t.nav.map(navItem)}
          </ul>
          <div className="ai-nav__right">
            <LangToggle onDark />
            <button className="ai-nav__burger" onClick={() => setOpen(true)} aria-label="Menu">
              <Icon.Menu s={22} c="#F5F5F3" />
            </button>
          </div>
        </div>
      </nav>
      {open && (
        <div className="ai-nav__overlay">
          <div className="ai-nav__overlay-top">
            <Logo dark size={34} />
            <button className="ai-nav__close" onClick={() => setOpen(false)} aria-label="Close">
              <Icon.Close s={26} c="#F5F5F3" />
            </button>
          </div>
          <ul className="ai-nav__overlay-links">
            {t.nav.map(n => (
              <React.Fragment key={n.id}>
                <li><a onClick={() => go(n.id)}>{n.label}</a></li>
                {/* Surface the sector list under Proyectos in the overlay —
                    no hover on touch, so sub-entries have to be inline. */}
                {n.id === "proyectos" && sectors.length > 0 && (
                  <li className="ai-nav__overlay-sub">
                    <ul>
                      {sectors.map(s => (
                        <li key={s.id}><a onClick={() => goSector(s.id)}>{s.label}</a></li>
                      ))}
                    </ul>
                  </li>
                )}
                {/* Same idea for the Talento subnav (Opportunities / Vida). */}
                {n.id === "talento" && talentoSubnav.length > 0 && (
                  <li className="ai-nav__overlay-sub">
                    <ul>
                      {talentoSubnav.map(s => (
                        <li key={s.id}><a onClick={() => go(s.route)}>{s.label}</a></li>
                      ))}
                    </ul>
                  </li>
                )}
              </React.Fragment>
            ))}
          </ul>
          <div style={{marginTop:"auto",padding:"32px 0"}}>
            <LangToggle onDark />
          </div>
        </div>
      )}
    </>
  );
};

window.Nav = Nav;
