/* ============================================================
   SIKA COCKPIT — App (assemble tout)
   ============================================================ */
const ItalyFlag = () => (
  <span className="flag"><svg width="18" height="13" viewBox="0 0 3 2"><rect width="1" height="2" fill="#0a8c4f" /><rect x="1" width="1" height="2" fill="#f0f0f0" /><rect x="2" width="1" height="2" fill="#cd2b34" /></svg></span>
);

function SortGet(a, k) {
  const d = a.d;
  switch (k) {
    case "title": return a.short;
    case "covG": return d.coverageGross; case "covN": return d.coverageNet;
    case "dem": return a.weeklyDemand; case "stock": return a.onHand;
    case "risk": return d.revenueAtRisk; case "price": return a.price; case "margin": return a.netMargin;
    case "deadline": return d.deadline ? d.deadline.getTime() : 0;
    case "comp": return { menace: 0, opportunite: 1, neutre: 2 }[a.compStatus];
    case "po": return { annule: 0, rejet_partiel: 1, confirme: 2 }[a.poStatus];
    default: return 0;
  }
}

function AboutPanel({ onClose }) {
  return (
    <div className="overlay" onClick={onClose}>
      <div className="inspector" style={{ width: 720 }} onClick={(e) => e.stopPropagation()}>
        <div className="insp-h"><span className="chip-act">PARTI PRIS DESIGN</span><span style={{ fontWeight: 600 }}>Cockpit proactif Sika × Amazon Vendor — POC</span><button className="x" onClick={onClose}>×</button></div>
        <div className="insp-b" style={{ fontSize: 12.5, lineHeight: 1.6, color: "var(--ink-2)" }}>
          <p style={{ marginTop: 0 }}>Conçu pour <b style={{ color: "var(--ink)" }}>Benjamin</b> (Key Account / Supply, Sika Italie) — profil power-user data. Deux vitesses dans un seul outil&nbsp;:</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, margin: "12px 0" }}>
            <div className="panel"><div className="panel-h">Décideur · 5 s</div><div className="panel-b" style={{ fontSize: 12 }}>KPIs en haut, feux, € à risque, date limite. « Quoi faire aujourd'hui ».</div></div>
            <div className="panel"><div className="panel-h">Analyste · profondeur</div><div className="panel-b" style={{ fontSize: 12 }}>Chaque chiffre cliquable jusqu'au JSON brut, hypothèses éditables, time-travel.</div></div>
          </div>
          <div className="panel"><div className="panel-h">Carte de drill-down N0 → N4</div><div className="panel-b">
            <div className="crumbs" style={{ marginBottom: 0 }}>
              <span className="n">N0 Portefeuille</span>›<span className="n">N1 ASIN (feu)</span>›<span className="n">N2 Dimension (onglet)</span>›<span className="n">N3 Série (graphe)</span>›<span className="n cur">N4 JSON brut</span>
            </div>
            <div style={{ fontSize: 11.5, marginTop: 10 }}>Aucun cul-de-sac : un clic sur n'importe quelle valeur (pointillé) ouvre le <b style={{ color: "var(--ink)" }}>Data Inspector</b> → formule, provenance, fraîcheur, champ source.</div>
          </div></div>
          <div className="panel"><div className="panel-h">Honnêteté de la donnée (jamais masquée)</div><div className="panel-b" style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            <Nature kind="réel" /> <Nature kind="estimé" /> <Nature kind="proxy" /> <Nature kind="hypothèse" /> <Nature kind="indisponible" />
            <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 4 }}>Badges de fraîcheur par source · CA à risque libellé « borne basse » · cause d'annulation « non exposée par l'API » · forecast P70/80/90 = bornes de probabilité.</div>
          </div></div>
          <p style={{ color: "var(--ink-3)", fontSize: 11.5 }}>Périmètre POC&nbsp;: Italie (amazon.it, EUR). Sélecteur marché prévu pour l'extension worldwide. Données factices mais structurées comme les rapports SP-API Vendor & Keepa réels.</p>
        </div>
      </div>
    </div>
  );
}

