/* Sourcing features — extras from zip variant (features 4-10)
 * Excludes conflicting components: OpportunityFinder, AsinLibrary, SupplierCompare
 * (already implemented in opportunity.jsx, asin-library.jsx, supplier-compare.jsx)
 */

const Samples = () => {
  const toast = (typeof useToastX === "function") ? useToastX() : null;
  const LS_SAMPLES = "kcc:samples";
  const SEED = [
    { id: "smp-001", asin: "B0CXYZ1234", name: "Diffuseur ultrasonique ambré 700ml",  status: "reçu",       received: "08 mai", votes: { clarens: "yes", kevin: "yes", carly: "yes" }, photos: 4, notes: "Qualité excellente · packaging à revoir" },
    { id: "smp-002", asin: "B0CABC4567", name: "Lampe écran USB 38cm dimmable",       status: "test",       received: "06 mai", votes: { clarens: "yes", kevin: null, carly: "no" },  photos: 3, notes: "Diffusion ok · sangle fragile après 200 cycles" },
    { id: "smp-003", asin: "B0CDEF8901", name: "Brosse anti-peluche rouleau",         status: "transit",    received: "—",      votes: {},                                            photos: 0, notes: "ETA 18 mai · DHL" },
    { id: "smp-004", asin: "B0CJKL6789", name: "Tapis yoga TPE 6mm",                   status: "rejeté",     received: "02 mai", votes: { clarens: "no", kevin: "no", carly: "yes" }, photos: 5, notes: "Odeur chimique persistante après 7j d'aération" },
  ];
  const load = () => { try { const s = localStorage.getItem(LS_SAMPLES); return s ? JSON.parse(s) : SEED; } catch { return SEED; } };
  const [samples, _set] = useState(load);
  const persist = (next) => {
    const v = typeof next === "function" ? next(samples) : next;
    _set(v);
    try { localStorage.setItem(LS_SAMPLES, JSON.stringify(v)); } catch {}
    fetch("/api/sync", { method: "PUT", body: JSON.stringify({ col: "samples", items: v }) }).catch(() => null);
  };
  const addSample = () => {
    const asin = (prompt("ASIN du produit ?", "B0") || "").trim();
    if (!asin) return;
    const name = (prompt("Nom du produit ?") || "Sans titre").trim();
    persist([{ id: "smp-" + Date.now(), asin, name, status: "demandé", received: "—", votes: {}, photos: 0, notes: "Nouvelle demande échantillon" }, ...samples]);
    toast?.push?.({ tone: "good", title: "Échantillon demandé" });
  };
  const vote = (id, userId, v) => persist(samples.map((s) => s.id === id ? { ...s, votes: { ...s.votes, [userId]: s.votes[userId] === v ? null : v } } : s));
  const placeholderPalette = ["#d4c3a8", "#a8c3d4", "#d4b8a8", "#a8d4b8"];
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Suivi d'échantillons</div>
          <div className="page-sub">Réceptions · tests qualité · vote des 3 cofondateurs · photos</div>
        </div>
        <button className="btn" data-variant="primary" onClick={addSample}><Icon name="plus" size={13}/> Demander échantillon</button>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
        {samples.map((s, i) => {
          const yeses = Object.values(s.votes).filter((v) => v === "yes").length;
          const nos   = Object.values(s.votes).filter((v) => v === "no").length;
          const decision = nos >= 2 ? "rejeté" : yeses >= 2 ? "validé" : "en cours";
          const tone = decision === "validé" ? "green" : decision === "rejeté" ? "red" : "amber";
          return (
            <div key={s.id} className="card" style={{ padding: 0, overflow: "hidden" }}>
              <div style={{ height: 80, background: `linear-gradient(135deg, ${placeholderPalette[i % 4]}, var(--bg-3))`, padding: 12, position: "relative" }}>
                <div className="row" style={{ position: "absolute", top: 10, left: 12, gap: 8 }}>
                  <span className="mono" style={{ fontSize: 10, color: "rgba(255,255,255,.9)" }}>{s.asin}</span>
                </div>
                <div style={{ position: "absolute", top: 10, right: 12 }}>
                  <Badge tone={tone}>{decision}</Badge>
                </div>
                <div style={{ position: "absolute", bottom: 8, left: 12, fontSize: 11, color: "rgba(255,255,255,.85)" }}>
                  {s.photos > 0 ? `${s.photos} photos` : "—"}
                </div>
              </div>
              <div style={{ padding: 14 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{s.name}</div>
                <div className="row" style={{ gap: 10, marginTop: 4, fontSize: 11, color: "var(--text-dim)" }}>
                  <span>Statut · <strong style={{ color: "var(--text)" }}>{s.status}</strong></span>
                  <span>·</span>
                  <span>Reçu · <strong style={{ color: "var(--text)" }} className="mono">{s.received}</strong></span>
                </div>
                <div style={{ marginTop: 10, fontSize: 11.5, color: "var(--text-muted)", lineHeight: 1.5 }}>{s.notes}</div>

                <div className="row" style={{ marginTop: 12, gap: 6, padding: 8, background: "var(--bg-2)", borderRadius: 8, justifyContent: "space-around" }}>
                  {USERS.map((u) => {
                    const v = s.votes[u.id];
                    return (
                      <div key={u.id} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                        <Avatar user={u.id} size="sm"/>
                        <span style={{ fontSize: 10, color: "var(--text-faint)" }}>{u.name}</span>
                        <div className="row" style={{ gap: 3 }}>
                          <button onClick={() => vote(s.id, u.id, "yes")} style={{
                            width: 22, height: 22, borderRadius: 6, border: "1px solid var(--border)",
                            background: v === "yes" ? "var(--green-soft)" : "transparent",
                            color: v === "yes" ? "var(--green)" : "var(--text-faint)",
                            cursor: "pointer",
                          }}>✓</button>
                          <button onClick={() => vote(s.id, u.id, "no")} style={{
                            width: 22, height: 22, borderRadius: 6, border: "1px solid var(--border)",
                            background: v === "no" ? "var(--red-soft)" : "transparent",
                            color: v === "no" ? "var(--red)" : "var(--text-faint)",
                            cursor: "pointer",
                          }}>✗</button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

/* ─── 7. Bulk-edit ───────────────────────────────────────────────── */
const BulkEdit = () => {
  const toast = (typeof useToastX === "function") ? useToastX() : null;
  const [selected, setSelected] = useState(new Set(PRODUCTS.slice(0, 5).map((p) => p.id)));
  const [field, setField] = useState("price");
  const [op, setOp] = useState("set");
  const [value, setValue] = useState("");
  const products = PRODUCTS.slice(0, 10);
  const FIELD_LBL = { price: "Prix", cost: "Coût", status: "Statut", owner: "Propriétaire", ppc: "Cap PPC" };
  const OP_LBL = { set: "= ", add: "+ ", multiply: "× ", percent: "+%" };
  const describe = () => `${FIELD_LBL[field]} ${OP_LBL[op]}${value || "?"} → ${selected.size} produit(s)`;
  const previewBulk = () => {
    if (!selected.size) { toast?.({ message: "Aucun produit sélectionné", tone: "amber" }); return; }
    if (!value.trim()) { toast?.({ message: "Saisissez une valeur", tone: "amber" }); return; }
    toast?.({ message: "Aperçu : " + describe(), tone: "blue" });
  };
  const applyBulk = () => {
    if (!selected.size) { toast?.({ message: "Aucun produit sélectionné", tone: "amber" }); return; }
    if (!value.trim()) { toast?.({ message: "Saisissez une valeur", tone: "amber" }); return; }
    if (!confirm(`Appliquer « ${describe()} » ?`)) return;
    const txId = "TX-" + Date.now().toString(36).toUpperCase();
    try {
      const log = JSON.parse(localStorage.getItem("kcc:bulk-edits") || "[]");
      log.unshift({ txId, ts: new Date().toISOString(), field, op, value, ids: [...selected] });
      localStorage.setItem("kcc:bulk-edits", JSON.stringify(log.slice(0, 50)));
    } catch {}
    fetch("/api/sync", { method: "PUT", body: JSON.stringify({ col: "_bulk", items: [{ txId, field, op, value, ids: [...selected] }] }) }).catch(() => null);
    toast?.({ message: `Appliqué à ${selected.size} produit(s) · ${txId}`, tone: "green" });
  };
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Bulk-edit produits</div>
          <div className="page-sub">Éditez prix, statut, propriétaire en masse · {selected.size} sélectionnés sur {products.length}</div>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 14, padding: 14 }}>
        <div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontSize: 10.5, color: "var(--text-dim)", marginBottom: 4 }}>Champ</div>
            <select className="input" value={field} onChange={(e) => setField(e.target.value)} style={{ width: 160 }}>
              <option value="price">Prix</option>
              <option value="cost">Coût</option>
              <option value="status">Statut</option>
              <option value="owner">Propriétaire</option>
              <option value="ppc">Cap PPC</option>
            </select>
          </div>
          <div>
            <div style={{ fontSize: 10.5, color: "var(--text-dim)", marginBottom: 4 }}>Opération</div>
            <select className="input" value={op} onChange={(e) => setOp(e.target.value)} style={{ width: 160 }}>
              <option value="set">Remplacer par</option>
              <option value="add">Ajouter</option>
              <option value="multiply">Multiplier par</option>
              <option value="percent">+ pourcentage</option>
            </select>
          </div>
          <div>
            <div style={{ fontSize: 10.5, color: "var(--text-dim)", marginBottom: 4 }}>Valeur</div>
            <input className="input" value={value} onChange={(e) => setValue(e.target.value)} placeholder="ex. 49.99" style={{ width: 160 }}/>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "flex-end", gap: 6 }}>
            <button className="btn" onClick={previewBulk}><Icon name="eye" size={13}/> Aperçu</button>
            <button className="btn" data-variant="primary" onClick={applyBulk}><Icon name="check" size={13}/> Appliquer à {selected.size}</button>
          </div>
        </div>
        <div style={{ marginTop: 10, padding: 10, background: "var(--accent-soft)", borderRadius: 6, fontSize: 11.5, color: "var(--accent)" }}>
          <Icon name="bell" size={11} style={{ verticalAlign: -1, marginRight: 4 }}/>
          Action réversible · sera ajoutée à l'historique avec un identifiant de transaction.
        </div>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 30 }}>
                <input type="checkbox" checked={selected.size === products.length}
                  onChange={() => setSelected(selected.size === products.length ? new Set() : new Set(products.map((p) => p.id)))}
                  style={{ accentColor: "var(--accent)" }}/>
              </th>
              <th>Produit</th>
              <th>ASIN</th>
              <th style={{ textAlign: "right" }}>Prix</th>
              <th style={{ textAlign: "right" }}>Marge</th>
              <th>Statut</th>
            </tr>
          </thead>
          <tbody>
            {products.map((p) => (
              <tr key={p.id} data-selected={selected.has(p.id)} onClick={() => {
                const next = new Set(selected);
                next.has(p.id) ? next.delete(p.id) : next.add(p.id);
                setSelected(next);
              }} style={{ cursor: "pointer" }}>
                <td><input type="checkbox" checked={selected.has(p.id)} onChange={() => {}} style={{ accentColor: "var(--accent)" }}/></td>
                <td style={{ maxWidth: 280, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</td>
                <td className="mono muted">{p.asin}</td>
                <td className="num" style={{ textAlign: "right" }}>${p.price.toFixed(2)}</td>
                <td className="num" style={{ textAlign: "right", color: "var(--green)" }}>{p.margin.toFixed(1)}%</td>
                <td><StatusBadge value={p.status}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

/* ─── 8. Price optimizer (elasticity sim) ────────────────────────── */
const PriceOptimizer = () => {
  const FALLBACK_PRODUCT = { name: "Produit démo", cat: "Maison", price: 29.99, cost: 8.50, fees: 6.20, vel: 4, margin: 35 };
  const [p] = useState((typeof PRODUCTS !== "undefined" && PRODUCTS && PRODUCTS[0]) || FALLBACK_PRODUCT);
  const [price, setPrice] = useState(p.price);
  // simplified elasticity curve
  const dPrice = (price - p.price) / p.price;
  const dDemand = -1.4 * dPrice; // elasticity ~ 1.4
  const newUnits = Math.max(0, p.vel * 30 * (1 + dDemand));
  const newRevenue = price * newUnits;
  const newMargin = ((price - p.cost - p.fees) / price) * 100;
  const newProfit = (price - p.cost - p.fees) * newUnits;
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Calculateur de prix optimal</div>
          <div className="page-sub">Simule l'élasticité demande/prix · {p.name}</div>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-head"><div><div className="card-title">Levier · prix de vente</div></div></div>
          <div className="card-body">
            <Slider label="Prix CAD" value={price} onChange={setPrice} min={p.cost + p.fees + 1} max={p.price * 1.5} step={0.5} format={(v) => "$" + v.toFixed(2)} help={`Prix actuel : $${p.price.toFixed(2)} · break-even $${(p.cost+p.fees).toFixed(2)}`}/>
            <div style={{ marginTop: 14, padding: 12, background: "var(--bg-2)", borderRadius: 8, fontSize: 11.5, color: "var(--text-muted)" }}>
              Élasticité prix-demande estimée : <span className="num" style={{ color: "var(--text)" }}>-1.4</span> (catégorie {p.cat})<br/>
              Pour chaque +1% de prix, demande -1.4%.
            </div>
          </div>
        </div>

        <div className="stack" style={{ gap: 14 }}>
          <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <KpiCard label="Revenu mensuel projeté" prefix="$" value={fmtMoney(newRevenue)} delta={((newRevenue / (p.price * p.vel * 30)) - 1) * 100}/>
            <KpiCard label="Profit mensuel projeté" prefix="$" value={fmtMoney(newProfit)} delta={((newProfit / ((p.price - p.cost - p.fees) * p.vel * 30)) - 1) * 100} sparkColor="var(--green)"/>
            <KpiCard label="Marge nette" value={newMargin.toFixed(1) + "%"} delta={newMargin - p.margin}/>
            <KpiCard label="Unités/mois" value={Math.round(newUnits).toString()} delta={dDemand * 100}/>
          </div>
          <div className="card" style={{ padding: 14, fontSize: 12, lineHeight: 1.6 }}>
            <div className="row" style={{ gap: 8, marginBottom: 8 }}>
              <JarvisLogo size={18} glow={false}/>
              <span style={{ fontWeight: 600 }}>Recommandation JARVIS</span>
            </div>
            {price > p.price * 1.1 ? "Prix agressif — risque de chute BSR. Tester progressivement avec +5% sur 14j." :
             price < p.price * 0.95 ? "Volume gagné mais marge serrée. Vérifier l'impact sur le rang Best Seller." :
             "Zone confort — gain de profit marginal, BSR stable."}
          </div>
        </div>
      </div>
    </div>
  );
};

/* ─── 9. Cannibalization detection ────────────────────────────────── */
const Cannibalization = () => {
  const conflicts = [
    { a: "Diffuseur 500ml", b: "Diffuseur 700ml", cat: "Maison & Cuisine", overlap: 84, lostSales: 6800, action: "Différencier packaging + keywords" },
    { a: "Tapis souris XL", b: "Tapis souris RGB", cat: "Électronique",    overlap: 71, lostSales: 3200, action: "Repositionner XL en gamme pro" },
    { a: "Brosse chien long", b: "Brosse chat",   cat: "Animalerie",       overlap: 32, lostSales: 800,  action: "Acceptable — segments distincts" },
  ];
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Détection de cannibalisation</div>
          <div className="page-sub">JARVIS scanne votre catalogue pour repérer les produits qui se volent du trafic</div>
        </div>
      </div>
      <div className="card" style={{ padding: 0 }}>
        <table className="table">
          <thead><tr><th>Produit A</th><th>Produit B</th><th>Catégorie</th><th style={{ textAlign: "right" }}>Recouvrement</th><th style={{ textAlign: "right" }}>Perte est./mois</th><th>Recommandation</th></tr></thead>
          <tbody>
            {conflicts.map((c, i) => (
              <tr key={i}>
                <td>{c.a}</td>
                <td>{c.b}</td>
                <td className="muted">{c.cat}</td>
                <td className="num" style={{ textAlign: "right", color: c.overlap >= 70 ? "var(--red)" : c.overlap >= 50 ? "var(--amber)" : "var(--text-muted)", fontWeight: 600 }}>{c.overlap}%</td>
                <td className="num" style={{ textAlign: "right" }}>${c.lostSales.toLocaleString()}</td>
                <td className="muted" style={{ fontSize: 11.5 }}>{c.action}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

/* ─── 10. Seasonality heatmap ─────────────────────────────────────── */
const Seasonality = () => {
  const months = ["Jan", "Fév", "Mar", "Avr", "Mai", "Jun", "Juil", "Août", "Sep", "Oct", "Nov", "Déc"];
  const cats = [
    { name: "Maison & Cuisine", data: [70, 65, 72, 78, 82, 75, 70, 68, 80, 92, 110, 145] },
    { name: "Électronique",     data: [85, 78, 80, 82, 85, 88, 82, 80, 88, 95, 115, 150] },
    { name: "Auto",             data: [60, 58, 75, 90, 95, 100, 95, 90, 82, 75, 70, 65] },
    { name: "Animalerie",       data: [88, 85, 90, 92, 95, 98, 95, 90, 92, 98, 105, 130] },
    { name: "Sport & Plein Air",data: [75, 72, 85, 105, 120, 130, 125, 115, 95, 80, 72, 70] },
    { name: "Bureau",           data: [72, 75, 88, 85, 80, 70, 65, 80, 130, 140, 105, 80] },
    { name: "Voyage",           data: [62, 60, 70, 85, 105, 130, 145, 140, 95, 75, 65, 60] },
  ];
  const max = Math.max(...cats.flatMap((c) => c.data));
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Saisonnalité</div>
          <div className="page-sub">Pattern de ventes mensuel par catégorie · moyenne 2 dernières années</div>
        </div>
      </div>
      <div className="card" style={{ padding: 18 }}>
        <table style={{ width: "100%", borderCollapse: "separate", borderSpacing: 0 }}>
          <thead>
            <tr>
              <th style={{ textAlign: "left", padding: "4px 8px", fontSize: 10.5, color: "var(--text-dim)" }}>Catégorie</th>
              {months.map((m) => <th key={m} style={{ fontSize: 10, color: "var(--text-faint)", padding: 4 }}>{m}</th>)}
              <th style={{ fontSize: 10, color: "var(--text-faint)", padding: 4 }}>Peak</th>
            </tr>
          </thead>
          <tbody>
            {cats.map((c) => {
              const peak = c.data.indexOf(Math.max(...c.data));
              return (
                <tr key={c.name}>
                  <td style={{ fontSize: 12, padding: "4px 8px" }}>{c.name}</td>
                  {c.data.map((v, i) => {
                    const intensity = v / max;
                    const bg = `oklch(${0.7 - intensity * 0.3} ${0.15 * intensity} 248 / ${0.15 + intensity * 0.7})`;
                    return (
                      <td key={i} style={{ padding: 2 }}>
                        <div style={{ background: bg, borderRadius: 3, padding: "6px 4px", textAlign: "center", fontSize: 10, color: intensity > 0.7 ? "white" : "var(--text)" }} className="num">{Math.round(v)}</div>
                      </td>
                    );
                  })}
                  <td style={{ fontSize: 11, color: "var(--accent)", padding: "4px 8px" }}>{months[peak]}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="row" style={{ marginTop: 14, gap: 8, justifyContent: "flex-end", fontSize: 10.5, color: "var(--text-dim)" }}>
          <span>Faible</span>
          {[0.15, 0.3, 0.5, 0.7, 0.9].map((i) => <span key={i} style={{ width: 18, height: 12, background: `oklch(${0.7 - i * 0.3} ${0.15 * i} 248 / ${0.15 + i * 0.7})`, borderRadius: 2 }}/>)}
          <span>Élevé</span>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Samples, BulkEdit, PriceOptimizer, Cannibalization, Seasonality });
