/* ============================================================
   MUIY — Chelation Setup Wizard
   Multi-step: Brand → Weight → Dose → Calculate → Schedule → Insights
   Loads AFTER sheets.jsx, BEFORE shell.jsx.
   ============================================================ */

const CHEL_STEPS = ['brand', 'weight', 'dose', 'calc', 'schedule', 'insights'];
const CHEL_TITLES = { brand: 'Select medication', weight: 'Your weight', dose: 'Daily dose', calc: 'Dose assessment', schedule: 'Adherence schedule', insights: 'Iron insights' };

/* ---- progress dots ---- */
function WizDots({ step, total }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginBottom: 16 }}>
      {Array.from({ length: total }, (_, i) => (
        <div key={i} style={{ width: i === step ? 22 : 8, height: 8, borderRadius: 4, background: i <= step ? 'var(--orange)' : 'var(--hairline-2)', transition: 'all .3s cubic-bezier(.22,1,.36,1)' }} />
      ))}
    </div>
  );
}

/* ---- dose range visualization bar ---- */
function DoseRangeBar({ mgPerKg, dosing }) {
  if (!dosing || !dosing.stdMin) return null;
  const visMax = dosing.sevMax * 1.35;
  const pct = (v) => Math.max(0, Math.min(100, (v / visMax) * 100));
  return (
    <div style={{ marginTop: 16, marginBottom: 8 }}>
      <div style={{ position: 'relative', height: 14, borderRadius: 7, background: 'var(--surface-2)', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', left: `${pct(dosing.stdMin)}%`, width: `${pct(dosing.stdMax) - pct(dosing.stdMin)}%`, height: '100%', background: 'var(--success-wash)' }} />
        <div style={{ position: 'absolute', left: `${pct(dosing.stdMax)}%`, width: `${pct(dosing.sevMax) - pct(dosing.stdMax)}%`, height: '100%', background: 'var(--warning-wash)' }} />
        <div style={{ position: 'absolute', left: `${pct(mgPerKg)}%`, top: -2, width: 4, height: 18, borderRadius: 2, background: 'var(--orange)', transform: 'translateX(-2px)', boxShadow: '0 1px 4px rgba(0,0,0,.15)' }} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, fontWeight: 700, color: 'var(--ink-3)', marginTop: 5, padding: '0 2px' }}>
        <span>{dosing.stdMin}</span>
        <span style={{ color: 'var(--success)' }}>Standard</span>
        <span style={{ color: 'var(--warning)' }}>Severe</span>
        <span>{dosing.sevMax}</span>
      </div>
    </div>
  );
}

/* ---- iron insight generator ---- */
function chelIronInsight(ferSt, doseKey) {
  if (!ferSt) return { tone: 'info', text: 'Add a ferritin reading to receive personalised iron insights based on your chelation dose.' };
  const dk = (!doseKey || doseKey === 'above') ? 'severe' : (doseKey === 'below' ? 'below' : doseKey);
  const m = {
    good_below: 'Iron levels are low but your dose is below standard. Discuss with your team whether current dose is sufficient.',
    good_standard: 'Excellent iron control. Your standard chelation dose is keeping iron levels in a healthy range.',
    good_severe: 'Iron responding well to intensive chelation. Your team may consider stepping down to standard dosing.',
    elevated_below: 'Moderate iron burden with below-standard dosing. Consider discussing an increase to standard range.',
    elevated_standard: 'Your chelation is managing moderate iron levels. Continue current regimen and monitor ferritin trends.',
    elevated_severe: 'Intensive chelation is addressing moderate iron burden. Continue and monitor — trends matter more than single readings.',
    high_below: 'High iron burden on below-standard dose. Discuss increasing to at least the standard range.',
    high_standard: 'Iron levels are elevated despite standard dosing. Your haematologist may consider a more intensive regimen.',
    high_severe: 'Intensive chelation is working on high iron levels. Stay adherent — consistent dosing is key.',
    critical_below: 'Very high iron on below-standard dose. Seek medical review promptly about dose intensification.',
    critical_standard: 'Very high iron levels on standard dose. Discuss urgent escalation or combination therapy with your team.',
    critical_severe: 'Very high iron despite intensive chelation. Your team should review all available options.',
  };
  return { tone: ferSt.key === 'good' ? 'good' : ferSt.key === 'elevated' ? 'info' : 'warn', text: m[`${ferSt.key}_${dk}`] || 'Continue your chelation regimen and follow up with your haematologist.' };
}

