/* Maschera 3 — Dettagli con drill-down via pannello laterale */
const { useState: r3us, useMemo: r3um } = React;

function Mask3Dettagli({ filters, onEditFilters }) {
  const D = window.DATA;
  const rows = r3um(() => D.applyFilters(filters), [filters]);

  // Pivot dimension
  const [pivotRow, setPivotRow] = r3us("dipartimento"); // dipartimento | drg | regime | fascia
  const [drillStack, setDrillStack] = r3us([]); // [{type, value, label}]

  function openDrill(node) {
    setDrillStack([node]);
  }
  function pushDrill(node) {
    setDrillStack(s => [...s, node]);
  }
  function popDrillTo(idx) {
    setDrillStack(s => s.slice(0, idx + 1));
  }
  function closeDrill() { setDrillStack([]); }

  // ---------- Aggregations for pivot ----------
  const pivot = r3um(() => {
    function aggregateBy(dim, getKey, getLabel) {
      const m = {};
      rows.forEach(r => {
        const k = getKey(r);
        if (!m[k]) m[k] = { key: k, label: getLabel(r, k), ricoveri: 0, pazienti: new Set(), gg: 0, ripetuti: 0, pesoSum: 0, pesoMedioSum: 0, urgenze: 0, dim };
        const e = m[k];
        e.ricoveri++;
        e.pazienti.add(r.pazId);
        e.gg += r.ggDegenza;
        if (r.ripetuto) e.ripetuti++;
        e.pesoSum += r.drgPeso;
        if (r.regime === "URG") e.urgenze++;
      });
      return Object.values(m).map(e => ({
        ...e,
        pazienti: e.pazienti.size,
        degMedia: e.ricoveri ? e.gg / e.ricoveri : 0,
        pesoMedio: e.ricoveri ? e.pesoSum / e.ricoveri : 0
      })).sort((a, b) => b.ricoveri - a.ricoveri);
    }
    if (pivotRow === "dipartimento") return aggregateBy("dipartimento", r => r.dipartimento, (r, k) => D.dipNome(k));
    if (pivotRow === "drg") return aggregateBy("drg", r => r.drg, r => "DRG " + r.drg + " — " + r.drgDesc);
    if (pivotRow === "regime") return aggregateBy("regime", r => r.regime, (r, k) => D.regimeNome(k));
    if (pivotRow === "fascia") return aggregateBy("fascia", r => D.fasciaPer(r.eta), (r, k) => "Età " + k);
    return [];
  }, [rows, pivotRow]);

  const totali = r3um(() => {
    const ric = rows.length;
    const paz = new Set(rows.map(r => r.pazId)).size;
    const gg = rows.reduce((s, r) => s + r.ggDegenza, 0);
    const peso = ric ? rows.reduce((s, r) => s + r.drgPeso, 0) / ric : 0;
    const ripetuti = rows.filter(r => r.ripetuto).length;
    const interventi = rows.filter(r => r.interventoEseguito).length;
    return { ric, paz, gg, peso, degMedia: ric ? gg / ric : 0, ripetuti, interventi };
  }, [rows]);

  // Ricoveri / Dimissioni per giorno della settimana
  const giorniSett = ["Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"];
  const weekday = r3um(() => {
    const ric = [0, 0, 0, 0, 0, 0, 0];
    const dim = [0, 0, 0, 0, 0, 0, 0];
    rows.forEach(r => {
      let dR = r.dataRicovero.getDay(); dR = (dR + 6) % 7;
      let dD = r.dataDimissione.getDay(); dD = (dD + 6) % 7;
      ric[dR]++;
      dim[dD]++;
    });
    return { ric, dim };
  }, [rows]);

  return (
    <div>
      <div className="content__header">
        <div>
          <h1 className="page-title">Maschera dettagli & drill-down</h1>
          <div className="page-sub">Tabelle pivot con gerarchia <strong style={{ color: "var(--c-text-2)" }}>Dipartimento → DRG → Paziente</strong>. Click su una riga per il drill di livello successivo.</div>
        </div>
        <div className="row">
          <button className="btn"><Icon name="download" size={12} /> Esporta XLSX</button>
        </div>
      </div>

      <FilterBar filters={filters} onEdit={onEditFilters} />

      {/* KPI strip */}
      <div className="kpis" style={{ marginBottom: 12, gridTemplateColumns: "repeat(6, 1fr)" }}>
        <KpiCard label="Pazienti" value={D.fmtNum(totali.paz)} icon="users-2" />
        <KpiCard label="Ricoveri" value={D.fmtNum(totali.ric)} icon="bed" />
        <KpiCard label="Interventi" value={D.fmtNum(totali.interventi)} icon="drill" />
        <KpiCard label="Deg. media" value={totali.degMedia.toFixed(1)} unit="gg" icon="clock" />
        <KpiCard label="Peso medio DRG" value={totali.peso.toFixed(2)} icon="reports" />
        <KpiCard label="Ricoveri ripetuti" value={D.fmtNum(totali.ripetuti)} icon="repeat" />
      </div>

      {/* Weekday */}
      <div className="grid grid-2" style={{ marginBottom: 12 }}>
        <Card title="Ricoveri per giorno della settimana" sub="Distribuzione degli ingressi">
          <WeekdayBars labels={giorniSett} values={weekday.ric} color="#008A3D" />
        </Card>
        <Card title="Dimissioni per giorno della settimana" sub="Distribuzione delle uscite">
          <WeekdayBars labels={giorniSett} values={weekday.dim} color="#0E7C8C" />
        </Card>
      </div>

      {/* Pivot controls */}
      <Card title="Tabella pivot" sub="Aggregazione per dimensione" action={
        <div className="row">
          <span className="filter-bar__label">Raggruppa per</span>
          <Segmented
            value={pivotRow}
            onChange={setPivotRow}
            options={[
              { value: "dipartimento", label: "Dipartimento" },
              { value: "drg", label: "DRG" },
              { value: "regime", label: "Regime" },
              { value: "fascia", label: "Fascia età" }
            ]}
          />
        </div>
      } flush>
        <table className="table table__pivot">
          <thead>
            <tr>
              <th style={{ width: 28 }}></th>
              <th>{pivotRow === "dipartimento" ? "Dipartimento" : pivotRow === "drg" ? "DRG" : pivotRow === "regime" ? "Regime" : "Fascia età"}</th>
              <th className="num">Ricoveri</th>
              <th className="num">Pazienti</th>
              <th className="num">Giornate</th>
              <th className="num">Deg. media</th>
              <th className="num">Peso medio DRG</th>
              <th className="num">Ripetuti</th>
              <th className="num">% Urgenze</th>
              <th style={{ width: 130 }}>Distribuzione</th>
              <th style={{ width: 36 }}></th>
            </tr>
          </thead>
          <tbody>
            {pivot.map(p => {
              const maxRic = Math.max(...pivot.map(x => x.ricoveri));
              const urgPct = p.ricoveri ? (p.urgenze / p.ricoveri) * 100 : 0;
              return (
                <tr key={p.key} className="is-clickable" onClick={() => openDrill({ type: pivotRow, value: p.key, label: p.label })}>
                  <td><Icon name="drill" size={14} color="#94A3B8" /></td>
                  <td><strong style={{ color: "var(--c-text)" }}>{p.label}</strong></td>
                  <td className="num tnum"><strong>{D.fmtNum(p.ricoveri)}</strong></td>
                  <td className="num tnum">{D.fmtNum(p.pazienti)}</td>
                  <td className="num tnum">{D.fmtNum(p.gg)}</td>
                  <td className="num tnum">{p.degMedia.toFixed(1)} gg</td>
                  <td className="num tnum">{p.pesoMedio.toFixed(2)}</td>
                  <td className="num tnum">{p.ripetuti > 0 && <Pill tone="warn">{p.ripetuti}</Pill>}</td>
                  <td className="num tnum">{urgPct.toFixed(1)}%</td>
                  <td>
                    <div style={{ height: 6, background: "#F1F5F9", borderRadius: 2, overflow: "hidden" }}>
                      <div style={{ height: "100%", width: (p.ricoveri / maxRic) * 100 + "%", background: "var(--c-primary)" }} />
                    </div>
                  </td>
                  <td><Icon name="chevron-right" size={14} color="#64748B" /></td>
                </tr>
              );
            })}
            <tr className="is-total">
              <td></td>
              <td>Totale</td>
              <td className="num tnum">{D.fmtNum(totali.ric)}</td>
              <td className="num tnum">{D.fmtNum(totali.paz)}</td>
              <td className="num tnum">{D.fmtNum(totali.gg)}</td>
              <td className="num tnum">{totali.degMedia.toFixed(1)} gg</td>
              <td className="num tnum">{totali.peso.toFixed(2)}</td>
              <td className="num tnum">{D.fmtNum(totali.ripetuti)}</td>
              <td className="num tnum"></td>
              <td></td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </Card>

      {/* Drill panel */}
      {drillStack.length > 0 && (
        <DrillPanel
          stack={drillStack}
          rows={rows}
          onClose={closeDrill}
          onPush={pushDrill}
          onBackTo={popDrillTo}
        />
      )}
    </div>
  );
}