const THEMES = [
  ["papier", "Papier — clair chaud", "#f4f1ea", "#cf2318"],
  ["clinique", "Clinique — blanc froid", "#ffffff", "#1f72e6"],
  ["graphite", "Graphite — gris structuré", "#e8eaed", "#2360c9"],
  ["sombre", "Sombre — power-user", "#12161c", "#6aa6ff"],
];
function ThemeSwitch({ theme, setTheme }) {
  return (
    <div className="theme-sw" role="group" aria-label="Thème">
      {THEMES.map(([id, label, bg, ac]) => (
        <button key={id} className={"sw" + (theme === id ? " on" : "")} title={"Thème — " + label} onClick={() => setTheme(id)}>
          <span className="sw-dot" style={{ background: bg }}><i style={{ background: ac }}></i></span>
        </button>
      ))}
    </div>
  );
}

function App() {
  const [A, setA] = useState(Object.assign({}, window.SIKA.DEFAULT_ASSUMPTIONS));
  const [mode, setMode] = useState("decideur");
  const [filter, setFilter] = useState(null);
  const [sort, setSort] = useState({ k: "risk", dir: -1 });
  const [picked, setPicked] = useState(null);
  const [showAssume, setShowAssume] = useState(false);
  const [inspect, setInspect] = useState(null);
  const [about, setAbout] = useState(false);
  const [query, setQuery] = useState("");
  const [throttle, setThrottle] = useState(true);
  const [theme, setTheme] = useState(() => { try { return localStorage.getItem("sika-theme") || "papier"; } catch (e) { return "papier"; } });

  useEffect(() => { document.body.setAttribute("data-theme", theme); try { localStorage.setItem("sika-theme", theme); } catch (e) {} }, [theme]);

  useEffect(() => { window.SikaUI = { inspect: setInspect, openAsin: setPicked }; }, []);
  useEffect(() => { document.body.className = "mode-" + mode; }, [mode]);

  const port = useMemo(() => window.SikaCompute.portfolio(window.SIKA.asins, A), [A]);

  const freshnessWorst = { label: "71 h", color: "var(--red)" };

  let rows = port.rows.slice();
  if (filter === "risk") rows = rows.filter((a) => a.d.revenueAtRisk > 0);
  else if (filter === "status") rows = rows.filter((a) => a.d.status !== "green");
  else if (filter === "peaks") rows = rows.filter((a) => a.d.nextPeak);
  else if (filter === "comp") rows = rows.filter((a) => a.compStatus !== "neutre");
  else if (filter === "po") rows = rows.filter((a) => a.poStatus !== "confirme");
  if (query.trim()) {
    const q = query.toLowerCase();
    rows = rows.filter((a) => (a.short + a.asin + a.sku + a.cat).toLowerCase().includes(q));
  }
  rows.sort((x, y) => { const vx = SortGet(x, sort.k), vy = SortGet(y, sort.k); return (vx > vy ? 1 : vx < vy ? -1 : 0) * sort.dir; });

  const FILTER_LABEL = { risk: "CA à risque > 0", status: "Feux rouge/orange", peaks: "Pic à venir", comp: "Concurrence active", po: "PO non confirmé" };

  function exportCSV() {
    const head = ["asin", "sku", "produit", "statut", "couv_brute", "couv_nette", "demande_hebdo", "stock", "po_entrant", "ca_a_risque_eur", "date_limite", "prix_proxy", "marge_nette_pct", "concurrence", "po_statut"];
    const lines = rows.map((a) => [a.asin, a.sku, '"' + a.short + '"', a.d.status, a.d.coverageGross.toFixed(2), a.d.coverageNet.toFixed(2), a.weeklyDemand, a.onHand, a.openPO, Math.round(a.d.revenueAtRisk), a.d.deadline ? a.d.deadline.toISOString().slice(0, 10) : "depasse", a.price, a.netMargin, a.compStatus, a.poStatus].join(","));
    const csv = head.join(",") + "\n" + lines.join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob); const el = document.createElement("a");
    el.href = url; el.download = "sika_cockpit_IT.csv"; el.click(); URL.revokeObjectURL(url);
  }

  return (
    <TipProvider>
      <div className="topbar">
        <div className="brand"><span className="brand-mark">S</span><span>Cockpit Proactif<br /></span><small style={{ marginLeft: -2 }}>Amazon Vendor · 1P</small></div>
        <div className="market-sel"><ItalyFlag /> Italie <span style={{ color: "var(--ink-4)" }}>·</span> <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>amazon.it · EUR</span> <span style={{ color: "var(--ink-4)" }}>▾</span></div>
        <div className="seg">
          <button className={mode === "decideur" ? "on" : ""} onClick={() => setMode("decideur")}>◴ Décideur</button>
          <button className={"analyst " + (mode === "analyste" ? "on" : "")} onClick={() => setMode("analyste")}>⌗ Analyste</button>
        </div>
        <div className="spacer"></div>
        <ThemeSwitch theme={theme} setTheme={setTheme} />
        <div className="search"><span>⌕</span><input placeholder="Rechercher ASIN, SKU, produit…" value={query} onChange={(e) => setQuery(e.target.value)} /></div>
        <button className="tb-btn" onClick={() => setShowAssume((v) => !v)}>⚙ Hypothèses</button>
        <button className="tb-btn" onClick={exportCSV}>↓ CSV</button>
        <button className="tb-btn" onClick={() => setAbout(true)}>ⓘ Parti pris</button>
      </div>

      {throttle && (
        <div style={{ padding: "6px 14px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)" }}>
          <div className="banner warn">
            <span>⚠︎</span>
            <span><b>Chargement partiel</b> — Net PPM (marge) renvoie <span className="mono">429 Throttled</span> par SP-API ; affichage de la dernière valeur connue (âge {ageLabel(window.SIKA.SOURCES.margin.ageHours)}). Keepa&nbsp;: 2 ASIN en attente de tokens.</span>
            <button className="tb-btn" style={{ marginLeft: "auto", padding: "3px 8px" }} onClick={() => setThrottle(false)}>Masquer</button>
          </div>
        </div>
      )}

      <KpiStrip port={port} A={A} filter={filter} setFilter={setFilter} freshnessWorst={freshnessWorst} />

      {(filter || query) && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 14px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)", fontSize: 11.5, color: "var(--ink-3)" }}>
          <span>Filtre&nbsp;:</span>
          {filter && <span className="badge" style={{ borderColor: "var(--sika)", color: "var(--sika-ink)" }}>{FILTER_LABEL[filter]} <span style={{ cursor: "pointer" }} onClick={() => setFilter(null)}>×</span></span>}
          {query && <span className="badge">« {query} » <span style={{ cursor: "pointer" }} onClick={() => setQuery("")}>×</span></span>}
          <span style={{ marginLeft: "auto" }} className="mono">{rows.length} ASIN</span>
        </div>
      )}

      <div className="workspace">
        <div className="main">
          <AsinTable rows={rows} A={A} onPick={(a) => setPicked(a.asin)} activeAsin={picked} sort={sort} setSort={setSort} />
        </div>
        <Drawer a={picked ? port.rows.find((r) => r.asin === picked) : null} A={A} open={!!picked} onClose={() => setPicked(null)} />
        <AssumptionsPanel A={A} setA={setA} port={port} open={showAssume} onClose={() => setShowAssume(false)} />
      </div>

      <div className="statusbar">
        <span className="ok">● {window.SIKA.asins.length} ASIN · marché IT</span>
        <span>Ventes/stock real-time <span className="ok">5 min</span></span>
        <span>Forecast <span className="warn">71 h</span></span>
        <span>Brand Analytics <span style={{ color: "var(--ink-4)" }}>non accordé</span></span>
        <span style={{ marginLeft: "auto" }}>Mode {mode === "decideur" ? "Décideur" : "Analyste"} · hypothèses : lead {A.leadTime}sem / buffer {A.buffer}sem / horizon {A.horizon}sem</span>
      </div>

      {inspect && <DataInspector payload={inspect} onClose={() => setInspect(null)} />}
      {about && <AboutPanel onClose={() => setAbout(false)} />}
    </TipProvider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
