// lalako-shared.jsx — shared header, i18n, lang selector for stories pages

const { useState, useContext, createContext, useEffect, useRef } = React;

/* ══════════════════════════════════════════════
   i18n for stories section
   ══════════════════════════════════════════════ */
const STORIES_I18N = {
  en: {
    practice:'Practice', stories:'Stories', about:'About', koreanReading:'Korean Reading', allLevels:'All',
    showTranslation:'Show translation', hideTranslation:'Hide translation',
    backToStories:'← Back to stories', translation:'Translation',
  },
  ru: {
    practice:'Практика', stories:'Истории', about:'О сайте', koreanReading:'Чтение на корейском', allLevels:'Все',
    showTranslation:'Показать перевод', hideTranslation:'Скрыть перевод',
    backToStories:'← К историям', translation:'Перевод',
  },
  kk: {
    practice:'Жаттығу', stories:'Әңгімелер', about:'Сайт туралы', koreanReading:'Корейше оқу', allLevels:'Барлығы',
    showTranslation:'Аудармасын көрсету', hideTranslation:'Аудармасын жасыру',
    backToStories:'← Әңгімелерге', translation:'Аударма',
  },
  uz: {
    practice:'Mashq', stories:'Hikoyalar', about:'Sayt haqida', koreanReading:'Koreyscha oʻqish', allLevels:'Barchasi',
    showTranslation:'Tarjimani koʻrsatish', hideTranslation:'Tarjimani yashirish',
    backToStories:'← Hikoyalarga', translation:'Tarjima',
  },
  ky: {
    practice:'Машыгуу', stories:'Окуялар', about:'Сайт жөнүндө', koreanReading:'Корейче окуу', allLevels:'Баары',
    showTranslation:'Котормосун көрсөтүү', hideTranslation:'Котормосун жашыруу',
    backToStories:'← Окуяларга', translation:'Котормо',
  },
  es: {
    practice:'Práctica', stories:'Historias', about:'Acerca de', koreanReading:'Lectura en coreano', allLevels:'Todos',
    showTranslation:'Mostrar traducción', hideTranslation:'Ocultar traducción',
    backToStories:'← Volver a historias', translation:'Traducción',
  },
  ja: {
    practice:'練習', stories:'読み物', about:'このサイト', koreanReading:'韓国語リーディング', allLevels:'すべて',
    showTranslation:'翻訳を表示', hideTranslation:'翻訳を隠す',
    backToStories:'← 読み物一覧へ', translation:'翻訳',
  },
  zh: {
    practice:'练习', stories:'故事', about:'关于', koreanReading:'韩语阅读', allLevels:'全部',
    showTranslation:'显示翻译', hideTranslation:'隐藏翻译',
    backToStories:'← 返回故事列表', translation:'翻译',
  },
};

/* ── Languages ── */
const SITE_LANGS = [
  { code:'en', label:'English', flag:'🇬🇧' },
  { code:'ru', label:'Русский', flag:'🇷🇺' },
  { code:'kk', label:'Қазақша', flag:'🇰🇿' },
  { code:'uz', label:"O'zbek", flag:'🇺🇿' },
  { code:'ky', label:'Кыргызча', flag:'🇰🇬' },
  { code:'es', label:'Español', flag:'🇪🇸' },
  { code:'ja', label:'日本語', flag:'🇯🇵' },
  { code:'zh', label:'中文', flag:'🇨🇳' },
];

/* ── Context ── */
const SiteLangCtx = createContext(null);
function useSiteLang() { return useContext(SiteLangCtx); }
function useSiteTxt() {
  const { lang } = useSiteLang();
  return STORIES_I18N[lang] || STORIES_I18N.en;
}

/* ── Palette ── */
const SC = {
  accent:'#7c5ce0', accentLight:'#ede8fc', accentMid:'#b8a5f0',
  bg:'#f5f4f8', white:'#ffffff', text:'#1e1e2e', textSec:'#6e6b7b',
  textTer:'#a9a6b5', border:'#e8e6ef',
};

/* ── LangProvider ── */
function SiteLangProvider({ children }) {
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem('lalako-lang') || 'en'; } catch(e) { return 'en'; }
  });
  useEffect(() => {
    try { localStorage.setItem('lalako-lang', lang); } catch(e) {}
  }, [lang]);
  return React.createElement(SiteLangCtx.Provider, { value: { lang, setLang } }, children);
}

/* ══════════════════════════════════════════════
   Language selector (mirrors main site)
   ══════════════════════════════════════════════ */
