import { browser } from '$app/environment';
import { loadTranslations, setLocale, setRoute } from '$lib/translations';
import { SUPPORTED_LOCALES } from '$lib/translations';

/**
 * @param {string | null} loc
 * @returns {loc is "en-US" | "pt-BR"}
 */
function isSupportedLocale(loc) {
  // @ts-ignore
  return loc !== null && Object.values(SUPPORTED_LOCALES).includes(loc);
}

/** @type {import('@sveltejs/kit').Load} */
export const load = async ({ data, url }) => {
  const route = url.pathname;

  /** @type {"en-US" | "pt-BR"} */
  let language;

  if (browser) {
    const stored = localStorage.getItem('locale');

    if (isSupportedLocale(stored)) {
      language = stored;
    } else {
      language = data?.fallbackLanguage ?? SUPPORTED_LOCALES.EN_US;
    }

    document.documentElement.lang = language;

    await loadTranslations(language, route);
    await setLocale(language);
    await setRoute(route);
  }

  return {};
};
