/** The Conscious Code — tiny i18n layer.
 *
 * A global language store (ES default, EN = plain American English) that any
 * component can subscribe to via useLang() / useT(). The Nav toggle flips
 * langStore and every subscribed component re-renders with the other language.
 *
 * Usage in a component:
 *   const t = useT();
 *   <h2>{t('Hola mundo', 'Hello world')}</h2>
 *
 * Data arrays: build them inside the component body (they re-evaluate on
 * re-render) and wrap each string with t(es, en).
 */

const LANG_KEY = 'tcc-lang';

const langStore = {
  lang: (typeof localStorage !== 'undefined' && localStorage.getItem(LANG_KEY)) || 'ES',
  listeners: new Set(),
  set(next) {
    if (next === this.lang) return;
    this.lang = next;
    try { localStorage.setItem(LANG_KEY, next); } catch (e) {}
    if (typeof document !== 'undefined') document.documentElement.lang = next.toLowerCase();
    this.listeners.forEach((fn) => fn());
  },
  toggle() { this.set(this.lang === 'ES' ? 'EN' : 'ES'); },
  subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); },
};

// Keep <html lang> in sync on first load.
if (typeof document !== 'undefined') document.documentElement.lang = langStore.lang.toLowerCase();

/** Subscribe a component to language changes. Returns { lang, setLang, t }. */
function useLang() {
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => langStore.subscribe(force), []);
  const t = React.useCallback(
    (es, en) => (langStore.lang === 'EN' ? (en === undefined ? es : en) : es),
    [langStore.lang]
  );
  return { lang: langStore.lang, setLang: (l) => langStore.set(l), toggle: () => langStore.toggle(), t };
}

/** Shorthand when you only need the translate function. */
function useT() {
  return useLang().t;
}

Object.assign(window, { langStore, useLang, useT });
