/* ============================================================
   JIT BATCH — Sezioni: Ricette, Ordini, Clienti e Cantieri
   ============================================================ */
const Icon = window.Icon;
const { Card: CCard, KPI: CKPI, Badge: CBadge, StatusBadge: CSB, Tag: CTag, LevelBar: CLB, toast: CToast, fmt: CFmt, Drawer: CDrawer, Modal: CModal } = window.UI;

/* =================== RICETTE =================== */
function SezRicette({ ctx }) {
  const { ricette, setRicette } = ctx;
  const [sel, setSel] = React.useState(null);
  const [draft, setDraft] = React.useState(null);
  const [q, setQ] = React.useState("");

  const open = (r) => { setSel(r.id); setDraft({ ...r }); };
  const rows = ricette.filter(r => (r.nome + r.id + r.classe).toLowerCase().includes(q.toLowerCase()));

  const ac = draft ? (draft.acqua / draft.cemento).toFixed(2) : 0;
  const saveDraft = () => {
    setRicette(ricette.map(r => r.id === draft.id ? draft : r));
    CToast({ type: "run", title: "Ricetta aggiornata", msg: `${draft.nome} salvata correttamente.` });
    setSel(null);
  };
  const toggleAttiva = (r, e) => {
    e.stopPropagation();
    setRicette(ricette.map(x => x.id === r.id ? { ...x, attiva: !x.attiva } : x));
    CToast({ type: r.attiva ? "warn" : "run", title: r.attiva ? "Ricetta disattivata" : "Ricetta attivata", msg: r.nome });
  };

  const Num = ({ k, lbl, unit, step = 1 }) => (
    <div className="field" style={{ flex: 1, minWidth: 110 }}>
      <label>{lbl} <span className="muted">{unit}</span></label>
      <input className="input mono" type="number" step={step} value={draft[k]}
        onChange={(e) => setDraft({ ...draft, [k]: parseFloat(e.target.value) || 0 })} />
    </div>
  );

  return (
    <div>
      <div className="page-head">
        <div className="ph-titles"><h1>Ricette Calcestruzzo</h1><p>{ricette.filter(r => r.attiva).length} ricette attive · distinte base di dosaggio per m³</p></div>
        <div className="ph-actions">
          <div className="search-box" style={{ minWidth: 200 }}><Icon name="search" size={15} /><input placeholder="Cerca ricetta…" value={q} onChange={e => setQ(e.target.value)} /></div>
          <button className="btn btn-accent" onClick={() => CToast({ type: "info", title: "Nuova ricetta", msg: "Apertura editor distinta base (demo)." })}><Icon name="plus" size={16} />Nuova ricetta</button>
        </div>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr>
              <th>Ricetta</th><th>Classe</th><th>Consist.</th>
              <th className="num">Cemento</th><th className="num">Sabbia</th><th className="num">Ghiaia</th>
              <th className="num">Acqua</th><th className="num">Additivo</th><th className="num">A/C</th><th className="num">Mix</th><th>Stato</th>
            </tr></thead>
            <tbody>
              {rows.map(r => (
                <tr key={r.id} className="clickable" onClick={() => open(r)}>
                  <td><div style={{ display: "flex", flexDirection: "column" }}><span className="strong">{r.nome}</span><span className="muted" style={{ fontSize: 12 }}>{r.uso}</span></div></td>
                  <td><CTag>{r.classe}</CTag></td>
                  <td className="mono">{r.consistenza}</td>
                  <td className="num strong">{r.cemento}</td>
                  <td className="num">{r.sabbia}</td>
                  <td className="num">{r.ghiaiaF + r.ghiaiaG}</td>
                  <td className="num">{r.acqua}</td>
                  <td className="num">{r.additivo}</td>
                  <td className="num">{(r.acqua / r.cemento).toFixed(2)}</td>
                  <td className="num">{r.mix}s</td>
                  <td onClick={e => toggleAttiva(r, e)} title="Attiva / disattiva">
                    <CBadge cls={r.attiva ? "run" : "idle"} label={r.attiva ? "Attiva" : "Non attiva"} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <p className="muted" style={{ fontSize: 12, marginTop: 10 }}>Valori espressi per m³ di calcestruzzo. Cemento/Sabbia/Ghiaia in kg · Acqua/Additivo in litri · Mix = tempo di miscelazione.</p>

      {sel && draft && (
        <CDrawer sub={`Distinta base · ${draft.classe}`} title={draft.nome} onClose={() => setSel(null)}
          footer={<React.Fragment>
            <button className="btn" onClick={() => setSel(null)}>Annulla</button>
            <button className="btn btn-primary" onClick={saveDraft}><Icon name="save" size={16} />Salva ricetta</button>
          </React.Fragment>}>
          <div style={{ display: "flex", gap: 8, marginBottom: 16, flexWrap: "wrap" }}>
            <CTag>{draft.classe}</CTag><CTag>Consistenza {draft.consistenza}</CTag><CTag>Dmax {draft.dmax}</CTag>
            <CBadge cls={draft.attiva ? "run" : "idle"} label={draft.attiva ? "Attiva" : "Non attiva"} />
          </div>
          <div className="card" style={{ background: "var(--bg-sunken)", border: "none", marginBottom: 16 }}>
            <div className="card-body" style={{ display: "flex", justifyContent: "space-around", textAlign: "center", padding: 14 }}>
              <div><div className="muted" style={{ fontSize: 12 }}>Rapporto A/C</div><div className="data" style={{ fontSize: 24, color: ac > 0.6 ? "var(--status-warn)" : "var(--status-run)" }}>{ac}</div></div>
              <div><div className="muted" style={{ fontSize: 12 }}>Massa totale</div><div className="data" style={{ fontSize: 24, color: "var(--fg-1)" }}>{CFmt.n(draft.cemento + draft.sabbia + draft.ghiaiaF + draft.ghiaiaG + draft.acqua)}<span style={{ fontSize: 13, color: "var(--fg-3)" }}> kg</span></div></div>
              <div><div className="muted" style={{ fontSize: 12 }}>Tempo mix</div><div className="data" style={{ fontSize: 24, color: "var(--fg-1)" }}>{draft.mix}<span style={{ fontSize: 13, color: "var(--fg-3)" }}> s</span></div></div>
            </div>
          </div>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Composizione (kg–l per m³)</div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <Num k="cemento" lbl="Cemento" unit="kg" /><Num k="sabbia" lbl="Sabbia 0/4" unit="kg" />
          </div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 10 }}>
            <Num k="ghiaiaF" lbl="Ghiaia 4/12" unit="kg" /><Num k="ghiaiaG" lbl="Ghiaia 12/20" unit="kg" />
          </div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 10 }}>
            <Num k="acqua" lbl="Acqua" unit="l" /><Num k="additivo" lbl="Additivo" unit="l" step={0.1} /><Num k="mix" lbl="Mix" unit="s" />
          </div>
          <div style={{ marginTop: 16, padding: 12, borderRadius: 8, background: "var(--status-info-bg)", color: "var(--status-info)", fontSize: 13, display: "flex", gap: 8 }}>
            <Icon name="info" size={16} /><span>Modifica simulata: i valori vengono applicati alle prossime produzioni di questa ricetta.</span>
          </div>
        </CDrawer>
      )}
    </div>
  );
}

