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

/**
 * Type guard that checks if a string is a supported locale.
 * @param {string | null} locale
 * @returns {locale is "en-US" | "pt-BR"}
 */
function isSupportedLocale(locale) {
  // @ts-ignore
  return locale !== null && Object.values(SUPPORTED_LOCALES).includes(locale);
}

/**
 * Client-side load function to initialize translations based on localStorage or server fallback.
 *
 * This function runs in the browser and:
 * - Prioritizes locale from localStorage (if valid)
 * - Falls back to the server-provided fallbackLanguage (from Accept-Language)
 * - Initializes translations and routing
 *
 * @type {import('@sveltejs/kit').Load}
 */
export const load = async ({ data, url }) => {
  /** @type {string} */
  const route = url.pathname;

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

  if (browser) {
    /**
     * Locale stored in the browser, if any.
     * @type {string | null}
     */
    const stored = localStorage.getItem('locale');

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

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

  return {};
};
