// ╔═══════════════════════════════════════════════════════════╗
// ║  KENSAI gokensai migration · Nav IA shell (FIFO 1, 05-36)   ║
// ║  Self-contained IA shell rendered from window.KENSAI_NAV_IA ║
// ║  (generated from the approved 05-27 manifest). Desktop       ║
// ║  dropdowns + mobile drawer. Preserves the existing landing   ║
// ║  anchors; migrated section routes are foundation targets.    ║
// ╚═══════════════════════════════════════════════════════════╝

// i18n (05-72): aria strings via t(); manifest-driven IA labels localize through the nav.labels
// lookup (sanctioned fallback to the manifest original for unmapped labels — structural navigation).
const t = window.t || ((k) => '⟪no-i18n:' + k + '⟫');
const navL = (label) => {
  const loc = window.__V4_I18N_LOCALE__ || 'en';
  const map = (window.__V4_COPY__ && window.__V4_COPY__[loc] && window.__V4_COPY__[loc].nav && window.__V4_COPY__[loc].nav.labels) || {};
  return map[label] || label;
};

const NavIAShell = () => {
  const IA = (window.KENSAI_NAV_IA && Array.isArray(window.KENSAI_NAV_IA.nav)) ? window.KENSAI_NAV_IA.nav : [];
  const [open, setOpen] = React.useState(null);   // label of the open desktop dropdown
  const [drawer, setDrawer] = React.useState(false);
  const [expanded, setExpanded] = React.useState(null); // mobile expanded section

  const hrefOf = (it) => it.route || it.anchor || (Array.isArray(it.dropdown) && it.dropdown[0] && it.dropdown[0].route) || '#';

  // ── Desktop top-level item (link, or a dropdown trigger) ──
  const DesktopItem = (it) => {
    const hasDrop = Array.isArray(it.dropdown) && it.dropdown.length > 0;
    const isOpen = open === it.label;
    return (
      <div key={it.label}
        className="nav-ia-item"
        style={{ position: 'relative', height: '100%' }}
        onMouseEnter={() => hasDrop && setOpen(it.label)}
        onMouseLeave={() => hasDrop && setOpen(null)}>
        <a href={hrefOf(it)}
          data-nav-ia={it.label}
          style={{
            padding: '0 15px', height: '100%', display: 'flex', alignItems: 'center', gap: 6,
            fontFamily: 'var(--v4-mono)', fontSize: 10.5, letterSpacing: '0.16em',
            fontWeight: 600, color: 'var(--v4-dim)', textTransform: 'uppercase',
            borderBottom: '2px solid transparent', textDecoration: 'none',
          }}
          onMouseEnter={e => { e.currentTarget.style.color = 'var(--v4-text)'; e.currentTarget.style.borderBottom = '2px solid var(--v4-signal-line)'; }}
          onMouseLeave={e => { e.currentTarget.style.color = 'var(--v4-dim)'; e.currentTarget.style.borderBottom = '2px solid transparent'; }}>
          {navL(it.label)}{hasDrop ? <span style={{ fontSize: 8, opacity: 0.7 }}>▾</span> : null}
        </a>
        {hasDrop && isOpen && (
          <div className="nav-ia-drop" role="menu" style={{
            position: 'absolute', top: '100%', left: 0, minWidth: 240,
            background: 'rgba(8,9,11,0.98)', backdropFilter: 'blur(10px)',
            border: '1px solid var(--v4-line)', borderTop: '2px solid var(--v4-signal-line)',
            padding: '6px 0', zIndex: 60,
          }}>
            {it.dropdown.map(d => (
              <a key={d.route} href={d.route} role="menuitem" style={{
                display: 'block', padding: '9px 16px',
                fontFamily: 'var(--v4-mono)', fontSize: 11, letterSpacing: '0.06em',
                color: 'var(--v4-dim)', textDecoration: 'none', whiteSpace: 'nowrap',
              }}
              onMouseEnter={e => { e.currentTarget.style.color = 'var(--v4-text)'; e.currentTarget.style.background = 'var(--v4-bg-1)'; }}
              onMouseLeave={e => { e.currentTarget.style.color = 'var(--v4-dim)'; e.currentTarget.style.background = 'transparent'; }}>
                {navL(d.label)}
                <span className="mono" style={{ marginLeft: 8, fontSize: 9, color: 'var(--v4-faint)' }}>{d.route}</span>
              </a>
            ))}
          </div>
        )}
      </div>
    );
  };

  return (
    <nav className="nav-ia-shell" aria-label={t('nav.ariaSite')} style={{ display: 'flex', height: '100%', alignItems: 'stretch' }}>
      {/* Desktop */}
      <div className="nav-ia-desktop" style={{ display: 'flex', height: '100%' }}>
        {IA.map(DesktopItem)}
      </div>

      {/* Mobile trigger */}
      <button className="nav-ia-burger" aria-label={t('nav.ariaMenu')} aria-expanded={drawer}
        onClick={() => setDrawer(d => !d)}
        style={{
          display: 'none', background: 'transparent', border: '1px solid var(--v4-line-2)',
          width: 40, height: 32, alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', color: 'var(--v4-text)', padding: 0,
        }}>
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
          {drawer
            ? <g><line x1="3" y1="3" x2="13" y2="13"/><line x1="13" y1="3" x2="3" y2="13"/></g>
            : <g><line x1="2" y1="4" x2="14" y2="4"/><line x1="2" y1="8" x2="14" y2="8"/><line x1="2" y1="12" x2="14" y2="12"/></g>}
        </svg>
      </button>

      {/* Mobile drawer */}
      {drawer && (
        <div className="nav-ia-drawer" style={{
          position: 'fixed', top: 48, left: 0, right: 0, bottom: 0,
          background: 'var(--v4-bg)', zIndex: 49, overflowY: 'auto',
          borderTop: '1px solid var(--v4-line)', padding: '8px 0',
        }}>
          {IA.map(it => {
            const hasDrop = Array.isArray(it.dropdown) && it.dropdown.length > 0;
            const isExp = expanded === it.label;
            return (
              <div key={it.label} style={{ borderBottom: '1px solid var(--v4-line)' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <a href={hrefOf(it)} onClick={() => !hasDrop && setDrawer(false)}
                    style={{
                      flex: 1, padding: '16px 22px', fontFamily: 'var(--v4-mono)', fontSize: 13,
                      letterSpacing: '0.18em', fontWeight: 600, color: 'var(--v4-text)',
                      textTransform: 'uppercase', textDecoration: 'none',
                    }}>{navL(it.label)}</a>
                  {hasDrop && (
                    <button aria-label={t('nav.ariaExpandPrefix') + navL(it.label)} onClick={() => setExpanded(isExp ? null : it.label)}
                      style={{ background: 'transparent', border: 'none', color: 'var(--v4-signal)', padding: '0 22px', fontSize: 16, cursor: 'pointer' }}>
                      {isExp ? '−' : '+'}
                    </button>
                  )}
                </div>
                {hasDrop && isExp && (
                  <div style={{ paddingBottom: 8 }}>
                    {it.dropdown.map(d => (
                      <a key={d.route} href={d.route} onClick={() => setDrawer(false)}
                        style={{
                          display: 'block', padding: '10px 34px', fontFamily: 'var(--v4-mono)',
                          fontSize: 11, letterSpacing: '0.05em', color: 'var(--v4-dim)', textDecoration: 'none',
                        }}>{navL(d.label)} <span style={{ color: 'var(--v4-faint)', fontSize: 9 }}>{d.route}</span></a>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </nav>
  );
};

Object.assign(window, { NavIAShell });