/* =================== ORDINI =================== */
function SezOrdini({ ctx }) {
  const { ordini, setOrdini, navigate, setProdOrder } = ctx;
  const [q, setQ] = React.useState("");
  const [fStato, setFStato] = React.useState("tutti");
  const [sel, setSel] = React.useState(null);

  const mandaInProd = (o, e) => {
    if (e) e.stopPropagation();
    setOrdini(ordini.map(x => x.id === o.id ? { ...x, stato: "in_produzione" } : x));
    CToast({ type: "run", title: `${o.id} in produzione`, msg: `${o.cliente} · ${o.ricetta} · ${o.tot} m³` });
    setProdOrder(o.id);
    setTimeout(() => navigate("produzione"), 350);
  };

  const rows = ordini.filter(o =>
    (fStato === "tutti" || o.stato === fStato) &&
    (o.id + o.cliente + o.cantiere + o.ricetta).toLowerCase().includes(q.toLowerCase()));

  const counts = {
    programmato: ordini.filter(o => o.stato === "programmato").length,
    in_produzione: ordini.filter(o => o.stato === "in_produzione").length,
    completato: ordini.filter(o => o.stato === "completato").length,
    sospeso: ordini.filter(o => o.stato === "sospeso").length,
  };
  const selO = ordini.find(o => o.id === sel);

  return (
    <div>
      <div className="page-head">
        <div className="ph-titles"><h1>Ordini</h1><p>Pianificazione e avanzamento delle forniture</p></div>
        <div className="ph-actions">
          <button className="btn btn-accent" onClick={() => CToast({ type: "info", title: "Nuovo ordine", msg: "Apertura modulo nuovo ordine (demo)." })}><Icon name="plus" size={16} />Nuovo ordine</button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: "var(--gap)" }}>
        <CKPI icon="calendar" label="Programmati" value={counts.programmato} accent="var(--status-info)" accentBg="var(--status-info-bg)" />
        <CKPI icon="activity" label="In produzione" value={counts.in_produzione} accent="var(--status-run)" accentBg="var(--status-run-bg)" />
        <CKPI icon="checkCircle" label="Completati oggi" value={counts.completato} accent="var(--status-idle)" accentBg="var(--status-idle-bg)" />
        <CKPI icon="triangle" label="Sospesi" value={counts.sospeso} accent="var(--status-warn)" accentBg="var(--status-warn-bg)" />
      </div>

      <div className="filterbar">
        <div className="search-box" style={{ minWidth: 240 }}><Icon name="search" size={15} /><input placeholder="Cerca ordine, cliente, cantiere…" value={q} onChange={e => setQ(e.target.value)} /></div>
        <select className="input" value={fStato} onChange={e => setFStato(e.target.value)}>
          <option value="tutti">Tutti gli stati</option>
          <option value="programmato">Programmato</option>
          <option value="in_produzione">In produzione</option>
          <option value="completato">Completato</option>
          <option value="sospeso">Sospeso</option>
        </select>
        <span className="muted" style={{ fontSize: 12.5, marginLeft: "auto" }}>{rows.length} ordini</span>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr>
              <th>Ordine</th><th>Cliente / Cantiere</th><th>Ricetta</th><th className="num">m³</th>
              <th style={{ width: 150 }}>Avanzamento</th><th>Consegna</th><th>Mezzo</th><th>Stato</th><th></th>
            </tr></thead>
            <tbody>
              {rows.map(o => {
                const pct = Math.round((o.prodotto / o.tot) * 100);
                return (
                  <tr key={o.id} className="clickable" onClick={() => setSel(o.id)}>
                    <td><span className="id-cell">{o.id}</span>{o.priorita === "alta" && <div><CTag color="var(--status-alarm)" bg="var(--status-alarm-bg)">PRIORITÀ ALTA</CTag></div>}</td>
                    <td><div style={{ display: "flex", flexDirection: "column" }}><span className="strong">{o.cliente}</span><span className="muted" style={{ fontSize: 12 }}>{o.cantiere}</span></div></td>
                    <td><CTag>{o.ricetta}</CTag></td>
                    <td className="num strong">{o.tot}</td>
                    <td>
                      <div className="row" style={{ gap: 8 }}>
                        <div className="progress" style={{ flex: 1, height: 8 }}><span style={{ width: `${pct}%` }} /></div>
                        <span className="mono" style={{ fontSize: 11.5, color: "var(--fg-3)", minWidth: 34 }}>{o.prodotto}/{o.tot}</span>
                      </div>
                    </td>
                    <td className="mono" style={{ fontSize: 12.5 }}>{o.consegna.split(" ")[1]}<div className="muted" style={{ fontSize: 11 }}>{o.consegna.split(" ")[0]}</div></td>
                    <td className="mono" style={{ fontSize: 12.5 }}>{o.mezzo || <span className="muted">—</span>}</td>
                    <td><CSB map="ordine" value={o.stato} /></td>
                    <td onClick={e => e.stopPropagation()}>
                      {o.stato === "programmato"
                        ? <button className="btn btn-sm btn-primary" onClick={(e) => mandaInProd(o, e)}><Icon name="play" size={13} />In produzione</button>
                        : <button className="btn btn-sm btn-ghost" onClick={() => setSel(o.id)}>Dettagli</button>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {selO && (
        <CDrawer sub={`Ordine · consegna ${selO.consegna}`} title={selO.id} onClose={() => setSel(null)}
          footer={<React.Fragment>
            {selO.stato === "programmato" && <button className="btn btn-primary" onClick={() => { mandaInProd(selO); setSel(null); }}><Icon name="play" size={16} />Manda in produzione</button>}
            <button className="btn" onClick={() => setSel(null)}>Chiudi</button>
          </React.Fragment>}>
          <div style={{ marginBottom: 14 }}><CSB map="ordine" value={selO.stato} /></div>
          <div className="deflist">
            <div className="defrow"><span className="dt">Cliente</span><span className="dd">{selO.cliente}</span></div>
            <div className="defrow"><span className="dt">Cantiere</span><span className="dd">{selO.cantiere}</span></div>
            <div className="defrow"><span className="dt">Ricetta</span><span className="dd"><CTag>{selO.ricetta}</CTag></span></div>
            <div className="defrow"><span className="dt">Quantità totale</span><span className="dd data">{selO.tot} m³</span></div>
            <div className="defrow"><span className="dt">Quantità prodotta</span><span className="dd data">{selO.prodotto} m³</span></div>
            <div className="defrow"><span className="dt">Consegna prevista</span><span className="dd">{selO.consegna}</span></div>
            <div className="defrow"><span className="dt">Automezzo</span><span className="dd">{selO.mezzo || "Non assegnato"}</span></div>
            <div className="defrow"><span className="dt">Priorità</span><span className="dd" style={{ textTransform: "capitalize" }}>{selO.priorita}</span></div>
          </div>
          {selO.notaSosp && <div style={{ marginTop: 14, padding: 12, borderRadius: 8, background: "var(--status-warn-bg)", color: "var(--orange-700)", fontSize: 13, display: "flex", gap: 8 }}><Icon name="triangle" size={16} /><span>{selO.notaSosp}</span></div>}
          <div style={{ marginTop: 18 }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Avanzamento produzione</div>
            <div className="progress" style={{ height: 14 }}><span style={{ width: `${Math.round((selO.prodotto / selO.tot) * 100)}%` }} /></div>
            <div className="row" style={{ justifyContent: "space-between", marginTop: 6 }}><span className="muted" style={{ fontSize: 12 }}>{selO.prodotto} m³ prodotti</span><span className="muted" style={{ fontSize: 12 }}>{selO.tot - selO.prodotto} m³ rimanenti</span></div>
          </div>
        </CDrawer>
      )}
    </div>
  );
}

/* =================== CLIENTI E CANTIERI =================== */
function SezClienti({ ctx }) {
  const { clienti } = ctx;
  const [q, setQ] = React.useState("");
  const [sel, setSel] = React.useState(null);
  const rows = clienti.filter(c => (c.nome + c.ref + c.cantiere + c.indirizzo).toLowerCase().includes(q.toLowerCase()));
  const selC = clienti.find(c => c.id === sel);

  return (
    <div>
      <div className="page-head">
        <div className="ph-titles"><h1>Clienti e Cantieri</h1><p>{clienti.length} clienti attivi · anagrafica e logistica consegne</p></div>
        <div className="ph-actions">
          <div className="search-box" style={{ minWidth: 220 }}><Icon name="search" size={15} /><input placeholder="Cerca cliente o cantiere…" value={q} onChange={e => setQ(e.target.value)} /></div>
          <button className="btn btn-accent" onClick={() => CToast({ type: "info", title: "Nuovo cliente", msg: "Apertura anagrafica (demo)." })}><Icon name="plus" size={16} />Nuovo cliente</button>
        </div>
      </div>
      <div className="card" style={{ overflow: "hidden" }}>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>Cliente</th><th>Referente</th><th>Telefono</th><th>Cantiere</th><th>Indirizzo</th><th className="num">Distanza</th><th></th></tr></thead>
            <tbody>
              {rows.map(c => (
                <tr key={c.id} className="clickable" onClick={() => setSel(c.id)}>
                  <td><div style={{ display: "flex", flexDirection: "column" }}><span className="strong">{c.nome}</span><span className="id-cell" style={{ fontSize: 11.5 }}>{c.id}</span></div></td>
                  <td>{c.ref}</td>
                  <td className="mono" style={{ fontSize: 12.5 }}>{c.tel}</td>
                  <td className="strong">{c.cantiere}</td>
                  <td className="muted" style={{ fontSize: 12.5, maxWidth: 220 }}>{c.indirizzo}</td>
                  <td className="num data">{CFmt.n(c.dist, 1)} km</td>
                  <td><Icon name="chevronR" size={16} className="muted" /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {selC && (
        <CDrawer sub={`Cliente · ${selC.id}`} title={selC.nome} onClose={() => setSel(null)}
          footer={<button className="btn" onClick={() => setSel(null)}>Chiudi</button>}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Contatti</div>
          <div className="deflist">
            <div className="defrow"><span className="dt">Referente</span><span className="dd">{selC.ref}</span></div>
            <div className="defrow"><span className="dt">Telefono</span><span className="dd mono">{selC.tel}</span></div>
          </div>
          <div className="eyebrow" style={{ margin: "18px 0 10px" }}>Cantiere</div>
          {/* map placeholder */}
          <div style={{ height: 140, borderRadius: 10, border: "1px solid var(--border)", background: "linear-gradient(135deg,var(--navy-50),var(--gray-100))", position: "relative", overflow: "hidden", marginBottom: 12 }}>
            <svg width="100%" height="100%" style={{ position: "absolute", inset: 0, opacity: 0.5 }}>
              <defs><pattern id="mapgrid" width="22" height="22" patternUnits="userSpaceOnUse"><path d="M22 0H0V22" fill="none" stroke="var(--navy-200)" strokeWidth="1" /></pattern></defs>
              <rect width="100%" height="100%" fill="url(#mapgrid)" />
              <path d="M0 90 Q120 60 260 100 T520 80" fill="none" stroke="var(--navy-300)" strokeWidth="3" />
            </svg>
            <div style={{ position: "absolute", left: 30, top: 50, color: "var(--navy-600)" }}><Icon name="factory" size={22} /><div style={{ fontSize: 10, fontWeight: 700 }}>Impianto</div></div>
            <div style={{ position: "absolute", right: 36, bottom: 28, color: "var(--jit-orange)", textAlign: "right" }}><Icon name="mapPin" size={24} /><div style={{ fontSize: 10, fontWeight: 700, color: "var(--orange-700)" }}>Cantiere</div></div>
          </div>
          <div className="deflist">
            <div className="defrow"><span className="dt">Cantiere</span><span className="dd">{selC.cantiere}</span></div>
            <div className="defrow"><span className="dt">Indirizzo</span><span className="dd" style={{ maxWidth: 280 }}>{selC.indirizzo}</span></div>
            <div className="defrow"><span className="dt">Distanza impianto</span><span className="dd data">{CFmt.n(selC.dist, 1)} km</span></div>
          </div>
          <div className="eyebrow" style={{ margin: "18px 0 8px" }}>Note operative</div>
          <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: 0, padding: 12, background: "var(--bg-sunken)", borderRadius: 8 }}>{selC.note}</p>
        </CDrawer>
      )}
    </div>
  );
}

window.Sezioni = Object.assign(window.Sezioni || {}, { SezRicette, SezOrdini, SezClienti });
