/* ============================================================
   JIT BATCH — Sezioni: Materie Prime, Silos e Aggregati, Automezzi
   ============================================================ */
const Icon = window.Icon;
const { Card: RCard, KPI: RKPI, Badge: RBadge, StatusBadge: RSB, Tag: RTag, LevelBar: RLB, toast: RToast, fmt: RFmt, Drawer: RDrawer } = window.UI;
const RPlant = window.PlantSchema;

function scortaStato(m) {
  if (m.disp <= m.min * 0.6) return "critico";
  if (m.disp <= m.min) return "basso";
  return "ok";
}

/* =================== MATERIE PRIME =================== */
function SezMaterie({ ctx }) {
  const { materie } = ctx;
  const [cat, setCat] = React.useState("Tutte");
  const cats = ["Tutte", ...Array.from(new Set(materie.map(m => m.cat)))];
  const rows = materie.filter(m => cat === "Tutte" || m.cat === cat);
  const crit = materie.filter(m => scortaStato(m) === "critico").length;
  const bassi = materie.filter(m => scortaStato(m) === "basso").length;

  return (
    <div>
      <div className="page-head">
        <div className="ph-titles"><h1>Materie Prime</h1><p>Scorte di magazzino · leganti, aggregati, acqua e additivi</p></div>
        <div className="ph-actions">
          <button className="btn" onClick={() => RToast({ type: "info", title: "Carico merce", msg: "Registrazione bolla di carico (demo)." })}><Icon name="download" size={16} />Registra carico</button>
          <button className="btn btn-accent" onClick={() => RToast({ type: "info", title: "Ordine fornitore", msg: "Generazione richiesta di approvvigionamento (demo)." })}><Icon name="plus" size={16} />Ordina scorta</button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: "var(--gap)" }}>
        <RKPI icon="package" label="Materiali a magazzino" value={materie.length} accent="var(--navy-600)" accentBg="var(--navy-50)" />
        <RKPI icon="triangle" label="Scorte basse" value={bassi} accent="var(--status-warn)" accentBg="var(--status-warn-bg)" foot={bassi ? "Riordino consigliato" : "Tutto regolare"} footIcon={bassi ? "arrowDown" : "check"} />
        <RKPI icon="alertCircle" label="Scorte critiche" value={crit} accent="var(--status-alarm)" accentBg="var(--status-alarm-bg)" foot={crit ? "Intervento urgente" : "Nessuna criticità"} footIcon={crit ? "arrowDown" : "check"} />
      </div>

      <div className="filterbar">
        <div className="chip-toggle">
          {cats.map(c => <button key={c} className={cat === c ? "on" : ""} onClick={() => setCat(c)}>{c}</button>)}
        </div>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>Materiale</th><th>Categoria</th><th className="num">Disponibile</th><th className="num">Capacità</th><th style={{ width: 180 }}>Livello</th><th>Stato</th><th>Fornitore</th><th>Ultimo carico</th></tr></thead>
            <tbody>
              {rows.map(m => {
                const pct = Math.round((m.disp / m.max) * 100);
                const st = scortaStato(m);
                return (
                  <tr key={m.id}>
                    <td className="strong">{m.nome}</td>
                    <td><RTag>{m.cat}</RTag></td>
                    <td className="num data" style={{ color: "var(--fg-1)" }}>{RFmt.n(m.disp, m.um === "t" ? 0 : 0)} {m.um}</td>
                    <td className="num muted">{RFmt.n(m.max)} {m.um}</td>
                    <td>
                      <div className="row" style={{ gap: 8 }}>
                        <RLB pct={pct} status={st} />
                        <span className="mono" style={{ fontSize: 11.5, minWidth: 32, color: "var(--fg-3)" }}>{pct}%</span>
                      </div>
                    </td>
                    <td><RSB map="scorta" value={st} /></td>
                    <td style={{ fontSize: 12.5 }}>{m.forn}</td>
                    <td className="mono" style={{ fontSize: 12.5 }}>{m.carico}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* =================== SILOS E AGGREGATI =================== */
function VesselBar({ v }) {
  const pct = v.liv;
  const col = pct <= 15 ? "var(--status-alarm)" : pct <= 30 ? "var(--status-warn)" : "var(--status-run)";
  const matCol = pct <= 15 ? "var(--status-alarm)" : pct <= 30 ? "var(--status-warn)" : "var(--navy-500)";
  const st = pct <= 15 ? "critico" : pct <= 30 ? "basso" : "ok";
  const icon = v.tipo === "silo" ? "silo" : v.tipo === "vasca" ? "droplet" : "layers";
  return (
    <div className="card" style={{ display: "flex", flexDirection: "column" }}>
      <div className="card-body" style={{ display: "flex", gap: 14, padding: 16 }}>
        {/* vertical gauge */}
        <div style={{ width: 56, flex: "none", display: "flex", flexDirection: "column", alignItems: "center" }}>
          <div style={{ position: "relative", width: 42, height: 150, borderRadius: 8, border: "2px solid var(--border-strong)", background: "var(--bg-sunken)", overflow: "hidden" }}>
            <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: `${pct}%`, background: `linear-gradient(180deg, ${matCol}, color-mix(in srgb, ${matCol} 75%, #000))`, transition: "height 700ms cubic-bezier(0.2,0,0,1)" }} />
            {[25, 50, 75].map(g => <div key={g} style={{ position: "absolute", left: 0, right: 0, bottom: `${g}%`, height: 1, background: "var(--border)" }} />)}
            <div style={{ position: "absolute", left: 0, right: 0, top: 6, textAlign: "center", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 13, color: pct > 70 ? "#fff" : "var(--fg-1)", textShadow: pct > 70 ? "0 1px 2px rgba(0,0,0,0.3)" : "none" }}>{pct}%</div>
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="row" style={{ gap: 8, marginBottom: 4 }}>
            <span className="kpi-ico" style={{ width: 26, height: 26, background: "var(--bg-sunken)", color: "var(--navy-600)" }}><Icon name={icon} size={15} /></span>
            <div style={{ minWidth: 0 }}><div className="strong" style={{ fontSize: 14, fontWeight: 700 }}>{v.nome}</div><div className="muted" style={{ fontSize: 11.5 }}>{v.contenuto}</div></div>
          </div>
          <div className="deflist" style={{ marginTop: 8 }}>
            <div className="defrow" style={{ padding: "7px 0" }}><span className="dt">Disponibile</span><span className="dd data">{RFmt.n(v.cap * v.liv / 100, v.um === "t" ? 1 : 0)} {v.um}</span></div>
            <div className="defrow" style={{ padding: "7px 0" }}><span className="dt">Capacità</span><span className="dd mono" style={{ fontWeight: 500, color: "var(--fg-3)" }}>{RFmt.n(v.cap)} {v.um}</span></div>
            <div className="defrow" style={{ padding: "7px 0", borderBottom: "none" }}><span className="dt">Temperatura</span><span className="dd data" style={{ color: "var(--fg-2)" }}>{v.temp}°C</span></div>
          </div>
          <div style={{ marginTop: 8 }}><RSB map="scorta" value={st} /></div>
        </div>
      </div>
    </div>
  );
}

function SezSilos({ ctx }) {
  const { silos } = ctx;
  const levels = {}; silos.forEach(s => levels[s.id] = s.liv);
  return (
    <div>
      <div className="page-head">
        <div className="ph-titles"><h1>Silos e Aggregati</h1><p>Stato vasche, silos e tramogge in tempo reale</p></div>
        <div className="ph-actions"><RBadge cls="run" label="Sincronizzazione PLC attiva" pulse /></div>
      </div>

      <RCard title="Schema impianto" icon="factory" sub="vista sinottica" style={{ marginBottom: "var(--gap)" }}>
        <RPlant phase="idle" levels={levels} height={360} />
      </RCard>

      <div className="eyebrow" style={{ marginBottom: 10 }}>Dettaglio contenitori</div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill,minmax(300px,1fr))" }}>
        {silos.map(v => <VesselBar key={v.id} v={v} />)}
      </div>
    </div>
  );
}

/* =================== AUTOMEZZI =================== */
function SezAutomezzi({ ctx }) {
  const { automezzi, setAutomezzi } = ctx;
  const [f, setF] = React.useState("tutti");
  const rows = automezzi.filter(a => f === "tutti" || a.stato === f);
  const c = (s) => automezzi.filter(a => a.stato === s).length;
  const capTot = automezzi.reduce((s, a) => s + a.capacita, 0);

  const setStato = (targa, stato) => {
    setAutomezzi(automezzi.map(a => a.targa === targa ? { ...a, stato, ordine: stato === "disponibile" ? null : a.ordine } : a));
    RToast({ type: "info", title: "Stato mezzo aggiornato", msg: `${targa} → ${window.UI.statusMaps.mezzo[stato].label}` });
  };

  return (
    <div>
      <div className="page-head">
        <div className="ph-titles"><h1>Automezzi</h1><p>Flotta autobetoniere · {automezzi.length} mezzi · {capTot} m³ capacità totale</p></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: "var(--gap)" }}>
        <RKPI icon="checkCircle" label="Disponibili" value={c("disponibile")} accent="var(--status-run)" accentBg="var(--status-run-bg)" />
        <RKPI icon="package" label="In carico" value={c("in_carico")} accent="var(--status-info)" accentBg="var(--status-info-bg)" />
        <RKPI icon="truck" label="In consegna" value={c("in_consegna")} accent="var(--status-warn)" accentBg="var(--status-warn-bg)" />
        <RKPI icon="wrench" label="In manutenzione" value={c("manutenzione")} accent="var(--status-idle)" accentBg="var(--status-idle-bg)" />
      </div>

      <div className="filterbar">
        <div className="chip-toggle">
          {[["tutti", "Tutti"], ["disponibile", "Disponibili"], ["in_carico", "In carico"], ["in_consegna", "In consegna"], ["manutenzione", "Manutenzione"]].map(([k, l]) =>
            <button key={k} className={f === k ? "on" : ""} onClick={() => setF(k)}>{l}</button>)}
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill,minmax(330px,1fr))" }}>
        {rows.map(a => (
          <div key={a.targa} className="card">
            <div className="card-body" style={{ padding: 16 }}>
              <div className="row" style={{ justifyContent: "space-between", marginBottom: 12 }}>
                <div className="row" style={{ gap: 10 }}>
                  <span className="kpi-ico" style={{ width: 38, height: 38, background: "var(--navy-50)", color: "var(--navy-600)" }}><Icon name="truck" size={22} /></span>
                  <div><div className="mono strong" style={{ fontSize: 15, fontWeight: 700, color: "var(--fg-1)", letterSpacing: "0.02em" }}>{a.targa}</div><div className="muted" style={{ fontSize: 12 }}>{a.autista}</div></div>
                </div>
                <RSB map="mezzo" value={a.stato} />
              </div>
              <div className="deflist">
                <div className="defrow" style={{ padding: "8px 0" }}><span className="dt">Capacità</span><span className="dd data">{a.capacita} m³</span></div>
                <div className="defrow" style={{ padding: "8px 0" }}><span className="dt">Ordine associato</span><span className="dd">{a.ordine || <span className="muted" style={{ fontWeight: 500 }}>—</span>}</span></div>
                <div className="defrow" style={{ padding: "8px 0" }}><span className="dt">{a.stato === "manutenzione" ? "Intervento" : "Rientro previsto"}</span><span className="dd" style={{ fontSize: 13 }}>{a.stato === "manutenzione" ? a.manutNote : a.rientro}</span></div>
                <div className="defrow" style={{ padding: "8px 0", borderBottom: "none" }}><span className="dt">Odometro</span><span className="dd mono" style={{ fontWeight: 500, color: "var(--fg-3)" }}>{RFmt.n(a.km)} km</span></div>
              </div>
              <div className="row" style={{ gap: 8, marginTop: 12 }}>
                {a.stato !== "disponibile"
                  ? <button className="btn btn-sm" style={{ flex: 1 }} onClick={() => setStato(a.targa, "disponibile")}><Icon name="check" size={14} />Segna disponibile</button>
                  : <button className="btn btn-sm btn-primary" style={{ flex: 1 }} onClick={() => setStato(a.targa, "in_carico")}><Icon name="package" size={14} />Assegna carico</button>}
                <button className="btn btn-sm btn-ghost" onClick={() => RToast({ type: "info", title: a.targa, msg: "Apertura scheda mezzo / GPS (demo)." })}><Icon name="mapPin" size={14} /></button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.Sezioni = Object.assign(window.Sezioni || {}, { SezMaterie, SezSilos, SezAutomezzi });
