/* Caballo Natural – data layer (loaded once, exposed on window) */

const CATEGORIES = [
  { name: "Verdauung & Magen", slug: "verdauung-magen", img: "assets/cat-verdauung-magen.jpg", short: "Magen, Darm, Kotwasser, Sensibilität", tag: "Verdauung" },
  { name: "Stoffwechsel, Leber, Niere, Entgiftung", slug: "stoffwechsel", img: "assets/cat-stoffwechsel.jpg", short: "EMS, Cushing, Leber & Niere", tag: "Stoffwechsel" },
  { name: "Haut, Fell & Immunsystem", slug: "haut-fell-immunsystem", img: "assets/cat-haut-fell-immunsystem.jpg", short: "Ekzem, Mauke, Fellwechsel, Allergie", tag: "Haut & Immun" },
  { name: "Atemwege", slug: "atemwege", img: "assets/cat-atemwege.jpg", short: "Husten, Asthma, Schleimhaut", tag: "Atemwege" },
  { name: "Hufe & Struktur", slug: "hufe-struktur", img: "assets/cat-hufe-struktur.jpg", short: "Rehe, Strahlfäule, Hornqualität", tag: "Hufe & Struktur" },
  { name: "Muskeln / Leistung / Regeneration", slug: "muskeln-leistung", img: "assets/cat-muskeln-leistung.jpg", short: "Oberlinie, PSSM, Aufbau, Sport", tag: "Muskeln" },
  { name: "Gelenke & Beweglichkeit", slug: "gelenke-beweglichkeit", img: "assets/cat-gelenke-beweglichkeit.jpg", short: "Arthrose, Steifheit, Sehnen, Bänder", tag: "Gelenke" },
  { name: "Nerven, Stress & Verhalten", slug: "nerven-stress", img: "assets/cat-nerven-stress.jpg", short: "Unruhe, Headshaking, Schlaf", tag: "Nerven & Stress" },
  { name: "Parasiten & Darmmilieu", slug: "parasiten-darmmilieu", img: "assets/cat-parasiten-darmmilieu.jpg", short: "Wurm-/Milbenmuster, Darmflora", tag: "Darmmilieu" },
  { name: "Senioren & tiefer Aufbau", slug: "senioren", img: "assets/cat-senioren.jpg", short: "Altersabbau, Vitalität, Substanz", tag: "Senioren" },
  { name: "Wachstum, Aufzucht & Zucht", slug: "wachstum-zucht", img: "assets/cat-wachstum-zucht.jpg", short: "Fohlen, Jungpferde, Zuchtstuten", tag: "Aufzucht & Zucht" },
];

const LEVELS = [
  { id: "Basis", desc: "Sanfter Einstieg bei beginnenden oder milden Beschwerden." },
  { id: "Intensiv", desc: "Tiefe Therapie bei akuten oder chronischen Bildern." },
  { id: "Aufbau", desc: "Rekonvaleszenz, Regeneration, Substanzaufbau nach Druckphase." },
  { id: "Erhaltung", desc: "Stabilisierung bei chronisch sensiblen Pferden, zyklisch." },
  { id: "Prävention", desc: "Vor bekannten Triggern: Fellwechsel, Anweiden, Transport, Saisonstart." },
];

// Product line classification (based on prefix/keyword)
function classifyProduct(name) {
  if (!name) return "Sonstiges";
  const n = name.toLowerCase();
  if (n.startsWith("cobs ")) return "Cobs – Basisfutter";
  if (n.startsWith("cuadra ")) return "Stalllinie – Tagesbegleiter";
  if (n.startsWith("fluido ")) return "Fluidkonzentrate";
  if (n.startsWith("polvo ")) return "Intensivpulver";
  if (n.startsWith("refuerzo ")) return "Intensiv-Booster";
  if (n.startsWith("bálsamo") || n.startsWith("solución") || n.startsWith("lavado") || n.startsWith("ungüento") || n.startsWith("óleo")) return "Externa – Salben & Lösungen";
  return "Dekoktlinie – Hauptkräuter";
}

function slugifyProduct(name) {
  return name.toLowerCase()
    .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");
}

