/* ============================================================
   SIKA COCKPIT — Drill-down tabs (suite) + shell du tiroir
   ============================================================ */
const Stat2 = () => window.DD_Stat;

// ---- Ventes -------------------------------------------------------------
function TabVentes({ a, A }) {
  const basis = A.salesBasis;
  const ser = a.sales.map((s) => ({ label: s.label, v: basis === "shipped" ? s.shippedUnits : s.orderedUnits, ordered: s.orderedUnits, shipped: s.shippedUnits, wk: s.wk }));
  const last = a.sales[a.sales.length - 1];
  return (
    <div>
      <div className="banner warn" style={{ marginBottom: 12 }}>
        <span>ⓘ</span><span>Vue <b>Manufacturing</b> — ne jamais sommer avec Sourcing. Base active&nbsp;: <b>{basis === "shipped" ? "shipped (facturé)" : "ordered (annulable)"}</b> (modifiable dans les hypothèses).</span>
      </div>
      <div className="panel">
        <div className="panel-h"><span>Ventes hebdo — 26 sem</span><Fresh src={S().sales} /></div>
        <div className="panel-b">
          <SeriesChart series={ser} overlay={basis === "shipped" ? "ordered" : "shipped"} valueLabel="u" color="var(--accent-2)" />
          <div className="legend">
            <span><i style={{ background: "var(--accent-2)" }}></i>{basis} (base active)</span>
            <span><i style={{ background: "var(--ink-3)" }}></i>{basis === "shipped" ? "ordered" : "shipped"}</span>
          </div>
        </div>
      </div>
      <div className="panel">
        <div className="panel-h"><span>Dernière semaine ({last.label})</span></div>
        <div className="panel-b">
          {window.DD_Stat({ label: "Ordered units", value: num(last.orderedUnits), unit: " u", nature: "réel", src: S().sales, payload: inspectPayload({ a, label: "orderedUnits", value: num(last.orderedUnits) + " u", nature: "réel", src: S().sales, field: "sales.orderedUnits", raw: last, crumbs: ["Portefeuille", a.short, "Ventes", last.label, "Brut"] }) })}
          {window.DD_Stat({ label: "Shipped units", value: num(last.shippedUnits), unit: " u", nature: "réel", src: S().sales, payload: inspectPayload({ a, label: "shippedUnits", value: num(last.shippedUnits) + " u", nature: "réel", src: S().sales, field: "sales.shippedUnits", raw: last }) })}
          {window.DD_Stat({ label: "Shipped revenue", value: eur(last.shippedRevenue), nature: "réel", src: S().sales, payload: inspectPayload({ a, label: "shippedRevenue", value: eur(last.shippedRevenue), nature: "réel", src: S().sales, field: "sales.shippedRevenue", raw: last }) })}
          {window.DD_Stat({ label: "Prix unitaire (proxy)", value: eur(a.price, 2), nature: "proxy", src: S().priceProxy, payload: inspectPayload({ a, label: "Prix unitaire (proxy)", value: eur(a.price, 2), nature: "proxy", src: S().priceProxy, field: "shippedRevenue / shippedUnits", raw: { shippedRevenue: last.shippedRevenue, shippedUnits: last.shippedUnits, priceProxy: a.price, note: "proxy revenu/unités — PAS le prix public affiché" }, formula: <>prix = <b>{eur(last.shippedRevenue)}</b> / <b>{last.shippedUnits} u</b> = <span className="res">{eur(a.price, 2)}</span></> }) })}
          {window.DD_Stat({ label: "Retours", value: num(last.returns), unit: " u", nature: "réel", src: S().sales })}
        </div>
      </div>
    </div>
  );
}