function SiteLangSelector() {
  const [open, setOpen] = useState(false);
  const { lang, setLang } = useSiteLang();
  const cur = SITE_LANGS.find(l => l.code === lang) || SITE_LANGS[0];
  const ref = useRef(null);
  useEffect(() => {
    function close(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, []);
  return (
    <div ref={ref} style={{ position:'relative' }}>
      <button onClick={() => setOpen(!open)} style={{ display:'flex', alignItems:'center', gap:6, border:'1px solid #e8e6ef', background:'#fff', borderRadius:10, padding:'7px 12px', fontSize:13, fontWeight:500, cursor:'pointer', fontFamily:'inherit', color:SC.text, transition:'border-color 0.2s' }}>
        <span>{cur.flag}</span><span>{cur.label}</span>
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke={SC.textSec} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : '', transition:'transform 0.2s' }}><path d="M3 4.5L6 7.5L9 4.5"/></svg>
      </button>
      {open && (
        <div style={{ position:'absolute', right:0, top:'calc(100% + 6px)', background:'#fff', borderRadius:14, padding:6, boxShadow:'0 4px 24px rgba(0,0,0,0.12)', border:'1px solid #f0edf6', zIndex:50, minWidth:160, animation:'fadeUp 0.2s ease' }}>
          {SITE_LANGS.map(l => (
            <button key={l.code} onClick={() => { setLang(l.code); setOpen(false); }}
              style={{ display:'flex', alignItems:'center', gap:8, width:'100%', border:'none', background: lang === l.code ? '#f0edf6' : 'transparent', borderRadius:10, padding:'8px 12px', fontSize:13, fontWeight:500, cursor:'pointer', fontFamily:'inherit', color:SC.text, transition:'background 0.15s' }}
              onMouseEnter={e => { if (lang !== l.code) e.currentTarget.style.background = '#f8f7fc'; }}
              onMouseLeave={e => { if (lang !== l.code) e.currentTarget.style.background = 'transparent'; }}>
              <span>{l.flag}</span><span>{l.label}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ══════════════════════════════════════════════
   Site header (shared across stories pages)
   ══════════════════════════════════════════════ */
function SiteHeader({ activePage }) {
  const txt = useSiteTxt();
  const { lang } = useSiteLang();
  const isPractice = activePage === 'practice';
  const isStories = activePage === 'stories';
  const isAbout = activePage === 'about';
  const aboutLangMap = {en:'about-en.html',ru:'about-ru.html',kk:'about-kk.html',uz:'about-uz.html',ky:'about-ky.html',es:'about-es.html',ja:'about-ja.html',zh:'about-zh.html'};
  const aboutHref = aboutLangMap[lang] || 'about-en.html';
  return (
    <header className="app-header" style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'16px 40px', borderBottom:'1px solid #f0edf6', background:'#fff', position:'sticky', top:0, zIndex:20 }}>
      <div style={{ display:'flex', alignItems:'center', gap:20 }}>
        <a href="index.html" className="app-header-logo" style={{ display:'flex', alignItems:'center', gap:8, textDecoration:'none' }}>
          <span style={{ fontSize:20, fontWeight:800, color:SC.accent }}>한</span>
          <span style={{ fontSize:16, fontWeight:700, color:SC.text }}>Lalako</span>
        </a>
        <a href="index.html" className="header-nav-link" style={{ fontSize:14, fontWeight:600, color: isPractice ? SC.accent : SC.textSec, textDecoration:'none', transition:'color 0.2s' }}
          onMouseEnter={e => e.currentTarget.style.color = SC.accent}
          onMouseLeave={e => { if (!isPractice) e.currentTarget.style.color = SC.textSec; }}>
          {txt.practice}
        </a>
        <a href="stories.html" className="header-nav-link" style={{ fontSize:14, fontWeight:600, color: isStories ? SC.accent : SC.textSec, textDecoration:'none', transition:'color 0.2s' }}
          onMouseEnter={e => e.currentTarget.style.color = SC.accent}
          onMouseLeave={e => { if (!isStories) e.currentTarget.style.color = SC.textSec; }}>
          {txt.stories}
        </a>
        <a href={aboutHref} className="header-nav-link" style={{ fontSize:14, fontWeight:600, color: isAbout ? SC.accent : SC.textSec, textDecoration:'none', transition:'color 0.2s' }}
          onMouseEnter={e => e.currentTarget.style.color = SC.accent}
          onMouseLeave={e => { if (!isAbout) e.currentTarget.style.color = SC.textSec; }}>
          {txt.about}
        </a>
      </div>
      <nav style={{ display:'flex', gap:4, alignItems:'center' }}>
        <SiteLangSelector/>
      </nav>
    </header>
  );
}

Object.assign(window, {
  STORIES_I18N, SITE_LANGS, SiteLangCtx, useSiteLang, useSiteTxt, SC,
  SiteLangProvider, SiteLangSelector, SiteHeader,
});
