// HelperMatch i18n React bindings — exposes useI18n() + LangSwitcher component.
// Requires: hm-i18n.js loaded first.
// Must be loaded as <script type="text/babel"> BEFORE any jsx that uses useI18n().

const { useState: i18nUseState, useEffect: i18nUseEffect, useCallback: i18nUseCallback, useRef: i18nUseRef } = React;

const useI18n = () => {
  const [lang, setLang] = i18nUseState(window.i18n.lang);
  i18nUseEffect(() => window.i18n.onChange((l) => setLang(l)), []);
  // t is stable in output but re-reads dict on each render (cheap)
  const t = i18nUseCallback((key, vars) => window.i18n.t(key, vars), [lang]);
  const labels = i18nUseCallback((key) => window.i18n.labels(key), [lang]);
  return { lang, setLang: window.i18n.setLang, t, labels, LANG_META: window.i18n.LANG_META };
};

// Inline dropdown switcher — use anywhere (header, footer, settings)
// props: variant ('compact' | 'full') — compact shows flag only; full shows label
const LangSwitcher = ({ variant = 'full', align = 'right', onBg = false, className = '', style = {} }) => {
  const { lang, setLang, LANG_META } = useI18n();
  const [open, setOpen] = i18nUseState(false);
  const ref = i18nUseRef(null);
  const meta = LANG_META[lang];

  i18nUseEffect(() => {
    if (!open) return;
    const h = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    setTimeout(() => document.addEventListener('mousedown', h), 0);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);

  const btnStyle = onBg
    ? { background: 'rgba(255,255,255,0.12)', color: '#fff', borderColor: 'rgba(255,255,255,0.2)' }
    : {};

  return (
    <div ref={ref} className={`hm-lang-switcher ${className}`} style={{ position: 'relative', display: 'inline-block', ...style }}>
      <button
        type="button"
        className="hm-lang-btn"
        onClick={() => setOpen(o => !o)}
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 6,
          padding: variant === 'compact' ? '6px 10px' : '7px 12px',
          fontSize: 13,
          fontWeight: 500,
          background: '#fff',
          border: '1px solid #E5E7EB',
          borderRadius: 8,
          cursor: 'pointer',
          color: '#374151',
          lineHeight: 1.2,
          ...btnStyle,
        }}
      >
        <span style={{ fontSize: 15, lineHeight: 1 }}>{meta.flag}</span>
        {variant === 'full' && <span>{meta.label}</span>}
        {variant === 'compact' && <span style={{ fontSize: 12, fontWeight: 600 }}>{meta.short}</span>}
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.5 }}><polyline points="6 9 12 15 18 9"/></svg>
      </button>
      {open && (
        <div
          role="menu"
          style={{
            position: 'absolute',
            top: 'calc(100% + 4px)',
            [align]: 0,
            minWidth: 180,
            background: '#fff',
            border: '1px solid #E5E7EB',
            borderRadius: 10,
            boxShadow: '0 8px 24px rgba(16,24,40,0.12), 0 2px 6px rgba(16,24,40,0.06)',
            padding: 4,
            zIndex: 1000,
          }}
        >
          {window.i18n.SUPPORTED.map(code => {
            const m = LANG_META[code];
            const active = code === lang;
            return (
              <button
                key={code}
                role="menuitem"
                onClick={() => { setLang(code); setOpen(false); }}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 10,
                  width: '100%',
                  padding: '8px 10px',
                  fontSize: 13,
                  background: active ? '#F3F4F6' : 'transparent',
                  border: 'none',
                  borderRadius: 6,
                  cursor: 'pointer',
                  textAlign: 'left',
                  color: active ? '#111827' : '#374151',
                  fontWeight: active ? 600 : 500,
                }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = '#F9FAFB'; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
              >
                <span style={{ fontSize: 16, lineHeight: 1 }}>{m.flag}</span>
                <span style={{ flex: 1 }}>{m.label}</span>
                {active && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#10B981" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};

window.useI18n = useI18n;
window.LangSwitcher = LangSwitcher;
