/* global React */

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

const useLang = () => React.useContext(LangContext);

const T = ({ no, en }) => {
  const { lang } = useLang();
  return lang === 'no' ? no : en;
};

const tt = (lang, no, en) => (lang === 'no' ? no : en);

const LangProvider = ({ children }) => {
  const [lang, setLangRaw] = React.useState(() => {
    try {
      return localStorage.getItem('normedisin-lang') || 'no';
    } catch (_e) {
      return 'no';
    }
  });
  const setLang = React.useCallback((next) => {
    setLangRaw(next);
    try { localStorage.setItem('normedisin-lang', next); } catch (_e) { /* noop */ }
  }, []);
  React.useEffect(() => {
    document.documentElement.lang = lang === 'no' ? 'nb' : 'en';
  }, [lang]);
  return (
    <LangContext.Provider value={{ lang, setLang }}>
      {children}
    </LangContext.Provider>
  );
};

const LangToggle = () => {
  const { lang, setLang } = useLang();
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      border: '1px solid var(--border-subtle-01)',
      height: 28, padding: 0, overflow: 'hidden',
    }}>
      {['no', 'en'].map((code) => {
        const active = lang === code;
        return (
          <button
            key={code}
            type="button"
            onClick={() => setLang(code)}
            style={{
              padding: '0 10px', height: '100%',
              background: active ? 'var(--background-selected)' : 'transparent',
              color: active ? 'var(--text-primary)' : 'var(--text-secondary)',
              border: 'none', cursor: 'pointer',
              font: '600 11px/1 var(--font-mono)', letterSpacing: '0.32px', textTransform: 'uppercase',
              transition: 'background 70ms var(--easing-standard-productive)',
            }}
            aria-pressed={active}
          >
            {code}
          </button>
        );
      })}
    </div>
  );
};

window.LangContext = LangContext;
window.LangProvider = LangProvider;
window.LangToggle = LangToggle;
window.useLang = useLang;
window.T = T;
window.tt = tt;
