import i18n from '../i18n';

export type SupportedLocale = 'de' | 'en';

export const SUPPORTED_LANGUAGES: Array<{ code: SupportedLocale; labelKey: string }> = [
  { code: 'de', labelKey: 'language.de' },
  { code: 'en', labelKey: 'language.en' },
];

function getCsrfToken(): string {
  return document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content ?? '';
}

async function persistLocale(locale: SupportedLocale): Promise<void> {
  const response = await fetch('/set-locale', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCsrfToken(),
      Accept: 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
    },
    body: JSON.stringify({ locale }),
    credentials: 'include',
  });

  if (!response.ok) {
    throw new Error(`locale update failed with status ${response.status}`);
  }
}

export function getCurrentLocale(): SupportedLocale {
  return (i18n.language || document.documentElement.lang || 'de') as SupportedLocale;
}

export async function switchLocale(locale: SupportedLocale): Promise<void> {
  await persistLocale(locale);
  await i18n.changeLanguage(locale);
  document.documentElement.setAttribute('lang', locale);
}
