// CountryContext — provider + hook useCountry()
// Résolution du pays par ordre de priorité :
//   1. Prop `country` passée au CountryProvider (priorité absolue, set par chaque shell HTML)
//   2. Query string ?country=mx|co (override pour dev/test)
//   3. localStorage.cb_country (persistance du choix utilisateur via switcher)
//   4. URL pathname (/mx/... ou /co/...)
//   5. Fallback : 'co' (avec USD pré-activé via ?currency=usd)
// Expuesto en window.CountryProvider, window.useCountry, window.swapCountryUrl.

const CountryContext = React.createContext(null);

const STORAGE_KEY = 'cb_country';
const VALID_COUNTRIES = ['mx', 'co'];

const resolveInitialCountry = (forced) => {
  if (forced && VALID_COUNTRIES.includes(forced)) return forced;
  if (typeof window === 'undefined') return 'co';
  try {
    const url = new URL(window.location.href);
    const q = url.searchParams.get('country');
    if (q && VALID_COUNTRIES.includes(q)) return q;
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored && VALID_COUNTRIES.includes(stored)) return stored;
    const path = url.pathname;
    if (path.startsWith('/mx/') || path === '/mx') return 'mx';
    if (path.startsWith('/co/') || path === '/co') return 'co';
  } catch (e) {
    // ignore
  }
  return 'co';
};

const getLocale = (country) => {
  if (country === 'mx') return window.MX_LOCALE;
  return window.CO_LOCALE;
};

// Échange le préfixe pays dans une URL : /mx/foo → /co/foo, /co/foo → /mx/foo.
// Si l'URL n'a pas de préfixe pays, on l'ajoute.
const swapCountryUrl = (pathname, targetCountry) => {
  if (!pathname) return `/${targetCountry}/`;
  if (pathname.startsWith('/mx/') || pathname.startsWith('/co/')) {
    return '/' + targetCountry + pathname.slice(3);
  }
  if (pathname === '/mx' || pathname === '/co') {
    return '/' + targetCountry;
  }
  // Pour les anciens URLs racines (/, /precios.html, /funcionalidades/..., /blog/...),
  // on préfixe avec /<country> seulement si la cible est /mx/ ou /co/ et que la page existe.
  // Plus simple : pour l'instant on renvoie vers la home du pays cible.
  return '/' + targetCountry + '/';
};

const CountryProvider = ({ country: forcedCountry, children }) => {
  const [country, setCountryState] = React.useState(() => resolveInitialCountry(forcedCountry));

  const setCountry = React.useCallback((c, opts = {}) => {
    if (!VALID_COUNTRIES.includes(c)) return;
    try { localStorage.setItem(STORAGE_KEY, c); } catch (e) {}
    setCountryState(c);
    if (opts.redirect !== false && typeof window !== 'undefined') {
      const targetUrl = swapCountryUrl(window.location.pathname, c);
      // Garder la query string si présente (pour ?currency=usd notamment)
      const search = window.location.search;
      window.location.href = targetUrl + (search || '');
    }
  }, []);

  const locale = getLocale(country);

  // Formatter monétaire actif (devise principale du pays)
  const fmtCurrency = React.useMemo(() => {
    try {
      return new Intl.NumberFormat(locale.numberLocale, {
        style: 'currency',
        currency: locale.currency.code,
        maximumFractionDigits: 0,
      });
    } catch (e) {
      return { format: (n) => `${locale.currency.symbol}${n}` };
    }
  }, [country]);

  // ATTENTION : on spread `locale` D'ABORD puis on overwrite `country` avec le CODE ('mx'/'co'),
  // sinon `locale.country` ('México'/'Colombia', le label) écrase le code et tous les checks
  // `ctx.country === 'mx'` retournent false dans les composants consommateurs.
  const value = React.useMemo(() => ({
    ...locale,
    countryName: locale.country,
    country,
    setCountry,
    fmt: (n) => fmtCurrency.format(n),
  }), [country, fmtCurrency, locale]);

  return React.createElement(CountryContext.Provider, { value }, children);
};

const useCountry = () => {
  const ctx = React.useContext(CountryContext);
  if (!ctx) {
    // Fallback safe : si un composant est rendu sans Provider, on retourne le locale CO par défaut.
    // Même règle que dans le Provider : on spread locale AVANT, puis on overwrite country avec le code.
    const locale = window.CO_LOCALE;
    return {
      ...locale,
      countryName: locale.country,
      country: 'co',
      setCountry: () => {},
      fmt: (n) => `${locale.currency.symbol}${n}`,
    };
  }
  return ctx;
};

window.CountryContext = CountryContext;
window.CountryProvider = CountryProvider;
window.useCountry = useCountry;
window.swapCountryUrl = swapCountryUrl;
