// ============================================================
//  Prodz — i18n. Two helpers power every screen:
//    useL()  -> { L, lang, setLang }   where L(it, en) -> string
//    tr(L, v) -> resolves a { it, en } content object (or string)
//  Language is persisted in localStorage and shared via context.
// ============================================================
const { createContext: createCtxI, useContext: useCtxI, useState: useStateI, useEffect: useEffectI } = React;

const LangContext = createCtxI(null);

function LangProvider({ children, initial }) {
  const [lang, setLangState] = useStateI(() => {
    try { return localStorage.getItem('prodz_lang') || initial || 'it'; } catch (_) { return initial || 'it'; }
  });
  const setLang = (l) => {
    setLangState(l);
    try { localStorage.setItem('prodz_lang', l); } catch (_) {}
    try { document.documentElement.lang = l; } catch (_) {}
  };
  useEffectI(() => { try { document.documentElement.lang = lang; } catch (_) {} }, [lang]);

  // L(it, en) — pick the string for the active language.
  const L = React.useCallback((it, en) => (lang === 'en' ? en : it), [lang]);

  return <LangContext.Provider value={{ lang, setLang, L }}>{children}</LangContext.Provider>;
}

function useL() {
  const ctx = useCtxI(LangContext);
  return ctx || { lang: 'it', setLang: () => {}, L: (it) => it };
}

// tr(L, value): value is a { it, en } object — or a plain string passthrough.
function tr(L, v) {
  if (v == null) return '';
  if (typeof v === 'string') return v;
  return L(v.it, v.en);
}

Object.assign(window, { LangContext, LangProvider, useL, tr });
