// ── Nav v6 : bandeau d'annonce + header sombre sticky ─────────
// Le markup est volontairement identique à celui pré-rendu par
// scripts/build-catalog.mjs (navHTML) : header pixel-identique d'une page
// à l'autre, avant comme après hydratation.
const PAGE_IDS = new Set(['scenarios', 'faq', 'contact']);

// Ancres de la home : préfixées « / » pour rester valides depuis les pages
// statiques (scenarios.html, faq.html, pages porte, pages légales).
// Libellés : src/content/ui.js (nav.<id>) ; chemins français traduits par
// window.__href pour la langue de la page.
const NAV_LINKS = [
  { id: 'offres',      href: '/#offres'      },
  { id: 'science',     href: '/#science'     },
  { id: 'rapport',     href: '/#rapport'     },
  { id: 'conformite',  href: '/#conformite'  },
  { id: 'scenarios',   href: '/scenarios.html' },
  { id: 'faq',         href: '/faq.html'     },
].map((l) => ({ ...l, label: window.__t(`nav.${l.id}`), href: window.__href(l.href) }));

// Sélecteur de langue : liens vers la home des autres langues (window.__LANG_SWITCH__).
function Mk2LangSwitch({ className = 'mk2-nav-lang' }) {
  return (window.__LANG_SWITCH__ || []).map((l) => (
    <a key={l.hreflang} className={className} href={l.href} hrefLang={l.hreflang} lang={l.hreflang} title={l.title}>{l.label}</a>
  ));
}

// Pages statiques SSG → vraie navigation, pas de routing SPA.
const STATIC_HREF = {
  scenarios: window.__href('/scenarios.html'),
  faq: window.__href('/faq.html'),
  formation: window.__href('/formation.html'),
  evaluation: window.__href('/evaluation.html'),
};

function Mk2Nav({ onNav, currentPage = 'home' }) {
  const [open, setOpen] = React.useState(false);
  const [solid, setSolid] = React.useState(false);

  // Header opaque dès qu'on quitte le haut de page (le hero passe sous la nav).
  React.useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const topbar = (typeof window !== 'undefined' && window.__HOME__ && window.__HOME__.topbar) || null;

  // Un lien n'est actif que sur SA propre page.
  const isActive = (id) => currentPage === id;

  const handleNav = (e, id) => {
    setOpen(false);
    if (STATIC_HREF[id]) return;          // navigation réelle
    if (id === 'contact') { e.preventDefault(); onNav?.('contact'); return; }
    // Ancre de home : laisser le navigateur faire, sauf si on est déjà sur la home
    // et qu'un routing SPA a affiché une autre page.
    if (currentPage !== 'home') return;
    const target = document.getElementById(id);
    if (!target) return;
    e.preventDefault();
    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <React.Fragment>
      {topbar && (
        <div className="mk2-topbar">
          {topbar.text}{' '}
          <a href={window.__href(topbar.href)}>{topbar.linkLabel}</a>
        </div>
      )}

      <nav className={`mk2-nav${solid ? ' is-solid' : ''}`}>
        <div className="mk2-container mk2-nav-bar">

          {/* Logo */}
          <a className="mk2-nav-brand" href={window.__href('/')} onClick={(e) => { e.preventDefault(); setOpen(false); onNav?.('home'); }}>
            <img src="/assets/brand/apprentisia-icon.svg" alt="" width="38" height="38"/>
            <span className="mk2-display">apprentisia</span>
          </a>

          {/* Links */}
          <div className="mk2-nav-links">
            {NAV_LINKS.map(({ id, label, href }) => (
              <a key={id}
                className={`mk2-nav-link${isActive(id) ? ' is-active' : ''}`}
                href={href}
                onClick={(e) => handleNav(e, id)}>
                {label}
              </a>
            ))}
          </div>

          {/* CTA desktop */}
          <div className="mk2-nav-cta-desktop">
            {/* Accès à l'application (plateforme Apprentisia) */}
            <Mk2LangSwitch/>
            <a className="mk2-btn mk2-btn-outline-dark mk2-btn-sm" href="https://app.apprentisia.com">
              {window.__t('nav.login')}
            </a>
            <button className="mk2-btn mk2-btn-primary mk2-btn-sm" onClick={() => onNav?.('contact')}>
              <span className="mk2-dot-live"/>
              {window.__t('nav.demo')}
            </button>
          </div>

          {/* Burger mobile */}
          <button className="mk2-burger" aria-label={window.__t('nav.menu')} aria-expanded={open}
            onClick={() => setOpen((o) => !o)}>
            {open ? (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
                <path d="M6 6 18 18M18 6 6 18"/>
              </svg>
            ) : (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
                <path d="M4 7h16M4 12h16M4 17h16"/>
              </svg>
            )}
          </button>
        </div>

        {/* Panneau mobile */}
        <div className={`mk2-mobile-panel${open ? ' open' : ''}`}>
          {NAV_LINKS.map(({ id, label, href }) => (
            <a key={id} href={href} onClick={(e) => handleNav(e, id)}>{label}</a>
          ))}
          <Mk2LangSwitch/>
          <a className="mk2-btn mk2-btn-outline-dark" href="https://app.apprentisia.com">{window.__t('nav.login')}</a>
          <button className="mk2-btn mk2-btn-primary" onClick={() => { setOpen(false); onNav?.('contact'); }}>{window.__t('nav.demo')}</button>
        </div>
      </nav>
    </React.Fragment>
  );
}

// Logo mark : deux points (signature Apprentisia)
function Mk2Mark({ size = 30, color = 'var(--mk2-ink)' }) {
  const dot = size * 0.18;
  const gap = size * 0.32;
  const w = dot * 2 + gap;
  return (
    <svg width={w} height={dot} viewBox={`0 0 ${w} ${dot}`} style={{ display: 'inline-block', verticalAlign: 'middle' }}>
      <circle cx={dot / 2} cy={dot / 2} r={dot / 2} fill={color}/>
      <circle cx={dot + gap + dot / 2} cy={dot / 2} r={dot / 2} fill={color}/>
    </svg>
  );
}

window.Mk2Nav = Mk2Nav;
window.Mk2Mark = Mk2Mark;
window.NAV_LINKS = NAV_LINKS;
window.PAGE_IDS = PAGE_IDS;
