// src/i18n.ts
import { createI18n } from "vue-i18n";

const modules = import.meta.glob("./locales/*.json", { eager: true });

const messages: Record<string, any> = {};

for (const path in modules) {
  const matched = path.match(/\.\/locales\/(.*)\.json$/);

  if (matched) {
    const locale = matched[1];
    messages[locale] = (modules[path] as any).default;
  }
}

export type MessageSchema = (typeof messages)["tr"];

const getInitialLocale = (): keyof typeof messages => {
  try {
    const storedLang = localStorage.getItem("lang");

    if (storedLang && storedLang in messages) {
      return storedLang as keyof typeof messages;
    }
  } catch {}

  return "tr";
};

const currentLocale = getInitialLocale();

if (typeof document !== "undefined") {
  document.documentElement.lang = currentLocale;
}

const i18n = createI18n<[MessageSchema], keyof typeof messages>({
  legacy: false,
  locale: currentLocale,
  fallbackLocale: "tr",
  messages,
});

export default i18n;
