export const PORTAL_LOCALE_COOKIE = 'beaver_locale';
export const PORTAL_LOCALE_STORAGE_KEY = 'beaver_locale';

export const PORTAL_LOCALES = ['zh-CN', 'en-US'] as const;

export type PortalLocale = (typeof PORTAL_LOCALES)[number];

export function normalizePortalLocale(value?: string | null): PortalLocale {
  const probe = value?.trim().toLowerCase() || '';
  if (probe.startsWith('en')) {
    return 'en-US';
  }
  return 'zh-CN';
}

function readCookieLocale(): string | null {
  if (typeof document === 'undefined') {
    return null;
  }

  const match = document.cookie
    .split('; ')
    .find((item) => item.startsWith(`${PORTAL_LOCALE_COOKIE}=`));
  if (!match) {
    return null;
  }
  return decodeURIComponent(match.slice(PORTAL_LOCALE_COOKIE.length + 1));
}

export function readBrowserPortalLocale(): PortalLocale {
  if (typeof window === 'undefined') {
    return 'zh-CN';
  }

  const fromDocument = document.documentElement.lang;
  if (fromDocument) {
    return normalizePortalLocale(fromDocument);
  }

  const fromStorage = window.localStorage.getItem(PORTAL_LOCALE_STORAGE_KEY);
  if (fromStorage) {
    return normalizePortalLocale(fromStorage);
  }

  const fromCookie = readCookieLocale();
  if (fromCookie) {
    return normalizePortalLocale(fromCookie);
  }

  return normalizePortalLocale(window.navigator.language);
}

export function persistPortalLocale(locale: PortalLocale): void {
  if (typeof window === 'undefined') {
    return;
  }

  document.documentElement.lang = locale;
  window.localStorage.setItem(PORTAL_LOCALE_STORAGE_KEY, locale);
  document.cookie = `${PORTAL_LOCALE_COOKIE}=${encodeURIComponent(locale)}; path=/; max-age=31536000; samesite=lax`;
}

export function getCurrentPortalLocale(): PortalLocale {
  if (typeof window === 'undefined') {
    return 'zh-CN';
  }
  return readBrowserPortalLocale();
}

export function pickPortalText<T>(locale: PortalLocale, zhValue: T, enValue: T): T {
  return locale === 'en-US' ? enValue : zhValue;
}
