// ── Klempnerei Walter — locale context ────────────────────────────────────
// Reads ?lang= on load; updates URL + html[lang] on switch.
// Requires window.TRANSLATIONS (translations.js loaded first).

const LOCALES = ['de', 'en', 'es'];

function getInitialLocale() {
  const param   = new URLSearchParams(window.location.search).get('lang');
  if (LOCALES.includes(param)) return param;
  const browser = (navigator.language || 'de').slice(0, 2).toLowerCase();
  return LOCALES.includes(browser) ? browser : 'de';
}

const LocaleContext = React.createContext({ locale: 'de', setLocale: () => {} });

function LocaleProvider({ children }) {
  const [locale, setLocaleState] = React.useState(getInitialLocale);

  const setLocale = React.useCallback((lang) => {
    if (!LOCALES.includes(lang)) return;
    setLocaleState(lang);
    const url = new URL(window.location.href);
    url.searchParams.set('lang', lang);
    window.history.replaceState({}, '', url);
    document.documentElement.lang = lang;
  }, []);

  // Sync html[lang] on first render
  React.useEffect(() => { document.documentElement.lang = locale; }, [locale]);

  return (
    <LocaleContext.Provider value={{ locale, setLocale }}>
      {children}
    </LocaleContext.Provider>
  );
}

const useLocale    = () => React.useContext(LocaleContext).locale;
const useSetLocale = () => React.useContext(LocaleContext).setLocale;
const useT         = () => TRANSLATIONS[React.useContext(LocaleContext).locale];

Object.assign(window, { LOCALES, LocaleContext, LocaleProvider, useLocale, useSetLocale, useT });
