// data.jsx — Charge dynamiquement le catalogue Fun Pizza depuis Firestore (MenuReserve).
// La source de vérité des plats vit dans /merchants/{id}/catalog.
// Les modifications faites depuis l'app MenuReserve se répercutent ici instantanément.

// Initialisation des globals avec des tableaux vides pour que le premier render
// de Menu/Landing ne plante pas pendant le chargement.
window.pizzaCategories = [];
window.allPizzas = [];
window.desserts = [];
window.beverages = [];
window.featured = [];
window.catalogLoading = true;
window.catalogError = null;

// Mapping entre les catégories Firestore et la structure historique.
const FP_PIZZA_CATEGORIES = [
  { name: "Base Tomate",   slug: "tomate", icon: "🍅" },
  { name: "Végétariennes", slug: "vege",   icon: "🌿" },
  { name: "Base Crème",    slug: "creme",  icon: "🥛" },
];

const FEATURED_NAMES = ["Margherita", "Cannibale", "Virginie"];

async function fpLoadCatalog() {
  const cfg = window.MENURESERVE_CONFIG;
  if (
    !cfg ||
    String(cfg.projectId).startsWith("REMPLACER") ||
    String(cfg.merchantId).startsWith("REMPLACER")
  ) {
    window.catalogError = "Configuration MenuReserve manquante.";
    window.catalogLoading = false;
    window.dispatchEvent(new CustomEvent("catalog-ready"));
    return;
  }

  try {
    const menureserve = new window.MenuReserve(cfg);
    const raw = await menureserve.fetchCatalog();
    const items = raw.filter(i => i.available !== false);

    const byCat = {};
    for (const it of items) {
      const cat = it.category || "Autres";
      (byCat[cat] = byCat[cat] || []).push(it);
    }

    const mapPizza = (it) => ({
      id: it.id,
      name: it.name,
      desc: it.description || "",
      price: Number(it.price) || 0,
      image: it.imageUrl || null,
      ingredients: Array.isArray(it.ingredients) ? it.ingredients : [],
      signature: it.badge === "Signature",
      vege: Array.isArray(it.tags) && it.tags.includes("veggie"),
    });

    window.pizzaCategories = FP_PIZZA_CATEGORIES.map(c => ({
      ...c,
      pizzas: (byCat[c.name] || []).map(mapPizza),
    }));

    window.allPizzas = window.pizzaCategories.flatMap(c =>
      c.pizzas.map(p => ({ ...p, category: c.name }))
    );

    window.desserts = (byCat["Desserts"] || []).map(it => ({
      id: it.id,
      name: it.name,
      desc: it.description || "",
      price: Number(it.price) || 0,
      image: it.imageUrl || null,
    }));

    window.beverages = (byCat["Boissons"] || []).map(it => ({
      id: it.id,
      name: it.name,
      price: Number(it.price) || 0,
      size: it.size || null,
    }));

    window.featured = FEATURED_NAMES
      .map(n => window.allPizzas.find(p => p.name === n))
      .filter(Boolean);

    window.catalogLoading = false;
  } catch (err) {
    console.error("MenuReserve — chargement du catalogue échoué :", err);
    window.catalogError = err.message || String(err);
    window.catalogLoading = false;
  } finally {
    window.dispatchEvent(new CustomEvent("catalog-ready"));
  }
}

// Démarrer le chargement dès que possible. La page se met à jour quand le
// catalogue arrive (cf. le hook dans app.jsx).
fpLoadCatalog();
