/**
 * 247ChatMate — Prebuilt Replies Loader
 * JSON-first, safe, cacheable, race-safe
 */

(function () {

  if (window.MATEWA_PREBUILT) return;

  window.MATEWA_PREBUILT = {};
  window.MATEWA_PREBUILT_LOADED = {};
  window.MATEWA_PREBUILT_LOADING = {};

  /**
   * Load language JSON on demand
   */
  window.matewaLoadLanguage = function (lang) {

    if (!lang) lang = 'en';

    // Normalise (pt_BR → pt-br)
    lang = lang.toLowerCase().replace('_', '-');

    // Already loaded
    if (window.MATEWA_PREBUILT_LOADED[lang]) {
      return Promise.resolve(window.MATEWA_PREBUILT[lang]);
    }

    // Already loading
    if (window.MATEWA_PREBUILT_LOADING[lang]) {
      return window.MATEWA_PREBUILT_LOADING[lang];
    }

    const base =
      window.MATEWA_I18N_BASE ||
      '/wp-content/plugins/247chatmate/public/i18n';

    const url = `${base}/${lang}.json`;

    window.MATEWA_PREBUILT_LOADING[lang] = fetch(url, {
      credentials: 'same-origin'
    })
      .then(res => {
        if (!res.ok) throw new Error('Language not found');
        return res.json();
      })
      .then(json => {
        window.MATEWA_PREBUILT[lang] = json;
        window.MATEWA_PREBUILT_LOADED[lang] = true;
        delete window.MATEWA_PREBUILT_LOADING[lang];
        return json;
      })
      .catch(() => {
        delete window.MATEWA_PREBUILT_LOADING[lang];

        // Fallback to English
        if (lang !== 'en') {
          return window.matewaLoadLanguage('en');
        }

        return null;
      });

    return window.MATEWA_PREBUILT_LOADING[lang];
  };

})();
