import { createI18n } from 'vue-i18n';
import yaml from 'js-yaml';

export const lang = [];

const systemLocale = navigator.language || 'en-US';
const savedLang = localStorage.getItem('lang');

const messages = {};
const modules = import.meta.glob('src/assets/lang/*.yaml', {
  eager: true,
  import: 'default',
  query: '?raw',
});

for (const path in modules) {
  const raw = modules[path];
  const parsed = yaml.load(raw);

  // Extract the file name (e.g., "en.yaml" → "en")
  const locale = path.split('/').pop().replace('.yaml', '');

  lang.push(locale);
  messages[locale] = parsed;
}

const i18n = createI18n({
  legacy: false, // Composition API mode
  locale: savedLang || systemLocale,
  fallbackLocale: systemLocale,
  messages,
});

export default ({ app }) => {
  app.use(i18n);
};

export { i18n };
