import { acceptHMRUpdate, defineStore } from 'pinia';

export const languageCodes = ['it', 'en', 'en_us', 'de', 'de_ch', 'fr', 'fr_ch'] as const;

export type LanguageCode = (typeof languageCodes)[number];

export const DEFAULT_LANGUAGE: LanguageCode = 'it';
export const LANGUAGE_STORAGE_KEY = 'preferences.language';

function isLanguageCode(value: string): value is LanguageCode {
  return languageCodes.includes(value as LanguageCode);
}

export function loadStoredLanguage(): LanguageCode {
  if (typeof localStorage === 'undefined') {
    return DEFAULT_LANGUAGE;
  }

  const storedLanguage = localStorage.getItem(LANGUAGE_STORAGE_KEY);

  if (storedLanguage && isLanguageCode(storedLanguage)) {
    return storedLanguage;
  }

  return DEFAULT_LANGUAGE;
}

export function resolveI18nLocale(language: LanguageCode): LanguageCode {
  switch (language) {
    case 'it':
    case 'en':
    case 'en_us':
    case 'de':
    case 'de_ch':
    case 'fr':
    case 'fr_ch':
      return language;
  }
}

export const usePreferencesStore = defineStore('preferences', {
  state: () => ({
    language: loadStoredLanguage(),
  }),

  actions: {
    setLanguage(language: LanguageCode) {
      this.language = language;

      if (typeof localStorage !== 'undefined') {
        localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
      }
    },
  },
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(usePreferencesStore, import.meta.hot));
}