/* ============================================================ */
function ChelationSetupWizard({ store, close, med }) {
  const editing = !!med;
  const [step, setStep] = React.useState(0);

  const [brand, setBrand] = React.useState(med ? med.brand : '');
  const [weight, setWeight] = React.useState(String(med ? (med.weightKg || store.patient.weightKg || '') : (store.patient.weightKg || '')));
  const [counts, setCounts] = React.useState(() => {
    if (med && med.strengths) { const o = {}; med.strengths.forEach(s => { o[s.mg] = s.count; }); return o; }
    return {};
  });
  const [freq, setFreq] = React.useState(med ? (med.frequency || '') : '');
  const [times, setTimes] = React.useState(med ? (med.times || []) : []);
  const [duration, setDuration] = React.useState(med ? (med.duration || '') : '');
  const [refill, setRefill] = React.useState(med ? (med.nextRefill || TC.inDaysDate(30)) : TC.inDaysDate(30));

  const cat = brand ? TC.findChelator(brand) : null;
  const isInfusion = !!(cat && cat.infusion);
  const wKg = parseFloat(weight) || 0;
  const freqOpts = isInfusion ? TC.INFUSION_FREQ : TC.FREQ_OPTIONS;
  const totalCount = Object.values(counts).reduce((a, b) => a + b, 0);
  const previewMed = cat ? { brand, frequency: freq, strengths: cat.strengths.filter(s => (counts[s.mg] || 0) > 0).map(s => ({ mg: s.mg, count: counts[s.mg], unit: s.unit || 'tablet' })) } : null;
  const dailyMg = previewMed ? TC.medDailyMg(previewMed) : 0;
  const mgPerKg = (dailyMg && wKg) ? dailyMg / wKg : 0;
  const doseCat = (mgPerKg && cat) ? TC.doseCategory(mgPerKg, brand) : null;
  const ferArr = [...(store.data.ferritinLog || [])].sort((a, b) => TC.parse(b.date) - TC.parse(a.date));
  const ferLatest = ferArr[0] || null;
  const ferSt = ferLatest ? TC.ferritinStatus(ferLatest.value) : null;

  const pickBrand = (b) => {
    setBrand(b);
    const c = TC.findChelator(b); if (!c) return;
    const init = {}; c.strengths.forEach(s => { init[s.mg] = 0; }); init[c.strengths[c.strengths.length - 1].mg] = 1;
    setCounts(init);
    setFreq(c.defaultFreq || (c.infusion ? 'daily' : 'once_daily'));
    setTimes([]); setDuration('');
  };
  const setCount = (mg, v) => setCounts(c => ({ ...c, [mg]: v }));
  const toggleTime = (t) => setTimes(ts => ts.includes(t) ? ts.filter(x => x !== t) : [...ts, t]);

  const groups = React.useMemo(() => {
    const g = {}; TC.CHELATORS.forEach(c => { if (!g[c.abbr]) g[c.abbr] = { abbr: c.abbr, name: c.chelator, brands: [] }; g[c.abbr].brands.push(c); });
    return Object.values(g);
  }, []);

  const canNext = { 0: !!brand, 1: wKg > 0, 2: totalCount > 0 && !!freq, 3: true, 4: true, 5: true };
  const next = () => { if (canNext[step]) setStep(s => Math.min(s + 1, 5)); };
  const back = () => setStep(s => Math.max(s - 1, 0));
  const isLast = step === 5;

  const save = () => {
    if (!cat || totalCount === 0) return;
    const strengths = cat.strengths.filter(s => (counts[s.mg] || 0) > 0).map(s => ({ mg: s.mg, count: counts[s.mg], unit: s.unit || 'tablet' }));
    store.mutate(d => {
      if (wKg > 0) d.patient.weightKg = wKg;
      const rec = { id: editing ? med.id : TC.uid(), name: cat.chelator, brand, form: cat.form, strengths, frequency: freq, times: isInfusion ? [] : times, duration: isInfusion ? duration : null, weightKg: wKg || null, dose: TC.medDoseLabel({ strengths }), nextRefill: refill };
      if (editing) { const i = d.patient.medications.findIndex(x => x.id === med.id); d.patient.medications[i] = rec; }
      else d.patient.medications.push(rec);
    });
    store.showToast(editing ? 'Medication updated' : 'Chelation set up', '💊'); close();
  };

  /* ---- step renderers ---- */
  const renderStep = () => {
    const sk = CHEL_STEPS[step];

    /* STEP 1 — SELECT BRAND */
    if (sk === 'brand') return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxHeight: 400, overflowY: 'auto', scrollbarWidth: 'none', paddingBottom: 4 }}>
        {groups.map(g => (
          <div key={g.abbr}>
            <div style={{ fontSize: 11, fontWeight: 900, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ background: 'var(--orange-wash)', color: 'var(--orange)', padding: '2px 7px', borderRadius: 6, fontSize: 10, fontWeight: 900 }}>{g.abbr}</span>{g.name}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {g.brands.map(c => {
                const on = brand === c.brand;
                return (
                  <button key={c.brand} onClick={() => pickBrand(c.brand)} className="qa-item" style={{ borderColor: on ? 'var(--orange)' : 'transparent', background: on ? 'var(--orange-wash)' : 'var(--surface-2)', padding: '12px 13px' }}>
                    <div className="qa-ic" style={{ background: on ? 'var(--orange)' : 'var(--orange-wash)', color: on ? '#fff' : 'var(--orange)', width: 38, height: 38 }}>
                      <Icon name={c.infusion ? 'sparkle' : 'pill'} size={17} color={on ? '#fff' : 'var(--orange)'} />
                    </div>
                    <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
                      <div style={{ fontWeight: 800, fontSize: 14 }}>{c.brand}®</div>
                      <div className="body" style={{ fontSize: 11 }}>{c.form} · {c.route}</div>
                      <div className="body" style={{ fontSize: 10.5, color: 'var(--ink-2)', marginTop: 1 }}>{c.bestFor}</div>
                    </div>
                    <div style={{ width: 20, height: 20, borderRadius: '50%', border: on ? 'none' : '1.5px solid var(--hairline-2)', background: on ? 'var(--orange)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
                      {on && <Icon name="check" size={11} color="#fff" sw={3} />}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    );

    /* STEP 2 — ENTER WEIGHT */
    if (sk === 'weight') return (
      <div>
        {cat && (
          <div className="card-flat" style={{ padding: '12px 14px', marginBottom: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div className="leaf" style={{ width: 38, height: 38, background: 'var(--orange-wash)', color: 'var(--orange)', borderRadius: 12 }}><Icon name="pill" size={17} color="var(--orange)" /></div>
            <div><div style={{ fontWeight: 800, fontSize: 14 }}>{cat.brand}®</div><div className="body" style={{ fontSize: 11.5 }}>{cat.form} · {cat.route}</div></div>
          </div>
        )}
        <label className="field-label">Body weight</label>
        <div className="row" style={{ gap: 10, marginBottom: 14 }}>
          <input className="input" type="number" inputMode="decimal" value={weight} onChange={e => setWeight(e.target.value)} placeholder="e.g. 58" style={{ fontSize: 22, fontWeight: 800, textAlign: 'center', padding: '16px 14px' }} />
          <span className="input" style={{ width: 'auto', flex: 'none', color: 'var(--ink-3)', display: 'flex', alignItems: 'center', fontSize: 16, fontWeight: 800 }}>kg</span>
        </div>
        <div className="body" style={{ fontSize: 12.5, lineHeight: 1.5 }}>Your weight is used to calculate the right dose in mg/kg/day — the standard way chelation doses are prescribed.</div>
        {(() => { const G = window.CLINICALGUARD; const wNote = G ? G.weightKg(weight) : null; return wNote ? <div style={{ marginTop: 12 }}><FieldNote note={wNote} onApplySuggest={wNote.suggest ? (x) => setWeight(x) : undefined} /></div> : null; })()}
        {wKg > 0 && cat && (
          <div className="card-flat" style={{ padding: '13px 14px', marginTop: 16, borderLeft: '3px solid var(--orange)' }}>
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--orange)', marginBottom: 6 }}>Recommended for {wKg} kg</div>
            <div style={{ fontWeight: 800, fontSize: 17, color: 'var(--ink)' }}>{cat.standardDoseLabel}</div>
            <div className="body" style={{ fontSize: 11.5, marginTop: 3 }}>Standard dose · {cat.bestFor}</div>
          </div>
        )}
      </div>
    );

    /* STEP 3 — ENTER DAILY DOSE */
    if (sk === 'dose') return (
      <div>
        <label className="field-label">How many of each strength — per dose</label>
        <div className="card-flat" style={{ padding: '4px 14px', marginBottom: 16 }}>
          {cat && cat.strengths.map((s, i) => (
            <div key={s.mg} className="between" style={{ alignItems: 'center', padding: '12px 0', borderTop: i > 0 ? '1px solid var(--hairline)' : 'none' }}>
              <div><div style={{ fontWeight: 800, fontSize: 15 }}>{TC.strengthLabel(s)}</div><div className="body" style={{ fontSize: 11.5 }}>{(s.unit || 'tablet') === 'mL' ? 'oral solution (mL)' : (s.unit || 'tablet') + ((counts[s.mg] || 0) === 1 ? '' : 's')} per dose</div></div>
              <MStepper value={counts[s.mg] || 0} onChange={v => setCount(s.mg, v)} />
            </div>
          ))}
        </div>
        <label className="field-label">How often</label>
        <div style={{ marginBottom: 16 }}><Chips options={freqOpts.map(o => ({ value: o.value, label: o.label }))} value={freq} onChange={setFreq} /></div>
        {isInfusion && <div className="field"><label className="field-label">Infusion duration</label><Chips options={TC.INFUSION_DURATIONS} value={duration} onChange={v => setDuration(duration === v ? '' : v)} /></div>}
        {dailyMg > 0 && (
          <div style={{ background: 'var(--orange-wash)', borderRadius: 14, padding: '12px 14px' }}>
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--orange)' }}>Daily total</div>
            <div className="row" style={{ gap: 6, alignItems: 'baseline', marginTop: 4 }}>
              <span className="num" style={{ fontWeight: 800, fontSize: 22, color: 'var(--ink)' }}>{dailyMg.toLocaleString()}</span>
              <span style={{ fontWeight: 700, fontSize: 13, color: 'var(--ink-2)' }}>mg/day</span>
              {mgPerKg > 0 && <span className="body" style={{ fontSize: 12, marginLeft: 'auto' }}>{mgPerKg.toFixed(1)} mg/kg/day</span>}
            </div>
          </div>
        )}
      </div>
    );

    /* STEP 4 — AUTO-CALCULATE + DOSE CATEGORY */
    if (sk === 'calc') return (
      <div>
        <div style={{ textAlign: 'center', padding: '10px 0 4px' }}>
          <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 6 }}>{cat ? cat.brand : ''}® · {wKg} kg</div>
          <div className="num" style={{ fontSize: 44, fontWeight: 800, color: 'var(--orange)', lineHeight: 1 }}>{mgPerKg.toFixed(1)}</div>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink-2)', marginTop: 4 }}>mg/kg/day</div>
        </div>
        {doseCat && (
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 14 }}>
            <span className="chip-status" style={{ background: doseCat.wash, color: doseCat.color, padding: '7px 16px', fontSize: 13, fontWeight: 800 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: doseCat.color, display: 'inline-block', marginRight: 8 }} />{doseCat.label}
            </span>
          </div>
        )}
        {cat && <DoseRangeBar mgPerKg={mgPerKg} dosing={cat.dosing} />}
        <div className="card-flat" style={{ padding: '13px 14px', marginTop: 14 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9, fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>
            <div className="between"><span>Daily dose</span><span style={{ fontWeight: 800, color: 'var(--ink)' }}>{dailyMg.toLocaleString()} mg/day</span></div>
            <div className="between"><span>Standard range</span><span style={{ fontWeight: 800, color: 'var(--success)' }}>{cat ? cat.standardDoseLabel : ''}</span></div>
            <div className="between"><span>Severe overload</span><span style={{ fontWeight: 800, color: 'var(--warning)' }}>{cat ? cat.severeDoseLabel : ''}</span></div>
            <div className="between"><span>Route</span><span style={{ fontWeight: 800, color: 'var(--ink)' }}>{cat ? cat.route : ''}</span></div>
            <div className="between"><span>Best for</span><span style={{ fontWeight: 800, color: 'var(--ink)' }}>{cat ? cat.bestFor : ''}</span></div>
          </div>
        </div>
        <div className="body" style={{ fontSize: 10.5, marginTop: 12, color: 'var(--ink-3)', textAlign: 'center' }}>Estimate only — always follow your haematologist's prescription.</div>
      </div>
    );

    /* STEP 5 — ADHERENCE SCHEDULE */
    if (sk === 'schedule') return (
      <div>
        {!isInfusion && (
          <div className="field">
            <label className="field-label">When do you take it?</label>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {['Morning', 'Afternoon', 'Evening', 'Night'].map(t => (
                <button key={t} className={'chip' + (times.includes(t) ? ' on' : '')} onClick={() => toggleTime(t)}>{t}</button>
              ))}
            </div>
          </div>
        )}
        <div className="field">
          <label className="field-label">Next refill date</label>
          <input className="input" type="date" value={refill} onChange={e => setRefill(e.target.value)} />
        </div>
        <div className="card-flat" style={{ padding: '14px 15px', marginTop: 8 }}>
          <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--orange)', marginBottom: 10 }}>Your schedule</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13, fontWeight: 600 }}>
            <div className="row" style={{ gap: 10 }}><Icon name="pill" size={16} color="var(--orange)" /><span>{cat ? cat.brand : ''}® · {previewMed ? TC.medDoseLabel(previewMed) : ''}</span></div>
            <div className="row" style={{ gap: 10 }}><Icon name="clock" size={16} color="var(--ink-2)" /><span>{TC.medFreqLabel(freq)}{times.length ? ` · ${times.join(', ')}` : ''}{isInfusion && duration ? ` · ${duration}` : ''}</span></div>
            <div className="row" style={{ gap: 10 }}><Icon name="calendar" size={16} color="var(--ink-2)" /><span>Next refill: {TC.fmtDate(refill)}</span></div>
            {dailyMg > 0 && <div className="row" style={{ gap: 10 }}><Icon name="sparkle" size={16} color="var(--orange)" /><span style={{ color: 'var(--orange)', fontWeight: 800 }}>{dailyMg.toLocaleString()} mg/day · {mgPerKg.toFixed(1)} mg/kg/day</span></div>}
          </div>
        </div>
      </div>
    );

    /* STEP 6 — IRON INSIGHTS */
    if (sk === 'insights') {
      const insight = chelIronInsight(ferSt, doseCat ? doseCat.key : null);
      const toneC = { good: ['var(--green-wash)', 'var(--success)'], info: ['var(--sky-wash)', 'var(--sky-deep)'], warn: ['var(--yellow-wash)', 'var(--waiting)'] };
      const [bg, col] = toneC[insight.tone] || toneC.info;
      return (
        <div>
          {ferLatest ? (
            <div className="card-flat" style={{ padding: '13px 14px', marginBottom: 12 }}>
              <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>Latest ferritin</div>
              <div className="row" style={{ gap: 8, alignItems: 'baseline' }}>
                <span className="num" style={{ fontWeight: 800, fontSize: 24, color: 'var(--ink)' }}>{ferLatest.value.toLocaleString()}</span>
                <span style={{ fontWeight: 700, fontSize: 12, color: 'var(--ink-3)' }}>ng/mL</span>
                {ferSt && <span className="chip-status" style={{ background: ferSt.wash, color: ferSt.color, padding: '3px 9px', fontSize: 10, marginLeft: 'auto' }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: ferSt.color, display: 'inline-block', marginRight: 5 }} />{ferSt.note}</span>}
              </div>
              <div className="body" style={{ fontSize: 11, marginTop: 3 }}>{TC.fmtDate(ferLatest.date)}</div>
            </div>
          ) : (
            <div className="card-flat" style={{ padding: '13px 14px', marginBottom: 12, background: 'var(--surface-2)' }}>
              <div className="body" style={{ fontSize: 12.5 }}>No ferritin readings yet. Log your first reading for personalised insights.</div>
            </div>
          )}
          <div className="card-flat" style={{ padding: '13px 14px', marginBottom: 12 }}>
            <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>Your chelation</div>
            <div className="between" style={{ alignItems: 'center' }}>
              <div>
                <div style={{ fontWeight: 800, fontSize: 14 }}>{cat ? cat.brand : ''}® · {dailyMg.toLocaleString()} mg/day</div>
                <div className="body" style={{ fontSize: 12, marginTop: 2 }}>{mgPerKg.toFixed(1)} mg/kg/day</div>
              </div>
              {doseCat && <span className="chip-status" style={{ background: doseCat.wash, color: doseCat.color, padding: '3px 9px', fontSize: 10, flex: 'none' }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: doseCat.color, display: 'inline-block', marginRight: 5 }} />{doseCat.label}</span>}
            </div>
          </div>
          <div style={{ background: bg, borderRadius: 16, padding: '15px 15px', marginBottom: 6 }}>
            <div className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
              <Icon name="sparkle" size={18} color={col} style={{ flex: 'none', marginTop: 2 }} />
              <div>
                <div style={{ fontWeight: 800, fontSize: 12.5, color: col, marginBottom: 4 }}>Iron insight</div>
                <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.5, color: col }}>{insight.text}</div>
              </div>
            </div>
          </div>
          <div className="body" style={{ fontSize: 10, marginTop: 8, color: 'var(--ink-3)', textAlign: 'center', lineHeight: 1.4 }}>These insights are informational only. All treatment decisions should be made with your haematologist.</div>
        </div>
      );
    }
    return null;
  };

  return (
    <MSheet title={CHEL_TITLES[CHEL_STEPS[step]]} onClose={close}>
      <WizDots step={step} total={6} />
      <div style={{ minHeight: 220 }}>{renderStep()}</div>
      <div className="row" style={{ gap: 10, marginTop: 14 }}>
        {step > 0 && <button className="btn btn-ghost" style={{ flex: 1 }} onClick={back}>Back</button>}
        {step === 0 && <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>}
        {isLast
          ? <button className="btn btn-primary" style={{ flex: 1.4 }} onClick={save}>{editing ? 'Save changes' : 'Save & start'}</button>
          : <button className="btn btn-primary" style={{ flex: 1.4, opacity: canNext[step] ? 1 : 0.5 }} onClick={next}>Continue</button>
        }
      </div>
      {editing && isLast && (
        <button className="btn btn-ghost" style={{ width: '100%', marginTop: 8, color: 'var(--waiting)', fontSize: 13 }}
          onClick={() => store.openModal('confirm', { title: 'Delete medication?', message: `"${cat ? cat.chelator : 'This medication'}" will be removed.`, confirmLabel: 'Delete', onConfirm: () => { store.mutate(d => { d.patient.medications = d.patient.medications.filter(x => x.id !== med.id); }); store.showToast('Medication removed', '🗑️'); } })}>
          Delete medication
        </button>
      )}
    </MSheet>
  );
}

Object.assign(window, { ChelationSetupWizard });
