const { useState, useEffect, useMemo, useRef } = React;

/* ============================================================
   ForniGo — Piattaforma B2B listini alimentari (prototipo)
   I dati sono salvati nel browser (localStorage).
   ============================================================ */

const ALLERGENS = [
  { key: "glutenFree",  label: "Senza glutine",          icon: "🌾" },
  { key: "lactoseFree", label: "Senza lattosio",         icon: "🥛" },
  { key: "eggFree",     label: "Senza uova",             icon: "🥚" },
  { key: "vegan",       label: "Vegano",                 icon: "🌱" },
  { key: "nutFree",     label: "Senza frutta a guscio",  icon: "🥜" },
  { key: "sugarFree",   label: "Senza zuccheri",         icon: "🍬" },
];

/* ---------- storage ---------- */
const DB = {
  users:    () => JSON.parse(localStorage.getItem("pl_users")    || "[]"),
  products: () => JSON.parse(localStorage.getItem("pl_products") || "[]"),
  links:    () => JSON.parse(localStorage.getItem("pl_links")    || "[]"),
  orders:   () => JSON.parse(localStorage.getItem("pl_orders")   || "[]"),
  messages: () => JSON.parse(localStorage.getItem("pl_messages") || "[]"),
  emails:   () => JSON.parse(localStorage.getItem("pl_emails")   || "[]"),
  session:  () => localStorage.getItem("pl_session") || null,
  save: (k, v) => localStorage.setItem("pl_" + k, JSON.stringify(v)),
  saveSession: (id) => id ? localStorage.setItem("pl_session", id) : localStorage.removeItem("pl_session"),
};

/* Collega Kepi: importa in un colpo solo il "pacchetto venditore" preparato dal
   gestionale Kepi (accesso, vetrina completa, condizioni e listino prodotti).
   Se l'account esiste già (stessa email) aggiorna vetrina e prodotti. */
async function collegaKepi(urlPassato) {
  const salvato = localStorage.getItem("pl_kepi_url") || "";
  const url = urlPassato || prompt(
    "Incolla il link del pacchetto Kepi\n(lo trovi in Kepi → Negozio online → Vendi su ForniGo):",
    salvato);
  if (!url) return;
  let p;
  try {
    const r = await fetch(url.trim());
    if (!r.ok) throw new Error("HTTP " + r.status);
    p = await r.json();
    if (!p || !p.fornigo || !p.azienda) throw new Error("contenuto non riconosciuto");
  } catch (e) {
    alert("Non riesco a leggere il pacchetto Kepi: " + e.message +
          "\nControlla il link e che Kepi sia raggiungibile.");
    return;
  }
  localStorage.setItem("pl_kepi_url", url.trim());
  const esito = applicaPacchettoKepi(p, url.trim(), { session: true });
  alert(`Collegamento riuscito! 🎉\n${esito.u.company} è su ForniGo con ${esito.quanti} prodotti.\n` +
        `Accesso: ${esito.u.email} (password in Kepi → Vendi su ForniGo).`);
  location.reload();
}

/* Applica un pacchetto Kepi: crea/aggiorna il produttore, la vetrina e
   SOSTITUISCE i suoi prodotti (nomi, foto, prezzi, temperature, schede).
   I prodotti aggiunti A MANO su ForniGo (manuale: true) restano com'erano. */
function applicaPacchettoKepi(p, url, opz) {
  const users = JSON.parse(localStorage.getItem("pl_users") || "[]");
  const az = p.azienda;
  const cond = p.condizioni || {};
  const rigaCond = [
    cond.pagamento ? "💶 Pagamento: " + cond.pagamento : "",
    cond.consegna ? "🚚 Consegna: " + cond.consegna : "",
    cond.minimo ? "📦 Ordine minimo: " + cond.minimo : "",
  ].filter(Boolean).join("  ·  ");
  const profile = {
    ...(p.profile || {}),
    description: ((p.profile || {}).description || "") + (rigaCond ? "\n\n" + rigaCond : ""),
  };
  let u = users.find(x => (x.email || "").toLowerCase() === (az.email || "").toLowerCase());
  if (u) {
    Object.assign(u, { company: az.company, vat: az.vat, address: az.address,
                       contact: az.contact, password: az.password || u.password, profile,
                       kepiAvvisi: url });
  } else {
    u = { id: Math.random().toString(36).slice(2, 10), role: "producer",
          company: az.company, vat: az.vat, address: az.address, contact: az.contact,
          email: az.email, password: az.password || "kepi",
          privacyAcceptedAt: new Date().toISOString(), profile,
          kepiAvvisi: url };
    users.push(u);
  }
  localStorage.setItem("pl_users", JSON.stringify(users));
  const tutti = JSON.parse(localStorage.getItem("pl_products") || "[]");
  const conservati = tutti.filter(x => x.producerId !== u.id || x.manuale);
  const daKepi = (p.prodotti || []).map(x => ({
    id: Math.random().toString(36).slice(2, 10), producerId: u.id,
    name: x.name, category: x.category || "", price: Number(x.price) || 0,
    description: x.description || "", photo: x.photo || "", datasheet: x.datasheet || "",
    glutenFree: !!x.glutenFree, lactoseFree: !!x.lactoseFree, eggFree: !!x.eggFree,
    vegan: !!x.vegan, nutFree: !!x.nutFree, sugarFree: !!x.sugarFree,
    storage: x.storage || "ambiente",
    nutrition: x.nutrition || null, photoAi: !!x.photoAi,
  })).filter(x => x.name);
  localStorage.setItem("pl_products", JSON.stringify(conservati.concat(daKepi)));
  if (opz && opz.session) localStorage.setItem("pl_session", u.id);
  return { u, quanti: daKepi.length };
}

/* AGGIORNAMENTO AUTOMATICO: se un produttore è collegato a Kepi, una volta al
   giorno ForniGo riscarica da solo il suo pacchetto (articoli, foto, prezzi). */
(async function () {
  const oggi = new Date().toISOString().slice(0, 10);
  if (localStorage.getItem("pl_kepi_sync") === oggi) return;
  const users = JSON.parse(localStorage.getItem("pl_users") || "[]");
  const daSync = users.filter(x => x.role === "producer" && x.kepiAvvisi);
  if (!daSync.length) return;
  localStorage.setItem("pl_kepi_sync", oggi);   // segnato PRIMA: mai cicli infiniti
  let aggiornati = 0;
  for (const x of daSync) {
    try {
      const r = await fetch(x.kepiAvvisi);
      if (!r.ok) continue;
      const p = await r.json();
      if (p && p.fornigo && p.azienda) { applicaPacchettoKepi(p, x.kepiAvvisi); aggiornati++; }
    } catch (e) { /* Kepi non raggiungibile: riproverà domani */ }
  }
  if (aggiornati) location.reload();
})();

/* Se Kepi apre ForniGo con ?kepi=<link>, il collegamento parte da solo. */
(function () {
  const p = new URLSearchParams(location.search).get("kepi");
  if (p) {
    history.replaceState({}, "", location.pathname);
    setTimeout(() => collegaKepi(p), 300);
  }
})();

/* Avvisa il Kepi del produttore (promemoria + Telegram) quando su ForniGo
   arriva qualcosa per lui. Silenzioso: se Kepi non risponde, pazienza. */
function avvisaKepi(producer, tipo, testo) {
  const base = producer && producer.kepiAvvisi;
  if (!base) return;
  fetch(base + "/avviso", {
    method: "POST", headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ tipo, testo }),
  }).catch(() => {});
}

const _DB_compat = {
};

const uid = () => Math.random().toString(36).slice(2, 10);
const euro = (n) => Number(n || 0).toLocaleString("it-IT", { style: "currency", currency: "EUR" });
const truthy = (v) => /^(s|sì|si|y|yes|true|1|x)$/i.test(String(v || "").trim());

/* ---------- carrello / preventivi ---------- */
function discountFor(links, clientId, producerId) {
  const l = links.find(l => l.clientId === clientId && l.producerId === producerId && l.status === "approved");
  return l ? (l.discount || 0) : 0;
}

// Raggruppa il carrello per produttore, calcolando sconto e totali.
function groupCart(cart, products, links, clientId) {
  const groups = {};
  cart.forEach(ci => {
    const p = products.find(x => x.id === ci.productId);
    if (!p) return;
    const discount = discountFor(links, clientId, p.producerId);
    const unitPrice = p.price;
    const lineTotal = unitPrice * (1 - discount / 100) * ci.qty;
    (groups[p.producerId] = groups[p.producerId] || []).push({ productId: p.id, name: p.name, qty: ci.qty, unitPrice, discount, lineTotal });
  });
  return groups;
}
const sumItems = (items) => items.reduce((s, i) => s + i.lineTotal, 0);

function downloadQuotePDF(producer, items, me) {
  const { jsPDF } = window.jspdf;
  const doc = new jsPDF();
  doc.setFontSize(20); doc.setTextColor(10, 151, 75); doc.text("Preventivo", 14, 22);
  doc.setFontSize(10); doc.setTextColor(60);
  doc.text(`Fornitore: ${producer.company}`, 14, 32);
  doc.text(`P.IVA: ${producer.vat || "-"}`, 14, 37);
  doc.text(`Cliente: ${me.company}  (P.IVA ${me.vat || "-"})`, 14, 44);
  doc.text(`Data: ${new Date().toLocaleDateString("it-IT")}`, 14, 49);
  doc.autoTable({
    startY: 55,
    head: [["Prodotto", "Q.tà", "Prezzo listino", "Sconto", "Totale riga"]],
    body: items.map(it => [it.name, String(it.qty), euro(it.unitPrice), it.discount ? `-${it.discount}%` : "—", euro(it.lineTotal)]),
    theme: "grid",
    headStyles: { fillColor: [10, 151, 75] },
    columnStyles: { 1: { halign: "center" }, 2: { halign: "right" }, 3: { halign: "center" }, 4: { halign: "right" } },
  });
  const y = doc.lastAutoTable.finalY + 10;
  doc.setFontSize(13); doc.setTextColor(20);
  doc.text(`Totale preventivo: ${euro(sumItems(items))}`, 14, y);
  doc.setFontSize(8); doc.setTextColor(150);
  doc.text("Preventivo generato con ForniGo · prezzi IVA esclusa salvo diversa indicazione.", 14, y + 10);
  doc.save(`preventivo_${producer.company.replace(/\s+/g, "_")}.pdf`);
}

function downloadOrdersCSV(orders, users, fileName) {
  const rows = [["Data", "Cliente", "Prodotto", "Quantità", "Prezzo unitario", "Sconto %", "Totale riga", "N. ordine"]];
  orders.forEach(o => {
    const client = users.find(u => u.id === o.clientId);
    o.items.forEach(it => rows.push([
      new Date(o.date).toLocaleDateString("it-IT"), client?.company || "", it.name, it.qty,
      String(it.unitPrice).replace(".", ","), it.discount, String(it.lineTotal.toFixed(2)).replace(".", ","), o.id,
    ]));
  });
  const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(";")).join("\n");
  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob(["﻿" + csv], { type: "text/csv" }));
  a.download = fileName; a.click();
}

// Genera una scheda tecnica PDF del singolo prodotto.
function downloadProductPDF(p, producer) {
  const { jsPDF } = window.jspdf;
  const doc = new jsPDF();
  doc.setFontSize(20); doc.setTextColor(10, 151, 75); doc.text("Scheda prodotto", 14, 22);
  doc.setFontSize(15); doc.setTextColor(20); doc.text(p.name, 14, 33);
  doc.setFontSize(10); doc.setTextColor(90);
  doc.text(`Produttore: ${producer?.company || "-"}`, 14, 42);
  doc.text(`Categoria: ${p.category || "-"}`, 14, 47);
  doc.text(`Prezzo di listino: ${euro(p.price)}`, 14, 52);
  const allerg = ALLERGENS.filter(a => p[a.key]).map(a => a.label);
  doc.autoTable({
    startY: 60,
    head: [["Caratteristica", "Valore"]],
    body: [
      ["Descrizione", p.description || "—"],
      ["Caratteristiche", allerg.length ? allerg.join(", ") : "—"],
    ],
    theme: "grid",
    headStyles: { fillColor: [10, 151, 75] },
    columnStyles: { 0: { cellWidth: 45, fontStyle: "bold" } },
  });
  const y = doc.lastAutoTable.finalY + 12;
  doc.setFontSize(8); doc.setTextColor(150);
  doc.text("Scheda generata con ForniGo · dati forniti dal produttore.", 14, y);
  doc.save(`scheda_${(p.name || "prodotto").replace(/\s+/g, "_")}.pdf`);
}

/* ---------- dati demo (solo la prima volta) ---------- */
function seedIfEmpty() {
  if (DB.users().length) return;
  const p1 = { id: uid(), role: "producer", company: "Molino Aurora",  vat: "01234567890", address: "Via dei Campi 12, Bologna", contact: "Luca Verdi",  email: "demo.molino@fornigo.it",  password: "demo", privacyAcceptedAt: new Date().toISOString(),
    profile: { description: "Da tre generazioni produciamo farine e mix gluten-free per laboratori professionali.", news: "Nuovo mix per pizza ad alta idratazione!", promo: "-15% sul primo ordine", logo: "" } };
  const p2 = { id: uid(), role: "producer", company: "Dolci Senza",     vat: "09876543210", address: "Corso Italia 9, Verona",     contact: "Sara Bianchi", email: "demo.dolci@fornigo.it",   password: "demo", privacyAcceptedAt: new Date().toISOString(),
    profile: { description: "Preparati per pasticceria senza glutine, lattosio e uova.", news: "", promo: "", logo: "" } };
  const c1 = { id: uid(), role: "client", company: "Ristorante Da Mario", vat: "05555555555", address: "Piazza Roma 1, Milano", contact: "Mario Rossi", email: "demo.cliente@fornigo.it", password: "demo", privacyAcceptedAt: new Date().toISOString(), profile: {} };
  const c2 = { id: uid(), role: "client", company: "Pasticceria Dolce Vita", vat: "07777777777", address: "Via Po 4, Torino", contact: "Anna Neri", email: "demo.cliente2@fornigo.it", password: "demo", privacyAcceptedAt: new Date().toISOString(), profile: {} };

  const prods = [
    { producerId: p1.id, name: "Mix Pane Rustico GF", category: "Farine e mix", price: 4.50, glutenFree:true,  lactoseFree:true,  eggFree:true,  vegan:true,  nutFree:true,  sugarFree:false, description:"Mix per pane rustico, alta resa.", photo:"img/pane-rustico.jpg" },
    { producerId: p1.id, name: "Mix Pizza Napoletana GF", category: "Farine e mix", price: 5.20, glutenFree:true,  lactoseFree:true,  eggFree:true,  vegan:true,  nutFree:true,  sugarFree:false, description:"Per pizza ad alta idratazione.", photo:"img/pizza-napoletana.jpg" },
    { producerId: p1.id, name: "Farina di Riso Fine", category: "Farine e mix", price: 2.80, glutenFree:true,  lactoseFree:true,  eggFree:true,  vegan:true,  nutFree:true,  sugarFree:true,  description:"Macinazione fine.", photo:"img/farina-riso.jpg" },
    { producerId: p2.id, name: "Preparato per Torte", category: "Pasticceria", price: 6.90, glutenFree:true,  lactoseFree:true,  eggFree:true,  vegan:true,  nutFree:false, sugarFree:false, description:"Soffice, pronto all'uso.", photo:"img/preparato-torte.jpg" },
    { producerId: p2.id, name: "Base Crostata GF", category: "Pasticceria", price: 5.40, glutenFree:true,  lactoseFree:false, eggFree:false, vegan:false, nutFree:true,  sugarFree:false, description:"Friabile e dorata.", photo:"img/base-crostata.jpg" },
  ].map((p, i) => ({ id: uid(), createdAt: Date.now() - (5 - i) * 86400e3, ...p }));

  DB.save("users", [p1, p2, c1, c2]);
  DB.save("products", prods);
  DB.save("links", [
    { id: uid(), clientId: c1.id, producerId: p1.id, status: "approved", discount: 10 },
    { id: uid(), clientId: c2.id, producerId: p1.id, status: "pending",  discount: 0 },
  ]);

  const oItems = [
    { productId: prods[0].id, name: prods[0].name, qty: 3, unitPrice: prods[0].price, discount: 10, lineTotal: prods[0].price * 0.9 * 3 },
    { productId: prods[2].id, name: prods[2].name, qty: 2, unitPrice: prods[2].price, discount: 10, lineTotal: prods[2].price * 0.9 * 2 },
  ];
  DB.save("orders", [{ id: "ORD-DEMO01", clientId: c1.id, producerId: p1.id, date: new Date().toISOString(), items: oItems, total: oItems.reduce((s,i)=>s+i.lineTotal,0), status: "ricevuto" }]);

  const now = Date.now();
  DB.save("messages", [
    { id: uid(), fromId: c1.id, toId: p1.id, text: "Buongiorno! Avete disponibilità del Mix Pane per la prossima settimana?", at: new Date(now - 3600e3).toISOString(), read: true },
    { id: uid(), fromId: p1.id, toId: c1.id, text: "Buongiorno! Sì, pronta consegna. Le confermo lo sconto del 10% riservato.", at: new Date(now - 3000e3).toISOString(), read: true },
    { id: uid(), fromId: c1.id, toId: p1.id, text: "Perfetto, grazie!", at: new Date(now - 600e3).toISOString(), read: false },
  ]);

  DB.save("emails", [
    { id: uid(), toId: p1.id, toEmail: p1.email, type: "contact", subject: `Nuova richiesta di collegamento da ${c2.company}`,
      body: `${c2.company} (referente ${c2.contact}) ha richiesto il collegamento al tuo catalogo. Accedi alla sezione "Clienti" per approvare o rifiutare.`,
      at: new Date(now - 1800e3).toISOString(), read: false },
    { id: uid(), toId: p1.id, toEmail: p1.email, type: "message", subject: `Nuovo messaggio da ${c1.company}`,
      body: `Hai ricevuto un nuovo messaggio: "Perfetto, grazie!". Accedi a ForniGo per rispondere.`,
      at: new Date(now - 600e3).toISOString(), read: false },
  ]);
}