/* ---------- Drill Panel ---------- */
function DrillPanel({ stack, rows, onClose, onPush, onBackTo }) {
  const D = window.DATA;

  // Filter rows down through the stack
  const drilled = r3um(() => {
    return rows.filter(r => stack.every(s => {
      if (s.type === "dipartimento") return r.dipartimento === s.value;
      if (s.type === "drg") return r.drg === s.value;
      if (s.type === "regime") return r.regime === s.value;
      if (s.type === "fascia") return D.fasciaPer(r.eta) === s.value;
      if (s.type === "paziente") return r.pazId === s.value;
      return true;
    }));
  }, [stack, rows]);

  const top = stack[stack.length - 1];

  return (
    <>
      <div className="drill-overlay" onClick={onClose} />
      <aside className="drill-panel" role="dialog" aria-label="Drill-down dettagli">
        <div className="drill-panel__head">
          <div style={{ flex: 1 }}>
            <div className="drill-panel__crumbs">
              <button onClick={() => onClose()}>Pivot</button>
              {stack.map((s, i) => (
                <React.Fragment key={i}>
                  <span style={{ margin: "0 6px" }}><Icon name="chevron-right" size={11} color="#94A3B8" /></span>
                  {i < stack.length - 1
                    ? <button onClick={() => onBackTo(i)}>{shortLabel(s.label)}</button>
                    : <strong>{shortLabel(s.label)}</strong>}
                </React.Fragment>
              ))}
            </div>
            <div className="drill-panel__title">{top.label}</div>
          </div>
          <button className="topbar__action"><Icon name="download" size={12} /></button>
          <button className="drill-panel__close" onClick={onClose}><Icon name="close" size={16} /></button>
        </div>

        <div className="drill-panel__body">
          <DrillContent stack={stack} drilled={drilled} onPush={onPush} />
        </div>
      </aside>
    </>
  );
}

