export async function createI18n({ locale: initialLocale, fallbackLocale, url }) {
  const cacheByLocale = {};
  let currentLocale = initialLocale;

  async function loadLocaleIfNeeded(targetLocale) {
    if (!targetLocale) return {};
    if (cacheByLocale[targetLocale]) return cacheByLocale[targetLocale];

    const base = String(url || '').replace(/\/$/, '');
    const response = await fetch(`${base}/${encodeURIComponent(targetLocale)}`, { credentials: 'same-origin' });
    const data = await response.json();
    cacheByLocale[targetLocale] = data.messages || {};
    return cacheByLocale[targetLocale];
  }

  function interpolate(template, params = {}) {
    return String(template).replace(/:([A-Za-z0-9_]+)/g, (_, key) => (params[key] ?? `:${key}`));
  }

  // Preload in parallel to avoid blocking later lookups
  await Promise.all([loadLocaleIfNeeded(fallbackLocale), loadLocaleIfNeeded(currentLocale)]);

  function __(key, params = {}) {
    const primary = (cacheByLocale[currentLocale] || {})[key];
    if (primary !== undefined) return interpolate(primary, params);

    if (fallbackLocale && fallbackLocale !== currentLocale) {
      const fallback = (cacheByLocale[fallbackLocale] || {})[key];
      if (fallback !== undefined) return interpolate(fallback, params);
    }

    return key;
  }

  function setLocale(nextLocale) {
    currentLocale = nextLocale;
  }

  // Create a synchronous version for Vue templates
  function __sync(key, params = {}) {
    const primary = (cacheByLocale[currentLocale] || {})[key];
    if (primary !== undefined) return interpolate(primary, params);

    if (fallbackLocale && fallbackLocale !== currentLocale) {
      const fallback = (cacheByLocale[fallbackLocale] || {})[key];
      if (fallback !== undefined) return interpolate(fallback, params);
    }

    return key;
  }

  return { __, setLocale, __sync, cacheByLocale, interpolate, locale: currentLocale, fallbackLocale };
}

export function createVueI18nPlugin(i18n) {
  return {
    install(app) {
      app.config.globalProperties.__ = i18n.__sync;
    },
  };
}