/* ============================================================
   UI di base
   ============================================================ */
function Logo({ size = "text-xl" }) {
  return (
    <div className={`flex items-center gap-2 font-extrabold ${size}`}>
      <span className="grid place-items-center w-8 h-8 rounded-xl bg-brand-500 text-white shadow-lg shadow-brand-500/30">F</span>
      <span className="tracking-tight">Forni<span className="text-brand-600">Go</span></span>
    </div>
  );
}

function Chip({ active, onClick, children }) {
  return (
    <button onClick={onClick}
      className={`px-3 py-1.5 rounded-full text-sm font-medium border transition active:scale-95
        ${active ? "bg-brand-600 text-white border-brand-600 shadow-md shadow-brand-600/25"
                 : "bg-white text-slate-600 border-slate-200 hover:border-brand-400 hover:text-brand-700"}`}>
      {children}
    </button>
  );
}

/* Temperatura di trasporto del prodotto: le spedizioni viaggiano separate. */
const TEMPS = {
  surgelato:   { icon: "🧊", label: "Surgelato",  cls: "bg-sky-50 text-sky-700 border-sky-200" },
  refrigerato: { icon: "❄️", label: "Fresco",     cls: "bg-cyan-50 text-cyan-700 border-cyan-200" },
  ambiente:    { icon: "🌡️", label: "Ambiente",   cls: "bg-amber-50 text-amber-700 border-amber-200" },
};
const tempDi = (p) => TEMPS[p.storage] ? p.storage : "ambiente";

function AllergenBadges({ p, small }) {
  const t = TEMPS[tempDi(p)];
  const active = ALLERGENS.filter(a => p[a.key]);
  const tempChip = (
    <span title={"Trasporto: " + t.label}
      className={`inline-flex items-center gap-1 rounded-full border ${t.cls} ${small ? "px-2 py-0.5 text-[11px]" : "px-2.5 py-1 text-xs"}`}>
      <span>{t.icon}</span>{!small && t.label}
    </span>
  );
  if (!active.length) return <div className="flex flex-wrap gap-1">{tempChip}</div>;
  return (
    <div className="flex flex-wrap gap-1">
      {tempChip}
      {active.map(a => (
        <span key={a.key} title={a.label}
          className={`inline-flex items-center gap-1 rounded-full bg-brand-50 text-brand-700 border border-brand-100 ${small ? "px-2 py-0.5 text-[11px]" : "px-2.5 py-1 text-xs"}`}>
          <span>{a.icon}</span>{!small && a.label}
        </span>
      ))}
    </div>
  );
}

const CATEGORY_ART = {
  "farine e mix": { icon: "🌾", from: "from-amber-100", to: "to-amber-300" },
  "pasticceria":  { icon: "🧁", from: "from-pink-100",  to: "to-rose-300" },
  "pasta":        { icon: "🍝", from: "from-yellow-100",to: "to-amber-200" },
  "pane":         { icon: "🍞", from: "from-orange-100",to: "to-amber-300" },
  "biscotti":     { icon: "🍪", from: "from-amber-100", to: "to-orange-200" },
  "snack":        { icon: "🥨", from: "from-yellow-100",to: "to-amber-300" },
  "bevande":      { icon: "🥤", from: "from-sky-100",   to: "to-cyan-300" },
};
function categoryArt(cat) {
  const key = (cat || "").toLowerCase().trim();
  if (CATEGORY_ART[key]) return CATEGORY_ART[key];
  const hit = Object.keys(CATEGORY_ART).find(k => key.includes(k));
  return hit ? CATEGORY_ART[hit] : { icon: "🛒", from: "from-brand-100", to: "to-brand-300" };
}
function ProductImage({ p, className = "" }) {
  if (p.photo) return (
    <div className={`relative overflow-hidden ${className}`}>
      <img src={p.photo} alt={p.name} className="object-cover w-full h-full" />
      {p.photoAi && (
        <span className="absolute bottom-1.5 left-2 text-[10px] font-semibold uppercase tracking-wide bg-white/80 text-slate-600 rounded px-1.5 py-0.5">
          immagine illustrativa
        </span>
      )}
    </div>
  );
  const art = categoryArt(p.category);
  return (
    <div className={`relative grid place-items-center bg-gradient-to-br ${art.from} ${art.to} overflow-hidden ${className}`}>
      <span className="text-5xl drop-shadow-sm select-none">{art.icon}</span>
      <span className="absolute bottom-1.5 right-2 text-[10px] font-semibold uppercase tracking-wide text-slate-700/60">{p.category || ""}</span>
    </div>
  );
}