function shortLabel(s) {
  if (s.length > 38) return s.slice(0, 36) + "…";
  return s;
}

function DrillContent({ stack, drilled, onPush }) {
  const D = window.DATA;
  const top = stack[stack.length - 1];

  // Mini KPI strip
  const ric = drilled.length;
  const paz = new Set(drilled.map(r => r.pazId)).size;
  const gg = drilled.reduce((s, r) => s + r.ggDegenza, 0);
  const degMedia = ric ? gg / ric : 0;
  const ripetuti = drilled.filter(r => r.ripetuto).length;
  const pesoMedio = ric ? drilled.reduce((s, r) => s + r.drgPeso, 0) / ric : 0;

  return (
    <div className="col" style={{ gap: 12 }}>
      <div className="kpis" style={{ gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
        <MiniKpi label="Ricoveri" value={D.fmtNum(ric)} />
        <MiniKpi label="Pazienti" value={D.fmtNum(paz)} />
        <MiniKpi label="Deg. media" value={degMedia.toFixed(1) + " gg"} />
        <MiniKpi label="Peso medio" value={pesoMedio.toFixed(2)} />
        <MiniKpi label="Giornate" value={D.fmtNum(gg)} />
        <MiniKpi label="Ripetuti" value={D.fmtNum(ripetuti)} />
      </div>

      {/* Next-level content */}
      {top.type === "dipartimento" && <NextLevelDRG drilled={drilled} onPush={onPush} />}
      {top.type === "drg" && stack.length === 1 && <NextLevelByDip drilled={drilled} onPush={onPush} />}
      {top.type === "regime" && <NextLevelDRG drilled={drilled} onPush={onPush} />}
      {top.type === "fascia" && <NextLevelDRG drilled={drilled} onPush={onPush} />}
      {(top.type === "drg" && stack.length >= 2) && <PatientList drilled={drilled} onPush={onPush} />}
      {top.type === "paziente" && <PatientDetail pazId={top.value} drilled={drilled} />}
    </div>
  );
}

function MiniKpi({ label, value }) {
  return (
    <div style={{ background: "var(--c-surface)", border: "1px solid var(--c-border)", borderRadius: 8, padding: "10px 12px" }}>
      <div style={{ fontSize: 10.5, color: "var(--c-text-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 700, color: "var(--c-text)", marginTop: 2, fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em" }}>{value}</div>
    </div>
  );
}

function NextLevelDRG({ drilled, onPush }) {
  const D = window.DATA;
  const byDrg = {};
  drilled.forEach(r => {
    if (!byDrg[r.drg]) byDrg[r.drg] = { codice: r.drg, desc: r.drgDesc, peso: r.drgPeso, ricoveri: 0, gg: 0 };
    byDrg[r.drg].ricoveri++;
    byDrg[r.drg].gg += r.ggDegenza;
  });
  const items = Object.values(byDrg).sort((a, b) => b.ricoveri - a.ricoveri);

  // Regime breakdown
  const byReg = {};
  drilled.forEach(r => byReg[r.regime] = (byReg[r.regime] || 0) + 1);
  const donutData = D.regimi.map(r => ({ id: r.id, label: r.nome, value: byReg[r.id] || 0, color: r.colore })).filter(x => x.value > 0);

  return (
    <>
      <Card title="Distribuzione per regime" tight>
        <div style={{ padding: 8 }}>
          <DonutChart data={donutData} colorKey="color" size={140} centerLabel="Ricoveri" centerValue={D.fmtNum(drilled.length)} />
        </div>
      </Card>

      <Card title="Suddivisione per DRG" sub="Click per scendere al livello paziente" flush>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 56 }}>DRG</th>
              <th>Descrizione</th>
              <th className="num">Ric.</th>
              <th className="num">Gg</th>
              <th className="num">Peso</th>
              <th style={{ width: 28 }}></th>
            </tr>
          </thead>
          <tbody>
            {items.map(d => (
              <tr key={d.codice} className="is-clickable" onClick={() => onPush({ type: "drg", value: d.codice, label: "DRG " + d.codice + " — " + d.desc })}>
                <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600 }}>{d.codice}</span></td>
                <td style={{ fontSize: 12 }}>{d.desc}</td>
                <td className="num tnum"><strong>{D.fmtNum(d.ricoveri)}</strong></td>
                <td className="num tnum">{D.fmtNum(d.gg)}</td>
                <td className="num tnum">{d.peso.toFixed(2)}</td>
                <td><Icon name="chevron-right" size={12} color="#94A3B8" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
}

function NextLevelByDip({ drilled, onPush }) {
  const D = window.DATA;
  const m = {};
  drilled.forEach(r => {
    if (!m[r.dipartimento]) m[r.dipartimento] = { dip: r.dipartimento, ricoveri: 0, gg: 0 };
    m[r.dipartimento].ricoveri++;
    m[r.dipartimento].gg += r.ggDegenza;
  });
  const items = Object.values(m).sort((a, b) => b.ricoveri - a.ricoveri);
  return (
    <Card title="Suddivisione per dipartimento" flush>
      <table className="table">
        <thead><tr><th>Dipartimento</th><th className="num">Ricoveri</th><th className="num">Giornate</th><th style={{ width: 28 }}></th></tr></thead>
        <tbody>
          {items.map(it => (
            <tr key={it.dip} className="is-clickable" onClick={() => onPush({ type: "dipartimento", value: it.dip, label: D.dipNome(it.dip) })}>
              <td><strong>{D.dipNome(it.dip)}</strong></td>
              <td className="num tnum">{D.fmtNum(it.ricoveri)}</td>
              <td className="num tnum">{D.fmtNum(it.gg)}</td>
              <td><Icon name="chevron-right" size={12} color="#94A3B8" /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function PatientList({ drilled, onPush }) {
  const D = window.DATA;
  // Group by patient
  const byPaz = {};
  drilled.forEach(r => {
    if (!byPaz[r.pazId]) byPaz[r.pazId] = { pazId: r.pazId, ricoveri: [], gg: 0 };
    byPaz[r.pazId].ricoveri.push(r);
    byPaz[r.pazId].gg += r.ggDegenza;
  });
  const items = Object.values(byPaz).sort((a, b) => b.ricoveri.length - a.ricoveri.length).slice(0, 80);

  return (
    <Card title={"Pazienti (" + D.fmtNum(Object.keys(byPaz).length) + ")"} sub="Mostrati i primi 80. Click per il dettaglio anonimizzato." flush>
      <table className="table">
        <thead>
          <tr>
            <th>ID Paziente</th>
            <th>Genere · Età</th>
            <th>Diagnosi principale</th>
            <th>Procedura</th>
            <th className="num">Ricoveri</th>
            <th className="num">Giornate</th>
            <th style={{ width: 28 }}></th>
          </tr>
        </thead>
        <tbody>
          {items.map(p => {
            const last = p.ricoveri[0];
            return (
              <tr key={p.pazId} className="is-clickable" onClick={() => onPush({ type: "paziente", value: p.pazId, label: "Paziente " + p.pazId })}>
                <td><span className="mono" style={{ color: "var(--c-primary)" }}>{p.pazId}</span></td>
                <td><span className="pill pill--neutral">{last.genere === "F" ? "♀" : "♂"} {last.eta}a</span></td>
                <td style={{ fontSize: 12 }}>{last.diagnosi}</td>
                <td style={{ fontSize: 12 }}>{last.procedura}</td>
                <td className="num tnum">
                  <strong>{p.ricoveri.length}</strong>
                  {p.ricoveri.length > 1 && <Pill tone="warn">ripetuti</Pill>}
                </td>
                <td className="num tnum">{p.gg}</td>
                <td><Icon name="chevron-right" size={12} color="#94A3B8" /></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </Card>
  );
}

function PatientDetail({ pazId, drilled }) {
  const D = window.DATA;
  // Show all ricoveri for this patient in raw data (broader scope: across all)
  const all = D.ricoveri.filter(r => r.pazId === pazId).sort((a, b) => b.dataRicovero - a.dataRicovero);
  const last = all[0];
  if (!last) return null;

  return (
    <>
      <Card title="Profilo paziente (anonimizzato)" tight>
        <div className="grid grid-3" style={{ padding: "4px 8px 8px", gap: 12 }}>
          <ProfRow label="ID" value={<span className="mono">{pazId}</span>} />
          <ProfRow label="Genere" value={last.genere === "F" ? "Femmina" : "Maschio"} />
          <ProfRow label="Età attuale" value={last.eta + " anni"} />
          <ProfRow label="Peso medio" value={last.peso + " kg"} />
          <ProfRow label="Provenienza" value={last.provenienza} />
          <ProfRow label="N° ricoveri (12m)" value={all.length} />
        </div>
      </Card>

      <Card title="Storia ricoveri" sub={all.length + " episodi"} flush>
        <table className="table">
          <thead>
            <tr>
              <th>Data ricovero</th>
              <th>Dipartimento</th>
              <th>Regime</th>
              <th>DRG</th>
              <th className="num">Gg</th>
            </tr>
          </thead>
          <tbody>
            {all.map(r => (
              <tr key={r.id}>
                <td className="tnum">{D.fmtDate(r.dataRicovero)}</td>
                <td style={{ fontSize: 12 }}>{D.dipNome(r.dipartimento)}</td>
                <td>
                  <span className="pill" style={{
                    background: D.regimeColore(r.regime) + "1A",
                    color: D.regimeColore(r.regime),
                    borderColor: D.regimeColore(r.regime) + "33"
                  }}>{D.regimeNome(r.regime)}</span>
                </td>
                <td><span className="mono" style={{ color: "var(--c-primary)", fontWeight: 600 }}>{r.drg}</span></td>
                <td className="num tnum">{r.ggDegenza}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
}

function ProfRow({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, color: "var(--c-text-3)", textTransform: "uppercase", letterSpacing: "0.04em", fontWeight: 600, marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 13, color: "var(--c-text)", fontWeight: 500 }}>{value}</div>
    </div>
  );
}

function WeekdayBars({ labels, values, color }) {
  const max = Math.max(1, ...values);
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 10, height: 160, padding: "8px 4px 4px" }}>
      {labels.map((l, i) => {
        const h = (values[i] / max) * 130;
        return (
          <div key={l} style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: 1, gap: 6 }}>
            <div className="tnum" style={{ fontSize: 11, fontWeight: 600, color: "var(--c-text-2)" }}>{window.DATA.fmtNum(values[i])}</div>
            <div style={{ width: "100%", maxWidth: 42, height: h, background: color, borderRadius: "3px 3px 0 0", minHeight: 2 }} title={values[i] + " — " + l} />
            <div style={{ fontSize: 11, color: "var(--c-text-3)", fontWeight: 500 }}>{l}</div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { Mask3Dettagli });
