/* global React */
(function () {
  const { useState: useStateC, useEffect: useEffectC } = React;
  const {
    TopBar: TopBarF, Footer: FooterF, navigate: navF,
    useScaleSession, ageFrom, interpret, computeScore
  } = window.RT;

  /* ── Shared helpers ──────────────────────────────────────────────────── */
  function InfoTip({ children }) {
    return (
      <span className="rt-tip-wrap">
        <span className="rt-tip">?</span>
        <span className="rt-tip-content">{children}</span>
      </span>
    );
  }

  function useShowErrors() {
    const [show, setShow] = useStateC(false);
    useEffectC(() => {
      const h = () => setShow(true);
      window.addEventListener("rt:show-errors", h);
      return () => window.removeEventListener("rt:show-errors", h);
    }, []);
    return show;
  }

  /* ── MetaPanel ───────────────────────────────────────────────────────── */
  function MetaPanel({ session, setSession, scale, score, total, completion, unit, onExport, canExport }) {
    const interp = interpret(scale, score);
    const scoreDisplay = score == null ? "—" : score;
    const totalDisplay = unit ? unit : (total != null ? `su ${total}` : "");

    return (
      <aside style={{ position: "sticky", top: 76, alignSelf: "start", display: "flex", flexDirection: "column", gap: 16 }}>

        {/* Score */}
        <div className="rt-card" style={{ padding: 24 }}>
          <div className="rt-eyebrow" style={{ marginBottom: 16 }}>Punteggio in tempo reale</div>
          <div className="rt-gauge">
            <div className="rt-gauge-num">{scoreDisplay}</div>
            <div className="rt-gauge-of">{totalDisplay}</div>
          </div>
          {interp && (
            <div style={{ marginTop: 16, padding: "12px 14px", borderRadius: 6, background: "var(--rt-navy-50)", borderLeft: `3px solid ${interp.color}` }}>
              <div style={{ fontSize: 11, color: "var(--rt-muted)", textTransform: "uppercase", letterSpacing: ".06em", fontWeight: 500 }}>Interpretazione</div>
              <div style={{ fontFamily: "var(--rt-serif)", fontSize: 17, color: "var(--rt-navy-900)", marginTop: 2 }}>{interp.label}</div>
            </div>
          )}
          <div style={{ marginTop: 16 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--rt-muted)", marginBottom: 6 }}>
              <span>Completamento</span>
              <span className="rt-mono">{Math.round(completion * 100)}%</span>
            </div>
            <div className="rt-progress"><div style={{ width: `${completion * 100}%` }}></div></div>
          </div>
        </div>

        {/* Patient */}
        <div className="rt-card" style={{ padding: 20 }}>
          <div className="rt-eyebrow" style={{ marginBottom: 14 }}>Paziente</div>
          <div style={{ display: "grid", gap: 12 }}>
            <div className="rt-field">
              <label>Nome*</label>
              <input className="rt-input" value={session.patient.firstName}
                onChange={e => setSession(s => ({ ...s, patient: { ...s.patient, firstName: e.target.value } }))} />
            </div>
            <div className="rt-field">
              <label>Cognome*</label>
              <input className="rt-input" value={session.patient.lastName}
                onChange={e => setSession(s => ({ ...s, patient: { ...s.patient, lastName: e.target.value } }))} />
            </div>
            <div className="rt-field">
              <label>Data di nascita*</label>
              <input type="date" className="rt-input" value={session.patient.dob}
                onChange={e => setSession(s => ({ ...s, patient: { ...s.patient, dob: e.target.value } }))} />
              {session.patient.dob && (
                <div style={{ fontSize: 12, color: "var(--rt-muted)", marginTop: 4 }}>{ageFrom(session.patient.dob)} anni</div>
              )}
            </div>
          </div>
        </div>

        {/* Clinician */}
        <div className="rt-card" style={{ padding: 20 }}>
          <div className="rt-eyebrow" style={{ marginBottom: 14 }}>Somministrazione</div>
          <div style={{ display: "grid", gap: 12 }}>
            <div className="rt-field">
              <label>Professionista</label>
              <input className="rt-input" placeholder="Es. Dr. Mario Rossi" value={session.clinician}
                onChange={e => setSession(s => ({ ...s, clinician: e.target.value }))} />
            </div>
            <div className="rt-field">
              <label>Data e ora</label>
              <input type="datetime-local" className="rt-input" value={session.administeredAt}
                onChange={e => setSession(s => ({ ...s, administeredAt: e.target.value }))} />
            </div>
            <div className="rt-field">
              <label>Note cliniche</label>
              <textarea className="rt-textarea" rows="3"
                placeholder="Osservazioni, contesto, ausili utilizzati…"
                value={session.notes}
                onChange={e => setSession(s => ({ ...s, notes: e.target.value }))} />
            </div>
          </div>
        </div>

        <button className="rt-btn primary lg" disabled={!canExport} onClick={onExport}
          style={{ justifyContent: "center", opacity: canExport ? 1 : 0.5, cursor: canExport ? "pointer" : "not-allowed" }}>
          Genera report PDF →
        </button>
        {!canExport && (
          <div style={{ fontSize: 12, color: "var(--rt-muted)", textAlign: "center", marginTop: -8 }}>
            Compila tutti i campi obbligatori per esportare.
          </div>
        )}
      </aside>
    );
  }

  /* ── RadioItem ───────────────────────────────────────────────────────── */
  function RadioItem({ item, idx, session, setSession, showErrors }) {
    const selected = session.answers[item.id];
    const missing = selected == null;
    return (
      <div className={`rt-item-row ${missing && showErrors ? "required-missing" : ""}`}>
        <div className="num">{String(idx + 1).padStart(2, "0")}</div>
        <div>
          <div className="item-title">
            {item.title}
            {item.tip && <InfoTip>{item.tip}</InfoTip>}
          </div>
          {item.help && <div className="item-help">{item.help}</div>}
          <div className="rt-choices">
            {item.options.map(opt => (
              <label key={opt.value} className={`rt-choice ${selected === opt.value ? "selected" : ""}`}>
                <input type="radio" name={item.id} checked={selected === opt.value}
                  onChange={() => setSession(s => ({ ...s, answers: { ...s.answers, [item.id]: opt.value } }))} />
                <span className="label-text">{opt.label}</span>
                <span className="points">{opt.value} pt</span>
              </label>
            ))}
          </div>
        </div>
        <div className="item-score">
          {selected != null ? <span style={{ color: "var(--rt-navy-900)", fontWeight: 600 }}>+{selected}</span> : "—"}
        </div>
      </div>
    );
  }

  /* ── BarthelForm ─────────────────────────────────────────────────────── */
  function BarthelForm({ session, setSession, showErrors }) {
    const items = window.RT_BARTHEL_ITEMS;
    return (
      <div className="rt-card" style={{ overflow: "hidden" }}>
        {items.map((item, i) => (
          <RadioItem key={item.id} item={item} idx={i} session={session} setSession={setSession} showErrors={showErrors} />
        ))}
      </div>
    );
  }

  /* ── VasForm ─────────────────────────────────────────────────────────── */
  function VasForm({ session, setSession }) {
    const v = session.vasValue;
    const stops = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    return (
      <div className="rt-card" style={{ padding: 32 }}>
        <div style={{ marginBottom: 24 }}>
          <div className="item-title" style={{ fontWeight: 500, fontSize: 16, color: "var(--rt-navy-900)" }}>
            Indica il livello di dolore percepito in questo momento
            <InfoTip>Chiedere al paziente di indicare un valore tra 0 (nessun dolore) e 10 (dolore massimo immaginabile). Si può somministrare con righello, scala numerica o scala visuo-analogica grafica.</InfoTip>
          </div>
          <div style={{ fontSize: 13, color: "var(--rt-muted)", marginTop: 4 }}>Spostare il cursore o cliccare sulla scala numerica.</div>
        </div>
        <div style={{ position: "relative", height: 80, margin: "32px 0 8px" }}>
          <div style={{
            position: "absolute", top: 32, left: 0, right: 0, height: 16, borderRadius: 8,
            background: "linear-gradient(90deg, #15803D 0%, #0E7C6B 20%, #B7791F 50%, #C97E16 75%, #B42318 100%)",
          }}></div>
          {v != null && (
            <div style={{
              position: "absolute", top: 16, left: `${(v / 10) * 100}%`, transform: "translateX(-50%)",
              width: 4, height: 48, background: "var(--rt-navy-900)", borderRadius: 2,
              boxShadow: "0 0 0 4px rgba(255,255,255,1), 0 0 0 5px var(--rt-navy-900)", transition: "left .15s",
            }}></div>
          )}
          {v != null && (
            <div style={{
              position: "absolute", top: -4, left: `${(v / 10) * 100}%`, transform: "translateX(-50%)",
              background: "var(--rt-navy-900)", color: "#fff", padding: "4px 10px", borderRadius: 4,
              fontFamily: "var(--rt-serif)", fontSize: 18, fontWeight: 600, transition: "left .15s",
            }}>{v}</div>
          )}
        </div>
        <input type="range" min="0" max="10" step="1" value={v ?? 0}
          onChange={e => setSession(s => ({ ...s, vasValue: Number(e.target.value) }))}
          style={{ width: "100%", accentColor: "var(--rt-navy-800)" }} />
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 16, gap: 4 }}>
          {stops.map(n => (
            <button key={n} onClick={() => setSession(s => ({ ...s, vasValue: n }))}
              style={{
                flex: 1, height: 40,
                border: `1px solid ${v === n ? "var(--rt-navy-800)" : "var(--rt-line)"}`,
                background: v === n ? "var(--rt-navy-800)" : "#fff",
                color: v === n ? "#fff" : "var(--rt-text)",
                fontFamily: "var(--rt-mono)", fontSize: 14, fontWeight: 500,
                borderRadius: 4, cursor: "pointer", transition: "all .12s",
              }}>{n}</button>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12, fontSize: 11, color: "var(--rt-muted)", textTransform: "uppercase", letterSpacing: ".04em" }}>
          <span>Nessun dolore</span><span>Dolore moderato</span><span>Peggior dolore immaginabile</span>
        </div>
      </div>
    );
  }

  /* ── GenericRadioForm ────────────────────────────────────────────────── */
  function GenericRadioForm({ items, session, setSession, showErrors }) {
    const hasSections = items.some(it => it.section);
    if (!hasSections) {
      return (
        <div className="rt-card" style={{ overflow: "hidden" }}>
          {items.map((item, i) => (
            <RadioItem key={item.id} item={item} idx={i} session={session} setSession={setSession} showErrors={showErrors} />
          ))}
        </div>
      );
    }
    // Group by section
    const sections = [];
    const map = {};
    for (const item of items) {
      const sec = item.section || "—";
      if (!map[sec]) { map[sec] = []; sections.push(sec); }
      map[sec].push(item);
    }
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        {sections.map(sec => {
          const secItems = map[sec];
          const secScore = secItems.reduce((s, it) => s + (session.answers[it.id] ?? 0), 0);
          const secMax = secItems.reduce((s, it) => s + Math.max(...it.options.map(o => o.value)), 0);
          return (
            <div key={sec}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: "var(--rt-muted)", textTransform: "uppercase", letterSpacing: ".08em" }}>{sec}</div>
                <div style={{ fontSize: 13, fontFamily: "var(--rt-mono)", color: "var(--rt-navy-900)" }}>{secScore}/{secMax}</div>
              </div>
              <div className="rt-card" style={{ overflow: "hidden" }}>
                {secItems.map((item, i) => (
                  <RadioItem key={item.id} item={item} idx={i} session={session} setSession={setSession} showErrors={showErrors} />
                ))}
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  /* ── TinettiForm ─────────────────────────────────────────────────────── */
  function TinettiForm({ session, setSession, showErrors }) {
    const bItems = window.RT_TINETTI_BALANCE_ITEMS;
    const gItems = window.RT_TINETTI_GAIT_ITEMS;
    const bScore = bItems.reduce((s, it) => s + (session.answers[it.id] ?? 0), 0);
    const gScore = gItems.reduce((s, it) => s + (session.answers[it.id] ?? 0), 0);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: "var(--rt-muted)", textTransform: "uppercase", letterSpacing: ".08em" }}>Sezione A — Equilibrio</div>
            <div style={{ fontSize: 13, fontFamily: "var(--rt-mono)", color: "var(--rt-navy-900)" }}>{bScore}/16</div>
          </div>
          <div className="rt-card" style={{ overflow: "hidden" }}>
            {bItems.map((item, i) => (
              <RadioItem key={item.id} item={item} idx={i} session={session} setSession={setSession} showErrors={showErrors} />
            ))}
          </div>
        </div>
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: "var(--rt-muted)", textTransform: "uppercase", letterSpacing: ".08em" }}>Sezione B — Deambulazione</div>
            <div style={{ fontSize: 13, fontFamily: "var(--rt-mono)", color: "var(--rt-navy-900)" }}>{gScore}/12</div>
          </div>
          <div className="rt-card" style={{ overflow: "hidden" }}>
            {gItems.map((item, i) => (
              <RadioItem key={item.id} item={item} idx={i} session={session} setSession={setSession} showErrors={showErrors} />
            ))}
          </div>
        </div>
      </div>
    );
  }

  /* ── OrdinalForm ─────────────────────────────────────────────────────── */
  function OrdinalForm({ scale, session, setSession }) {
    const selected = session.answers.__ordinal;
    return (
      <div className="rt-card" style={{ padding: 24 }}>
        <div style={{ fontSize: 13, color: "var(--rt-muted)", marginBottom: 16, lineHeight: 1.55 }}>
          Selezionare il livello che descrive meglio la situazione del paziente.
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {scale.singleOptions.map(opt => (
            <label key={opt.value}
              className={`rt-choice ${selected === opt.value ? "selected" : ""}`}
              style={{ padding: "12px 16px", alignItems: "flex-start" }}>
              <input type="radio" name="ordinal" checked={selected === opt.value}
                onChange={() => setSession(s => ({ ...s, answers: { ...s.answers, __ordinal: opt.value } }))} />
              <span className="label-text" style={{ lineHeight: 1.4 }}>{opt.label}</span>
            </label>
          ))}
        </div>
      </div>
    );
  }

  /* ── NumericForm ─────────────────────────────────────────────────────── */
  function NumericForm({ scale, session, setSession }) {
    return (
      <div className="rt-card" style={{ padding: 32 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <input
            type="number" min="0" step={scale.id === "tug" ? "0.1" : "1"}
            className="rt-input"
            style={{ fontSize: 28, textAlign: "center", width: 160, fontFamily: "var(--rt-mono)", fontWeight: 600 }}
            value={session.numericValue ?? ""}
            onChange={e => setSession(s => ({
              ...s,
              numericValue: e.target.value === "" ? null : Number(e.target.value)
            }))}
            placeholder="—"
          />
          <span style={{ fontSize: 20, color: "var(--rt-muted)", fontWeight: 400 }}>{scale.unit}</span>
        </div>
        {scale.lowerIsBetter && (
          <div style={{ marginTop: 16, fontSize: 12, color: "var(--rt-muted)" }}>
            ↓ Valori più bassi indicano prestazione migliore
          </div>
        )}
        {!scale.lowerIsBetter && (
          <div style={{ marginTop: 16, fontSize: 12, color: "var(--rt-muted)" }}>
            ↑ Valori più alti indicano prestazione migliore
          </div>
        )}
      </div>
    );
  }

  /* ── SliderForm ──────────────────────────────────────────────────────── */
  function SliderForm({ scale, session, setSession }) {
    const v = session.sliderValue;
    const stops = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const labs = scale.sliderLabels || { 0: "Nessuna", 5: "Moderata", 10: "Massima" };
    const labKeys = Object.keys(labs);
    return (
      <div className="rt-card" style={{ padding: 32 }}>
        <div style={{ marginBottom: 24 }}>
          <div className="item-title" style={{ fontWeight: 500, fontSize: 16, color: "var(--rt-navy-900)" }}>
            Indica il livello percepito in questo momento
          </div>
          <div style={{ fontSize: 13, color: "var(--rt-muted)", marginTop: 4 }}>
            Spostare il cursore o cliccare sulla scala numerica.
          </div>
        </div>
        <div style={{ position: "relative", height: 80, margin: "32px 0 8px" }}>
          <div style={{
            position: "absolute", top: 32, left: 0, right: 0, height: 16, borderRadius: 8,
            background: "linear-gradient(90deg, #15803D 0%, #0E7C6B 20%, #B7791F 50%, #C97E16 75%, #B42318 100%)",
          }}></div>
          {v != null && (
            <div style={{
              position: "absolute", top: 16, left: `${v * 10}%`, transform: "translateX(-50%)",
              width: 4, height: 48, background: "var(--rt-navy-900)", borderRadius: 2,
              boxShadow: "0 0 0 4px rgba(255,255,255,1), 0 0 0 5px var(--rt-navy-900)", transition: "left .15s",
            }}></div>
          )}
          {v != null && (
            <div style={{
              position: "absolute", top: -4, left: `${v * 10}%`, transform: "translateX(-50%)",
              background: "var(--rt-navy-900)", color: "#fff", padding: "4px 10px", borderRadius: 4,
              fontFamily: "var(--rt-serif)", fontSize: 18, fontWeight: 600, transition: "left .15s",
            }}>{v}</div>
          )}
        </div>
        <input type="range" min="0" max="10" step="1" value={v ?? 0}
          onChange={e => setSession(s => ({ ...s, sliderValue: Number(e.target.value) }))}
          style={{ width: "100%", accentColor: "var(--rt-navy-800)" }} />
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 16, gap: 4 }}>
          {stops.map(n => (
            <button key={n} onClick={() => setSession(s => ({ ...s, sliderValue: n }))}
              style={{
                flex: 1, height: 40,
                border: `1px solid ${v === n ? "var(--rt-navy-800)" : "var(--rt-line)"}`,
                background: v === n ? "var(--rt-navy-800)" : "#fff",
                color: v === n ? "#fff" : "var(--rt-text)",
                fontFamily: "var(--rt-mono)", fontSize: 14, fontWeight: 500,
                borderRadius: 4, cursor: "pointer", transition: "all .12s",
              }}>{n}</button>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12, fontSize: 11, color: "var(--rt-muted)", textTransform: "uppercase", letterSpacing: ".04em" }}>
          {labKeys.map(k => <span key={k}>{labs[k]}</span>)}
        </div>
      </div>
    );
  }

  /* ── Eq5dForm ────────────────────────────────────────────────────────── */
  function Eq5dForm({ session, setSession }) {
    const dims = [
      { id: "eq5d_1", title: "Mobilità", help: "Capacità di camminare / spostarsi" },
      { id: "eq5d_2", title: "Cura di sé", help: "Capacità di lavarsi, vestirsi" },
      { id: "eq5d_3", title: "Attività abituali", help: "Lavoro, studio, lavori domestici, attività familiari o ricreative" },
      { id: "eq5d_4", title: "Dolore / fastidio", help: "Presenza di dolore o fastidio fisico" },
      { id: "eq5d_5", title: "Ansia / depressione", help: "Stato emotivo, livello di ansia o depressione" },
    ];
    const dimOptions = [
      { value: 1, label: "Nessun problema" },
      { value: 2, label: "Problemi lievi" },
      { value: 3, label: "Problemi moderati" },
      { value: 4, label: "Problemi gravi" },
      { value: 5, label: "Impossibile / problemi estremi" },
    ];
    const vas = session.answers.__eq5dvas;
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        <div className="rt-card" style={{ overflow: "hidden" }}>
          {dims.map((dim, i) => {
            const selected = session.answers[dim.id];
            return (
              <div key={dim.id} className="rt-item-row">
                <div className="num">{String(i + 1).padStart(2, "0")}</div>
                <div>
                  <div className="item-title">{dim.title}</div>
                  <div className="item-help">{dim.help}</div>
                  <div className="rt-choices">
                    {dimOptions.map(opt => (
                      <label key={opt.value} className={`rt-choice ${selected === opt.value ? "selected" : ""}`}>
                        <input type="radio" name={dim.id} checked={selected === opt.value}
                          onChange={() => setSession(s => ({ ...s, answers: { ...s.answers, [dim.id]: opt.value } }))} />
                        <span className="label-text">{opt.label}</span>
                        <span className="points">{opt.value}</span>
                      </label>
                    ))}
                  </div>
                </div>
                <div className="item-score">
                  {selected != null ? <span style={{ color: "var(--rt-navy-900)", fontWeight: 600 }}>{selected}</span> : "—"}
                </div>
              </div>
            );
          })}
        </div>

        {/* EQ-VAS 0–100 */}
        <div className="rt-card" style={{ padding: 28 }}>
          <div className="item-title" style={{ marginBottom: 6 }}>Stato di salute oggi (EQ-VAS)</div>
          <div style={{ fontSize: 13, color: "var(--rt-muted)", marginBottom: 20 }}>
            Indica lo stato di salute odierno su scala 0–100 (0 = peggior stato immaginabile, 100 = miglior stato immaginabile).
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ fontSize: 11, color: "var(--rt-muted)", minWidth: 16, textAlign: "center" }}>0</span>
            <input type="range" min="0" max="100" step="1" value={vas ?? 50}
              onChange={e => setSession(s => ({ ...s, answers: { ...s.answers, __eq5dvas: Number(e.target.value) } }))}
              style={{ flex: 1, accentColor: "var(--rt-navy-800)" }} />
            <span style={{ fontSize: 11, color: "var(--rt-muted)", minWidth: 24 }}>100</span>
            <div style={{
              minWidth: 64, height: 44, background: "var(--rt-navy-800)", color: "#fff",
              display: "flex", alignItems: "center", justifyContent: "center",
              borderRadius: 8, fontFamily: "var(--rt-mono)", fontSize: 22, fontWeight: 600
            }}>{vas ?? "—"}</div>
          </div>
        </div>
      </div>
    );
  }

  /* ── PsfsForm ────────────────────────────────────────────────────────── */
  function PsfsForm({ session, setSession }) {
    const activities = session.psfs || [
      { name: "", score: null }, { name: "", score: null }, { name: "", score: null }
    ];
    const stops = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    const update = (i, field, val) => {
      setSession(s => {
        const acts = [...(s.psfs || [{ name: "", score: null }, { name: "", score: null }, { name: "", score: null }])];
        acts[i] = { ...acts[i], [field]: val };
        return { ...s, psfs: acts };
      });
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ padding: "12px 16px", background: "#fff", border: "1px solid var(--rt-line)", borderRadius: "var(--rt-r-lg)", fontSize: 13, color: "var(--rt-muted)", lineHeight: 1.55 }}>
          Il paziente identifica 3 attività che trova difficoltose e le valuta da 0 (incapace) a 10 (stesso livello di prima del problema).
        </div>
        {activities.map((act, i) => (
          <div key={i} className="rt-card" style={{ padding: 20 }}>
            <div className="rt-eyebrow" style={{ marginBottom: 12 }}>Attività {i + 1}</div>
            <div className="rt-field" style={{ marginBottom: 16 }}>
              <label>Descrizione dell'attività</label>
              <input className="rt-input"
                placeholder="Es. Salire le scale, portare la spesa, correre…"
                value={act.name}
                onChange={e => update(i, "name", e.target.value)} />
            </div>
            <div style={{ fontSize: 12, color: "var(--rt-muted)", marginBottom: 10 }}>
              Livello di difficoltà attuale (0 = incapace, 10 = nessuna difficoltà)
            </div>
            <div style={{ display: "flex", gap: 4 }}>
              {stops.map(n => (
                <button key={n} onClick={() => update(i, "score", n)}
                  style={{
                    flex: 1, height: 36,
                    border: `1px solid ${act.score === n ? "var(--rt-navy-800)" : "var(--rt-line)"}`,
                    background: act.score === n ? "var(--rt-navy-800)" : "#fff",
                    color: act.score === n ? "#fff" : "var(--rt-text)",
                    fontFamily: "var(--rt-mono)", fontSize: 13, fontWeight: 500,
                    borderRadius: 4, cursor: "pointer", transition: "all .12s",
                  }}>{n}</button>
              ))}
            </div>
            {act.score != null && (
              <div style={{ marginTop: 8, fontSize: 12, color: "var(--rt-muted)" }}>
                Punteggio selezionato: <strong style={{ color: "var(--rt-navy-900)" }}>{act.score}/10</strong>
              </div>
            )}
          </div>
        ))}
      </div>
    );
  }

  /* ── ScaleCompile ────────────────────────────────────────────────────── */
  const ITEMS_KEY_MAP = {
    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"
  };

  function ScaleCompile({ scaleId }) {
    const scale = window.RT_SCALES.find(s => s.id === scaleId);
    const [session, setSession] = useScaleSession(scaleId);
    const showErrors = useShowErrors();

    if (!scale) {
      return (
        <>
          <TopBarF active="scales" now="" />
          <main className="rt-container" style={{ padding: 64, flex: 1 }}>
            <h1>Scala non trovata</h1>
            <a href="#/scales" className="rt-btn" style={{ marginTop: 16 }}>← Torna alle scale</a>
          </main>
          <FooterF />
        </>
      );
    }

    const { score, total, completion, unit } = computeScore(scale, session);
    const patientOk = session.patient.firstName.trim() && session.patient.lastName.trim() && session.patient.dob;
    const itemsOk = completion === 1;
    const canExport = patientOk && itemsOk;

    const onExport = () => {
      if (!canExport) { window.dispatchEvent(new Event("rt:show-errors")); return; }
      navF(`/scale/${scaleId}/report`);
    };

    // Choose the right form
    let formEl = null;
    const { form, itemsKey } = scale;

    if (form === "barthel") {
      formEl = <BarthelForm session={session} setSession={setSession} showErrors={showErrors} />;
    } else if (form === "vas") {
      formEl = <VasForm session={session} setSession={setSession} />;
    } else if (form === "radioItems" || form === "mrc") {
      const items = form === "mrc"
        ? window.RT_MRC_ITEMS
        : window[ITEMS_KEY_MAP[itemsKey]];
      formEl = <GenericRadioForm items={items} session={session} setSession={setSession} showErrors={showErrors} />;
    } else if (form === "quickdash") {
      formEl = <GenericRadioForm items={window.RT_QUICKDASH_ITEMS} session={session} setSession={setSession} showErrors={showErrors} />;
    } else if (form === "tinetti") {
      formEl = <TinettiForm session={session} setSession={setSession} showErrors={showErrors} />;
    } else if (form === "ordinal") {
      formEl = <OrdinalForm scale={scale} session={session} setSession={setSession} />;
    } else if (form === "numeric") {
      formEl = <NumericForm scale={scale} session={session} setSession={setSession} />;
    } else if (form === "slider") {
      formEl = <SliderForm scale={scale} session={session} setSession={setSession} />;
    } else if (form === "eq5d") {
      formEl = <Eq5dForm session={session} setSession={setSession} />;
    } else if (form === "psfs") {
      formEl = <PsfsForm session={session} setSession={setSession} />;
    } else {
      formEl = <div style={{ padding: 24, color: "var(--rt-muted)" }}>Form non ancora implementato per questo tipo di scala.</div>;
    }

    const tagColor = scale.category === "Dolore" ? "amber" : "teal";

    const now = new Date().toLocaleString("it-IT", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" });

    return (
      <>
        <TopBarF active="scales" now={now} />
        <main style={{ flex: 1, padding: "32px 0 64px" }}>
          <div className="rt-container">
            {/* Breadcrumb */}
            <div style={{ marginBottom: 24, display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--rt-muted)" }}>
              <a href="#/scales" style={{ color: "var(--rt-muted)" }}>Scale</a>
              <span>/</span>
              <span style={{ color: "var(--rt-navy-900)" }}>{scale.short}</span>
            </div>

            {/* Scale header */}
            <div style={{ display: "flex", gap: 20, alignItems: "flex-start", marginBottom: 32 }}>
              <div className="rt-glyph" style={{ width: 56, height: 56, fontSize: 16 }}>{scale.glyph}</div>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 6 }}>
                  <span className={`rt-tag ${tagColor}`}>{scale.category}</span>
                  <span style={{ fontSize: 12, color: "var(--rt-muted)" }}>· {scale.duration}</span>
                </div>
                <h1 style={{ fontSize: 32, marginBottom: 6 }}>{scale.name}</h1>
                <div style={{ fontSize: 14, color: "var(--rt-muted)", fontStyle: "italic" }}>
                  {scale.nameEn} · {scale.reference}
                </div>
              </div>
            </div>

            {/* Two-column layout */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 32, alignItems: "flex-start" }}>
              <div>
                {form !== "psfs" && (
                  <div style={{ marginBottom: 16, padding: "14px 18px", background: "#fff", border: "1px solid var(--rt-line)", borderRadius: "var(--rt-r-lg)", fontSize: 13, color: "var(--rt-muted)", lineHeight: 1.55 }}>
                    {scale.description}
                  </div>
                )}
                {formEl}
              </div>
              <MetaPanel
                session={session} setSession={setSession}
                scale={scale} score={score} total={total}
                completion={completion} unit={unit}
                onExport={onExport} canExport={canExport}
              />
            </div>
          </div>
        </main>
        <FooterF />
      </>
    );
  }

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