// Loader
window.__CN = window.__CN || {};
window.__CN.ready = (async () => {
  const [programs, prices, lines] = await Promise.all([
    fetch("data/programs.json").then(r => r.json()),
    fetch("data/prices.json").then(r => r.json()),
    fetch("data/product-lines.json").then(r => r.json()).catch(() => ({ dekokte: [], stall: [], fluide: [], booster: [] })),
  ]);

  // Großverbraucher-only products
  window.__CN.wholesaleNames = new Set([...(lines.dekokte || []), ...(lines.stall || [])]);
  window.__CN.fluidNames = new Set(lines.fluide || []);
  window.__CN.boosterNames = new Set(lines.booster || []);

  // Group programs by category & by level
  const byCategory = {};
  for (const p of programs) {
    const cat = p["Hauptkategorie"];
    if (!byCategory[cat]) byCategory[cat] = [];
    byCategory[cat].push(p);
  }

  // Unique products list with line classification
  const productMap = new Map();
  for (const p of programs) {
    for (const prod of p._products) {
      if (!productMap.has(prod)) {
        productMap.set(prod, {
          name: prod,
          line: classifyProduct(prod),
          slug: slugifyProduct(prod),
          usedIn: [],
        });
      }
      productMap.get(prod).usedIn.push(p.ID);
    }
  }
  // Also add basisfutter
  for (const p of programs) {
    const bf = p["Cobs-Basisfutter"] || "";
    for (const f of bf.split(/\boder\b/i)) {
      const cf = f.trim();
      if (cf && !productMap.has(cf)) {
        productMap.set(cf, { name: cf, line: classifyProduct(cf), slug: slugifyProduct(cf), usedIn: [] });
      }
    }
  }
  // Add Fluide that aren't in programs (so toRetailVariant can find them)
  for (const f of (lines.fluide || [])) {
    if (!productMap.has(f)) {
      productMap.set(f, { name: f, line: classifyProduct(f), slug: slugifyProduct(f), usedIn: [] });
    }
  }

  window.__CN.data = {
    programs,
    prices,
    byCategory,
    products: [...productMap.values()],
    productByName: Object.fromEntries([...productMap.values()].map(p => [p.name, p])),
    categories: CATEGORIES,
    levels: LEVELS,
  };
  return window.__CN.data;
})();

window.__CN.CATEGORIES = CATEGORIES;
window.__CN.LEVELS = LEVELS;
window.__CN.classifyProduct = classifyProduct;
window.__CN.slugifyProduct = slugifyProduct;

// === Retail / Wholesale split ===
// Only "Stalllinie" (Cuadra X Base) is reserved for Großverbraucher.
// Dekokte (Hauptkräuter, ~18 €/Monat) are recommended directly to end customers
// because they are significantly günstiger als die Fluide-Variante (~30 €/Monat).
window.__CN.isWholesale = (name) => {
  if (!name) return false;
  if (/^cuadra /i.test(name)) return true;            // Stalllinie
  return false;
};

// Substitute wholesale → retail variant for end-customer programs
// Stalllinie wird ausgeblendet; Dekokte bleiben wie sie sind (günstigere Empfehlung).
window.__CN.toRetailVariant = (name) => {
  if (!name) return name;
  if (/^cuadra /i.test(name)) return null;            // Stalllinie: hide entirely
  return name;                                         // Dekokt bleibt Dekokt
};

// Find program by category name + level
window.__CN.findProgram = (catName, level) => {
  if (!window.__CN.data) return null;
  return (window.__CN.data.byCategory[catName] || []).find(p => p["Nebenebene"] === level);
};

// Format price helper
window.__CN.formatPrice = (val, currency = "EUR") => {
  if (val == null || val === "") return null;
  const num = typeof val === "number" ? val : parseFloat(val);
  if (isNaN(num)) return null;
  const symbol = { EUR: "€", USD: "$" }[currency] || currency;
  return symbol + num.toFixed(2).replace(".", ",");
};

window.__CN.getCategoryBySlug = (slug) => CATEGORIES.find(c => c.slug === slug);
