/* Maschera 1 — Riepilogo dati pazienti ricoverati */
const { useState: r1us, useMemo: r1um } = React;

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

  // KPI calculations
  const kpis = r1um(() => {
    const tot = rows.length;
    const totDays = rows.reduce((s, r) => s + r.ggDegenza, 0);
    const mediaDeg = tot ? totDays / tot : 0;
    const pesoMedio = tot ? rows.reduce((s, r) => s + r.drgPeso, 0) / tot : 0;
    const ripetuti = rows.filter(r => r.ripetuto).length;
    const ripetutiPct = tot ? (ripetuti / tot) * 100 : 0;
    const pazienti = new Set(rows.map(r => r.pazId)).size;
    const interventi = rows.filter(r => r.interventoEseguito).length;
    const etaMedia = tot ? rows.reduce((s, r) => s + r.eta, 0) / tot : 0;
    return { tot, mediaDeg, pesoMedio, ripetuti, ripetutiPct, pazienti, interventi, etaMedia, totDays };
  }, [rows]);

  // Per-dipartimento bars
  const perDip = r1um(() => {
    const m = {};
    rows.forEach(r => { m[r.dipartimento] = (m[r.dipartimento] || 0) + 1; });
    return D.dipartimenti
      .map(d => ({ id: d.id, label: d.nome, value: m[d.id] || 0 }))
      .filter(x => x.value > 0)
      .sort((a, b) => b.value - a.value);
  }, [rows]);

  // Per-regime donut
  const perRegime = r1um(() => {
    const m = {};
    rows.forEach(r => { m[r.regime] = (m[r.regime] || 0) + 1; });
    return D.regimi.map(reg => ({ id: reg.id, label: reg.nome, value: m[reg.id] || 0, color: reg.colore })).filter(x => x.value > 0);
  }, [rows]);

  // Monthly trend (12 mesi)
  const trend = r1um(() => {
    const months = [];
    const counts = { ORD: [], DH: [], DS: [], URG: [] };
    const start = new Date(filters.periodoTo);
    start.setDate(1);
    start.setMonth(start.getMonth() - 11);
    for (let i = 0; i < 12; i++) {
      const m = new Date(start); m.setMonth(start.getMonth() + i);
      months.push(D.fmtMonth(m));
      const mEnd = new Date(m); mEnd.setMonth(m.getMonth() + 1);
      const slice = rows.filter(r => r.dataRicovero >= m && r.dataRicovero < mEnd);
      counts.ORD.push(slice.filter(s => s.regime === "ORD").length);
      counts.DH.push(slice.filter(s => s.regime === "DH").length);
      counts.DS.push(slice.filter(s => s.regime === "DS").length);
      counts.URG.push(slice.filter(s => s.regime === "URG").length);
    }
    return { months, counts };
  }, [rows, filters]);

  // Heatmap: dipartimento (top 8) x giorno settimana
  const giorniSett = ["Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"];
  const heatmap = r1um(() => {
    const topDips = perDip.slice(0, 8);
    const matrix = topDips.map(dip => {
      const row = [0, 0, 0, 0, 0, 0, 0];
      rows.forEach(r => {
        if (r.dipartimento === dip.id) {
          let dow = r.dataRicovero.getDay();
          dow = (dow + 6) % 7; // Lun=0
          row[dow]++;
        }
      });
      return row;
    });
    return { rows: topDips.map(d => D.dipNome(d.id).replace(/^Chirurgia /, "Chir. ")), cols: giorniSett, matrix };
  }, [rows, perDip]);

  // Top DRG
  const topDrg = r1um(() => {
    const m = {};
    rows.forEach(r => {
      if (!m[r.drg]) m[r.drg] = { codice: r.drg, desc: r.drgDesc, peso: r.drgPeso, count: 0, gg: 0 };
      m[r.drg].count++;
      m[r.drg].gg += r.ggDegenza;
    });
    return Object.values(m).sort((a, b) => b.count - a.count).slice(0, 8);
  }, [rows]);

  // Age x Gender
  const ageGender = r1um(() => {
    const m = {};
    D.fasceEta.forEach(f => m[f.id] = { F: 0, M: 0 });
    rows.forEach(r => { m[D.fasciaPer(r.eta)][r.genere]++; });
    return D.fasceEta.map(f => ({ id: f.id, label: f.nome, F: m[f.id].F, M: m[f.id].M, total: m[f.id].F + m[f.id].M }));
  }, [rows]);

  // Provenienza
  const perProvenienza = r1um(() => {
    const m = {};
    rows.forEach(r => { m[r.provenienza] = (m[r.provenienza] || 0) + 1; });
    const palette = ["#008A3D", "#0E7C8C", "#7C3AED", "#C2410C", "#1E5BA8"];
    return D.provenienze.map((p, i) => ({ label: p, value: m[p] || 0, color: palette[i] })).filter(x => x.value > 0);
  }, [rows]);

  // Elettivo vs PS/Urgenza
  const tipoBreakdown = r1um(() => {
    const el = rows.filter(r => r.tipoIntervento === "EL").length;
    const ps = rows.filter(r => r.tipoIntervento === "PS").length;
    return [
      { label: "Elettivo", value: el, color: "#008A3D" },
      { label: "PS / Urgenza", value: ps, color: "#C8102E" }
    ];
  }, [rows]);

  return (
    <div>
      <div className="content__header">
        <div>
          <h1 className="page-title">Riepilogo dati pazienti ricoverati</h1>
          <div className="page-sub">
            <span className="status-dot" />Dati aggiornati al {D.fmtDate(new Date(2026, 4, 25))} · Periodo selezionato: <strong style={{ color: "var(--c-text-2)" }}>{D.fmtDate(filters.periodoFrom)} — {D.fmtDate(filters.periodoTo)}</strong>
          </div>
        </div>
        <div className="row">
          <Segmented value="anno" options={[{ value: "mese", label: "Mese" }, { value: "trim", label: "Trim." }, { value: "anno", label: "Anno" }]} onChange={() => {}} />
        </div>
      </div>

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

      {/* KPI row */}
      <div className="kpis" style={{ marginBottom: 12 }}>
        <KpiCard label="Ricoveri" value={D.fmtNum(kpis.tot)} delta={6.4} icon="bed" />
        <KpiCard label="Pazienti distinti" value={D.fmtNum(kpis.pazienti)} delta={4.1} icon="users-2" />
        <KpiCard label="Interventi eseguiti" value={D.fmtNum(kpis.interventi)} delta={5.2} icon="drill" />
        <KpiCard label="Età media" value={kpis.etaMedia.toFixed(1)} unit="anni" deltaLabel="sui ricoveri selezionati" icon="users-2" tone="accent" />
      </div>
      <div className="kpis" style={{ marginBottom: 16, gridTemplateColumns: "repeat(4, 1fr)" }}>
        <KpiCard label="Degenza media" value={kpis.mediaDeg.toFixed(1)} unit="gg" delta={-3.2} deltaLabel="vs anno precedente" icon="clock" />
        <KpiCard label="Peso medio DRG" value={kpis.pesoMedio.toFixed(2)} delta={2.1} icon="reports" />
        <KpiCard label="Giornate di degenza" value={D.fmtNum(kpis.totDays)} delta={1.8} />
        <KpiCard label="Ricoveri ripetuti" value={D.fmtNum(kpis.ripetuti)} deltaLabel={kpis.ripetutiPct.toFixed(1) + "% del totale"} icon="repeat" />
      </div>

      {/* Row: bar by dipartimento + donut regime */}
      <div className="grid grid-3-2" style={{ marginBottom: 12 }}>
        <Card title="Ricoveri per dipartimento" sub="Click su una barra per filtrare la vista">
          <BarChartH data={perDip} onClick={(d) => onGoToDettagli({ dipartimenti: [d.id] })} maxBars={10} />
        </Card>
        <Card title="Distribuzione per regime di ricovero">
          <DonutChart data={perRegime} colorKey="color" size={180} centerLabel="Ricoveri" centerValue={D.fmtNum(kpis.tot)} />
        </Card>
      </div>

      {/* Trend */}
      <Card title="Andamento mensile ricoveri per regime" sub="Ultimi 12 mesi" >
        <LineChart
          xLabels={trend.months}
          series={[
            { label: "Ordinario", data: trend.counts.ORD, color: "#008A3D" },
            { label: "Day Surgery", data: trend.counts.DS, color: "#7C3AED" },
            { label: "Day Hospital", data: trend.counts.DH, color: "#0E7C8C" },
            { label: "Urgenza", data: trend.counts.URG, color: "#C8102E" }
          ]}
        />
        <div className="legend" style={{ marginTop: 10, justifyContent: "center" }}>
          <span><span className="legend__dot" style={{ background: "#008A3D" }} />Ordinario</span>
          <span><span className="legend__dot" style={{ background: "#7C3AED" }} />Day Surgery</span>
          <span><span className="legend__dot" style={{ background: "#0E7C8C" }} />Day Hospital</span>
          <span><span className="legend__dot" style={{ background: "#C8102E" }} />Urgenza</span>
        </div>
      </Card>

      {/* Heatmap + age */}
      <div className="grid grid-2" style={{ marginTop: 12, marginBottom: 12 }}>
        <Card title="Ricoveri per dipartimento e giorno settimana" sub="Click su una cella per drill-down">
          <Heatmap rows={heatmap.rows} cols={heatmap.cols} matrix={heatmap.matrix} formatValue={v => v + " ricoveri"} onCellClick={(c) => {
            const dipId = D.dipartimenti.filter(d => D.dipNome(d.id).replace(/^Chirurgia /, "Chir. ") === c.row)[0]?.id;
            if (dipId) onGoToDettagli({ dipartimenti: [dipId] });
          }} />
        </Card>

        <Card title="Distribuzione per fascia di età e genere">
          <AgeGenderChart data={ageGender} />
        </Card>
      </div>

      {/* Provenienza + Elettivo/PS */}
      <div className="grid grid-2" style={{ marginBottom: 12 }}>
        <Card title="Provenienza pazienti" sub="Modalità di accesso al ricovero">
          <DonutChart data={perProvenienza} colorKey="color" size={170} centerLabel="Ricoveri" centerValue={D.fmtNum(kpis.tot)} />
        </Card>
        <Card title="Tipo intervento" sub="Elettivo vs PS / Urgenza">
          <div className="grid grid-2" style={{ alignItems: "center", gap: 24 }}>
            <DonutChart data={tipoBreakdown} colorKey="color" size={150} centerLabel="Ricoveri" centerValue={D.fmtNum(kpis.tot)} />
            <div className="col" style={{ gap: 14 }}>
              {tipoBreakdown.map(t => {
                const pct = kpis.tot ? (t.value / kpis.tot * 100) : 0;
                return (
                  <div key={t.label}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
                      <span style={{ fontSize: 12, fontWeight: 500, color: "var(--c-text-2)" }}>
                        <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 2, background: t.color, marginRight: 6 }} />
                        {t.label}
                      </span>
                      <span className="tnum" style={{ fontSize: 13, fontWeight: 700, color: "var(--c-text)" }}>{D.fmtNum(t.value)}</span>
                    </div>
                    <div style={{ height: 6, background: "#F1F5F9", borderRadius: 2, overflow: "hidden" }}>
                      <div style={{ height: "100%", width: pct + "%", background: t.color }} />
                    </div>
                    <div className="muted text-sm" style={{ marginTop: 4 }}>{pct.toFixed(1)}% del totale</div>
                  </div>
                );
              })}
            </div>
          </div>
        </Card>
      </div>

      {/* Top DRG table */}
      <Card title="Top 8 DRG per volume" sub="Ordinato per numero di ricoveri" action={
        <button className="btn btn--sm" onClick={() => onGoToDettagli({})}><Icon name="external" size={12} /> Vai ai dettagli</button>
      } flush>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 70 }}>DRG</th>
              <th>Descrizione</th>
              <th className="num" style={{ width: 80 }}>Peso</th>
              <th className="num" style={{ width: 80 }}>Ricoveri</th>
              <th className="num" style={{ width: 80 }}>Giornate</th>
              <th className="num" style={{ width: 90 }}>Deg. media</th>
              <th style={{ width: 100 }}>Trend 12m</th>
              <th style={{ width: 40 }}></th>
            </tr>
          </thead>
          <tbody>
            {topDrg.map((d, i) => {
              const sparkData = trend.months.map((_, mi) => {
                const start = new Date(filters.periodoTo); start.setDate(1); start.setMonth(start.getMonth() - 11 + mi);
                const end = new Date(start); end.setMonth(start.getMonth() + 1);
                return rows.filter(r => r.drg === d.codice && r.dataRicovero >= start && r.dataRicovero < end).length;
              });
              return (
                <tr key={d.codice} className="is-clickable" onClick={() => onGoToDettagli({ drg: [d.codice] })}>
                  <td><span className="mono" style={{ fontWeight: 600, color: "var(--c-primary)" }}>{d.codice}</span></td>
                  <td>{d.desc}</td>
                  <td className="num tnum">{d.peso.toFixed(2)}</td>
                  <td className="num tnum"><strong>{D.fmtNum(d.count)}</strong></td>
                  <td className="num tnum">{D.fmtNum(d.gg)}</td>
                  <td className="num tnum">{(d.gg / d.count).toFixed(1)} gg</td>
                  <td><Sparkline data={sparkData} /></td>
                  <td><Icon name="chevron-right" size={14} color="#94A3B8" /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function AgeGenderChart({ data }) {
  const max = Math.max(1, ...data.map(d => Math.max(d.F, d.M)));
  const rowH = 44;
  const labelW = 90;
  const barAreaW = "calc(50% - " + (labelW / 2) + "px)";
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8, padding: "4px 0" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 8px 4px", fontSize: 11, color: "var(--c-text-3)", fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase" }}>
        <span style={{ width: barAreaW, textAlign: "right" }}>Femmine</span>
        <span style={{ width: labelW, textAlign: "center" }}>Età</span>
        <span style={{ width: barAreaW, textAlign: "left" }}>Maschi</span>
      </div>
      {data.map(d => (
        <div key={d.id} style={{ display: "flex", alignItems: "center" }}>
          <div style={{ width: barAreaW, display: "flex", justifyContent: "flex-end", alignItems: "center", gap: 8 }}>
            <span className="tnum" style={{ fontSize: 11.5, color: "var(--c-text-3)" }}>{window.DATA.fmtNum(d.F)}</span>
            <div style={{ height: 14, width: (d.F / max) * 100 + "%", background: "#C8102E", borderRadius: 2, minWidth: 2 }} />
          </div>
          <div style={{ width: labelW, textAlign: "center", fontSize: 11.5, fontWeight: 600, color: "var(--c-text-2)" }}>{d.id}</div>
          <div style={{ width: barAreaW, display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{ height: 14, width: (d.M / max) * 100 + "%", background: "#008A3D", borderRadius: 2, minWidth: 2 }} />
            <span className="tnum" style={{ fontSize: 11.5, color: "var(--c-text-3)" }}>{window.DATA.fmtNum(d.M)}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Mask1Riepilogo });