// ---- Inventaire ---------------------------------------------------------
function TabInventaire({ a, A }) {
  const raw = { sellableOnHandInventoryUnits: a.onHand, unsellableInventoryUnits: Math.round(a.onHand * 0.04), aged90PlusDaysSellableUnits: Math.round(a.onHand * 0.07), openPurchaseOrderUnits: a.openPO, unfilledCustomerOrderedUnits: Math.round(a.weeklyDemand * 0.12), sellThroughRate: +(a.weeklyDemand / Math.max(1, a.onHand)).toFixed(2), vendorConfirmationRate: 0.78, leadTimeWeeks_HYP: A.leadTime };
  return (
    <div>
      <div className="panel">
        <div className="panel-h"><span>Inventaire</span><Fresh src={S().inventory} /></div>
        <div className="panel-b">
          {window.DD_Stat({ label: "Sellable on-hand", value: num(raw.sellableOnHandInventoryUnits), unit: " u", nature: "réel", src: S().inventory, payload: inspectPayload({ a, label: "sellableOnHandInventoryUnits", value: num(raw.sellableOnHandInventoryUnits) + " u", nature: "réel", src: S().inventory, field: "sellableOnHandInventoryUnits", raw, crumbs: ["Portefeuille", a.short, "Inventaire", "Brut"] }) })}
          {window.DD_Stat({ label: "Invendable", value: num(raw.unsellableInventoryUnits), unit: " u", nature: "réel", src: S().inventory })}
          {window.DD_Stat({ label: "Vieillissant 90j+", value: num(raw.aged90PlusDaysSellableUnits), unit: " u", nature: "réel", src: S().inventory })}
          {window.DD_Stat({ label: "PO entrant (open)", value: num(raw.openPurchaseOrderUnits), unit: " u", nature: "réel", src: S().po, payload: inspectPayload({ a, label: "openPurchaseOrderUnits", value: num(raw.openPurchaseOrderUnits) + " u", nature: "réel", src: S().po, field: "openPurchaseOrderUnits", raw }) })}
          {window.DD_Stat({ label: "Cmd client non honorées", value: num(raw.unfilledCustomerOrderedUnits), unit: " u", nature: "réel", src: S().inventory })}
          {window.DD_Stat({ label: "Sell-through (sem)", value: pct(raw.sellThroughRate * 100, 0), nature: "proxy", src: S().inventory })}
          {window.DD_Stat({ label: "Real-time (≈5 min)", value: num(a.onHand - Math.round(a.weeklyDemand * 0.03)), unit: " u", nature: "réel", src: S().realtimeInv, payload: inspectPayload({ a, label: "Inventaire temps réel", value: num(a.onHand - Math.round(a.weeklyDemand * 0.03)) + " u", nature: "réel", src: S().realtimeInv, field: "realTimeInventory.units", raw: { units: a.onHand - Math.round(a.weeklyDemand * 0.03), note: "absence ≠ zéro — un ASIN manquant n'est pas un stock nul" } }) })}
        </div>
      </div>
    </div>
  );
}

