// Sportistry marketing website — i18n.jsx
// Bilingual (HU / EN) support. Loaded BEFORE the other scripts so the
// `tr()` helper and `sportLabel()` are global by the time anything renders.
//
// Mechanism: the active language lives on `window.__lang` (single source of
// truth). `tr(en, hu)` reads it at call time, so every string is resolved on
// each render. `setSiteLang()` updates it, persists the choice, and asks the
// Root component to re-render via `window.__onLangChange`. Because the data
// arrays (events, FAQ, posts…) are built inside render via helper functions,
// switching language re-localises everything — nothing is frozen at load.

(function initLang() {
  const KEY = 'sb_site_lang';
  function detect() {
    try {
      const saved = localStorage.getItem(KEY);
      if (saved === 'hu' || saved === 'en') return saved;
    } catch (e) {}
    try {
      if ((navigator.language || '').toLowerCase().startsWith('hu')) return 'hu';
    } catch (e) {}
    return 'hu'; // Hungarian-first product
  }
  window.__lang = detect();
  try { document.documentElement.lang = window.__lang; } catch (e) {}
})();

// Resolve a string for the active language.
function tr(en, hu) { return window.__lang === 'hu' ? hu : en; }

// Change language: persist, update <html lang>, and re-render the app.
function setSiteLang(lang) {
  if (lang !== 'hu' && lang !== 'en') return;
  window.__lang = lang;
  try { localStorage.setItem('sb_site_lang', lang); } catch (e) {}
  try { document.documentElement.lang = lang; } catch (e) {}
  if (typeof window.__onLangChange === 'function') window.__onLangChange(lang);
}

// Localised sport names (the tints/keys live in WEB_SPORTS in components.jsx).
function sportLabel(key) {
  const M = {
    soccer:   tr('Soccer', 'Foci'),
    basket:   tr('Basketball', 'Kosárlabda'),
    tennis:   tr('Tennis', 'Tenisz'),
    running:  tr('Running', 'Futás'),
    cycling:  tr('Cycling', 'Kerékpár'),
    volley:   tr('Volleyball', 'Röplabda'),
    climbing: tr('Climbing', 'Mászás'),
    padel:    tr('Padel', 'Padel'),
    fitness:  tr('Fitness', 'Fitnesz'),
    swimming:    tr('Swimming', 'Úszás'),
    hiking:      tr('Hiking', 'Túrázás'),
    badminton:   tr('Badminton', 'Tollaslabda'),
    yoga:        tr('Yoga', 'Jóga'),
    bouldering:  tr('Bouldering', 'Bouldering'),
    boxing:      tr('Boxing', 'Box'),
    handball:    tr('Handball', 'Kézilabda'),
    golf:        tr('Golf', 'Golf'),
    martialarts: tr('Martial Arts', 'Harcművészet'),
    hockey:      tr('Hockey', 'Hoki'),
    baseball:    tr('Baseball', 'Baseball'),
  };
  return M[key] || key;
}

// ───────────────────── Language dropdown (sits in the nav) ─────────────────────
function LangToggle() {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const cur = window.__lang;
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);
  const opts = [['hu', 'Magyar'], ['en', 'English']];
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} aria-label={tr('Change language', 'Nyelvváltás')} style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        background: 'rgba(255,255,255,0.10)', color: 'white',
        border: '1px solid rgba(255,255,255,0.16)', borderRadius: 999,
        padding: '7px 11px', cursor: 'pointer',
        fontFamily: FB, fontWeight: 700, fontSize: 13, lineHeight: 1, whiteSpace: 'nowrap',
      }}
        onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.18)'}
        onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.10)'}>
        <WIcon name="globe" size={15} color="rgba(255,255,255,0.85)"/>
        {cur === 'hu' ? 'HU' : 'EN'}
        <WIcon name="chevronDown" size={14} color="rgba(255,255,255,0.7)"/>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0, minWidth: 150,
          background: '#121726', border: '1px solid rgba(255,255,255,0.10)', borderRadius: 12,
          boxShadow: '0 18px 40px rgba(0,0,0,0.45)', padding: 6, zIndex: 60,
        }}>
          {opts.map(([code, label]) => {
            const active = cur === code;
            return (
              <button key={code} onClick={() => { setSiteLang(code); setOpen(false); }} style={{
                width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                background: active ? 'rgba(198,247,60,0.12)' : 'transparent',
                color: active ? SB.lime : 'rgba(255,255,255,0.85)',
                border: 'none', borderRadius: 8, padding: '10px 12px', cursor: 'pointer', textAlign: 'left',
                fontFamily: FB, fontWeight: 600, fontSize: 14,
              }}
                onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'rgba(255,255,255,0.06)'; }}
                onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
                {label}
                {active && <WIcon name="check" size={15} color={SB.lime}/>}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { tr, setSiteLang, sportLabel, LangToggle });
