<%_ if (microfrontend) { _%>
import { loadRemote } from '@module-federation/<%- clientBundlerVite ? '' : 'enhanced/' %>runtime';
<%_ } _%>
import axios from 'axios';
import { type Composer } from 'vue-i18n';
import dayjs from 'dayjs';
import languages from '@/shared/config/languages';

export default class TranslationService {
  private readonly i18n: Composer;
  private readonly languages = languages();
  private readonly loadedLanguages: Set<string> = new Set();

  constructor(i18n: Composer) {
    this.i18n = i18n;
  }

  async refreshTranslation(newLanguage: string) {
    if (this.i18n && !this.loadedLanguages.has(newLanguage)) {
<%_ if (exposeMicrofrontend) { _%>
      this.i18n.setLocaleMessage(newLanguage, {});
      // Load translations exposed by microfrontend
<%_ } _%>
      <%- exposeMicrofrontend ? '// ' : '' %>const translations = await import(`../../i18n/${newLanguage}/${newLanguage}.js`);
      <%- exposeMicrofrontend ? '// ' : '' %>this.i18n.setLocaleMessage(newLanguage, translations.default);
<%_ if (microfrontend) { _%>

      await Promise.all([
  <%_ for (const remote of microfrontends) { _%>
        loadRemote<any>(`<%- remote.moduleFederationName %>/i18n-${newLanguage}`)
          .then(<%- remote.moduleFederationName %>Translations => this.i18n.mergeLocaleMessage(newLanguage, <%- remote.moduleFederationName %>Translations.default)),
  <%_ } _%>
      ]);
<%_ } _%>

      this.loadedLanguages.add(newLanguage);
    }
  }

  setLocale(lang: string) {
    dayjs.locale(lang);
    this.i18n.locale.value = lang;
    axios.defaults.headers.common['Accept-Language'] = lang;
    document.querySelector('html').setAttribute('lang', lang);
<%_ if (enableI18nRTL) { _%>
    this.updatePageDirection(lang);
<%_ } _%>
  }
<%_ if (enableI18nRTL) { _%>

    private isRTL(lang: string): boolean {
      return this.languages[lang]?.rtl;
    }

    private updatePageDirection(currentLanguage: string): void {
      document.querySelector('html').setAttribute('dir', this.isRTL(currentLanguage) ? 'rtl' : 'ltr');
    }
<%_ } _%>

  isLanguageSupported(lang: string) {
    return Boolean(this.languages[lang]);
  }

  getLocalStoreLanguage(): string | null {
    return localStorage.getItem('currentLanguage');
  }
}