const NUTRI_RIGHE = [
  ["energia", "Energia", (n) => [n.energia_kj != null ? `${n.energia_kj} kJ` : null, n.energia_kcal != null ? `${n.energia_kcal} kcal` : null].filter(Boolean).join(" / ")],
  ["grassi", "Grassi", (n) => n.grassi != null ? `${n.grassi} g` : ""],
  ["grassi_saturi", "di cui acidi grassi saturi", (n) => n.grassi_saturi != null ? `${n.grassi_saturi} g` : ""],
  ["carboidrati", "Carboidrati", (n) => n.carboidrati != null ? `${n.carboidrati} g` : ""],
  ["zuccheri", "di cui zuccheri", (n) => n.zuccheri != null ? `${n.zuccheri} g` : ""],
  ["fibre", "Fibre", (n) => n.fibre != null ? `${n.fibre} g` : ""],
  ["proteine", "Proteine", (n) => n.proteine != null ? `${n.proteine} g` : ""],
  ["sale", "Sale", (n) => n.sale != null ? `${n.sale} g` : ""],
];
function NutritionTable({ p }) {
  const n = p.nutrition;
  if (!n || !Object.keys(n).length) return null;
  const righe = NUTRI_RIGHE.map(([k, label, fmt]) => [k, label, fmt(n)]).filter(r => r[2]);
  if (!righe.length) return null;
  return (
    <div className="mt-4 rounded-2xl border border-slate-100 overflow-hidden">
      <div className="bg-slate-50 px-4 py-2 text-xs font-bold uppercase tracking-wide text-slate-500">Valori nutrizionali medi per 100 g</div>
      <table className="w-full text-sm">
        <tbody>
          {righe.map(([k, label, val]) => (
            <tr key={k} className="border-t border-slate-50">
              <td className={`px-4 py-1.5 ${label.startsWith("di cui") ? "pl-7 text-slate-500" : "font-medium text-slate-700"}`}>{label}</td>
              <td className="px-4 py-1.5 text-right text-slate-700">{val}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// Evidenzia in giallo il testo cercato dentro una stringa.
function Highlight({ text = "", q = "" }) {
  const query = (q || "").trim();
  if (!query) return <>{text}</>;
  const i = text.toLowerCase().indexOf(query.toLowerCase());
  if (i === -1) return <>{text}</>;
  return (
    <>{text.slice(0, i)}<mark className="bg-amber-200 text-inherit rounded px-0.5">{text.slice(i, i + query.length)}</mark>{text.slice(i + query.length)}</>
  );
}

function Avatar({ user, className = "w-10 h-10", text = "text-base" }) {
  const logo = user?.profile?.logo;
  if (logo) return <img src={logo} alt={user.company} className={`object-cover rounded-2xl ${className}`} />;
  return (
    <div className={`rounded-2xl bg-gradient-to-br from-brand-200 to-brand-400 grid place-items-center text-white font-extrabold ${text} ${className}`}>
      {(user?.company || "?")[0]}
    </div>
  );
}

function Field({ label, required, children }) {
  return (
    <label className="block">
      <span className="text-sm font-medium text-slate-600">{label}{required && <span className="text-brand-600"> *</span>}</span>
      <div className="mt-1">{children}</div>
    </label>
  );
}
const inputCls = "w-full rounded-xl border border-slate-200 bg-white px-3.5 py-2.5 text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-200 transition";

function Toast({ msg, onDone }) {
  useEffect(() => { const t = setTimeout(onDone, 2600); return () => clearTimeout(t); }, []);
  return (
    <div className="fixed bottom-5 left-1/2 -translate-x-1/2 z-50 animate-pop">
      <div className="rounded-2xl bg-slate-900 text-white px-5 py-3 shadow-2xl text-sm font-medium">{msg}</div>
    </div>
  );
}

function Modal({ open, onClose, title, children, wide }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-40 grid place-items-center p-4">
      <div className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm" onClick={onClose}></div>
      <div className={`relative z-10 w-full ${wide ? "max-w-3xl" : "max-w-md"} rounded-3xl bg-white p-6 shadow-2xl animate-pop max-h-[90vh] overflow-auto`}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-bold text-slate-800">{title}</h3>
          <button onClick={onClose} className="grid place-items-center w-8 h-8 rounded-full hover:bg-slate-100 text-slate-500">✕</button>
        </div>
        {children}
      </div>
    </div>
  );
}

function EmptyState({ icon = "🗂️", title, hint, action }) {
  return (
    <div className="rounded-3xl border-2 border-dashed border-slate-200 bg-white/50 p-10 sm:p-14 text-center animate-fade-up">
      <div className="text-5xl mb-3">{icon}</div>
      <div className="font-bold text-slate-700">{title}</div>
      {hint && <div className="text-sm text-slate-500 mt-1 max-w-sm mx-auto">{hint}</div>}
      {action && <div className="mt-5">{action}</div>}
    </div>
  );
}

/* ============================================================
   INVITA UN PRODUTTORE — passaparola (link + WhatsApp + email)
   Nulla parte da solo: l'utente sceglie e invia dal proprio telefono.
   ============================================================ */
function InviteModal({ open, onClose, role = "producer", inviterCompany }) {
  const [copied, setCopied] = useState(false);
  if (!open) return null;
  const url = (typeof location !== "undefined" && location.origin.startsWith("http"))
    ? location.origin : "https://fornigo.it";
  const isProd = role === "producer";
  const firma = inviterCompany ? ` (te l'ho segnalato io, ${inviterCompany})` : "";
  const msg = isProd
    ? `Ciao! Ti segnalo ForniGo, il marketplace B2B gratuito per produttori alimentari${firma}. Pubblichi i tuoi listini in un attimo (anche da CSV) e ricevi ordini da negozi, ristoranti e laboratori, con prezzi e sconti dedicati per cliente. È gratis, provalo qui: ${url}`
    : `Ciao! Ti segnalo ForniGo${firma}: trovi produttori alimentari, filtri per allergeni (senza glutine, lattosio…), prezzi dedicati, preventivi e ordini online. È gratis: ${url}`;
  const wa = `https://wa.me/?text=${encodeURIComponent(msg)}`;
  const mail = `mailto:?subject=${encodeURIComponent("Ti segnalo ForniGo")}&body=${encodeURIComponent(msg)}`;
  const copyMsg = () => {
    try { navigator.clipboard.writeText(msg); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (e) {}
  };
  const btn = "inline-flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-semibold text-sm transition";
  return (
    <Modal open onClose={onClose} title="📣 Invita un produttore su ForniGo" wide>
      <p className="text-slate-600 text-sm">
        Più produttori ci sono, più ForniGo è utile per tutti. Conosci un'azienda che potrebbe
        pubblicare i suoi listini? Mandale l'invito già pronto qui sotto — decidi tu come e a chi.
      </p>
      <div className="mt-4 rounded-2xl bg-slate-50 border border-slate-100 p-4 text-sm text-slate-700 whitespace-pre-wrap">{msg}</div>
      <div className="mt-4 grid sm:grid-cols-3 gap-2">
        <a href={wa} target="_blank" rel="noopener noreferrer" className={btn + " bg-[#25D366] text-white hover:brightness-95"}>🟢 WhatsApp</a>
        <a href={mail} className={btn + " bg-brand-600 text-white hover:bg-brand-700"}>✉️ Email</a>
        <button onClick={copyMsg} className={btn + " bg-white border border-slate-200 hover:border-brand-400"}>{copied ? "✓ Copiato!" : "📋 Copia testo"}</button>
      </div>
      <div className="mt-4 flex items-center gap-2 rounded-xl border border-slate-200 bg-white p-2">
        <span className="text-xs text-slate-400 px-2 shrink-0">Link</span>
        <input readOnly value={url} className="flex-1 bg-transparent text-sm text-slate-600 outline-none" onFocus={e => e.target.select()} />
        <button onClick={() => { try { navigator.clipboard.writeText(url); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (e) {} }}
          className="px-3 py-1.5 rounded-lg bg-slate-100 text-sm font-semibold hover:bg-slate-200 shrink-0">Copia link</button>
      </div>
    </Modal>
  );
}

/* ============================================================
   App
   ============================================================ */
// Piccolo aiutante per parlare col motore (backend). I cookie di sessione
// viaggiano da soli; se una chiamata fallisce, alza un errore leggibile.
const api = {
  async call(method, path, body) {
    const res = await fetch(path, {
      method,
      credentials: "same-origin",
      headers: body ? { "Content-Type": "application/json" } : undefined,
      body: body ? JSON.stringify(body) : undefined,
    });
    let data = {};
    try { data = await res.json(); } catch (e) {}
    if (!res.ok) throw new Error(data.error || ("Errore " + res.status));
    return data;
  },
  get: (p) => api.call("GET", p),
  post: (p, b) => api.call("POST", p, b),
  put: (p, b) => api.call("PUT", p, b),
  del: (p) => api.call("DELETE", p),
};

function App() {
  const [route, setRoute] = useState("home");      // home | login | register
  const [me, setMe] = useState(null);
  const [producers, setProducers] = useState([]);
  const [partners, setPartners] = useState([]);
  const [products, setProducts] = useState([]);
  const [links, setLinks] = useState([]);
  const [orders, setOrders] = useState([]);
  const [messages, setMessages] = useState([]);
  const [emails, setEmails] = useState([]);        // avvisi/notifiche
  const [emailAttiva, setEmailAttiva] = useState(false);  // il motore manda davvero le email (Resend attivo)
  const [ready, setReady] = useState(false);
  const [regRole, setRegRole] = useState("client");
  const [toast, setToast] = useState(null);

  const notify = (m) => setToast(m);
  const goRegister = (role) => { setRegRole(role || "client"); setRoute("register"); };

  // Link dalla vetrina: /app/?registrati=produttore|cliente oppure /app/?accedi
  useEffect(() => {
    const q = new URLSearchParams(location.search);
    const r = q.get("registrati");
    if (r !== null) goRegister(r === "produttore" ? "producer" : "client");
    else if (q.has("accedi")) setRoute("login");
    if (r !== null || q.has("accedi")) {
      q.delete("registrati"); q.delete("accedi");
      const resto = q.toString();
      history.replaceState({}, "", location.pathname + (resto ? "?" + resto : "") + location.hash);
    }
  }, []);

  // Carica i dati dal motore: se sei loggato lo stato completo (con isolamento),
  // altrimenti solo la parte pubblica (vetrina + catalogo senza prezzi).
  const reload = async () => {
    try {
      const meRes = await api.get("/api/me");
      if (meRes.me) {
        const s = await api.get("/api/state");
        setMe(s.me || null); setProducers(s.producers || []); setPartners(s.partners || []);
        setProducts(s.products || []); setLinks(s.links || []); setOrders(s.orders || []);
        setMessages(s.messages || []); setEmails(s.notifications || []); setEmailAttiva(!!s.emailAttiva);
      } else {
        setMe(null); setPartners([]); setLinks([]); setOrders([]); setMessages([]); setEmails([]);
        const p = await api.get("/api/public");
        setProducers(p.producers || []); setProducts(p.products || []);
      }
    } catch (e) { /* motore non raggiungibile: si riprova al prossimo giro */ }
    setReady(true);
  };
  useEffect(() => { reload(); }, []);
  // Sincronizzazione live col motore (chat, ordini, collegamenti tra dispositivi).
  useEffect(() => {
    if (!me) return;
    const id = setInterval(reload, 4000);
    return () => clearInterval(id);
  }, [me && me.id]);

  // Elenco unico di aziende per cercare i nomi (produttori pubblici + controparti collegate + me).
  const users = useMemo(() => {
    const map = {};
    [...producers, ...partners].forEach(u => { map[u.id] = u; });
    if (me) map[me.id] = me;
    return Object.values(map);
  }, [producers, partners, me]);

  // Azioni: ognuna parla col motore e poi ricarica lo stato aggiornato.
  const login = async (email, password) => { await api.post("/api/login", { email, password }); await reload(); };
  const register = async (form, role) => { await api.post("/api/register", { ...form, role, privacy: true }); await reload(); };
  const logout = async () => { try { await api.post("/api/logout"); } catch (e) {} setRoute("home"); await reload(); };
  const addProduct = async (p) => { await api.post("/api/products", p); await reload(); };
  const importProducts = async (rows) => { const d = await api.post("/api/products/import", { products: rows }); await reload(); return d; };
  const deleteProduct = async (id) => { await api.del("/api/products/" + id); await reload(); };
  const requestLink = async (producerId) => { await api.post("/api/links", { producerId }); await reload(); };
  const updateLink = async (id, patch) => { await api.put("/api/links/" + id, patch); await reload(); };
  const createOrder = async (o) => { const d = await api.post("/api/orders", o); await reload(); return d; };
  const sendMessage = async (toId, text) => { await api.post("/api/messages", { toId, text }); await reload(); };
  const markMessagesRead = async (fromId) => { try { await api.post("/api/messages/read", { fromId }); } catch (e) {} reload(); };
  const updateProfile = async (profile) => { await api.put("/api/profile", { profile }); await reload(); };
  const importKepi = async (url) => { const d = await api.post("/api/kepi/import", url ? { url } : {}); await reload(); return d; };
  const deleteAccount = async (password) => {
    const d = await api.post("/api/account/delete", { password }); setRoute("home"); await reload();
    notify(d && d.emailInviata ? "Account cancellato. Ti abbiamo mandato una conferma via email." : "Account cancellato.");
  };
  const markNotificationsRead = async () => { try { await api.post("/api/notifications/read"); } catch (e) {} reload(); };
  const sendEmail = () => {};  // gli avvisi ora li crea il motore da solo

  const ctx = { users, producers, partners, products, links, orders, messages, emails, me,
    setRoute, goRegister, notify, sendEmail,
    login, register, logout, addProduct, importProducts, deleteProduct,
    requestLink, updateLink, createOrder, sendMessage, markMessagesRead,
    updateProfile, importKepi, markNotificationsRead, deleteAccount, emailAttiva };

  // Il produttore può passare alla "vista cliente" per vedere ForniGo
  // (catalogo, prezzi, vetrine) esattamente come lo vedono i suoi clienti.
  const [vistaProd, setVistaProd] = useState(() => localStorage.getItem("pl_vista") || "produttore");
  const cambiaVista = (v) => { setVistaProd(v); localStorage.setItem("pl_vista", v); };

  let screen;
  if (!ready) {
    screen = (
      <div className="min-h-screen grid place-items-center text-slate-400">
        <div className="text-center animate-pop"><div className="text-3xl mb-2">🥖</div>Carico ForniGo…</div>
      </div>
    );
  }
  else if (me && me.role === "producer") {
    screen = vistaProd === "cliente" ? <ClientDash {...ctx} /> : <ProducerDash {...ctx} />;
  }
  else if (me && me.role === "client") screen = <ClientDash {...ctx} />;
  else if (route === "login") screen = <Auth mode="login" {...ctx} />;
  else if (route === "register") screen = <Auth mode="register" initialRole={regRole} {...ctx} />;
  else screen = <Home {...ctx} />;

  return (
    <div className="min-h-screen font-sans text-slate-800">
      {me && me.role === "producer" && (
        <div className={`sticky top-0 z-50 px-4 py-2 flex flex-wrap items-center justify-center gap-2 text-sm text-white ${vistaProd === "cliente" ? "bg-amber-600" : "bg-slate-900"}`}>
          <span>👀 Stai guardando ForniGo come:</span>
          <select value={vistaProd} onChange={e => cambiaVista(e.target.value)}
            className="rounded-lg border border-white/30 bg-black/20 px-2 py-1 text-white font-semibold">
            <option value="produttore" className="text-slate-800">🏭 Produttore — il mio pannello</option>
            <option value="cliente" className="text-slate-800">🛒 Cliente — come mi vedono i clienti</option>
          </select>
          {vistaProd === "cliente" && <span className="text-white/80">catalogo e prezzi come li vede un cliente non collegato</span>}
        </div>
      )}
      {screen}
      {toast && <Toast msg={toast} onDone={() => setToast(null)} />}
    </div>
  );
}

/* ============================================================
   DEMO ANIMATA (esplicativa, tipo "video")
   ============================================================ */
function AnimatedDemo() {
  const captions = [
    "1 · Il produttore carica il listino in CSV",
    "2 · Il cliente filtra per intolleranze",
    "3 · Preventivo con sconto automatico",
    "4 · Ordine e chat con il fornitore",
  ];
  const [i, setI] = useState(0);
  const [paused, setPaused] = useState(false);
  useEffect(() => {
    if (paused) return;
    const t = setInterval(() => setI(x => (x + 1) % captions.length), 3800);
    return () => clearInterval(t);
  }, [paused]);

  const csvRows = [["Mix Pane GF","4,50 €"],["Mix Pizza GF","5,20 €"],["Farina di Riso","2,80 €"],["Base Crostata","5,40 €"]];
  const miniCards = [["MP",true],["PZ",true],["FR",true],["CR",false],["BR",false],["TO",true]];
  const quoteRows = [["2× Mix Pane GF","8,10 €"],["1× Mix Pizza GF","4,68 €"]];

  const scene = (
    <div key={i} className="animate-fade-up h-full">
      {i === 0 && (
        <div className="space-y-2">
          <div className="flex items-center gap-2 text-sm font-semibold text-slate-700"><span>📄</span> listino.csv <span className="ml-auto text-xs text-brand-600">importazione…</span></div>
          {csvRows.map((r, idx) => (
            <div key={idx} style={{ animationDelay: `${idx * 0.28}s` }} className="animate-fade-up flex items-center justify-between bg-white rounded-xl px-3 py-2.5 border border-slate-100 shadow-sm">
              <span className="text-sm font-medium">{r[0]}</span>
              <span className="flex items-center gap-2 text-sm"><span className="text-slate-400">{r[1]}</span><span className="text-brand-600 font-bold">✓</span></span>
            </div>
          ))}
        </div>
      )}
      {i === 1 && (
        <div>
          <div className="flex flex-wrap gap-1.5 mb-3">
            {["🌾 Senza glutine","🥛 Senza lattosio","🌱 Vegano"].map((c, k) => (
              <span key={k} className={`text-xs px-2.5 py-1 rounded-full font-medium ${k<2?"bg-brand-600 text-white":"bg-white border border-slate-200 text-slate-500"}`}>{c}</span>
            ))}
          </div>
          <div className="grid grid-cols-3 gap-2">
            {miniCards.map(([t, on], idx) => (
              <div key={idx} style={{ animationDelay: `${idx * 0.08}s` }} className={`animate-fade-up rounded-xl border border-slate-100 p-2 bg-white ${on?"":"opacity-30"}`}>
                <div className="h-10 rounded-lg bg-gradient-to-br from-brand-100 to-brand-300 grid place-items-center text-brand-800 text-xs font-bold">{t}</div>
                <div className="mt-1.5 h-1.5 w-3/4 bg-slate-200 rounded-full"></div>
                <div className="mt-1 h-1.5 w-1/2 bg-slate-100 rounded-full"></div>
              </div>
            ))}
          </div>
        </div>
      )}
      {i === 2 && (
        <div className="bg-white rounded-2xl border border-slate-100 p-4 shadow-sm">
          <div className="flex items-center justify-between text-sm font-semibold border-b border-slate-100 pb-2">
            <span>🧾 Preventivo · Molino Aurora</span><span className="text-xs bg-brand-600 text-white px-2 py-0.5 rounded-full">-10%</span>
          </div>
          {quoteRows.map((r, idx) => (
            <div key={idx} style={{ animationDelay: `${idx * 0.3}s` }} className="animate-fade-up flex items-center justify-between py-2 text-sm border-b border-slate-50">
              <span>{r[0]}</span><span className="font-semibold">{r[1]}</span>
            </div>
          ))}
          <div className="flex items-center justify-between pt-3">
            <span className="font-bold">Totale</span><span className="font-extrabold text-brand-700 text-lg">12,78 €</span>
          </div>
          <div className="mt-3 flex gap-2">
            <div className="flex-1 text-center text-xs font-semibold bg-slate-100 rounded-lg py-2">⬇ PDF</div>
            <div className="flex-1 text-center text-xs font-semibold bg-brand-600 text-white rounded-lg py-2">📨 Invia ordine</div>
          </div>
        </div>
      )}
      {i === 3 && (
        <div className="space-y-2 pt-2">
          {[["Buongiorno! Disponibilità Mix Pane?", false],["Sì, pronta consegna 👍", true],["Perfetto, vi mando l'ordine!", false],["Ricevuto, grazie!", true]].map(([t, mine], idx) => (
            <div key={idx} style={{ animationDelay: `${idx * 0.4}s` }} className={`animate-fade-up flex ${mine?"justify-end":"justify-start"}`}>
              <div className={`max-w-[78%] px-3 py-2 rounded-2xl text-sm ${mine?"bg-brand-600 text-white rounded-br-md":"bg-white border border-slate-200 rounded-bl-md"}`}>{t}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );

  return (
    <div onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      <div className="rounded-3xl bg-white shadow-2xl border border-slate-100 overflow-hidden">
        <div className="flex items-center gap-1.5 px-4 py-3 border-b border-slate-100 bg-slate-50">
          <span className="w-3 h-3 rounded-full bg-red-300"></span>
          <span className="w-3 h-3 rounded-full bg-amber-300"></span>
          <span className="w-3 h-3 rounded-full bg-green-300"></span>
          <div className="ml-3 flex-1 text-center text-xs text-slate-400 bg-white rounded-full py-1 border border-slate-100">fornigo.it</div>
        </div>
        <div className="h-[320px] p-5 overflow-hidden bg-[#f6f8f7]">{scene}</div>
      </div>
      <div className="mt-4 text-center">
        <div className="font-semibold text-slate-700 h-6">{captions[i]}</div>
        <div className="flex justify-center gap-1.5 mt-2">
          {captions.map((_, k) => (
            <button key={k} onClick={() => setI(k)} className={`h-1.5 rounded-full transition-all ${k===i?"w-6 bg-brand-600":"w-2 bg-slate-300 hover:bg-slate-400"}`}></button>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   HOME pubblica
   ============================================================ */
function HowItWorksCard({ title, color, steps }) {
  return (
    <div className="rounded-3xl bg-white border border-slate-100 p-6 card-hover">
      <div className={`inline-flex items-center gap-2 rounded-full px-3 py-1 text-sm font-semibold ${color}`}>{title}</div>
      <ol className="mt-5 space-y-4">
        {steps.map((s, i) => (
          <li key={i} className="flex gap-3">
            <span className="shrink-0 w-7 h-7 rounded-full bg-brand-600 text-white grid place-items-center text-sm font-bold">{i+1}</span>
            <div><div className="font-semibold">{s.t}</div><div className="text-sm text-slate-500">{s.d}</div></div>
          </li>
        ))}
      </ol>
    </div>
  );
}

/* ============================================================
   BANNER PUBBLICITARIO — Kepi (gestionale per laboratori alimentari)
   variant "wide" = home pubblica · "card" = dashboard produttore
   ============================================================ */
// La pubblicità porta alla VETRINA di Kepi (pagina di presentazione e prezzi),
// non alla schermata di accesso del gestionale.
const KEPI_URL = "https://www.kepigestionale.it/vetrina";
const KEPI_PLUS = [
  ["📦", "Magazzino e lotti", "Carichi, scarichi e tracciabilità sempre in ordine."],
  ["🧪", "Ricette e food cost", "Sai quanto ti costa davvero ogni impasto."],
  ["🏷️", "Etichette a norma", "Allergeni in grassetto, pronte da stampare."],
  ["🛒", "Vendi online e fatturi", "Negozio, marketplace e fatture elettroniche."],
];

function KepiBanner({ variant = "wide" }) {
  const AdLabel = () => (
    <span className="inline-flex items-center gap-1 rounded-full bg-white/10 border border-white/25 px-2.5 py-1 text-[11px] font-semibold text-white/70 uppercase tracking-wide">
      Pubblicità
    </span>
  );
  const Mark = ({ big }) => (
    <span className={`shrink-0 grid place-items-center rounded-2xl bg-white text-brand-700 font-black shadow-lg shadow-black/20 ring-1 ring-white/60 animate-float ${big ? "w-14 h-14 text-2xl" : "w-12 h-12 text-xl"}`}>K</span>
  );
  const Cta = ({ full }) => (
    <a href={KEPI_URL} target="_blank" rel="noopener noreferrer"
       className={`${full ? "w-full sm:w-auto " : ""}group inline-flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-white text-brand-800 font-extrabold text-sm shadow-lg shadow-black/20 hover:shadow-xl hover:-translate-y-0.5 transition`}>
      Scopri Kepi <span className="transition group-hover:translate-x-0.5">→</span>
    </a>
  );

  if (variant === "card") {
    return (
      <div className="relative overflow-hidden rounded-3xl p-6 text-white bg-gradient-to-br from-brand-700 via-brand-800 to-emerald-950 shadow-xl shadow-brand-900/25">
        <div className="pointer-events-none absolute -top-16 -right-12 w-52 h-52 rounded-full bg-brand-400/25 blur-3xl"></div>
        <div className="relative flex items-start justify-between gap-3">
          <div className="flex items-center gap-3"><Mark /><div>
            <div className="font-extrabold text-lg leading-tight">Kepi · il gestionale del tuo laboratorio</div>
            <div className="text-white/70 text-sm">Magazzino, food cost, etichette, fatture e vendita online.</div>
          </div></div>
          <AdLabel />
        </div>
        <div className="relative mt-4 flex flex-wrap gap-2">
          {KEPI_PLUS.map(([i, t]) => (
            <span key={t} className="rounded-full bg-white/10 border border-white/15 px-3 py-1.5 text-xs font-medium">{i} {t}</span>
          ))}
        </div>
        <div className="relative mt-5"><Cta /></div>
      </div>
    );
  }

  return (
    <section className="max-w-6xl mx-auto px-5 pb-6">
      <div className="relative overflow-hidden rounded-[28px] p-8 sm:p-10 text-white shadow-2xl shadow-brand-900/30 bg-gradient-to-br from-brand-700 via-brand-800 to-emerald-950">
        <div className="pointer-events-none absolute -top-24 -right-20 w-80 h-80 rounded-full bg-brand-400/25 blur-3xl animate-float"></div>
        <div className="pointer-events-none absolute -bottom-28 -left-16 w-72 h-72 rounded-full bg-emerald-300/15 blur-3xl"></div>
        <div className="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/50 to-transparent"></div>
        <div className="relative">
          <div className="flex items-start justify-between gap-3">
            <div className="flex items-center gap-4"><Mark big /><div>
              <span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 border border-white/25 px-3 py-1 text-[11px] font-bold uppercase tracking-wider">✦ Il gestionale dei laboratori</span>
              <div className="mt-2 text-2xl sm:text-3xl font-extrabold leading-[1.12]">Produci senza glutine?<br className="hidden sm:block" /> Metti ordine con <span className="text-brand-200">Kepi</span>.</div>
              <div className="text-white/70 mt-1.5 max-w-xl">Magazzino, ricette, food cost, etichette a norma, fatture e vendita online. Fatto da chi produce, non da informatici.</div>
            </div></div>
            <div className="hidden sm:block"><AdLabel /></div>
          </div>
          <div className="mt-7 grid sm:grid-cols-2 lg:grid-cols-4 gap-3.5">
            {KEPI_PLUS.map(([i, t, d]) => (
              <div key={t} className="rounded-2xl bg-white/[0.07] border border-white/10 p-4 hover:bg-white/[0.12] hover:-translate-y-0.5 transition">
                <div className="text-2xl">{i}</div>
                <div className="font-bold mt-2 text-sm">{t}</div>
                <div className="text-white/60 text-xs mt-1 leading-relaxed">{d}</div>
              </div>
            ))}
          </div>
          <div className="mt-8 flex flex-wrap items-center gap-4">
            <Cta full />
            <span className="inline-flex items-center gap-2 text-white/70 text-sm">
              <span className="inline-flex items-center rounded-full bg-brand-400/20 border border-brand-300/30 px-2.5 py-1 text-xs font-bold text-brand-100">30 giorni gratis</span>
              Hai già Kepi? Collega il tuo listino a ForniGo in 1 minuto.
            </span>
          </div>
        </div>
      </div>
    </section>
  );
}

function Home({ products, users, setRoute, goRegister }) {
  const producers = users.filter(u => u.role === "producer");
  const [filters, setFilters] = useState({});
  const [q, setQ] = useState("");
  const [category, setCategory] = useState("");
  const [supplier, setSupplier] = useState("");
  const [sort, setSort] = useState("nov");
  const [previewId, setPreviewId] = useState(null);
  const [invite, setInvite] = useState(false);
  const [showTop, setShowTop] = useState(false);
  useEffect(() => {
    const onScroll = () => setShowTop(window.scrollY > 600);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const categories = [...new Set(products.map(p => p.category).filter(Boolean))].sort((a,b)=>a.localeCompare(b,"it"));
  const qn = q.trim().toLowerCase();
  const list = products.filter(p =>
    Object.keys(filters).every(k => !filters[k] || (k === "_temp" ? tempDi(p) === filters[k] : p[k])) &&
    (!category || p.category === category) &&
    (!supplier || p.producerId === supplier) &&
    (!qn || [p.name, p.category, p.description].some(v => (v||"").toLowerCase().includes(qn)))
  );
  const sortedList = [...list].sort((a, b) =>
    sort === "nome" ? a.name.localeCompare(b.name, "it")
    : sort === "cat" ? (a.category||"").localeCompare(b.category||"", "it") || a.name.localeCompare(b.name, "it")
    : (b.createdAt||0) - (a.createdAt||0)
  );
  const previewP = products.find(p => p.id === previewId);
  const previewProducer = previewP && users.find(u => u.id === previewP.producerId);

  // Salta al catalogo applicando un filtro (categoria, fornitore o testo)
  const goToCatalog = (patch = {}) => {
    if ("category" in patch) setCategory(patch.category);
    if ("supplier" in patch) setSupplier(patch.supplier);
    if ("q" in patch) setQ(patch.q);
    setTimeout(() => document.getElementById("catalogo")?.scrollIntoView({ behavior: "smooth" }), 50);
  };
  // Conteggi per le vetrine marketplace
  const countByCat = {}; products.forEach(p => { if (p.category) countByCat[p.category] = (countByCat[p.category]||0)+1; });
  const topCategories = categories.map(c => ({ name: c, count: countByCat[c], art: categoryArt(c) }))
    .sort((a,b) => b.count - a.count).slice(0, 8);
  const showcase = producers.map(pr => ({ pr, count: products.filter(p => p.producerId === pr.id).length }))
    .filter(x => x.count > 0).sort((a,b) => b.count - a.count).slice(0, 6);
  const novita = [...products].sort((a,b) => (b.createdAt||0) - (a.createdAt||0)).slice(0, 4);
  const [storeId, setStoreId] = useState(null);
  const storeProducer = storeId && users.find(u => u.id === storeId);
  const storeProducts = storeId ? products.filter(p => p.producerId === storeId) : [];
  const openStore = (id) => { setPreviewId(null); setStoreId(id); };
  const similar = previewP
    ? products.filter(p => p.id !== previewP.id && (p.producerId === previewP.producerId || p.category === previewP.category)).slice(0, 3)
    : [];

  const features = [
    ["🔎","Filtri per intolleranze","Senza glutine, lattosio, uova e altro: trovi subito ciò che ti serve."],
    ["⚡","Listini in CSV","Il produttore carica centinaia di prodotti in un attimo da Excel."],
    ["🏷️","Sconti personalizzati","Ogni produttore decide il prezzo dedicato a ciascun cliente."],
    ["🧾","Preventivi in PDF","Sconto già calcolato, preventivo pronto da scaricare."],
    ["💬","Chat diretta","Parla col fornitore senza uscire dalla piattaforma."],
    ["🆓","Gratis per tutti","Nessun costo per produttori e clienti."],
  ];

  return (
    <div className="mesh min-h-screen">
      <header className="glass sticky top-0 z-20 border-b border-white/60">
        <div className="max-w-6xl mx-auto px-5 h-16 flex items-center justify-between">
          <Logo />
          <div className="flex items-center gap-2">
            <a href="#come-funziona" className="hidden sm:block px-4 py-2 rounded-xl text-slate-600 font-medium hover:bg-white/70">Come funziona</a>
            <button onClick={() => setRoute("login")} className="px-4 py-2 rounded-xl text-slate-700 font-semibold hover:bg-white/70">Accedi</button>
            <button onClick={() => goRegister("client")} className="px-4 py-2 rounded-xl bg-brand-600 text-white font-semibold shadow-lg shadow-brand-600/30 hover:bg-brand-700 transition">Registrati</button>
          </div>
        </div>
      </header>

      {/* HERO */}
      <section className="max-w-6xl mx-auto px-5 pt-14 pb-10 grid md:grid-cols-2 gap-10 items-center">
        <div className="animate-fade-up">
          <span className="inline-flex items-center gap-2 rounded-full bg-white/80 border border-brand-100 px-3 py-1 text-sm font-semibold text-brand-700">
            🟢 Solo aziende · B2B · Gratis
          </span>
          <h1 className="mt-4 text-4xl md:text-5xl font-extrabold tracking-tight leading-[1.1]">
            Il punto d'incontro tra <span className="text-brand-600">produttori alimentari</span> e chi acquista.
          </h1>
          <p className="mt-4 text-lg text-slate-600 max-w-md">
            Il mercato all'ingrosso del cibo. I produttori pubblicano i listini, i clienti cercano, filtrano per intolleranze, ricevono prezzi dedicati e ordinano.
          </p>
          <form onSubmit={e => { e.preventDefault(); goToCatalog(); }} className="mt-6 max-w-md">
            <div className="flex items-center gap-2 rounded-2xl bg-white border-2 border-brand-200 shadow-lg shadow-brand-600/10 p-1.5 focus-within:border-brand-500 transition">
              <input value={q} onChange={e => setQ(e.target.value)}
                placeholder="Cerca farine, pasta, dolci, pane..."
                className="flex-1 bg-transparent px-3 py-2.5 outline-none text-slate-800" />
              <button type="submit" className="px-5 py-2.5 rounded-xl bg-amber-400 text-slate-900 font-bold hover:bg-amber-300 transition shrink-0">🔎 Cerca</button>
            </div>
          </form>
          <div className="mt-7 grid sm:grid-cols-2 gap-3 max-w-md">
            <button onClick={() => goRegister("client")} className="px-5 py-4 rounded-2xl bg-brand-600 text-white font-semibold shadow-lg shadow-brand-600/30 hover:bg-brand-700 transition text-left">
              <div className="text-base">Sono un Cliente →</div>
              <div className="text-xs font-normal text-brand-50/90">Negozio, ristorante, laboratorio</div>
            </button>
            <button onClick={() => goRegister("producer")} className="px-5 py-4 rounded-2xl bg-white border-2 border-brand-600 text-brand-700 font-semibold hover:bg-brand-50 transition text-left">
              <div className="text-base">Sono un Produttore →</div>
              <div className="text-xs font-normal text-slate-500">Voglio pubblicare i miei listini</div>
            </button>
          </div>
          <div className="mt-8 flex gap-8 text-sm text-slate-500">
            <div><b className="text-2xl text-slate-800 block">{producers.length}</b>produttori</div>
            <div><b className="text-2xl text-slate-800 block">{products.length}</b>prodotti</div>
            <div><b className="text-2xl text-slate-800 block">{ALLERGENS.length}</b>filtri intolleranze</div>
          </div>
        </div>
        <div className="animate-fade-up"><AnimatedDemo /></div>
      </section>

      {/* CATEGORIE (stile marketplace) */}
      {topCategories.length > 0 && (
        <section className="max-w-6xl mx-auto px-5 py-8 animate-fade-up">
          <div className="flex items-end justify-between gap-4 mb-5">
            <h2 className="text-2xl font-bold">Sfoglia per categoria</h2>
            <button onClick={() => goToCatalog({ category: "", supplier: "", q: "" })} className="text-brand-700 font-semibold text-sm hover:underline shrink-0">Vedi tutto →</button>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            {topCategories.map(({ name, count, art }) => (
              <button key={name} onClick={() => goToCatalog({ category: name, supplier: "", q: "" })}
                className={`card-hover rounded-3xl border border-slate-100 p-5 text-left bg-gradient-to-br ${art.from} ${art.to}`}>
                <div className="text-4xl">{art.icon}</div>
                <div className="font-bold mt-3 text-slate-800">{name}</div>
                <div className="text-sm text-slate-600/80">{count} {count === 1 ? "prodotto" : "prodotti"}</div>
              </button>
            ))}
          </div>
        </section>
      )}

      {/* PRODUTTORI IN VETRINA */}
      {showcase.length > 0 && (
        <section className="max-w-6xl mx-auto px-5 py-8 animate-fade-up">
          <div className="flex items-end justify-between gap-4 mb-5">
            <div>
              <h2 className="text-2xl font-bold">Produttori in vetrina</h2>
              <p className="text-slate-500">Aziende che hanno già scelto ForniGo.</p>
            </div>
          </div>
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {showcase.map(({ pr, count }) => (
              <button key={pr.id} onClick={() => openStore(pr.id)}
                className="card-hover rounded-3xl bg-white border border-slate-100 p-5 flex items-center gap-4 text-left">
                <Avatar user={pr} className="w-14 h-14" text="text-xl" />
                <div className="min-w-0">
                  <div className="font-bold truncate">{pr.company}</div>
                  <div className="text-sm text-slate-500">{count} {count === 1 ? "prodotto" : "prodotti"} a catalogo</div>
                  <div className="text-brand-700 font-semibold text-sm mt-1">Vedi la vetrina →</div>
                </div>
              </button>
            ))}
          </div>
        </section>
      )}

      {/* NOVITÀ / ULTIMI ARRIVI */}
      {novita.length > 0 && (
        <section className="max-w-6xl mx-auto px-5 py-8 animate-fade-up">
          <div className="flex items-end justify-between gap-4 mb-5">
            <div>
              <h2 className="text-2xl font-bold">✨ Novità</h2>
              <p className="text-slate-500">Gli ultimi prodotti aggiunti dai produttori.</p>
            </div>
            <button onClick={() => goToCatalog({ category: "", supplier: "", q: "" })} className="text-brand-700 font-semibold text-sm hover:underline shrink-0">Vedi tutto →</button>
          </div>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {novita.map(p => {
              const prod = users.find(u => u.id === p.producerId);
              return (
                <button key={p.id} onClick={() => setPreviewId(p.id)} className="card-hover rounded-3xl bg-white border border-slate-100 overflow-hidden text-left relative">
                  <span className="absolute top-2 left-2 z-10 rounded-full bg-amber-400 text-slate-900 text-[11px] font-bold px-2 py-0.5 shadow">Novità</span>
                  <ProductImage p={p} className="w-full h-36" />
                  <div className="p-3">
                    <div className="text-[11px] font-semibold text-brand-600 truncate">{prod?.company}</div>
                    <div className="font-bold text-sm mt-0.5 line-clamp-1">{p.name}</div>
                    <div className="mt-2"><AllergenBadges p={p} small /></div>
                  </div>
                </button>
              );
            })}
          </div>
        </section>
      )}

      {/* COME FUNZIONA */}
      <section id="come-funziona" className="max-w-6xl mx-auto px-5 py-14">
        <div className="text-center max-w-2xl mx-auto">
          <h2 className="text-3xl font-extrabold">Come funziona</h2>
          <p className="text-slate-500 mt-2">Semplice per tutti. Scegli il tuo ruolo e parti in pochi minuti.</p>
        </div>
        <div className="grid md:grid-cols-2 gap-5 mt-8">
          <HowItWorksCard title="🛒 Per i Clienti" color="bg-brand-50 text-brand-700" steps={[
            { t:"Registrati gratis", d:"Inserisci i dati aziendali e accetta la privacy." },
            { t:"Trova e collegati ai fornitori", d:"Filtra i prodotti per intolleranze e chiedi il collegamento." },
            { t:"Preventivi e ordini", d:"Ricevi prezzi dedicati, scarica preventivi e invia gli ordini." },
          ]} />
          <HowItWorksCard title="🏭 Per i Produttori" color="bg-amber-50 text-amber-700" steps={[
            { t:"Crea il profilo azienda", d:"Presentazione, novità, promo e logo." },
            { t:"Carica il listino in CSV", d:"Centinaia di prodotti con prezzi e allergeni in un attimo." },
            { t:"Gestisci clienti e ordini", d:"Approva i clienti, imposta sconti, scarica gli ordini." },
          ]} />
        </div>
        <div className="text-center mt-8">
          <button onClick={() => goRegister("client")} className="px-7 py-3.5 rounded-xl bg-brand-600 text-white font-semibold shadow-lg shadow-brand-600/30 hover:bg-brand-700 transition">Crea il tuo account gratuito</button>
        </div>
      </section>

      {/* FEATURES */}
      <section className="max-w-6xl mx-auto px-5 py-10">
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {features.map(([icon, t, d]) => (
            <div key={t} className="rounded-3xl bg-white border border-slate-100 p-6 card-hover">
              <div className="text-3xl">{icon}</div>
              <div className="font-bold mt-3">{t}</div>
              <div className="text-sm text-slate-500 mt-1">{d}</div>
            </div>
          ))}
        </div>
      </section>

      {/* CATALOGO pubblico (senza prezzi) */}
      <section id="catalogo" className="max-w-6xl mx-auto px-5 py-14">
        <div className="mb-5">
          <h2 className="text-2xl font-bold">Dai un'occhiata al catalogo</h2>
          <p className="text-slate-500">I prezzi sono visibili dopo l'accesso (riservato alle aziende).</p>
        </div>
        <div className="space-y-3 mb-5">
          <div className="flex flex-wrap items-center gap-2">
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="🔎 Cerca prodotto..."
              className="rounded-xl border border-slate-200 bg-white px-3.5 py-2.5 text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-200 transition w-full sm:max-w-xs" />
            <select value={category} onChange={e => setCategory(e.target.value)}
              className="rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-700 outline-none focus:border-brand-500">
              <option value="">Tutte le categorie</option>
              {categories.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
            <select value={supplier} onChange={e => setSupplier(e.target.value)}
              className="rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-700 outline-none focus:border-brand-500">
              <option value="">Tutti i produttori</option>
              {producers.map(pr => <option key={pr.id} value={pr.id}>{pr.company}</option>)}
            </select>
            <select value={sort} onChange={e => setSort(e.target.value)}
              className="rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-700 outline-none focus:border-brand-500">
              <option value="nov">Ordina: novità</option>
              <option value="nome">Nome A-Z</option>
              <option value="cat">Categoria</option>
            </select>
            {(q || category || supplier || Object.values(filters).some(Boolean)) && (
              <button onClick={() => { setQ(""); setCategory(""); setSupplier(""); setFilters({}); }}
                className="px-3 py-2 rounded-xl text-sm font-semibold text-slate-500 hover:text-slate-700 hover:bg-slate-100">✕ Azzera</button>
            )}
          </div>
          <div className="flex flex-wrap gap-2">
            {ALLERGENS.map(a => (
              <Chip key={a.key} active={!!filters[a.key]} onClick={() => setFilters(f => ({ ...f, [a.key]: !f[a.key] }))}>
                {a.icon} {a.label}
              </Chip>
            ))}
            {Object.entries(TEMPS).map(([k, t]) => (
              <Chip key={k} active={filters._temp === k}
                onClick={() => setFilters(f => ({ ...f, _temp: f._temp === k ? "" : k }))}>
                {t.icon} {t.label}
              </Chip>
            ))}
          </div>
        </div>
        <div className="text-sm text-slate-400 mb-3">{list.length} {list.length === 1 ? "prodotto" : "prodotti"}</div>
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {sortedList.map(p => {
            const prod = users.find(u => u.id === p.producerId);
            return (
              <button key={p.id} onClick={() => setPreviewId(p.id)} className="card-hover rounded-3xl bg-white border border-slate-100 overflow-hidden text-left">
                <ProductImage p={p} className="w-full h-40" />
                <div className="p-4">
                  <div className="text-xs font-semibold text-brand-600">{prod?.company}</div>
                  <div className="font-bold mt-0.5"><Highlight text={p.name} q={q} /></div>
                  <div className="text-sm text-slate-500 mt-1 line-clamp-2">{p.description}</div>
                  <div className="mt-3"><AllergenBadges p={p} small /></div>
                  <div className="mt-4 flex items-center justify-between">
                    <span className="text-slate-400 text-sm">🔒 Prezzo riservato</span>
                    <span className="text-brand-700 font-semibold text-sm">Vedi scheda →</span>
                  </div>
                </div>
              </button>
            );
          })}
        </div>
        {!list.length && (
          <EmptyState icon="🔍" title="Nessun prodotto trovato"
            hint="Prova a cambiare le parole della ricerca o a togliere qualche filtro."
            action={<button onClick={() => { setQ(""); setCategory(""); setSupplier(""); setFilters({}); }} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">✕ Azzera i filtri</button>} />
        )}
      </section>

      {/* BANNER PUBBLICITARIO */}
      <KepiBanner variant="wide" />

      {/* CTA FINALE */}
      <section className="max-w-6xl mx-auto px-5 pb-16">
        <div className="rounded-3xl bg-gradient-to-br from-brand-600 to-brand-800 text-white p-10 text-center shadow-2xl shadow-brand-600/30">
          <h2 className="text-3xl font-extrabold">Pronto a iniziare?</h2>
          <p className="mt-2 text-brand-50/90">È gratis e bastano pochi minuti.</p>
          <div className="mt-6 flex flex-wrap justify-center gap-3">
            <button onClick={() => goRegister("client")} className="px-6 py-3 rounded-xl bg-white text-brand-700 font-semibold hover:bg-brand-50 transition">Registrati come Cliente</button>
            <button onClick={() => goRegister("producer")} className="px-6 py-3 rounded-xl bg-brand-500 text-white font-semibold border border-white/30 hover:bg-brand-400 transition">Registrati come Produttore</button>
          </div>
        </div>
      </section>

      {/* INVITA */}
      <section className="max-w-6xl mx-auto px-5 pb-8">
        <div className="rounded-3xl bg-white border border-slate-100 p-6 flex flex-wrap items-center justify-between gap-4">
          <div>
            <div className="font-bold text-lg">Conosci un produttore alimentare?</div>
            <div className="text-slate-500 text-sm">Invitalo su ForniGo: è gratis e aiuta tutta la rete a crescere.</div>
          </div>
          <button onClick={() => setInvite(true)} className="px-5 py-3 rounded-xl bg-amber-400 text-slate-900 font-bold text-sm hover:bg-amber-300 shrink-0">📣 Invita un produttore</button>
        </div>
      </section>

      <footer className="border-t border-slate-100 bg-white/60">
        <div className="max-w-6xl mx-auto px-5 py-12 grid gap-8 sm:grid-cols-2 lg:grid-cols-4">
          <div className="sm:col-span-2 lg:col-span-1">
            <Logo />
            <p className="text-sm text-slate-500 mt-3 max-w-xs">Il mercato all'ingrosso del cibo: produttori e clienti alimentari si incontrano in un unico posto. Gratis, solo per aziende.</p>
          </div>
          <div>
            <div className="font-bold text-slate-700 mb-3 text-sm">ForniGo</div>
            <ul className="space-y-2 text-sm text-slate-500">
              <li><a href="#come-funziona" className="hover:text-brand-700">Come funziona</a></li>
              <li><a href="#catalogo" className="hover:text-brand-700">Catalogo</a></li>
              <li><button onClick={() => setInvite(true)} className="hover:text-brand-700">Invita un produttore</button></li>
            </ul>
          </div>
          <div>
            <div className="font-bold text-slate-700 mb-3 text-sm">Inizia</div>
            <ul className="space-y-2 text-sm text-slate-500">
              <li><button onClick={() => goRegister("client")} className="hover:text-brand-700">Registrati come Cliente</button></li>
              <li><button onClick={() => goRegister("producer")} className="hover:text-brand-700">Registrati come Produttore</button></li>
              <li><button onClick={() => setRoute("login")} className="hover:text-brand-700">Accedi</button></li>
            </ul>
          </div>
          <div>
            <div className="font-bold text-slate-700 mb-3 text-sm">Chi siamo</div>
            <p className="text-sm text-slate-500">ForniGo nasce per semplificare la vendita all'ingrosso di prodotti alimentari, con un'attenzione speciale al mondo senza glutine e agli allergeni.</p>
          </div>
        </div>
        <div className="border-t border-slate-100 py-5 text-center text-xs text-slate-400">
          © {new Date().getFullYear()} ForniGo · prototipo dimostrativo · i dati sono salvati solo nel tuo browser.
        </div>
      </footer>

      <InviteModal open={invite} onClose={() => setInvite(false)} role="producer" />

      {showTop && (
        <button onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
          title="Torna su" aria-label="Torna su"
          className="fixed bottom-5 right-5 z-30 w-12 h-12 rounded-full bg-brand-600 text-white text-xl shadow-2xl shadow-brand-600/40 hover:bg-brand-700 transition grid place-items-center animate-pop">↑</button>
      )}

      {previewP && (
        <Modal open={true} onClose={() => setPreviewId(null)} title="Scheda prodotto" wide>
          <div className="grid sm:grid-cols-2 gap-5">
            <ProductImage p={previewP} className="w-full h-48 sm:h-full rounded-2xl" />
            <div>
              {previewProducer && (
                <button onClick={() => openStore(previewProducer.id)} className="text-xs font-semibold text-brand-600 hover:underline">{previewProducer.company} · vedi la vetrina →</button>
              )}
              <h3 className="text-xl font-extrabold mt-1">{previewP.name}</h3>
              {previewP.category && <div className="text-sm text-slate-400">{previewP.category}</div>}
              <p className="text-sm text-slate-600 mt-3">{previewP.description || "Nessuna descrizione."}</p>
              <div className="mt-4"><AllergenBadges p={previewP} /></div>
              <NutritionTable p={previewP} />
              {previewP.datasheet && (
                <a href={previewP.datasheet} target="_blank" rel="noopener noreferrer"
                   className="mt-4 inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">
                  📄 Scarica la scheda tecnica (PDF)
                </a>
              )}
              <div className="mt-5 rounded-2xl bg-slate-50 border border-slate-100 p-4 text-center">
                <div className="text-slate-500 text-sm">🔒 Il prezzo è riservato alle aziende registrate</div>
                <div className="mt-3 flex flex-wrap justify-center gap-2">
                  <button onClick={() => goRegister("client")} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30">Registrati per vedere il prezzo</button>
                  <button onClick={() => setRoute("login")} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">Accedi</button>
                </div>
              </div>
            </div>
          </div>
          {similar.length > 0 && (
            <div className="mt-6">
              <div className="font-bold text-sm text-slate-700 mb-3">Prodotti simili</div>
              <div className="grid grid-cols-3 gap-3">
                {similar.map(s => (
                  <button key={s.id} onClick={() => setPreviewId(s.id)} className="card-hover rounded-2xl bg-white border border-slate-100 overflow-hidden text-left">
                    <ProductImage p={s} className="w-full h-24" />
                    <div className="p-2">
                      <div className="font-semibold text-xs line-clamp-1">{s.name}</div>
                      <div className="text-[11px] text-slate-400 line-clamp-1">{s.category}</div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}
        </Modal>
      )}

      {storeProducer && (
        <Modal open={true} onClose={() => setStoreId(null)} title="Vetrina del produttore" wide>
          <div className="flex items-center gap-4">
            <Avatar user={storeProducer} className="w-16 h-16" text="text-2xl" />
            <div className="min-w-0">
              <h3 className="text-xl font-extrabold truncate">{storeProducer.company}</h3>
              <div className="text-sm text-slate-500">{storeProducts.length} {storeProducts.length === 1 ? "prodotto" : "prodotti"} a catalogo</div>
            </div>
          </div>
          {(storeProducer.profile?.promo || storeProducer.profile?.news) && (
            <div className="mt-4 flex flex-wrap gap-2">
              {storeProducer.profile?.promo && <span className="rounded-full bg-amber-100 text-amber-800 px-3 py-1 text-sm font-semibold">🏷️ {storeProducer.profile.promo}</span>}
              {storeProducer.profile?.news && <span className="rounded-full bg-brand-50 text-brand-700 px-3 py-1 text-sm font-semibold">📣 {storeProducer.profile.news}</span>}
            </div>
          )}
          {storeProducer.profile?.description && <p className="text-sm text-slate-600 mt-4">{storeProducer.profile.description}</p>}
          {storeProducts.length === 0 ? (
            <div className="mt-5"><EmptyState icon="📦" title="Vetrina in allestimento" hint="Questo produttore non ha ancora pubblicato prodotti. Torna a trovarlo presto." /></div>
          ) : (
            <div className="mt-5 grid grid-cols-2 sm:grid-cols-3 gap-3">
              {storeProducts.map(p => (
                <button key={p.id} onClick={() => setPreviewId(p.id)} className="card-hover rounded-2xl bg-white border border-slate-100 overflow-hidden text-left">
                  <ProductImage p={p} className="w-full h-28" />
                  <div className="p-2.5">
                    <div className="font-semibold text-sm line-clamp-1">{p.name}</div>
                    <div className="mt-1.5"><AllergenBadges p={p} small /></div>
                  </div>
                </button>
              ))}
            </div>
          )}
          <div className="mt-6 rounded-2xl bg-slate-50 border border-slate-100 p-4 text-center">
            <div className="text-slate-500 text-sm">🔒 Prezzi e collegamento riservati alle aziende registrate</div>
            <div className="mt-3 flex flex-wrap justify-center gap-2">
              <button onClick={() => goRegister("client")} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30">Registrati per collegarti</button>
              <button onClick={() => setRoute("login")} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">Accedi</button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}

/* ============================================================
   AUTH — registrazione / login
   ============================================================ */
function Auth({ mode, login, register, setRoute, notify, initialRole }) {
  const [role, setRole] = useState(initialRole || "client");
  const [form, setForm] = useState({ company:"", vat:"", address:"", contact:"", email:"", password:"" });
  const [privacy, setPrivacy] = useState(false);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  async function submit(e) {
    e.preventDefault();
    setErr("");
    if (busy) return;
    if (mode === "login") {
      setBusy(true);
      try { await login(form.email, form.password); notify("Bentornato su ForniGo"); }
      catch (er) { setErr(er.message || "Email o password non corretti."); }
      finally { setBusy(false); }
      return;
    }
    // registrazione: tutti i campi obbligatori + privacy
    for (const [k, v] of Object.entries(form)) if (!String(v).trim()) return setErr("Compila tutti i campi obbligatori.");
    if (!privacy) return setErr("Per registrarti devi accettare l'informativa privacy e le condizioni d'uso.");
    setBusy(true);
    try { await register(form, role); notify("Registrazione completata 🎉"); }
    catch (er) { setErr(er.message || "Registrazione non riuscita."); }
    finally { setBusy(false); }
  }

  return (
    <div className="mesh min-h-screen grid place-items-center p-5">
      <div className="w-full max-w-md">
        <button onClick={() => setRoute("home")} className="mb-6"><Logo /></button>
        <div className="rounded-3xl bg-white shadow-2xl p-7 animate-fade-up">
          <h1 className="text-2xl font-bold">{mode === "login" ? "Accedi" : "Crea il tuo account"}</h1>
          <p className="text-slate-500 mt-1">{mode === "login" ? "Bentornato su ForniGo." : "Riservato alle aziende (B2B)."}</p>

          {mode === "register" && (
            <div className="mt-5 grid grid-cols-2 gap-2 p-1 bg-slate-100 rounded-2xl">
              {[["client","Sono un Cliente"],["producer","Sono un Produttore"]].map(([v,l]) => (
                <button key={v} onClick={() => setRole(v)}
                  className={`py-2.5 rounded-xl text-sm font-semibold transition ${role===v?"bg-white shadow text-brand-700":"text-slate-500"}`}>{l}</button>
              ))}
            </div>
          )}

          <form onSubmit={submit} className="mt-5 space-y-3">
            {mode === "register" && <>
              <Field label="Ragione sociale" required><input className={inputCls} value={form.company} onChange={set("company")} placeholder="Es. Forno Bianchi srl" /></Field>
              <div className="grid grid-cols-2 gap-3">
                <Field label="Partita IVA" required><input className={inputCls} value={form.vat} onChange={set("vat")} /></Field>
                <Field label="Referente" required><input className={inputCls} value={form.contact} onChange={set("contact")} /></Field>
              </div>
              <Field label="Indirizzo" required><input className={inputCls} value={form.address} onChange={set("address")} placeholder="Via, città" /></Field>
            </>}
            <Field label="Email" required><input type="email" className={inputCls} value={form.email} onChange={set("email")} /></Field>
            <Field label="Password" required><input type="password" className={inputCls} value={form.password} onChange={set("password")} /></Field>

            {mode === "register" && (
              <label className="flex items-start gap-3 text-sm text-slate-600 bg-slate-50 rounded-xl p-3 cursor-pointer">
                <input type="checkbox" checked={privacy} onChange={e=>setPrivacy(e.target.checked)} className="mt-0.5 w-4 h-4 accent-brand-600" />
                <span>Ho letto l'<a href="/privacy" target="_blank" rel="noopener" className="font-semibold text-brand-700 underline">informativa privacy</a> e accetto le <a href="/condizioni" target="_blank" rel="noopener" className="font-semibold text-brand-700 underline">condizioni d'uso</a> di ForniGo. <span className="text-brand-600">*</span></span>
              </label>
            )}

            {err && <div className="text-sm text-red-600 bg-red-50 rounded-xl px-3 py-2">{err}</div>}

            <button disabled={busy} className="w-full py-3 rounded-xl bg-brand-600 text-white font-semibold shadow-lg shadow-brand-600/30 hover:bg-brand-700 transition disabled:opacity-60">
              {busy ? "Attendi…" : (mode === "login" ? "Entra" : "Registrati")}
            </button>
          </form>

          <button onClick={()=>setRoute("register")}
            className="mt-4 w-full py-3 rounded-xl bg-emerald-50 border-2 border-emerald-600 text-emerald-800 font-bold hover:bg-emerald-100 transition">
            ⚡ Hai Kepi? Registrati come produttore e importa il listino
          </button>
          <p className="mt-1 text-center text-xs text-slate-400">Dopo la registrazione, dalla sezione «I miei prodotti» premi «Importa da Kepi».</p>
          <div className="mt-4 text-center text-sm text-slate-500">
            {mode === "login"
              ? <>Non hai un account? <button onClick={()=>setRoute("register")} className="text-brand-700 font-semibold">Registrati</button></>
              : <>Hai già un account? <button onClick={()=>setRoute("login")} className="text-brand-700 font-semibold">Accedi</button></>}
          </div>
          {mode==="login" && <p className="mt-3 text-center text-xs text-slate-400">Demo: demo.molino@fornigo.it / demo.cliente@fornigo.it · password: <b>demo</b></p>}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   AVVISI / NOTIFICHE (anteprima delle email)
   ============================================================ */
const EMAIL_ICON = { contact: "🤝", approval: "✅", message: "💬", order: "📥" };

function NotificationsBell({ me, emails, markNotificationsRead, emailAttiva, variant = "sidebar" }) {
  const [open, setOpen] = useState(false);
  const mine = emails.filter(e => e.toId === me.id).sort((a, b) => new Date(b.at) - new Date(a.at));
  const unread = mine.filter(e => !e.read).length;

  function openPanel() {
    setOpen(true);
    if (unread && markNotificationsRead) markNotificationsRead();
  }

  const trigger = variant === "sidebar" ? (
    <button onClick={openPanel}
      className="w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 transition">
      <span className="flex items-center gap-2.5"><span>🔔</span>Avvisi</span>
      {unread ? <span className="text-xs px-2 py-0.5 rounded-full bg-red-500 text-white">{unread}</span> : null}
    </button>
  ) : (
    <button onClick={openPanel} className="relative grid place-items-center w-9 h-9 rounded-full hover:bg-slate-100 text-lg">
      🔔{unread ? <span className="absolute -top-0.5 -right-0.5 text-[10px] bg-red-500 text-white rounded-full min-w-[16px] h-4 px-1 grid place-items-center">{unread}</span> : null}
    </button>
  );

  return (
    <>
      {trigger}
      <Modal open={open} onClose={() => setOpen(false)} title="🔔 I tuoi avvisi">
        <div className="rounded-xl bg-brand-50 border border-brand-100 text-brand-800 text-xs p-3 mb-3">
          {emailAttiva
            ? <>📩 Questi avvisi ti arrivano anche <b>via email</b>, all'indirizzo del tuo account.</>
            : <>📩 Qui trovi gli avvisi su richieste di collegamento, ordini e messaggi.</>}
        </div>
        {mine.length === 0 ? (
          <p className="text-center text-slate-400 py-8 text-sm">Nessun avviso per ora.</p>
        ) : (
          <div className="space-y-2 max-h-[55vh] overflow-auto">
            {mine.map(e => (
              <div key={e.id} className="flex gap-3 rounded-2xl border border-slate-100 bg-white p-3">
                <span className="text-xl shrink-0">{EMAIL_ICON[e.type] || "✉️"}</span>
                <div className="min-w-0">
                  <div className="font-semibold text-sm">{e.subject}</div>
                  <div className="text-sm text-slate-500 mt-0.5">{e.body}</div>
                  <div className="text-[11px] text-slate-400 mt-1">{new Date(e.at).toLocaleString("it-IT", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </Modal>
    </>
  );
}

/* ============================================================
   Layout dashboard (sidebar)
   ============================================================ */
// Cancellazione dell'account: l'utente la fa da solo, con la password, e tutto sparisce subito.
function DeleteAccount({ me, deleteAccount, emailAttiva }) {
  const [open, setOpen] = useState(false);
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const close = () => { setOpen(false); setPassword(""); setError(""); };
  const submit = async (e) => {
    e.preventDefault();
    if (!password) { setError("Scrivi la tua password."); return; }
    setBusy(true); setError("");
    try { await deleteAccount(password); }
    catch (err) { setError(err.message); setBusy(false); }
  };
  return (
    <div className="mt-12 pt-6 border-t border-slate-200 text-center">
      <button onClick={() => setOpen(true)} className="text-xs text-slate-400 hover:text-red-600 hover:underline">Elimina il mio account e i miei dati</button>
      <Modal open={open} onClose={close} title="Eliminare l'account?">
        <form onSubmit={submit} className="space-y-4 text-left">
          <p className="text-sm text-slate-600">Cancelliamo subito e per sempre l'account di <b>{me.company}</b>
            {me.role === "producer" ? ", i tuoi prodotti e la tua vetrina" : ""}, i collegamenti, gli ordini, i messaggi e gli avvisi.
            Non si può annullare.{emailAttiva ? " Ti arriva un'email di conferma." : ""}</p>
          <Field label="Per confermare scrivi la tua password" required>
            <input type="password" autoComplete="current-password" className={inputCls} value={password} onChange={e => setPassword(e.target.value)} />
          </Field>
          {error && <p className="text-sm font-medium text-red-600">{error}</p>}
          <div className="flex flex-wrap gap-2 justify-end">
            <button type="button" onClick={close} className="px-4 py-2.5 rounded-xl text-sm font-semibold text-slate-600 hover:bg-slate-100">Annulla</button>
            <button type="submit" disabled={busy} className="px-4 py-2.5 rounded-xl text-sm font-semibold bg-red-600 text-white hover:bg-red-700 disabled:opacity-60">{busy ? "Cancello…" : "Elimina definitivamente"}</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}

function DashShell({ me, logout, setRoute, tabs, tab, setTab, badges = {}, emails = [], markNotificationsRead, deleteAccount, emailAttiva, children }) {
  return (
    <div className="min-h-screen flex bg-[#f6f8f7]">
      <aside className="w-64 shrink-0 hidden md:flex flex-col bg-white border-r border-slate-100 p-4">
        <div className="px-2 py-2"><Logo /></div>
        <div className="mt-4 px-3 py-3 rounded-2xl bg-brand-50 border border-brand-100">
          <div className="text-xs font-semibold text-brand-700">{me.role === "producer" ? "PRODUTTORE" : "CLIENTE"}</div>
          <div className="font-bold text-sm mt-0.5 truncate">{me.company}</div>
        </div>
        <nav className="mt-4 space-y-1">
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)}
              className={`w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium transition
                ${tab===t.id ? "bg-brand-600 text-white shadow-md shadow-brand-600/25" : "text-slate-600 hover:bg-slate-100"}`}>
              <span className="flex items-center gap-2.5"><span>{t.icon}</span>{t.label}</span>
              {badges[t.id] ? <span className={`text-xs px-2 py-0.5 rounded-full ${tab===t.id?"bg-white/25":"bg-brand-100 text-brand-700"}`}>{badges[t.id]}</span> : null}
            </button>
          ))}
          <NotificationsBell me={me} emails={emails} markNotificationsRead={markNotificationsRead} emailAttiva={emailAttiva} variant="sidebar" />
        </nav>
        <button onClick={() => logout()} className="mt-auto px-3 py-2.5 rounded-xl text-sm font-medium text-slate-500 hover:bg-slate-100 text-left">↩ Esci</button>
      </aside>

      <div className="flex-1 min-w-0 flex flex-col">
        <header className="md:hidden glass sticky top-0 z-20 border-b border-slate-100 px-4 h-14 flex items-center justify-between">
          <Logo size="text-lg" />
          <div className="flex items-center gap-1">
            <NotificationsBell me={me} emails={emails} markNotificationsRead={markNotificationsRead} emailAttiva={emailAttiva} variant="mobile" />
            <button onClick={() => logout()} className="text-sm text-slate-500">Esci</button>
          </div>
        </header>
        <main className="flex-1 p-5 md:p-8 max-w-6xl w-full mx-auto">{children}<DeleteAccount me={me} deleteAccount={deleteAccount} emailAttiva={emailAttiva} /></main>
        <nav className="md:hidden sticky bottom-0 bg-white border-t border-slate-100 flex">
          {tabs.slice(0,5).map(t => (
            <button key={t.id} onClick={()=>setTab(t.id)} className={`flex-1 py-2.5 text-[11px] flex flex-col items-center gap-0.5 relative ${tab===t.id?"text-brand-700":"text-slate-400"}`}>
              <span className="text-lg">{t.icon}</span>{t.label}
              {badges[t.id] ? <span className="absolute top-1 right-1/4 text-[9px] bg-brand-600 text-white rounded-full px-1.5">{badges[t.id]}</span> : null}
            </button>
          ))}
        </nav>
      </div>
    </div>
  );
}

function PageHead({ title, sub, children }) {
  return (
    <div className="flex flex-wrap items-end justify-between gap-3 mb-6">
      <div><h1 className="text-2xl font-bold">{title}</h1>{sub && <p className="text-slate-500 mt-0.5">{sub}</p>}</div>
      {children}
    </div>
  );
}

/* ============================================================
   CHAT / MESSAGGI (condivisa cliente ⇄ produttore)
   ============================================================ */
function unreadCount(messages, meId) {
  return messages.filter(m => m.toId === meId && !m.read).length;
}

function MessagesView({ me, users, links, messages, sendMessage, markMessagesRead, role, notify }) {
  // contatti = controparti collegate e approvate
  const partnerIds = links
    .filter(l => l.status === "approved" && (role === "producer" ? l.producerId === me.id : l.clientId === me.id))
    .map(l => role === "producer" ? l.clientId : l.producerId);
  const partners = partnerIds.map(id => users.find(u => u.id === id)).filter(Boolean);

  const [selId, setSelId] = useState(partners[0]?.id || null);
  const [text, setText] = useState("");
  const endRef = useRef();

  const thread = messages
    .filter(m => (m.fromId === me.id && m.toId === selId) || (m.fromId === selId && m.toId === me.id))
    .sort((a, b) => new Date(a.at) - new Date(b.at));

  // segna come letti (sul motore) i messaggi della conversazione aperta
  useEffect(() => {
    if (!selId) return;
    const toRead = messages.filter(m => m.fromId === selId && m.toId === me.id && !m.read);
    if (toRead.length && markMessagesRead) markMessagesRead(selId);
  }, [selId, messages.length]);

  useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [thread.length, selId]);

  async function send() {
    const t = text.trim();
    if (!t || !selId) return;
    setText("");
    try { await sendMessage(selId, t); }
    catch (e) { notify(e.message || "Messaggio non inviato"); setText(t); }
  }

  const lastMsg = (pid) => messages.filter(m => (m.fromId === me.id && m.toId === pid) || (m.fromId === pid && m.toId === me.id)).sort((a,b)=>new Date(b.at)-new Date(a.at))[0];
  const unreadFrom = (pid) => messages.filter(m => m.fromId === pid && m.toId === me.id && !m.read).length;

  if (!partners.length) return (
    <div className="animate-fade-up">
      <PageHead title="Messaggi" sub="Scrivi ai tuoi contatti collegati." />
      <div className="rounded-3xl border-2 border-dashed border-slate-200 p-12 text-center text-slate-400">
        {role === "producer"
          ? "Ancora nessun cliente collegato con cui chattare. Approva una richiesta nella sezione Clienti."
          : "Non sei ancora collegato a nessun fornitore. Vai in Fornitori e richiedi un collegamento."}
      </div>
    </div>
  );

  const sel = users.find(u => u.id === selId);

  return (
    <div className="animate-fade-up h-[calc(100vh-9rem)] md:h-[calc(100vh-5rem)]">
      <div className="grid md:grid-cols-[280px_1fr] gap-4 h-full">
        {/* elenco conversazioni */}
        <div className="rounded-3xl bg-white border border-slate-100 overflow-auto">
          <div className="px-4 py-3 font-bold border-b border-slate-100">Conversazioni</div>
          {partners.map(p => {
            const lm = lastMsg(p.id); const un = unreadFrom(p.id);
            return (
              <button key={p.id} onClick={() => setSelId(p.id)}
                className={`w-full text-left px-4 py-3 border-b border-slate-50 flex items-center gap-3 transition ${selId===p.id?"bg-brand-50":"hover:bg-slate-50"}`}>
                <div className="w-10 h-10 rounded-full bg-gradient-to-br from-brand-200 to-brand-400 grid place-items-center text-white font-bold shrink-0">{p.company[0]}</div>
                <div className="min-w-0 flex-1">
                  <div className="font-semibold text-sm truncate">{p.company}</div>
                  <div className="text-xs text-slate-400 truncate">{lm ? (lm.fromId===me.id?"Tu: ":"") + lm.text : "Nessun messaggio"}</div>
                </div>
                {un > 0 && <span className="shrink-0 text-xs bg-brand-600 text-white rounded-full w-5 h-5 grid place-items-center">{un}</span>}
              </button>
            );
          })}
        </div>

        {/* thread */}
        <div className="rounded-3xl bg-white border border-slate-100 flex flex-col overflow-hidden">
          <div className="px-5 py-3 border-b border-slate-100 flex items-center gap-3">
            <div className="w-9 h-9 rounded-full bg-gradient-to-br from-brand-200 to-brand-400 grid place-items-center text-white font-bold">{sel?.company[0]}</div>
            <div><div className="font-bold text-sm">{sel?.company}</div><div className="text-xs text-slate-400">{sel?.contact}</div></div>
          </div>
          <div className="flex-1 overflow-auto p-5 space-y-2 bg-[#f6f8f7]">
            {thread.length === 0 && <p className="text-center text-slate-400 text-sm mt-8">Inizia la conversazione 👋</p>}
            {thread.map(m => {
              const mine = m.fromId === me.id;
              return (
                <div key={m.id} className={`flex ${mine?"justify-end":"justify-start"}`}>
                  <div className={`max-w-[75%] px-3.5 py-2 rounded-2xl text-sm animate-pop ${mine?"bg-brand-600 text-white rounded-br-md":"bg-white border border-slate-200 rounded-bl-md"}`}>
                    {m.text}
                    <div className={`text-[10px] mt-1 ${mine?"text-white/70":"text-slate-400"}`}>{new Date(m.at).toLocaleTimeString("it-IT",{hour:"2-digit",minute:"2-digit"})}</div>
                  </div>
                </div>
              );
            })}
            <div ref={endRef}></div>
          </div>
          <div className="p-3 border-t border-slate-100 flex gap-2">
            <input value={text} onChange={e=>setText(e.target.value)} onKeyDown={e=>e.key==="Enter"&&send()}
              placeholder="Scrivi un messaggio..." className={inputCls} />
            <button onClick={send} className="px-5 rounded-xl bg-brand-600 text-white font-semibold shrink-0 hover:bg-brand-700">Invia</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   DASHBOARD PRODUTTORE
   ============================================================ */
function ProducerDash(props) {
  const { me, products, links, users, orders, messages } = props;
  const [tab, setTab] = useState("home");
  const [invite, setInvite] = useState(false);

  const myProducts = products.filter(p => p.producerId === me.id);
  const myLinks = links.filter(l => l.producerId === me.id);
  const pending = myLinks.filter(l => l.status === "pending");
  const approved = myLinks.filter(l => l.status === "approved");
  const myOrders = orders.filter(o => o.producerId === me.id);
  const unread = unreadCount(messages, me.id);

  const tabs = [
    { id:"home",     label:"Home",      icon:"🏠" },
    { id:"products", label:"Prodotti",  icon:"📦" },
    { id:"orders",   label:"Ordini",    icon:"📥" },
    { id:"clients",  label:"Clienti",   icon:"👥" },
    { id:"messages", label:"Messaggi",  icon:"💬" },
    { id:"profile",  label:"Vetrina",   icon:"🏷️" },
  ];

  return (
    <DashShell {...props} tabs={tabs} tab={tab} setTab={setTab} badges={{ clients: pending.length || null, orders: myOrders.length || null, messages: unread || null }}>
      {tab === "home" && (
        <div className="animate-fade-up">
          <PageHead title={`Ciao, ${me.company}`} sub="Ecco la tua attività di oggi." />
          <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {[
              ["Prodotti a catalogo", myProducts.length, "📦", "products"],
              ["Ordini ricevuti", myOrders.length, "📥", "orders"],
              ["Clienti collegati", approved.length, "🤝", "clients"],
              ["Richieste in attesa", pending.length, "⏳", "clients"],
            ].map(([l,v,i,go]) => (
              <button key={l} onClick={()=>setTab(go)} className="card-hover text-left rounded-3xl bg-white border border-slate-100 p-5">
                <div className="text-2xl">{i}</div>
                <div className="text-3xl font-extrabold mt-2">{v}</div>
                <div className="text-slate-500 text-sm">{l}</div>
              </button>
            ))}
          </div>
          {pending.length > 0 && (
            <div className="mt-6 rounded-3xl bg-amber-50 border border-amber-200 p-5">
              <b>Hai {pending.length} richiesta/e di collegamento</b> da approvare.
              <button onClick={()=>setTab("clients")} className="ml-2 text-amber-700 font-semibold underline">Gestisci →</button>
            </div>
          )}
          <div className="mt-6 rounded-3xl bg-gradient-to-br from-brand-600 to-brand-800 text-white p-6 flex flex-wrap items-center justify-between gap-4">
            <div>
              <div className="font-extrabold text-lg">Fai crescere ForniGo (e i tuoi affari)</div>
              <div className="text-brand-50/90 text-sm mt-0.5">Conosci un altro produttore? Invitalo: più aziende ci sono, più clienti arrivano per tutti.</div>
            </div>
            <button onClick={() => setInvite(true)} className="px-5 py-3 rounded-xl bg-white text-brand-700 font-bold text-sm hover:bg-brand-50 shrink-0">📣 Invita un produttore</button>
          </div>
          <div className="mt-6"><KepiBanner variant="card" /></div>
        </div>
      )}

      <InviteModal open={invite} onClose={() => setInvite(false)} role="producer" inviterCompany={me.company} />

      {tab === "products" && <ProducerProducts me={me} myProducts={myProducts} addProduct={props.addProduct} importProducts={props.importProducts} deleteProduct={props.deleteProduct} importKepi={props.importKepi} notify={props.notify} />}
      {tab === "orders"   && <ProducerOrders me={me} orders={myOrders} users={users} notify={props.notify} />}
      {tab === "clients"  && <ProducerClients me={me} links={links} updateLink={props.updateLink} users={users} notify={props.notify} />}
      {tab === "messages" && <MessagesView me={me} users={users} links={links} messages={messages} sendMessage={props.sendMessage} markMessagesRead={props.markMessagesRead} role="producer" notify={props.notify} />}
      {tab === "profile"  && <ProducerProfile {...props} />}
    </DashShell>
  );
}

function ProducerProducts({ me, myProducts, addProduct, importProducts, deleteProduct, importKepi, notify }) {
  const [preview, setPreview] = useState(null); // righe importate dal CSV
  const [manuale, setManuale] = useState(null); // modulo "aggiungi a mano"
  const [busy, setBusy] = useState(false);

  async function aggiornaKepi() {
    let url = me.kepiUrl || "";
    if (!url) {
      url = window.prompt("Incolla il link del pacchetto Kepi\n(lo trovi in Kepi → Negozio online → Vendi su ForniGo):", "");
      if (!url) return;
    }
    setBusy(true);
    try { const d = await importKepi(url); notify(`Importati ${d.count} prodotti da Kepi ✅`); }
    catch (e) { notify(e.message || "Import da Kepi non riuscito"); }
    finally { setBusy(false); }
  }
  const [q, setQ] = useState("");
  const [category, setCategory] = useState("");
  const [allerg, setAllerg] = useState({});
  const fileRef = useRef();
  const categories = [...new Set(myProducts.map(p => p.category).filter(Boolean))].sort((a,b)=>a.localeCompare(b,"it"));
  const qn = q.trim().toLowerCase();
  const shown = myProducts.filter(p =>
    (!qn || [p.name, p.category, p.description].some(v => (v||"").toLowerCase().includes(qn))) &&
    (!category || p.category === category) &&
    Object.keys(allerg).every(k => !allerg[k] || p[k])
  );
  const vuotoManuale = { name: "", category: "", price: "", storage: "ambiente",
    description: "", photo: "", datasheet: "", glutenFree: true, lactoseFree: false,
    eggFree: false, vegan: false, nutFree: false, sugarFree: false };

  async function salvaManuale() {
    if (!manuale.name.trim()) { notify("Scrivi almeno il nome del prodotto"); return; }
    setBusy(true);
    try { await addProduct(manuale); notify(`«${manuale.name}» aggiunto al catalogo ✅`); setManuale(null); }
    catch (e) { notify(e.message || "Errore nel salvataggio"); }
    finally { setBusy(false); }
  }

  function onCsv(e) {
    const file = e.target.files[0]; if (!file) return;
    Papa.parse(file, { header: true, skipEmptyLines: true, complete: (res) => {
      const rows = res.data.map(r => ({
        id: uid(), producerId: me.id, createdAt: Date.now(),
        name: r.nome || r.Nome || r.prodotto || "",
        category: r.categoria || r.Categoria || "",
        price: parseFloat(String(r.prezzo || r.Prezzo || "0").replace(",", ".")) || 0,
        description: r.descrizione || r.Descrizione || "",
        photo: r.foto || r.Foto || "",
        datasheet: r.scheda_tecnica || r.datasheet || r.Scheda_tecnica || "",
        glutenFree: truthy(r.senza_glutine), lactoseFree: truthy(r.senza_lattosio), eggFree: truthy(r.senza_uova),
        vegan: truthy(r.vegano), nutFree: truthy(r.senza_frutta_guscio), sugarFree: truthy(r.senza_zuccheri),
      })).filter(p => p.name);
      setPreview(rows);
    }});
    e.target.value = "";
  }

  async function confirmImport() {
    setBusy(true);
    try { const d = await importProducts(preview); notify(`${d.count} prodotti aggiunti al catalogo`); setPreview(null); }
    catch (e) { notify(e.message || "Errore nell'import"); }
    finally { setBusy(false); }
  }
  async function removeProduct(id) {
    try { await deleteProduct(id); } catch (e) { notify(e.message || "Errore"); }
  }

  function downloadTemplate() {
    const csv = "nome,categoria,prezzo,senza_glutine,senza_lattosio,senza_uova,vegano,senza_frutta_guscio,senza_zuccheri,descrizione,foto,scheda_tecnica\nMix Pane GF,Farine,4.50,si,si,si,si,si,no,Mix per pane rustico,,\n";
    const a = document.createElement("a");
    a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv" }));
    a.download = "modello_listino.csv"; a.click();
  }

  return (
    <div className="animate-fade-up">
      <PageHead title="I miei prodotti" sub="Aggiorna da Kepi, carica un CSV o aggiungi i prodotti a mano.">
        <div className="flex flex-wrap gap-2">
          <button onClick={aggiornaKepi} disabled={busy}
            className="px-4 py-2.5 rounded-xl bg-emerald-600 text-white font-semibold text-sm shadow-lg shadow-emerald-600/30 hover:bg-emerald-700 disabled:opacity-60">{busy ? "Attendi…" : (me.kepiUrl ? "🔄 Aggiorna da Kepi" : "⚡ Importa da Kepi")}</button>
          <button onClick={()=>setManuale({...vuotoManuale})} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">➕ Aggiungi a mano</button>
          <button onClick={downloadTemplate} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">⬇ Modello CSV</button>
          <button onClick={()=>fileRef.current.click()} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30 hover:bg-brand-700">⬆ Carica listino CSV</button>
          <input ref={fileRef} type="file" accept=".csv" className="hidden" onChange={onCsv} />
        </div>
      </PageHead>
      {me.kepiUrl && (
        <p className="text-xs text-slate-400 mb-4">🔗 Collegato a Kepi: premi «Aggiorna da Kepi» per
          risincronizzare articoli, foto e prezzi. I prodotti aggiunti a mano qui su ForniGo non vengono toccati.</p>
      )}

      <Modal open={!!manuale} onClose={()=>setManuale(null)} title="➕ Aggiungi un prodotto a mano">
        {manuale && (
          <div className="space-y-3">
            <Field label="Nome prodotto" required>
              <input className={inputCls} value={manuale.name} onChange={e=>setManuale(m=>({...m, name: e.target.value}))} placeholder="Es. Mix Pane Rustico GF" /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Categoria"><input className={inputCls} value={manuale.category} onChange={e=>setManuale(m=>({...m, category: e.target.value}))} placeholder="Es. Farine e mix" /></Field>
              <Field label="Prezzo (€, netto)"><input className={inputCls} value={manuale.price} onChange={e=>setManuale(m=>({...m, price: e.target.value}))} placeholder="Es. 4,50" /></Field>
            </div>
            <Field label="Temperatura di trasporto">
              <select className={inputCls} value={manuale.storage} onChange={e=>setManuale(m=>({...m, storage: e.target.value}))}>
                {Object.entries(TEMPS).map(([k, t]) => <option key={k} value={k}>{t.icon} {t.label}</option>)}
              </select></Field>
            <Field label="Descrizione"><textarea rows="2" className={inputCls} value={manuale.description} onChange={e=>setManuale(m=>({...m, description: e.target.value}))} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Foto (link immagine)"><input className={inputCls} value={manuale.photo} onChange={e=>setManuale(m=>({...m, photo: e.target.value}))} placeholder="https://..." /></Field>
              <Field label="Scheda tecnica (link PDF)"><input className={inputCls} value={manuale.datasheet} onChange={e=>setManuale(m=>({...m, datasheet: e.target.value}))} placeholder="https://..." /></Field>
            </div>
            <div className="flex flex-wrap gap-3 text-sm">
              {[["glutenFree","Senza glutine"],["lactoseFree","Senza lattosio"],["eggFree","Senza uova"],
                ["vegan","Vegano"],["nutFree","Senza frutta a guscio"],["sugarFree","Senza zuccheri"]].map(([k, l]) => (
                <label key={k} className="flex items-center gap-1.5 cursor-pointer">
                  <input type="checkbox" checked={!!manuale[k]} onChange={e=>setManuale(m=>({...m, [k]: e.target.checked}))} className="w-4 h-4 accent-brand-600" /> {l}
                </label>
              ))}
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <button onClick={()=>setManuale(null)} className="px-4 py-2.5 rounded-xl border border-slate-200 font-semibold">Annulla</button>
              <button onClick={salvaManuale} disabled={busy} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold disabled:opacity-60">{busy ? "Attendi…" : "Aggiungi al catalogo"}</button>
            </div>
          </div>
        )}
      </Modal>

      {myProducts.length === 0 && (
        <EmptyState icon="📦" title="Il tuo catalogo è vuoto"
          hint="Aggiungi i prodotti a mano, oppure scarica il modello CSV, compilalo con Excel e caricalo: centinaia di prodotti in un attimo."
          action={
            <div className="flex flex-wrap justify-center gap-2">
              <button onClick={()=>setManuale({...vuotoManuale})} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm">➕ Aggiungi a mano</button>
              <button onClick={downloadTemplate} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">⬇ Scarica modello CSV</button>
            </div>
          } />
      )}

      {myProducts.length > 0 && (
        <div className="space-y-3 mb-4">
          <div className="flex flex-wrap items-center gap-2">
            <input value={q} onChange={e=>setQ(e.target.value)} placeholder="🔎 Cerca tra i tuoi prodotti..."
              className={inputCls + " w-full sm:max-w-xs"} />
            <select value={category} onChange={e=>setCategory(e.target.value)}
              className="rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-700 outline-none focus:border-brand-500">
              <option value="">Tutte le categorie</option>
              {categories.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
            {(q || category || Object.values(allerg).some(Boolean)) && (
              <button onClick={()=>{ setQ(""); setCategory(""); setAllerg({}); }}
                className="px-3 py-2 rounded-xl text-sm font-semibold text-slate-500 hover:text-slate-700 hover:bg-slate-100">✕ Azzera</button>
            )}
          </div>
          <div className="flex flex-wrap gap-2">
            {ALLERGENS.map(a => (
              <Chip key={a.key} active={!!allerg[a.key]} onClick={()=>setAllerg(f=>({...f,[a.key]:!f[a.key]}))}>{a.icon} {a.label}</Chip>
            ))}
          </div>
        </div>
      )}

      {myProducts.length > 0 && (
        <div className="text-sm text-slate-400 mb-3">
          {shown.length === myProducts.length
            ? `${myProducts.length} ${myProducts.length === 1 ? "prodotto" : "prodotti"} a catalogo`
            : `${shown.length} di ${myProducts.length} prodotti`}
        </div>
      )}

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {shown.map(p => (
          <div key={p.id} className="card-hover rounded-3xl bg-white border border-slate-100 overflow-hidden">
            <ProductImage p={p} className="w-full h-32" />
            <div className="p-4">
              <div className="text-xs text-brand-600 font-semibold">{p.category || "—"}</div>
              <div className="font-bold">{p.name}</div>
              <div className="text-lg font-extrabold text-slate-800 mt-1">{euro(p.price)}</div>
              <div className="mt-2"><AllergenBadges p={p} small /></div>
              <button onClick={()=>removeProduct(p.id)} className="mt-3 text-xs text-red-500 hover:underline">Elimina</button>
            </div>
          </div>
        ))}
      </div>
      {myProducts.length > 0 && shown.length === 0 && (
        <div className="rounded-3xl border-2 border-dashed border-slate-200 p-12 text-center text-slate-400">
          Nessun prodotto con questi criteri. Prova a togliere qualche filtro.
        </div>
      )}

      <Modal open={!!preview} onClose={()=>setPreview(null)} title={`Anteprima import — ${preview?.length || 0} prodotti`} wide>
        <div className="max-h-[55vh] overflow-auto rounded-xl border border-slate-100">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 sticky top-0"><tr className="text-left text-slate-500">
              <th className="p-2">Nome</th><th className="p-2">Prezzo</th><th className="p-2">Intolleranze</th></tr></thead>
            <tbody>
              {preview?.map(p => (
                <tr key={p.id} className="border-t border-slate-100">
                  <td className="p-2 font-medium">{p.name}</td><td className="p-2">{euro(p.price)}</td>
                  <td className="p-2"><AllergenBadges p={p} small /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="mt-4 flex justify-end gap-2">
          <button onClick={()=>setPreview(null)} className="px-4 py-2.5 rounded-xl border border-slate-200 font-semibold">Annulla</button>
          <button onClick={confirmImport} disabled={busy} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold disabled:opacity-60">{busy ? "Attendi…" : "Conferma e pubblica"}</button>
        </div>
      </Modal>
    </div>
  );
}

function ProducerClients({ me, links, updateLink, users, notify }) {
  const myLinks = links.filter(l => l.producerId === me.id);
  const pending = myLinks.filter(l => l.status === "pending");
  const approved = myLinks.filter(l => l.status === "approved");
  const clientOf = (l) => users.find(u => u.id === l.clientId);

  async function approve(l) {
    try { await updateLink(l.id, { status: "approved" }); notify("Cliente approvato"); }
    catch (e) { notify(e.message || "Errore"); }
  }
  async function reject(l) {
    try { await updateLink(l.id, { status: "rejected" }); notify("Richiesta rifiutata"); }
    catch (e) { notify(e.message || "Errore"); }
  }
  async function saveDiscount(id, value) {
    const d = Math.max(0, Math.min(100, Number(value) || 0));
    try { await updateLink(id, { discount: d }); notify("Sconto aggiornato"); }
    catch (e) { notify(e.message || "Errore"); }
  }

  return (
    <div className="animate-fade-up">
      <PageHead title="I miei clienti" sub="Vedi solo i clienti collegati a te. Imposta gli sconti personalizzati." />

      {pending.length > 0 && (
        <div className="mb-6">
          <h3 className="font-bold text-slate-700 mb-2">⏳ Richieste in attesa</h3>
          <div className="space-y-2">
            {pending.map(l => { const c = clientOf(l); return (
              <div key={l.id} className="flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-amber-50 border border-amber-200 p-4">
                <div>
                  <div className="font-bold">{c?.company}</div>
                  <div className="text-sm text-slate-500">{c?.contact} · {c?.address}</div>
                </div>
                <div className="flex gap-2">
                  <button onClick={()=>approve(l)} className="px-4 py-2 rounded-xl bg-brand-600 text-white font-semibold text-sm">Approva</button>
                  <button onClick={()=>reject(l)} className="px-4 py-2 rounded-xl bg-white border border-slate-200 font-semibold text-sm">Rifiuta</button>
                </div>
              </div>
            ); })}
          </div>
        </div>
      )}

      <h3 className="font-bold text-slate-700 mb-2">🤝 Clienti attivi ({approved.length})</h3>
      {approved.length === 0 ? (
        <EmptyState icon="🤝" title="Ancora nessun cliente collegato"
          hint={pending.length > 0
            ? "Approva le richieste qui sopra per iniziare a lavorare con i tuoi clienti."
            : "Quando un cliente ti chiederà il collegamento lo vedrai qui. Intanto puoi invitare i tuoi clienti a registrarsi su ForniGo."} />
      ) : (
        <div className="rounded-3xl bg-white border border-slate-100 overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-slate-50"><tr className="text-left text-slate-500">
              <th className="p-4">Azienda</th><th className="p-4 hidden sm:table-cell">Referente</th><th className="p-4">Sconto dedicato</th></tr></thead>
            <tbody>
              {approved.map(l => { const c = clientOf(l); return (
                <tr key={l.id} className="border-t border-slate-100">
                  <td className="p-4"><div className="font-semibold">{c?.company}</div><div className="text-xs text-slate-400">{c?.email}</div></td>
                  <td className="p-4 hidden sm:table-cell text-slate-600">{c?.contact}</td>
                  <td className="p-4">
                    <div className="flex items-center gap-2">
                      <input type="number" min="0" max="100" key={l.discount || 0} defaultValue={l.discount || 0}
                        onBlur={e=>{ if (Number(e.target.value) !== (l.discount||0)) saveDiscount(l.id, e.target.value); }}
                        onKeyDown={e=>{ if (e.key === "Enter") e.target.blur(); }}
                        className="w-20 rounded-lg border border-slate-200 px-2 py-1.5" />
                      <span className="text-slate-500">%</span>
                    </div>
                  </td>
                </tr>
              ); })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function ProducerOrders({ me, orders, users }) {
  const sorted = [...orders].sort((a,b) => new Date(b.date) - new Date(a.date));
  const total = sorted.reduce((s,o) => s + o.total, 0);
  return (
    <div className="animate-fade-up">
      <PageHead title="Ordini ricevuti" sub="Gli ordini inviati dai tuoi clienti collegati.">
        {sorted.length > 0 &&
          <button onClick={()=>downloadOrdersCSV(sorted, users, `ordini_${me.company.replace(/\s+/g,"_")}.csv`)}
            className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30 hover:bg-brand-700">⬇ Scarica ordini CSV</button>}
      </PageHead>

      {sorted.length === 0 ? (
        <div className="rounded-3xl border-2 border-dashed border-slate-200 p-12 text-center text-slate-400">Nessun ordine ricevuto per ora.</div>
      ) : <>
        <div className="grid sm:grid-cols-3 gap-4 mb-6">
          <div className="rounded-3xl bg-white border border-slate-100 p-5"><div className="text-3xl font-extrabold">{sorted.length}</div><div className="text-slate-500 text-sm">Ordini totali</div></div>
          <div className="rounded-3xl bg-white border border-slate-100 p-5"><div className="text-3xl font-extrabold text-brand-700">{euro(total)}</div><div className="text-slate-500 text-sm">Valore totale</div></div>
          <div className="rounded-3xl bg-white border border-slate-100 p-5"><div className="text-3xl font-extrabold">{new Set(sorted.map(o=>o.clientId)).size}</div><div className="text-slate-500 text-sm">Clienti che hanno ordinato</div></div>
        </div>
        <div className="space-y-4">
          {sorted.map(o => { const client = users.find(u => u.id === o.clientId); return (
            <div key={o.id} className="rounded-3xl bg-white border border-slate-100 overflow-hidden">
              <div className="flex flex-wrap items-center justify-between gap-2 px-5 py-4 bg-slate-50 border-b border-slate-100">
                <div><div className="font-bold">{client?.company}
                  {o.trasporto && TEMPS[o.trasporto] && (
                    <span className={`ml-2 inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] align-middle ${TEMPS[o.trasporto].cls}`}>
                      {TEMPS[o.trasporto].icon} Spedizione {TEMPS[o.trasporto].label.toLowerCase()}</span>
                  )}</div>
                  <div className="text-xs text-slate-400">{o.id} · {new Date(o.date).toLocaleDateString("it-IT")} · {client?.contact}</div></div>
                <span className="font-bold text-brand-700">{euro(o.total)}</span>
              </div>
              <div className="px-5 py-3 text-sm text-slate-600">
                {o.items.map(it => <div key={it.productId} className="flex justify-between py-0.5"><span>{it.qty}× {it.name}{it.discount?` (-${it.discount}%)`:""}</span><span>{euro(it.lineTotal)}</span></div>)}
              </div>
            </div>
          ); })}
        </div>
      </>}
    </div>
  );
}

function ProducerProfile({ me, updateProfile, notify }) {
  const [p, setP] = useState(me.profile || {});
  const [busy, setBusy] = useState(false);
  const set = (k) => (e) => setP(v => ({ ...v, [k]: e.target.value }));
  async function save() {
    setBusy(true);
    try { await updateProfile(p); notify("Vetrina aggiornata"); }
    catch (e) { notify(e.message || "Errore nel salvataggio"); }
    finally { setBusy(false); }
  }
  const previewUser = { ...me, profile: p };
  return (
    <div className="animate-fade-up grid lg:grid-cols-2 gap-6 items-start">
      <div>
        <PageHead title="Vetrina aziendale" sub="Presentazione, novità e promo che i clienti vedono sul tuo profilo." />
        <div className="space-y-4 rounded-3xl bg-white border border-slate-100 p-6">
          <Field label="Presentazione azienda"><textarea rows="3" className={inputCls} value={p.description||""} onChange={set("description")} /></Field>
          <Field label="Novità"><input className={inputCls} value={p.news||""} onChange={set("news")} placeholder="Es. Nuovo prodotto in arrivo" /></Field>
          <Field label="Promo in corso"><input className={inputCls} value={p.promo||""} onChange={set("promo")} placeholder="Es. -15% sul primo ordine" /></Field>
          <Field label="Logo (link immagine)"><input className={inputCls} value={p.logo||""} onChange={set("logo")} placeholder="https://..." /></Field>
          <button onClick={save} disabled={busy} className="px-5 py-2.5 rounded-xl bg-brand-600 text-white font-semibold shadow-lg shadow-brand-600/30 disabled:opacity-60">{busy ? "Attendi…" : "Salva"}</button>
        </div>
      </div>
      <div className="lg:sticky lg:top-6">
        <div className="text-sm font-semibold text-slate-500 mb-2">Anteprima — così ti vedono i clienti</div>
        <div className="rounded-3xl bg-white border border-slate-100 p-6 shadow-sm">
          <div className="flex items-center gap-4">
            <Avatar user={previewUser} className="w-16 h-16" text="text-2xl" />
            <div className="min-w-0">
              <div className="font-extrabold text-lg truncate">{me.company}</div>
              <div className="text-xs text-slate-400 truncate">{me.address}</div>
            </div>
          </div>
          {p.promo && <div className="mt-4 inline-block text-xs font-semibold bg-amber-100 text-amber-700 px-3 py-1 rounded-full">🎁 {p.promo}</div>}
          {p.news && <div className="mt-2 inline-block text-xs font-semibold bg-brand-50 text-brand-700 px-3 py-1 rounded-full ml-2">📣 {p.news}</div>}
          <p className="text-sm text-slate-600 mt-4">{p.description || "La tua presentazione apparirà qui."}</p>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   DASHBOARD CLIENTE
   ============================================================ */
function ClientDash(props) {
  const { me, products, users, links, orders, messages } = props;
  const [tab, setTab] = useState("catalog");
  const unread = unreadCount(messages, me.id);

  const cartKey = "pl_cart_" + me.id;
  const [cart, setCart] = useState(() => JSON.parse(localStorage.getItem(cartKey) || "[]"));
  useEffect(() => { localStorage.setItem(cartKey, JSON.stringify(cart)); }, [cart]);

  const myLinks = links.filter(l => l.clientId === me.id);
  const approvedIds = myLinks.filter(l => l.status === "approved").map(l => l.producerId);
  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const myOrders = orders.filter(o => o.clientId === me.id);

  const addToCart = (productId) => setCart(c => {
    const e = c.find(x => x.productId === productId);
    return e ? c.map(x => x.productId === productId ? { ...x, qty: x.qty + 1 } : x) : [...c, { productId, qty: 1 }];
  });
  const setQty = (productId, qty) => setCart(c => qty <= 0 ? c.filter(x => x.productId !== productId) : c.map(x => x.productId === productId ? { ...x, qty } : x));

  async function requestLink(producerId) {
    if (links.some(l => l.clientId === me.id && l.producerId === producerId)) { props.notify("Richiesta già inviata o già collegato."); return; }
    try {
      await props.requestLink(producerId);
      const producer = users.find(u => u.id === producerId);
      avvisaKepi(producer, "collegamento",
        `${me.company} (referente ${me.contact}) chiede il collegamento al tuo catalogo su ForniGo. Entra su ForniGo → Clienti per approvare.`);
      props.notify("Richiesta di collegamento inviata ✅");
    } catch (e) { props.notify(e.message || "Errore nella richiesta"); }
  }

  const [overlay, setOverlay] = useState(null); // {kind:'product'|'store', id}
  const openProduct = (id) => setOverlay({ kind: "product", id });
  const openStore = (id) => setOverlay({ kind: "store", id });
  const closeOverlay = () => setOverlay(null);

  const shared = { me, products, users, links, approvedIds, addToCart, requestLink, openProduct, openStore, notify: props.notify };

  const tabs = [
    { id:"catalog",   label:"Catalogo",  icon:"🔎" },
    { id:"quote",     label:"Preventivo",icon:"🧾" },
    { id:"orders",    label:"Ordini",    icon:"📥" },
    { id:"messages",  label:"Messaggi",  icon:"💬" },
    { id:"suppliers", label:"Fornitori", icon:"🤝" },
  ];

  return (
    <DashShell {...props} tabs={tabs} tab={tab} setTab={setTab} badges={{ quote: cartCount || null, orders: myOrders.length || null, messages: unread || null }}>
      {tab === "catalog"   && <ClientCatalog {...shared} />}
      {tab === "quote"     && <ClientQuote me={me} products={products} users={users} links={links} cart={cart} setQty={setQty} setCart={setCart} createOrder={props.createOrder} setTab={setTab} notify={props.notify} />}
      {tab === "orders"    && <ClientOrders me={me} users={users} orders={myOrders} />}
      {tab === "messages"  && <MessagesView me={me} users={users} links={links} messages={messages} sendMessage={props.sendMessage} markMessagesRead={props.markMessagesRead} role="client" notify={props.notify} />}
      {tab === "suppliers" && <ClientSuppliers {...shared} setTab={setTab} />}

      {overlay?.kind === "product" && <ProductModal productId={overlay.id} {...shared} onClose={closeOverlay} />}
      {overlay?.kind === "store"   && <StoreModal producerId={overlay.id} {...shared} onClose={closeOverlay} />}
    </DashShell>
  );
}

function ClientQuote({ me, products, users, links, cart, setQty, setCart, createOrder, setTab, notify }) {
  const groups = groupCart(cart, products, links, me.id);
  const producerIds = Object.keys(groups);

  async function sendOrder(producerId, items) {
    // Un ordine per ogni CATEGORIA DI TRASPORTO (surgelato/fresco/ambiente):
    // viaggiano con spedizioni diverse, quindi il fornitore li riceve separati.
    const perTemp = {};
    for (const it of items) {
      const p = products.find(x => x.id === it.productId);
      const t = p ? tempDi(p) : "ambiente";
      (perTemp[t] = perTemp[t] || []).push(it);
    }
    const gruppi = Object.entries(perTemp);
    try {
      for (const [t, righe] of gruppi) {
        await createOrder({ producerId, items: righe, total: sumItems(righe), trasporto: t });
      }
    } catch (e) { notify(e.message || "Ordine non inviato"); return; }
    setCart(cart.filter(ci => { const p = products.find(x => x.id === ci.productId); return !p || p.producerId !== producerId; }));
    const producer = users.find(u => u.id === producerId);
    const totale = gruppi.reduce((s, [t, righe]) => s + sumItems(righe), 0);
    avvisaKepi(producer, "ordine",
      `${me.company} ha ordinato per ${euro(totale)} su ForniGo. Entra su ForniGo → Ordini per i dettagli.`);
    notify(gruppi.length > 1
      ? `Ordine inviato, diviso in ${gruppi.length} spedizioni (${gruppi.map(([t]) => TEMPS[t].label).join(" + ")}) ✅`
      : "Ordine inviato al fornitore ✅");
    setTab("orders");
  }

  if (!producerIds.length) return (
    <div className="animate-fade-up">
      <PageHead title="Preventivo" sub="Aggiungi prodotti dei tuoi fornitori dal catalogo." />
      <div className="rounded-3xl border-2 border-dashed border-slate-200 p-12 text-center text-slate-400">
        Il preventivo è vuoto. Vai nel <b>Catalogo</b> e premi “+ Preventivo” sui prodotti dei fornitori collegati.
      </div>
    </div>
  );

  return (
    <div className="animate-fade-up space-y-6">
      <PageHead title="Preventivo" sub="Lo sconto del tuo fornitore è già applicato. Scarica il PDF o invia l'ordine." />
      {producerIds.map(pid => {
        const producer = users.find(u => u.id === pid);
        const items = groups[pid];
        return (
          <div key={pid} className="rounded-3xl bg-white border border-slate-100 overflow-hidden">
            <div className="flex items-center justify-between px-5 py-4 bg-slate-50 border-b border-slate-100">
              <div className="font-bold">{producer?.company}</div>
              <div className="text-sm text-slate-500">Totale: <b className="text-brand-700">{euro(sumItems(items))}</b></div>
            </div>
            <table className="w-full text-sm">
              <thead><tr className="text-left text-slate-400">
                <th className="px-5 py-2">Prodotto</th><th className="px-2 py-2">Q.tà</th><th className="px-2 py-2 hidden sm:table-cell">Listino</th><th className="px-2 py-2">Sconto</th><th className="px-5 py-2 text-right">Totale</th></tr></thead>
              <tbody>
                {items.map(it => (
                  <tr key={it.productId} className="border-t border-slate-100">
                    <td className="px-5 py-3 font-medium">{it.name}</td>
                    <td className="px-2 py-3">
                      <div className="inline-flex items-center rounded-lg border border-slate-200">
                        <button onClick={()=>setQty(it.productId, it.qty-1)} className="w-7 h-7 text-slate-500">−</button>
                        <span className="w-8 text-center">{it.qty}</span>
                        <button onClick={()=>setQty(it.productId, it.qty+1)} className="w-7 h-7 text-slate-500">+</button>
                      </div>
                    </td>
                    <td className="px-2 py-3 hidden sm:table-cell text-slate-500">{euro(it.unitPrice)}</td>
                    <td className="px-2 py-3">{it.discount ? <span className="text-brand-600 font-semibold">-{it.discount}%</span> : "—"}</td>
                    <td className="px-5 py-3 text-right font-semibold">{euro(it.lineTotal)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="flex flex-wrap justify-end gap-2 px-5 py-4 border-t border-slate-100">
              <button onClick={()=>downloadQuotePDF(producer, items, me)} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">⬇ Scarica preventivo PDF</button>
              <button onClick={()=>sendOrder(pid, items)} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30 hover:bg-brand-700">📨 Invia ordine</button>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function ClientOrders({ me, users, orders }) {
  const sorted = [...orders].sort((a,b) => new Date(b.date) - new Date(a.date));
  return (
    <div className="animate-fade-up">
      <PageHead title="I miei ordini" sub="Storico degli ordini inviati ai tuoi fornitori." />
      {sorted.length === 0 ? <p className="text-slate-400">Non hai ancora inviato ordini.</p> : (
        <div className="space-y-4">
          {sorted.map(o => { const producer = users.find(u => u.id === o.producerId); return (
            <div key={o.id} className="rounded-3xl bg-white border border-slate-100 overflow-hidden">
              <div className="flex flex-wrap items-center justify-between gap-2 px-5 py-4 bg-slate-50 border-b border-slate-100">
                <div><div className="font-bold">{producer?.company}</div><div className="text-xs text-slate-400">{o.id} · {new Date(o.date).toLocaleDateString("it-IT")}</div></div>
                <div className="flex items-center gap-3">
                  <span className="text-xs font-semibold bg-brand-50 text-brand-700 px-2.5 py-1 rounded-full">{o.status}</span>
                  <span className="font-bold text-brand-700">{euro(o.total)}</span>
                </div>
              </div>
              <div className="px-5 py-3 text-sm text-slate-600">
                {o.items.map(it => <div key={it.productId} className="flex justify-between py-0.5"><span>{it.qty}× {it.name}</span><span>{euro(it.lineTotal)}</span></div>)}
              </div>
            </div>
          ); })}
        </div>
      )}
    </div>
  );
}

function priceFor(p, approvedIds, links, me) {
  const link = links.find(l => l.clientId === me.id && l.producerId === p.producerId && l.status === "approved");
  const discount = link?.discount || 0;
  const connected = approvedIds.includes(p.producerId);
  const final = p.price * (1 - discount/100);
  return { connected, discount, final };
}

function PriceBlock({ p, connected, discount, final }) {
  if (!connected) return (
    <div><div className="text-xl font-extrabold text-slate-800">{euro(p.price)}</div><div className="text-[11px] text-slate-400">prezzo di listino</div></div>
  );
  return (
    <div>
      {discount > 0 && <div className="text-xs text-slate-400 line-through">{euro(p.price)}</div>}
      <div className="text-xl font-extrabold text-brand-700">{euro(final)}</div>
    </div>
  );
}

function ClientProductCard({ p, me, users, links, approvedIds, addToCart, requestLink, openProduct, notify, q = "" }) {
  const prod = users.find(u => u.id === p.producerId);
  const { connected, discount, final } = priceFor(p, approvedIds, links, me);
  return (
    <div className="card-hover rounded-3xl bg-white border border-slate-100 overflow-hidden flex flex-col">
      <button onClick={()=>openProduct(p.id)} className="relative block text-left">
        <ProductImage p={p} className="w-full h-40" />
        {connected && discount>0 && <span className="absolute top-3 left-3 bg-brand-600 text-white text-xs font-bold px-2 py-1 rounded-full shadow">-{discount}%</span>}
      </button>
      <div className="p-4 flex flex-col flex-1">
        <div className="text-xs font-semibold text-brand-600">{prod?.company}</div>
        <button onClick={()=>openProduct(p.id)} className="font-bold mt-0.5 text-left hover:text-brand-700 transition"><Highlight text={p.name} q={q} /></button>
        <div className="text-sm text-slate-500 mt-1 line-clamp-2">{p.description}</div>
        <div className="mt-3"><AllergenBadges p={p} small /></div>
        <div className="mt-4 flex items-end justify-between gap-2">
          <PriceBlock p={p} connected={connected} discount={discount} final={final} />
          {!connected
            ? <button onClick={()=>requestLink(p.producerId)} className="text-sm px-3 py-1.5 rounded-lg bg-brand-50 text-brand-700 font-semibold border border-brand-100 hover:bg-brand-100 shrink-0">+ Collegati</button>
            : <button onClick={()=>{addToCart(p.id); notify("Aggiunto al preventivo");}} className="text-sm px-3 py-1.5 rounded-lg bg-brand-600 text-white font-semibold shadow hover:bg-brand-700 shrink-0">+ Preventivo</button>}
        </div>
      </div>
    </div>
  );
}

function ProductModal({ productId, onClose, openStore, ...ctx }) {
  const { products, users, links, approvedIds, me, addToCart, requestLink, notify } = ctx;
  const p = products.find(x => x.id === productId);
  if (!p) return null;
  const producer = users.find(u => u.id === p.producerId);
  const { connected, discount, final } = priceFor(p, approvedIds, links, me);
  return (
    <Modal open={true} onClose={onClose} title="Scheda prodotto" wide>
      <div className="grid sm:grid-cols-2 gap-5">
        <ProductImage p={p} className="w-full h-48 sm:h-full rounded-2xl" />
        <div>
          <button onClick={()=>openStore(producer.id)} className="text-xs font-semibold text-brand-600 hover:underline">{producer?.company} · vedi vetrina →</button>
          <h3 className="text-xl font-extrabold mt-1">{p.name}</h3>
          {p.category && <div className="text-sm text-slate-400">{p.category}</div>}
          <p className="text-sm text-slate-600 mt-3">{p.description || "Nessuna descrizione."}</p>
          <div className="mt-4"><AllergenBadges p={p} /></div>
          <NutritionTable p={p} />
          <div className="mt-5"><PriceBlock p={p} connected={connected} discount={discount} final={final} /></div>
          <div className="mt-5 flex flex-wrap gap-2">
            {!connected
              ? <button onClick={()=>{requestLink(p.producerId); onClose();}} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30">+ Collegati per il prezzo dedicato</button>
              : <button onClick={()=>{addToCart(p.id); notify("Aggiunto al preventivo");}} className="px-4 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30">+ Aggiungi al preventivo</button>}
            <button onClick={()=>downloadProductPDF(p, producer)} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">⬇ Scheda PDF</button>
            {p.datasheet && <a href={p.datasheet} target="_blank" rel="noopener noreferrer" className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400">📄 Scheda tecnica</a>}
          </div>
        </div>
      </div>
    </Modal>
  );
}

function StoreModal({ producerId, onClose, ...ctx }) {
  const { products, users, links, approvedIds, me, requestLink } = ctx;
  const producer = users.find(u => u.id === producerId);
  if (!producer) return null;
  const its = products.filter(p => p.producerId === producerId);
  const link = links.find(l => l.clientId === me.id && l.producerId === producerId);
  const status = link?.status;
  const prof = producer.profile || {};
  return (
    <Modal open={true} onClose={onClose} title="Vetrina del produttore" wide>
      <div className="flex items-center gap-4">
        <Avatar user={producer} className="w-16 h-16" text="text-2xl" />
        <div className="min-w-0">
          <div className="font-extrabold text-lg truncate">{producer.company}</div>
          <div className="text-xs text-slate-400 truncate">{producer.address} · P.IVA {producer.vat}</div>
        </div>
      </div>
      <div className="flex flex-wrap gap-2 mt-3">
        {prof.promo && <span className="text-xs font-semibold bg-amber-100 text-amber-700 px-3 py-1 rounded-full">🎁 {prof.promo}</span>}
        {prof.news && <span className="text-xs font-semibold bg-brand-50 text-brand-700 px-3 py-1 rounded-full">📣 {prof.news}</span>}
      </div>
      {prof.description && <p className="text-sm text-slate-600 mt-3">{prof.description}</p>}

      <div className="mt-4">
        {!status && <button onClick={()=>{requestLink(producerId); onClose();}} className="px-5 py-2.5 rounded-xl bg-brand-600 text-white font-semibold text-sm shadow-lg shadow-brand-600/30">Richiedi collegamento</button>}
        {status === "pending"  && <span className="inline-block px-4 py-2 rounded-xl bg-amber-50 text-amber-700 font-semibold text-sm">⏳ In attesa di approvazione</span>}
        {status === "approved" && <span className="inline-block px-4 py-2 rounded-xl bg-brand-50 text-brand-700 font-semibold text-sm">✓ Collegato{link.discount>0?` · sconto ${link.discount}%`:""}</span>}
        {status === "rejected" && <span className="inline-block px-4 py-2 rounded-xl bg-slate-100 text-slate-500 font-semibold text-sm">Richiesta rifiutata</span>}
      </div>

      <div className="mt-6 border-t border-slate-100 pt-5">
        <div className="font-bold mb-3">Catalogo ({its.length})</div>
        {its.length === 0 ? <p className="text-slate-400 text-sm">Questo produttore non ha ancora prodotti.</p> : (
          <div className="grid sm:grid-cols-2 gap-4">
            {its.map(p => <ClientProductCard key={p.id} p={p} {...ctx} />)}
          </div>
        )}
      </div>
    </Modal>
  );
}

function ClientCatalog({ me, products, users, links, approvedIds, addToCart, requestLink, openProduct, openStore, notify }) {
  const [filters, setFilters] = useState({});
  const [q, setQ] = useState("");
  const [onlyMine, setOnlyMine] = useState(false);
  const [category, setCategory] = useState("");
  const [supplier, setSupplier] = useState("");
  const [sort, setSort] = useState("rel");

  const categories = [...new Set(products.map(p => p.category).filter(Boolean))].sort();
  const producers = users.filter(u => u.role === "producer");

  const qn = q.trim().toLowerCase();
  const list = products.filter(p =>
    Object.keys(filters).every(k => !filters[k] || (k === "_temp" ? tempDi(p) === filters[k] : p[k])) &&
    (!qn || [p.name, p.category, p.description].some(v => (v||"").toLowerCase().includes(qn))) &&
    (!onlyMine || approvedIds.includes(p.producerId)) &&
    (!category || p.category === category) &&
    (!supplier || p.producerId === supplier)
  );
  const eff = (p) => { const { connected, final } = priceFor(p, approvedIds, links, me); return connected ? final : p.price; };
  const sorted = [...list];
  if (sort === "price-asc")  sorted.sort((a,b) => eff(a) - eff(b));
  if (sort === "price-desc") sorted.sort((a,b) => eff(b) - eff(a));
  if (sort === "name")       sorted.sort((a,b) => a.name.localeCompare(b.name, "it"));

  const selCls = "rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-700 outline-none focus:border-brand-500";

  return (
    <div className="animate-fade-up">
      <PageHead title="Catalogo" sub="Cerca, filtra e ordina i prodotti dei produttori." />
      <div className="space-y-3 mb-5">
        <div className="flex flex-wrap items-center gap-2">
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="🔎 Cerca prodotto..." className={inputCls + " max-w-xs"} />
          <select value={category} onChange={e=>setCategory(e.target.value)} className={selCls}>
            <option value="">Tutte le categorie</option>
            {categories.map(c => <option key={c} value={c}>{c}</option>)}
          </select>
          <select value={supplier} onChange={e=>setSupplier(e.target.value)} className={selCls}>
            <option value="">Tutti i fornitori</option>
            {producers.map(pr => <option key={pr.id} value={pr.id}>{pr.company}</option>)}
          </select>
          <select value={sort} onChange={e=>setSort(e.target.value)} className={selCls}>
            <option value="rel">Ordina: rilevanza</option>
            <option value="price-asc">Prezzo crescente</option>
            <option value="price-desc">Prezzo decrescente</option>
            <option value="name">Nome A-Z</option>
          </select>
          <Chip active={onlyMine} onClick={()=>setOnlyMine(v=>!v)}>Solo i miei fornitori</Chip>
          {(q || category || supplier || onlyMine || sort!=="rel" || Object.values(filters).some(Boolean)) && (
            <button onClick={()=>{ setQ(""); setCategory(""); setSupplier(""); setOnlyMine(false); setSort("rel"); setFilters({}); }}
              className="px-3 py-2 rounded-xl text-sm font-semibold text-slate-500 hover:text-slate-700 hover:bg-slate-100">✕ Azzera</button>
          )}
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {ALLERGENS.map(a => (
            <Chip key={a.key} active={!!filters[a.key]} onClick={()=>setFilters(f=>({...f,[a.key]:!f[a.key]}))}>{a.icon} {a.label}</Chip>
          ))}
          {Object.entries(TEMPS).map(([k, t]) => (
            <Chip key={k} active={filters._temp === k}
              onClick={()=>setFilters(f=>({...f, _temp: f._temp === k ? "" : k}))}>{t.icon} {t.label}</Chip>
          ))}
        </div>
      </div>

      <div className="text-sm text-slate-400 mb-3">{sorted.length} {sorted.length === 1 ? "prodotto" : "prodotti"}</div>
      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
        {sorted.map(p => (
          <ClientProductCard key={p.id} p={p} me={me} users={users} links={links} approvedIds={approvedIds}
            addToCart={addToCart} requestLink={requestLink} openProduct={openProduct} notify={notify} q={q} />
        ))}
      </div>
      {!sorted.length && (
        <EmptyState icon="🔍" title="Nessun prodotto con questi criteri"
          hint="Prova a togliere qualche filtro o a cambiare le parole della ricerca." />
      )}
    </div>
  );
}

function ClientSuppliers({ me, products, users, links, approvedIds, addToCart, requestLink, openProduct, openStore, notify, setTab }) {
  const producers = users.filter(u => u.role === "producer");
  const linkWith = (pid) => links.find(l => l.clientId === me.id && l.producerId === pid);

  if (!producers.length) return (
    <div className="animate-fade-up">
      <PageHead title="I miei fornitori" sub="Collegati ai produttori per vedere prezzi dedicati e ordinare." />
      <div className="rounded-3xl border-2 border-dashed border-slate-200 p-12 text-center text-slate-400">Nessun produttore presente per ora.</div>
    </div>
  );

  return (
    <div className="animate-fade-up">
      <PageHead title="I miei fornitori" sub="Collegati ai produttori per vedere prezzi dedicati e ordinare." />
      <div className="grid sm:grid-cols-2 gap-4">
        {producers.map(p => {
          const l = linkWith(p.id);
          const status = l?.status;
          const count = products.filter(x => x.producerId === p.id).length;
          return (
            <div key={p.id} className="rounded-3xl bg-white border border-slate-100 p-5 card-hover">
              <button onClick={()=>openStore(p.id)} className="flex items-center gap-3 text-left w-full">
                <Avatar user={p} className="w-12 h-12" text="text-lg" />
                <div className="min-w-0">
                  <div className="font-bold truncate hover:text-brand-700 transition">{p.company}</div>
                  <div className="text-xs text-slate-400 truncate">{p.address} · {count} prodotti</div>
                </div>
              </button>
              {p.profile?.description && <p className="text-sm text-slate-500 mt-3 line-clamp-2">{p.profile.description}</p>}
              {p.profile?.promo && <div className="mt-2 inline-block text-xs font-semibold bg-amber-100 text-amber-700 px-2 py-1 rounded-full">🎁 {p.profile.promo}</div>}
              <div className="mt-4 flex gap-2">
                <button onClick={()=>openStore(p.id)} className="px-4 py-2.5 rounded-xl bg-white border border-slate-200 font-semibold text-sm hover:border-brand-400 shrink-0">Vedi vetrina</button>
                {!status && <button onClick={()=>requestLink(p.id)} className="flex-1 py-2.5 rounded-xl bg-brand-600 text-white font-semibold">Richiedi collegamento</button>}
                {status === "pending"  && <div className="flex-1 py-2.5 text-center rounded-xl bg-amber-50 text-amber-700 font-semibold">⏳ In attesa</div>}
                {status === "approved" && <div className="flex-1 py-2.5 text-center rounded-xl bg-brand-50 text-brand-700 font-semibold">✓ Collegato{l.discount>0?` · -${l.discount}%`:""}</div>}
                {status === "rejected" && <div className="flex-1 py-2.5 text-center rounded-xl bg-slate-100 text-slate-500 font-semibold">Rifiutata</div>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- avvio ---------- */
// I dati demo ora li semina il motore (server.py); qui non tocchiamo più il browser.
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
