/* ═══════════════════════════════════════════════════════════════════════════
   ESBART — Shared <Nav> component
   Props:
     lang     — current language ('ca' | 'es' | 'en')
     setLang  — setter
     t        — merged i18n dict (at least: navInici, navAbout, navActs, navPatri,
                navNews, navPart, navCta)
     heroMode — boolean, when true renders the nav in "over dark hero" style
     current  — optional: which nav link is active (matches the nav key, e.g. "vine")

   Exports: window.EsbartNav = <Nav>
   ═══════════════════════════════════════════════════════════════════════════ */

function EsbartNav({ lang, setLang, t, heroMode, current }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  const burgerRef = React.useRef(null);

  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 80);
    on();
    window.addEventListener('scroll', on);
    return () => window.removeEventListener('scroll', on);
  }, []);

  // Mobile menu: scroll-lock + Esc-to-close + focus-trap + restore focus.
  React.useEffect(() => {
    const menu = menuRef.current;
    if (menu) menu.inert = !menuOpen;        // off-canvas menu is unreachable when closed
    if (!menuOpen || !menu) return;

    const prevFocus = document.activeElement;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    const focusables = () =>
      Array.from(menu.querySelectorAll('a[href], button:not([disabled])'))
        .filter(el => el.offsetParent !== null);

    const first = focusables()[0];
    if (first) first.focus();

    const onKey = (e) => {
      if (e.key === 'Escape') { e.preventDefault(); setMenuOpen(false); return; }
      if (e.key !== 'Tab') return;
      const items = focusables();
      if (!items.length) return;
      const f = items[0], l = items[items.length - 1];
      if (e.shiftKey && document.activeElement === f) { e.preventDefault(); l.focus(); }
      else if (!e.shiftKey && document.activeElement === l) { e.preventDefault(); f.focus(); }
    };
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
      const back = burgerRef.current || prevFocus;
      if (back && back.focus) back.focus();
    };
  }, [menuOpen]);

  const onSkip = (e) => {
    const m = document.getElementById('main-content');
    if (m) { e.preventDefault(); m.focus(); }   // focus() also scrolls it into view
  };

  // Nav links with target href. Using absolute HTML pages so nav works across site.
  const links = [
    { key: 'inici', label: t.navInici, href: 'index.html' },
    { key: 'sobre', label: t.navAbout, href: 'Sobre-lEsbart.html' },
    { key: 'activitats', label: t.navActs, href: 'Activitats.html' },
    { key: 'patrimoni', label: t.navPatri, href: 'Patrimoni.html' },
    { key: 'noticies', label: t.navNews, href: 'Noticies.html' },
    { key: 'participa', label: t.navPart, href: 'Participa.html' },
  ];

  return (
    <>
      <a href="#main-content" className="skip-link" onClick={onSkip}>
        {t.skipToContent || 'Salta al contingut principal'}
      </a>
      <nav className={`nav ${scrolled ? 'scrolled' : ''} ${heroMode ? 'hero-mode' : ''}`}
           aria-label={t.ariaPrimaryNav || 'Navegació principal'}>
        <div className="wrap nav-inner">
          <a href="index.html" className="nav-logo">
            <img src="assets/logo-ecd.png" alt="Esbart Català de Dansaires" />
            <div className="word">Esbart Català<small>de Dansaires · 1908</small></div>
          </a>

          <div className="nav-links">
            {links.map(l => (
              <a
                key={l.key}
                href={l.href}
                className={current === l.key ? 'active' : ''}
                aria-current={current === l.key ? 'page' : undefined}
              >
                {l.label}
              </a>
            ))}
            <a href="Vine-a-ballar.html" className={`cta ${current === 'vine' ? 'active' : ''}`}
               aria-current={current === 'vine' ? 'page' : undefined}>{t.navCta}</a>
          </div>

          <div className="nav-util">
            <div className="lang" role="group" aria-label={t.ariaLangNav || 'Idioma'}>
              {["ca", "es", "en"].map(l => (
                <button
                  key={l}
                  className={lang === l ? "active" : ""}
                  aria-pressed={lang === l}
                  onClick={() => setLang(l)}
                >
                  {l.toUpperCase()}
                </button>
              ))}
            </div>
            <a className="icon-btn util-hide" href="Cataleg.html" aria-label={t.ariaSearch || 'Cerca al catàleg'}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true">
                <circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>
              </svg>
            </a>
            <button
              ref={burgerRef}
              className="burger"
              onClick={() => setMenuOpen(true)}
              aria-label={t.ariaMenuOpen || 'Obre el menú'}
              aria-haspopup="dialog"
              aria-expanded={menuOpen}
              aria-controls="mobile-menu"
            >
              <span></span><span></span><span></span>
            </button>
          </div>
        </div>
      </nav>

      <div
        id="mobile-menu"
        ref={menuRef}
        className={`mobile-menu ${menuOpen ? 'open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-label={t.ariaPrimaryNav || 'Navegació principal'}
        aria-hidden={!menuOpen}
      >
        <div className="mm-head">
          <div className="nav-logo">
            <img src="assets/logo-ecd.png" alt="" style={{filter:'brightness(0) invert(1)', width:46}} />
            <div className="word" style={{color:'#fff'}}>
              Esbart Català<small style={{color:'var(--gold-soft, #f5d5a6)'}}>de Dansaires</small>
            </div>
          </div>
          <button className="close" onClick={() => setMenuOpen(false)} aria-label={t.ariaMenuClose || 'Tanca el menú'}>×</button>
        </div>
        {links.map(l => (
          <a
            key={l.key}
            onClick={() => setMenuOpen(false)}
            href={l.href}
            aria-current={current === l.key ? 'page' : undefined}
          >{l.label}</a>
        ))}
        <a onClick={() => setMenuOpen(false)} href="Vine-a-ballar.html" className="cta"
           aria-current={current === 'vine' ? 'page' : undefined}>{t.navCta} →</a>
      </div>
    </>
  );
}

window.EsbartNav = EsbartNav;
