/* global React */
(function () {
  const { useEffect: useEffectR } = React;
  const {
    TopBar: TopBarR, useScaleSession: useSession,
    formatDate, formatDateTime, ageFrom, interpret,
    navigate: navR, computeScore
  } = window.RT;

  /* ── ScoreBar ─────────────────────────────────────────────────────────── */
  function ScoreBar({ scale, score, total }) {
    const interp = interpret(scale, score);
    const max = total || 100;
    const pct = score != null ? Math.min(100, Math.max(0, (score / max) * 100)) : 0;

    const bands = scale.interpretation.map(b => ({
      from: Math.min(100, (b.from / max) * 100),
      to: Math.min(100, (b.to >= 999 ? 100 : (b.to / max) * 100)),
      color: b.color,
    }));

    const tickCount = max <= 10 ? max : (max <= 30 ? 3 : 4);
    const ticks = Array.from({ length: tickCount - 1 }, (_, i) =>
      Math.round(max / tickCount * (i + 1))
    );

    return (
      <div style={{ position: "relative", marginTop: 10 }}>
        <div style={{ position: "relative", height: 22, borderRadius: 4, overflow: "hidden", background: "#F1F3F7", border: "1px solid #D9DEE8" }}>
          {bands.map((b, i) => (
            <div key={i} style={{
              position: "absolute", top: 0, bottom: 0,
              left: `${b.from}%`,
              width: `${Math.max(0.5, b.to - b.from)}%`,
              background: b.color, opacity: 0.85,
            }}></div>
          ))}
          {score != null && (
            <div style={{
              position: "absolute", top: -4, bottom: -4,
              left: `calc(${pct}% - 2px)`, width: 4,
              background: "#0F1B33", borderRadius: 2,
              boxShadow: "0 0 0 2px #fff",
            }}></div>
          )}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontSize: 8, color: "#5B6678", fontFamily: "ui-monospace, monospace" }}>
          <span>0</span>
          {ticks.map(t => <span key={t}>{t}</span>)}
          <span>{max}</span>
        </div>
        <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>
          {scale.interpretation.map((b, i) => {
            const active = interp && interp.label === b.label;
            return (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 5,
                padding: "3px 8px", borderRadius: 3,
                background: active ? b.color : "transparent",
                color: active ? "#fff" : "#5B6678",
                fontSize: 9, fontWeight: active ? 600 : 400,
                border: active ? "none" : "1px solid #E7EAF1",
              }}>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: active ? "#fff" : b.color }}></span>
                <span>{b.from === b.to ? `${b.from}` : `${b.from}–${b.to >= 999 ? "∞" : b.to}`}: {b.label}</span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  /* ── ItemTable ────────────────────────────────────────────────────────── */
  function ItemTable({ rows, scoreTotal, scoreLabel }) {
    return (
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 9, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--rt-navy-700)", fontWeight: 600, marginBottom: 6 }}>
          Dettaglio item
        </div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 9.5 }}>
          <thead>
            <tr>
              <th style={thStyle("#", true)}>#</th>
              <th style={thStyle("Item")}>Item</th>
              <th style={thStyle("Risposta")}>Risposta</th>
              <th style={{ ...thStyle("Punti"), textAlign: "right", width: 50 }}>Punti</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}>
                <td style={tdMono}>{String(i + 1).padStart(2, "0")}{r.section ? ` · ${r.section}` : ""}</td>
                <td style={{ ...tdBase, fontWeight: 500, color: "var(--rt-navy-900)" }}>{r.title}</td>
                <td style={{ ...tdBase, color: "#1F2937" }}>{r.label}</td>
                <td style={{ ...tdBase, textAlign: "right", fontFamily: "ui-monospace, monospace", fontWeight: 600, color: "var(--rt-navy-900)" }}>{r.value}</td>
              </tr>
            ))}
            <tr>
              <td colSpan="3" style={{ padding: "8px 10px", textAlign: "right", fontWeight: 600, color: "var(--rt-navy-900)", textTransform: "uppercase", letterSpacing: ".06em", fontSize: 9 }}>
                {scoreLabel || "Totale"}
              </td>
              <td style={{ padding: "8px 10px", textAlign: "right", fontFamily: "ui-monospace, monospace", fontWeight: 700, color: "var(--rt-navy-900)", fontSize: 12 }}>
                {scoreTotal}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }

  const tdBase = { padding: "5px 10px", borderBottom: "1px solid #E7EAF1" };
  const tdMono = { ...tdBase, fontFamily: "ui-monospace, monospace", color: "#5B6678", fontSize: 8, width: 40 };
  function thStyle(_, small) {
    return {
      textAlign: "left", padding: "6px 10px",
      borderBottom: "1.5px solid var(--rt-navy-900)",
      fontSize: 8, textTransform: "uppercase",
      letterSpacing: ".06em", color: "#5B6678", fontWeight: 600,
      ...(small ? { width: 22 } : {})
    };
  }

  /* ── buildItemRows ────────────────────────────────────────────────────── */
  function buildItemRows(scale, session) {
    const { form, itemsKey } = scale;
    const IMAP = {
      WOMAC: "RT_WOMAC_ITEMS", LEFS: "RT_LEFS_ITEMS", BERG: "RT_BERG_ITEMS",
      FGA: "RT_FGA_ITEMS", SCIM: "RT_SCIM_ITEMS", SARA: "RT_SARA_ITEMS",
      CPAX: "RT_CPAX_ITEMS", PFIT: "RT_PFIT_ITEMS", MRCSS: "RT_MRCSS_ITEMS",
      QUICKDASH: "RT_QUICKDASH_ITEMS"
    };

    let items = null;
    if (form === "barthel") items = window.RT_BARTHEL_ITEMS;
    else if (form === "mrc") items = window.RT_MRC_ITEMS;
    else if (form === "radioItems" || form === "quickdash") items = window[IMAP[itemsKey]];
    else if (form === "tinetti") items = [
      ...(window.RT_TINETTI_BALANCE_ITEMS || []),
      ...(window.RT_TINETTI_GAIT_ITEMS || [])
    ];

    if (!items) return null;
    return items.map(it => {
      const v = session.answers[it.id];
      const opt = v != null ? it.options.find(o => o.value === v) : null;
      return {
        title: it.title,
        section: it.section || null,
        label: opt ? opt.label : "—",
        value: v != null ? v : "—"
      };
    });
  }

  /* ── hashStr ──────────────────────────────────────────────────────────── */
  function hashStr(s) {
    let h = 0;
    for (let i = 0; i < s.length; i++) { h = ((h << 5) - h) + s.charCodeAt(i); h |= 0; }
    return h;
  }

  /* ── Report ───────────────────────────────────────────────────────────── */
  function Report({ scaleId }) {
    const scale = window.RT_SCALES.find(s => s.id === scaleId);
    const [session] = useSession(scaleId);

    if (!scale) {
      return <div style={{ padding: 64, textAlign: "center" }}>Scala non trovata. <a href="#/scales">Torna alle scale</a></div>;
    }

    const { score, total, unit } = computeScore(scale, session);
    const max = total || 100;
    const interp = interpret(scale, score);
    const ageY = ageFrom(session.patient.dob);

    // Score label for display (e.g. "35 s" vs "35/100")
    const scoreStr = score != null
      ? (unit ? `${score} ${unit}` : `${score}`)
      : "—";
    const maxStr = unit ? "" : `/${max}`;

    // Item rows for radio-type scales
    const itemRows = buildItemRows(scale, session);

    // Score label for table footer
    let scoreLabel = "Totale";
    if (scale.form === "quickdash") scoreLabel = "Score QuickDASH";

    const onPrint = () => window.print();
    const onBack = () => navR(`/scale/${scaleId}`);

    return (
      <>
        {/* Action bar */}
        <div className="rt-no-print" style={{
          background: "var(--rt-navy-900)", color: "#fff",
          padding: "12px 0", position: "sticky", top: 0, zIndex: 30
        }}>
          <div className="rt-container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
            <button onClick={onBack} className="rt-btn"
              style={{ background: "transparent", color: "#fff", borderColor: "rgba(255,255,255,.2)" }}>
              ← Modifica valutazione
            </button>
            <div style={{ fontSize: 13, color: "rgba(255,255,255,.7)" }}>
              Anteprima report · {scale.name}
            </div>
            <button onClick={onPrint} className="rt-btn primary"
              style={{ background: "#fff", color: "var(--rt-navy-900)", borderColor: "#fff" }}>
              Stampa / Salva PDF →
            </button>
          </div>
        </div>

        {/* Report A4 */}
        <div className="rt-report" id="rt-report-page">

          {/* Header band */}
          <div style={{
            background: "var(--rt-navy-900)", color: "#fff", padding: "14px 18px",
            margin: "-16mm -18mm 14px -18mm",
            display: "flex", alignItems: "center", justifyContent: "space-between",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 24, height: 24, background: "#fff", color: "var(--rt-navy-900)", borderRadius: 3, display: "grid", placeItems: "center", fontFamily: "var(--rt-serif)", fontWeight: 700, fontSize: 13 }}>R</div>
              <div>
                <div style={{ fontFamily: "var(--rt-serif)", fontSize: 14, fontWeight: 600, lineHeight: 1.1 }}>Rehab Tools</div>
                <div style={{ fontSize: 9, opacity: 0.7, marginTop: 2 }}>Report di valutazione clinica</div>
              </div>
            </div>
            <div style={{ textAlign: "right", fontSize: 9, opacity: 0.85, fontFamily: "ui-monospace, monospace", lineHeight: 1.4 }}>
              <div>Documento N. {(Math.abs(hashStr(scaleId + (session.patient.lastName || "") + (session.administeredAt || ""))) % 999999).toString().padStart(6, "0")}</div>
              <div>Generato: {formatDateTime(new Date())}</div>
            </div>
          </div>

          {/* Title */}
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 9, color: "var(--rt-navy-700)", textTransform: "uppercase", letterSpacing: ".1em", fontWeight: 600 }}>{scale.category} · {scale.domain}</div>
            <h1 style={{ fontSize: 22, marginTop: 4, color: "var(--rt-navy-900)" }}>{scale.name}</h1>
            <div style={{ fontSize: 10, color: "#5B6678", fontStyle: "italic", marginTop: 2 }}>{scale.nameEn} — {scale.reference}</div>
          </div>

          {/* Patient + clinician */}
          <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 0, border: "1px solid #D9DEE8", borderRadius: 4, marginBottom: 14, overflow: "hidden" }}>
            <div style={{ padding: "10px 14px", borderRight: "1px solid #E7EAF1", background: "#F8F9FC" }}>
              <div style={{ fontSize: 8, textTransform: "uppercase", letterSpacing: ".08em", color: "#5B6678", fontWeight: 600, marginBottom: 4 }}>Paziente</div>
              <div style={{ fontFamily: "var(--rt-serif)", fontSize: 14, fontWeight: 600, color: "var(--rt-navy-900)" }}>
                {(session.patient.lastName || "—").toUpperCase()}, {session.patient.firstName || "—"}
              </div>
              <div style={{ display: "flex", gap: 16, marginTop: 6, fontSize: 10, color: "#1F2937" }}>
                <div><span style={{ color: "#5B6678" }}>Data nascita:</span> <strong>{formatDate(session.patient.dob)}</strong></div>
                {ageY != null && <div><span style={{ color: "#5B6678" }}>Età:</span> <strong>{ageY} anni</strong></div>}
              </div>
            </div>
            <div style={{ padding: "10px 14px" }}>
              <div style={{ fontSize: 8, textTransform: "uppercase", letterSpacing: ".08em", color: "#5B6678", fontWeight: 600, marginBottom: 4 }}>Somministrazione</div>
              <div style={{ fontSize: 10, color: "#1F2937", lineHeight: 1.6 }}>
                <div><span style={{ color: "#5B6678" }}>Professionista:</span> <strong>{session.clinician || "—"}</strong></div>
                <div><span style={{ color: "#5B6678" }}>Data e ora:</span> <strong>{formatDateTime(session.administeredAt)}</strong></div>
              </div>
            </div>
          </div>

          {/* Score panel */}
          <div style={{ background: "var(--rt-navy-50)", border: "1px solid var(--rt-navy-100)", borderRadius: 4, padding: "14px 16px", marginBottom: 14 }}>
            <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 18, alignItems: "center" }}>
              <div style={{ textAlign: "center" }}>
                <div style={{ fontFamily: "var(--rt-mono)", fontSize: 8, color: "#5B6678", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 600 }}>Punteggio</div>
                <div style={{ fontFamily: "var(--rt-serif)", fontSize: 44, fontWeight: 600, color: "var(--rt-navy-900)", lineHeight: 1, marginTop: 2 }}>
                  {scoreStr}<span style={{ fontSize: 18, color: "#5B6678", fontWeight: 400 }}>{maxStr}</span>
                </div>
              </div>
              <div>
                <ScoreBar scale={scale} score={score} total={max} />
              </div>
              <div style={{ minWidth: 140, textAlign: "right" }}>
                <div style={{ fontSize: 8, color: "#5B6678", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 600 }}>Interpretazione</div>
                {interp ? (
                  <div style={{ marginTop: 4, padding: "6px 10px", background: "#fff", border: `2px solid ${interp.color}`, borderRadius: 3, display: "inline-block" }}>
                    <div style={{ fontFamily: "var(--rt-serif)", fontSize: 13, fontWeight: 600, color: interp.color, lineHeight: 1.2 }}>{interp.label}</div>
                  </div>
                ) : <div style={{ marginTop: 4, fontSize: 10, color: "#5B6678" }}>—</div>}
              </div>
            </div>
          </div>

          {/* Item detail — radio-type scales */}
          {itemRows && (
            <ItemTable
              rows={itemRows}
              scoreTotal={scale.form === "quickdash" ? `${score ?? "—"}/100` : `${score ?? "—"}/${max}`}
              scoreLabel={scoreLabel}
            />
          )}

          {/* EQ-5D detail */}
          {scale.form === "eq5d" && (() => {
            const dims = [
              { id: "eq5d_1", title: "Mobilità" }, { id: "eq5d_2", title: "Cura di sé" },
              { id: "eq5d_3", title: "Attività abituali" }, { id: "eq5d_4", title: "Dolore / fastidio" },
              { id: "eq5d_5", title: "Ansia / depressione" },
            ];
            const dimLabels = ["", "Nessun problema", "Problemi lievi", "Problemi moderati", "Problemi gravi", "Problemi estremi"];
            return (
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 9, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--rt-navy-700)", fontWeight: 600, marginBottom: 6 }}>
                  Profilo EQ-5D (5 dimensioni)
                </div>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 9.5 }}>
                  <thead>
                    <tr>
                      <th style={thStyle()}>Dimensione</th>
                      <th style={thStyle()}>Livello</th>
                      <th style={{ ...thStyle(), textAlign: "right", width: 40 }}>Cod.</th>
                    </tr>
                  </thead>
                  <tbody>
                    {dims.map((d, i) => {
                      const v = session.answers[d.id];
                      return (
                        <tr key={d.id}>
                          <td style={{ ...tdBase, fontWeight: 500, color: "var(--rt-navy-900)" }}>{d.title}</td>
                          <td style={{ ...tdBase, color: "#1F2937" }}>{v != null ? dimLabels[v] : "—"}</td>
                          <td style={{ ...tdBase, textAlign: "right", fontFamily: "ui-monospace, monospace", fontWeight: 600, color: "var(--rt-navy-900)" }}>{v ?? "—"}</td>
                        </tr>
                      );
                    })}
                    <tr>
                      <td colSpan="2" style={{ ...tdBase, textAlign: "right", fontWeight: 600, fontSize: 9, color: "var(--rt-navy-900)", textTransform: "uppercase", letterSpacing: ".06em" }}>
                        EQ-VAS (stato di salute)
                      </td>
                      <td style={{ ...tdBase, textAlign: "right", fontFamily: "ui-monospace, monospace", fontWeight: 700, fontSize: 12, color: "var(--rt-navy-900)" }}>
                        {session.answers.__eq5dvas ?? "—"}/100
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            );
          })()}

          {/* PSFS detail */}
          {scale.form === "psfs" && (() => {
            const acts = session.psfs || [];
            return (
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 9, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--rt-navy-700)", fontWeight: 600, marginBottom: 6 }}>
                  Attività identificate dal paziente
                </div>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 9.5 }}>
                  <thead>
                    <tr>
                      <th style={thStyle("#", true)}>#</th>
                      <th style={thStyle()}>Attività</th>
                      <th style={{ ...thStyle(), textAlign: "right", width: 60 }}>Punteggio</th>
                    </tr>
                  </thead>
                  <tbody>
                    {acts.map((a, i) => (
                      <tr key={i}>
                        <td style={tdMono}>{String(i + 1).padStart(2, "0")}</td>
                        <td style={{ ...tdBase, color: "#1F2937" }}>{a.name || "(non specificata)"}</td>
                        <td style={{ ...tdBase, textAlign: "right", fontFamily: "ui-monospace, monospace", fontWeight: 600, color: "var(--rt-navy-900)" }}>
                          {a.score != null ? `${a.score}/10` : "—"}
                        </td>
                      </tr>
                    ))}
                    <tr>
                      <td colSpan="2" style={{ padding: "8px 10px", textAlign: "right", fontWeight: 600, fontSize: 9, color: "var(--rt-navy-900)", textTransform: "uppercase", letterSpacing: ".06em" }}>
                        Media
                      </td>
                      <td style={{ padding: "8px 10px", textAlign: "right", fontFamily: "ui-monospace, monospace", fontWeight: 700, fontSize: 12, color: "var(--rt-navy-900)" }}>
                        {score != null ? `${score}/10` : "—"}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            );
          })()}

          {/* Ordinal detail */}
          {scale.form === "ordinal" && (() => {
            const v = session.answers.__ordinal;
            const opt = v != null ? scale.singleOptions.find(o => o.value === v) : null;
            return (
              <div style={{ marginBottom: 14, fontSize: 10, color: "#1F2937", lineHeight: 1.55, padding: "10px 14px", background: "#F8F9FC", borderLeft: "3px solid var(--rt-navy-700)", borderRadius: 2 }}>
                {opt
                  ? <>Livello selezionato: <strong>{opt.label}</strong></>
                  : <>Nessun livello selezionato.</>
                }
              </div>
            );
          })()}

          {/* Numeric detail */}
          {scale.form === "numeric" && (() => {
            return (
              <div style={{ marginBottom: 14, fontSize: 10, color: "#1F2937", lineHeight: 1.55, padding: "10px 14px", background: "#F8F9FC", borderLeft: "3px solid var(--rt-navy-700)", borderRadius: 2 }}>
                Il paziente ha ottenuto un risultato di{" "}
                <strong>{score != null ? `${score} ${unit || ""}` : "—"}</strong>{" "}
                {interp ? <>corrispondente alla categoria <strong>{interp.label.toLowerCase()}</strong>.</> : "."}
                {scale.lowerIsBetter && " Per questa scala, valori più bassi indicano prestazione migliore."}
              </div>
            );
          })()}

          {/* Slider / VAS detail */}
          {(scale.form === "slider" || scale.form === "vas") && (() => {
            return (
              <div style={{ marginBottom: 14, fontSize: 10, color: "#1F2937", lineHeight: 1.55, padding: "10px 14px", background: "#F8F9FC", borderLeft: "3px solid var(--rt-navy-700)", borderRadius: 2 }}>
                Il paziente ha indicato un livello pari a <strong>{score ?? "—"}</strong> su una scala da 0 a 10
                {interp ? <>, corrispondente alla categoria <strong>{interp.label.toLowerCase()}</strong>.</> : "."}
              </div>
            );
          })()}

          {/* Notes */}
          {session.notes && session.notes.trim() && (
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 9, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--rt-navy-700)", fontWeight: 600, marginBottom: 4 }}>Note cliniche</div>
              <div style={{ fontSize: 10, color: "#1F2937", lineHeight: 1.55, padding: "10px 14px", border: "1px solid #E7EAF1", borderRadius: 3, background: "#fff", whiteSpace: "pre-wrap" }}>
                {session.notes}
              </div>
            </div>
          )}

          {/* Signature */}
          <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
            <div>
              <div style={{ borderBottom: "1px solid #1F2937", height: 32 }}></div>
              <div style={{ fontSize: 8, textTransform: "uppercase", letterSpacing: ".08em", color: "#5B6678", fontWeight: 600, marginTop: 4 }}>Firma del professionista</div>
              <div style={{ fontSize: 10, color: "var(--rt-navy-900)", marginTop: 2, fontWeight: 500 }}>{session.clinician || "—"}</div>
            </div>
            <div>
              <div style={{ borderBottom: "1px solid #1F2937", height: 32 }}></div>
              <div style={{ fontSize: 8, textTransform: "uppercase", letterSpacing: ".08em", color: "#5B6678", fontWeight: 600, marginTop: 4 }}>Timbro / struttura</div>
            </div>
          </div>

          {/* Footer */}
          <div style={{ position: "absolute", bottom: 8, left: "18mm", right: "18mm", paddingTop: 8, borderTop: "1px solid #E7EAF1", fontSize: 8, color: "#5B6678", display: "flex", justifyContent: "space-between" }}>
            <span>Rehab Tools · Report clinico generato digitalmente</span>
            <span>Pagina 1 di 1</span>
          </div>

        </div>
      </>
    );
  }

  window.RT.Report = Report;
})();