// ---- PO -----------------------------------------------------------------
function TabPO({ a }) {
  const pos = window.SIKA.purchaseOrders.filter((p) => p.asin === a.asin);
  if (!pos.length) return <div className="state-box"><div className="ic">◷</div>Aucun PO récent pour cet ASIN.</div>;
  return (
    <div>
      {pos.map((p) => {
        const loss = p.cancelled * p.listPrice;
        return (
          <div className="panel" key={p.id}>
            <div className="panel-h"><span>{p.id} · {p.date}</span>
              <span className="badge" style={{ borderColor: p.confRate >= 80 ? "var(--green-bd)" : "var(--red-bd)", color: p.confRate >= 80 ? "var(--green)" : "var(--red)" }}>conf. {pct(p.confRate, 0)}</span>
            </div>
            <div className="panel-b">
              <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 1, background: "var(--line)", borderRadius: 5, overflow: "hidden", marginBottom: 10 }}>
                {[["Commandé", p.ordered, "var(--ink)"], ["Accepté", p.accepted, "var(--green)"], ["Rejeté", p.rejected, "var(--amber)"], ["Reçu", p.received, "var(--accent)"], ["Annulé", p.cancelled, "var(--red)"]].map(([l, v, c]) => (
                  <div key={l} style={{ background: "var(--bg)", padding: "8px 6px", textAlign: "center" }}>
                    <div style={{ fontSize: 9.5, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: .3 }}>{l}</div>
                    <div className="mono" style={{ fontSize: 15, color: c, marginTop: 3 }}>{num(v)}</div>
                  </div>
                ))}
              </div>
              {window.DD_Stat({ label: "CA perdu (annulations)", value: eur(loss), nature: "estimé", src: S().po, payload: inspectPayload({ a, label: "CA perdu — annulations", value: eur(loss), nature: "estimé", src: S().po, field: "cancelledUnits × listPrice", raw: { poId: p.id, ordered: p.ordered, accepted: p.accepted, rejected: p.rejected, received: p.received, cancelled: p.cancelled, listPrice: p.listPrice, netCost: p.netCost, confirmationStatus: p.confirmationStatus, rejectionReason_Sika: p.rejectionReason, cancellationCause: p.causeApi ? "NON exposée par l'API Amazon" : null }, formula: <>perte = <b>{p.cancelled}</b> × <b>{eur(p.listPrice, 2)}</b> = <span className="res">{eur(loss)}</span></>, crumbs: ["Portefeuille", a.short, "PO", p.id, "Brut"] }) })}
              {p.rejectionReason && window.DD_Stat({ label: "Motif de rejet (renvoyé par Sika)", value: p.rejectionReason, nature: "réel", src: S().po })}
              {p.causeApi && (
                <div className="banner err" style={{ marginTop: 8 }}>
                  <span>⊘</span><span><b>Cause d'annulation non exposée par l'API Amazon.</b> Le cockpit détecte et chiffre l'annulation mais ne peut pas en donner la raison — à ne pas confondre avec le <i>rejectionReason</i> (motif renvoyé par Sika).</span>
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---- Concurrence (Keepa) ------------------------------------------------
function TabConcurrence({ a }) {
  const k = a.keepa;
  const last = k[k.length - 1];
  const ser = k.map((x) => ({ label: x.label, v: x.buyBoxPrice, amazon: x.amazonPrice, wk: x.wk }));
  const lostBuyBox = a.compStatus === "menace";
  const oppo = a.compStatus === "opportunite";
  return (
    <div>
      <div className={"banner " + (lostBuyBox ? "err" : oppo ? "ok" : "warn")}>
        <span>{lostBuyBox ? "⚑" : oppo ? "◎" : "ⓘ"}</span>
        <span>
          {lostBuyBox && <><b>Menace — Buy Box perdue</b> face à un 3P (<b>{a.rival}</b>) à prix cassé.</>}
          {oppo && <><b>Opportunité</b> — concurrent en rupture {pct(last.outOfStock90, 0)} du temps (90j). Pousser le réappro / la visibilité.</>}
          {a.compStatus === "neutre" && <>Position stable, Buy Box détenue par Amazon.it.</>}
        </span>
      </div>
      <div className="panel" style={{ marginTop: 12 }}>
        <div className="panel-h"><span>Prix Buy Box vs Amazon — 12 sem (Keepa)</span><Fresh src={S().keepa} /></div>
        <div className="panel-b">
          <SeriesChart series={ser} overlay="amazon" color={lostBuyBox ? "var(--red)" : "var(--green)"} valueLabel="€" />
          <div className="legend">
            <span><i style={{ background: lostBuyBox ? "var(--red)" : "var(--green)" }}></i>prix Buy Box</span>
            <span><i style={{ background: "var(--ink-3)" }}></i>prix Amazon</span>
          </div>
        </div>
      </div>
      <div className="panel">
        <div className="panel-h"><span>Signaux concurrence</span><Nature kind="estimé" note="Keepa estime monthlySold et la Buy Box." /></div>
        <div className="panel-b">
          {window.DD_Stat({ label: "Détenteur Buy Box", value: last.buyBoxOwner, nature: "estimé", src: S().keepa, payload: inspectPayload({ a, label: "buyBoxSellerId", value: last.buyBoxOwner, nature: "estimé", src: S().keepa, field: "buyBoxSellerId (historique)", raw: { buyBoxSellerId: last.buyBoxOwner, history: k.map(x => ({ wk: x.label, owner: x.buyBoxOwner, price: x.buyBoxPrice })) }, crumbs: ["Portefeuille", a.short, "Concurrence", "Buy Box", "Brut"] }) })}
          {window.DD_Stat({ label: "Prix Buy Box", value: eur(last.buyBoxPrice, 2), nature: "estimé", src: S().keepa })}
          {window.DD_Stat({ label: "Sales rank", value: "#" + num(last.salesRank), nature: "estimé", src: S().keepa })}
          {window.DD_Stat({ label: "Rupture concurrent (90j)", value: pct(last.outOfStock90, 0), nature: "estimé", src: S().keepa, payload: inspectPayload({ a, label: "outOfStockPercentage90", value: pct(last.outOfStock90, 0), nature: "estimé", src: S().keepa, field: "outOfStockPercentage90", raw: { outOfStockPercentage90: last.outOfStock90, outOfStockPercentage30: Math.round(last.outOfStock90 * 0.8) } }) })}
          {window.DD_Stat({ label: "monthlySold (estimé Keepa)", value: "~" + num(Math.round(a.weeklyDemand * 4.3)), unit: " u", nature: "estimé", src: S().keepa })}
        </div>
      </div>
    </div>
  );
}

// ---- Demande amont (Brand Analytics — état dégradé) ---------------------
function TabBrand({ a }) {
  return (
    <div>
      <div className="state-box" style={{ padding: 26 }}>
        <div className="ic" style={{ color: "var(--amber)" }}>⊘</div>
        <div style={{ color: "var(--ink-2)", fontWeight: 600, marginBottom: 6 }}>Brand Analytics — accès non accordé</div>
        <div style={{ fontSize: 12, maxWidth: 360, margin: "0 auto", lineHeight: 1.55 }}>
          searchQueryVolume, entonnoir impressions→clics→achats, asinPurchaseShare et top search terms nécessitent le rôle <span className="mono">Brand Analytics</span> + <span className="mono">Brand Registry IT</span>.
        </div>
        <div style={{ marginTop: 14, display: "flex", gap: 8, justifyContent: "center" }}>
          <Nature kind="indisponible" />
          <span className="badge">rôle requis : Brand Analytics</span>
        </div>
        <button className="tb-btn cta" style={{ margin: "16px auto 0" }}>Demander l'accès</button>
      </div>
      <div style={{ fontSize: 10.5, color: "var(--ink-4)", marginTop: 10, textAlign: "center" }}>État dégradé propre — le reste du cockpit reste pleinement fonctionnel sans cette source.</div>
    </div>
  );
}

window.TabVentes = TabVentes;
window.TabInventaire = TabInventaire;
window.TabPO = TabPO;
window.TabConcurrence = TabConcurrence;
window.TabBrand = TabBrand;
