/* Tiny i18n layer.
   - LanguageProvider wraps the app and holds the current locale ('en' | 'es').
   - useT() returns { t, lang, setLang } where t('hero.title_pre') resolves a dotted path.
   - Default locale on first load is Spanish; toggle persists in localStorage.

   To add a third language later: add window.TB_STRINGS_XX in i18n/xx.js,
   register it in DICTS, and add it to the toggle.
*/
(function () {
  const { createContext, useContext, useState, useMemo, useEffect } = React;

  const DICTS = {
    en: () => window.TB_STRINGS_EN,
    es: () => window.TB_STRINGS_ES
  };

  const STORAGE_KEY = "tb_lang";
  const DEFAULT_LANG = "es"; // load Spanish first

  function getInitialLang() {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved && DICTS[saved]) return saved;
    } catch (e) {}
    return DEFAULT_LANG;
  }

  // Resolve a dotted path against a dict; return the path itself if missing
  // so untranslated strings are visible during development.
  function resolve(dict, path) {
    if (!dict) return path;
    const parts = path.split(".");
    let cur = dict;
    for (let i = 0; i < parts.length; i++) {
      if (cur == null) return path;
      cur = cur[parts[i]];
    }
    return cur === undefined ? path : cur;
  }

  const LanguageContext = createContext({ lang: DEFAULT_LANG, setLang: () => {}, t: (k) => k });

  function LanguageProvider({ children }) {
    const [lang, setLangState] = useState(getInitialLang);

    useEffect(() => {
      try { localStorage.setItem(STORAGE_KEY, lang); } catch (e) {}
      document.documentElement.setAttribute("lang", lang);
      const dict = DICTS[lang] && DICTS[lang]();
      const title = dict && dict.meta && dict.meta.title;
      if (title) document.title = title;
    }, [lang]);

    const value = useMemo(() => {
      const dict = DICTS[lang] && DICTS[lang]();
      return {
        lang,
        setLang: (next) => { if (DICTS[next]) setLangState(next); },
        toggle: () => setLangState(lang === "en" ? "es" : "en"),
        t: (path) => resolve(dict, path)
      };
    }, [lang]);

    return React.createElement(LanguageContext.Provider, { value }, children);
  }

  function useT() {
    return useContext(LanguageContext);
  }

  function useMobile() {
    const [mobile, setMobile] = React.useState(() => window.innerWidth < 768);
    React.useEffect(() => {
      const fn = () => setMobile(window.innerWidth < 768);
      window.addEventListener("resize", fn, { passive: true });
      return () => window.removeEventListener("resize", fn);
    }, []);
    return mobile;
  }

  window.LanguageProvider = LanguageProvider;
  window.useT = useT;
  window.useMobile = useMobile;
})();
