import { defaultLocale, supportedLocales } from "./types.ts";
import type { SupportedLocale } from "./types.ts";

export function isSupportedLocale(locale: string | null | undefined): locale is SupportedLocale {
  return supportedLocales.includes(locale as SupportedLocale);
}

export function resolveLocaleFromNavigator(languages: readonly string[] = []): SupportedLocale {
  for (const language of languages) {
    const normalizedLanguage = language.toLowerCase();

    if (normalizedLanguage.startsWith("zh")) {
      return "zh-CN";
    }

    if (normalizedLanguage.startsWith("en")) {
      return "en-US";
    }

    if (normalizedLanguage.startsWith("th")) {
      return "th-TH";
    }
  }

  return defaultLocale;
}

type ResolveInitialLocaleOptions = {
  storedLocale?: string | null;
  navigatorLanguages?: readonly string[];
};

export function resolveInitialLocale(options: ResolveInitialLocaleOptions = {}): SupportedLocale {
  if (isSupportedLocale(options.storedLocale)) {
    return options.storedLocale;
  }

  return resolveLocaleFromNavigator(options.navigatorLanguages);
}
