// Integración Mercadona: búsqueda de productos vía Algolia (la misma que usa
// tienda.mercadona.es). La usa el registro multi-súper (src/stores.jsx); la
// resolución CP → almacén vive en api/_stores/mercadona.mjs
// (/api/stores/locate) y api/warehouse.js se mantiene para apps antiguas.
//
// Credenciales Algolia extraídas del bundle público del SPA de Mercadona
// (2026-07-20). Son claves search-only públicas (viajan en cada visita a la
// tienda), pero Mercadona puede rotarlas: si empieza a responder 403 marcamos
// `unavailable` y la UI muestra un aviso en vez de romper.
const MERCA_ALGOLIA_APP = '7UZJKL1DJ0';
const MERCA_ALGOLIA_KEY = '9d8f2e39e90df472b4f2e559a116fe17';

function __mercaNormalizeHit(hit) {
  const pi = hit.price_instructions || {};
  return {
    pid: String(hit.id),
    name: hit.display_name || '',
    brand: hit.brand || '',
    packaging: hit.packaging || '',
    price: pi.unit_price || null,        // precio del envase, string "1.60"
    bulk_price: pi.bulk_price || null,   // precio por kg/L, string "8.00"
    size_format: pi.size_format || pi.reference_format || '',
    thumbnail: hit.thumbnail || '',
    url: hit.share_url || '',
  };
}

const Mercadona = {
  unavailable: false,

  async search(query, warehouse, hitsPerPage = 6) {
    const q = (query || '').trim();
    const wh = (warehouse || '').trim();
    if (!q || !wh) return [];
    try {
      const res = await fetch(
        `https://${MERCA_ALGOLIA_APP}-dsn.algolia.net/1/indexes/products_prod_${encodeURIComponent(wh)}_es/query`,
        {
          method: 'POST',
          headers: {
            'x-algolia-application-id': MERCA_ALGOLIA_APP,
            'x-algolia-api-key': MERCA_ALGOLIA_KEY,
            'content-type': 'application/json',
          },
          body: JSON.stringify({ query: q, hitsPerPage }),
        },
      );
      if (res.status === 403) { Mercadona.unavailable = true; return []; }
      if (!res.ok) return [];
      Mercadona.unavailable = false;
      const data = await res.json();
      return (data.hits || []).filter(h => h.published !== false).map(__mercaNormalizeHit);
    } catch (_) {
      return [];
    }
  },
};

window.Mercadona = Mercadona;
