/* i18n.jsx — bilingual TH/EN system
 * - Global `t({th, en})` helper for pair-style strings
 * - LangContext + useLang() hook for components that need to react
 * - LangToggle pill component (TH | EN)
 * - Default = TH, persisted to localStorage
 */

const LangContext = React.createContext({ lang: 'th', setLang: () => {} });

function LangProvider({ children }) {
  const [lang, setLang] = React.useState(() => {
    try { return localStorage.getItem('kiosk-lang') || 'th'; }
    catch { return 'th'; }
  });
  React.useEffect(() => {
    try { localStorage.setItem('kiosk-lang', lang); } catch {}
    window.__lang = lang;
    // notify any non-React listeners
    window.dispatchEvent(new CustomEvent('kiosk-lang-change', { detail: lang }));
  }, [lang]);
  return (
    <LangContext.Provider value={{ lang, setLang }}>
      {children}
    </LangContext.Provider>
  );
}

function useLang() {
  return React.useContext(LangContext);
}

/**
 * t(pair) — pick the right string by current global lang.
 * Accepts:
 *   t({ th: 'สวัสดี', en: 'Hello' })
 *   t({ th: 'A', en: 'B' }, 'en')   // explicit lang override
 *   t('plain string')                // pass-through
 */
function t(pair, langOverride) {
  if (pair == null) return '';
  if (typeof pair === 'string' || typeof pair === 'number') return pair;
  const lang = langOverride || window.__lang || 'th';
  if (typeof pair === 'object') {
    return pair[lang] != null ? pair[lang] : (pair.th != null ? pair.th : pair.en || '');
  }
  return String(pair);
}

/**
 * useT() — hook version that re-renders on lang change.
 * Returns (pair) => string scoped to current language.
 */
function useT() {
  const { lang } = useLang();
  return React.useCallback((pair) => t(pair, lang), [lang]);
}

// ─────────────────────────────────────────────────────────────
// Lang toggle pill — TH | EN
// ─────────────────────────────────────────────────────────────
function LangToggle({ size = 'md', tone = 'light' }) {
  const { lang, setLang } = useLang();
  const isDark = tone === 'dark';
  const wrapCls = size === 'sm'
    ? 'h-8 p-0.5'
    : size === 'lg'
    ? 'h-10 sm:h-12 md:h-14 p-1'
    : 'h-9 sm:h-10 p-1';
  const btnCls = size === 'sm'
    ? 'px-3 font-bold leading-none text-sm'
    : size === 'lg'
    ? 'px-4 sm:px-5 font-bold leading-none text-base sm:text-lg lg:text-xl'
    : 'px-3 sm:px-4 font-bold leading-none text-base';
  return (
    <div className={wrapCls} style={{
      display: 'inline-flex',
      background: isDark ? 'rgba(255,255,255,.12)' : '#F1F9F9',
      border: `1px solid ${isDark ? 'rgba(255,255,255,.18)' : 'rgba(47,82,82,.15)'}`,
      borderRadius: 999,
      alignItems: 'center', gap: 0,
    }}>
      {['th', 'en'].map(L => {
        const active = lang === L;
        return (
          <button
            key={L}
            onClick={() => setLang(L)}
            className={btnCls}
            style={{
              border: 'none',
              background: active ? (isDark ? '#fff' : '#2F5252') : 'transparent',
              color: active ? (isDark ? '#2F5252' : '#fff') : (isDark ? 'rgba(255,255,255,.85)' : '#2F5252'),
              height: '100%',
              borderRadius: 999,
              letterSpacing: 1.2,
              cursor: 'pointer',
              transition: 'all .15s',
            }}>
            {L === 'th' ? 'ไทย' : 'EN'}
          </button>
        );
      })}
    </div>
  );
}

window.LangContext = LangContext;
window.LangProvider = LangProvider;
window.useLang = useLang;
window.useT = useT;
window.t = t;
window.LangToggle = LangToggle;

// initialize default
window.__lang = (function() {
  try { return localStorage.getItem('kiosk-lang') || 'th'; } catch { return 'th'; }
})();
