/* ============================================================
   MUIY 2.0 — Health screen (trends · records · chelation)
   ============================================================ */

/* ---- shared range config for trend windows ---- */
const TREND_RANGES = [
{ k: '90', l: '3 months' },
{ k: '180', l: '6 months' },
{ k: '270', l: '9 months' },
{ k: '365', l: '1 year' },
{ k: 'all', l: 'All time' }];

const cutoffOf = (r) => r === 'all' ? 999999 : parseInt(r, 10);

/* ---- a compact dropdown picker for the trend window ---- */
function RangePicker({ value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const cur = TREND_RANGES.find((o) => o.k === value) || TREND_RANGES[0];
  return (
    <div style={{ position: 'relative' }}>
      <button
        className="chip"
        onClick={() => setOpen((o) => !o)}
        style={{ background: open ? 'var(--orange-wash)' : 'var(--surface-2)', borderColor: open ? 'var(--orange)' : 'var(--hairline-2)', color: open ? 'var(--orange)' : 'var(--ink)', fontWeight: 800, paddingRight: 10 }}>
        
        <Icon name="calendar" size={14} color={open ? 'var(--orange)' : 'var(--ink-2)'} />
        {cur.l}
        <Icon name="chevD" size={14} color={open ? 'var(--orange)' : 'var(--ink-3)'} style={{ transform: open ? 'rotate(180deg)' : 'none', transition: '.18s' }} />
      </button>
      {open &&
      <React.Fragment>
          <div style={{ position: 'fixed', inset: 0, zIndex: 40 }} onClick={() => setOpen(false)} />
          <div style={{ position: 'absolute', top: 'calc(100% + 7px)', right: 0, zIndex: 41, minWidth: 160, background: 'var(--surface)', border: '1.5px solid var(--hairline)', borderRadius: 16, boxShadow: 'var(--sh)', padding: 6, animation: 'sheetUp .18s cubic-bezier(.2,.8,.2,1)' }}>
            {TREND_RANGES.map((o) => {
            const on = o.k === value;
            return (
              <button key={o.k} onClick={() => {onChange(o.k);setOpen(false);}} className="between" style={{ width: '100%', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', background: on ? 'var(--orange-wash)' : 'transparent', color: on ? 'var(--orange)' : 'var(--ink)', fontWeight: on ? 800 : 700, fontSize: 14, padding: '10px 12px', borderRadius: 11 }}>
                  {o.l}
                  {on && <Icon name="check" size={15} color="var(--orange)" sw={2.6} />}
                </button>);

          })}
          </div>
        </React.Fragment>
      }
    </div>);

}

/* ---- single-metric line chart with a green TARGET ZONE band ---- */
function axisTicks(min, max, step) {
  const out = [];const start = Math.ceil(min / step) * step;
  for (let v = start; v <= max + 0.0001; v += step) out.push(+v.toFixed(2));
  return out;
}
function MetricChart({ rows, metric, range, targets }) {
  const cutoff = cutoffOf(range);
  const data = rows.filter((d) => TC.relDays(d.date) <= cutoff).slice().reverse();
  const W = 320,HT = 172,padL = 30,padR = 8,padT = 16,padB = 22;
  const xs = (i, n) => padL + (n <= 1 ? (W - padL - padR) / 2 : i / (n - 1) * (W - padL - padR));
  const isHb = metric === 'hb';
  const vals = data.map((d) => d.value);
  const T = targets || TC.DEFAULT_HB_TARGETS;

  let min, max, band, ticks, fmtTick;
  if (isHb) {
    const dmin = vals.length ? Math.min(...vals) : T.belowMax;
    const dmax = vals.length ? Math.max(...vals) : T.onMax;
    min = Math.floor(Math.min(dmin, T.belowMax) - 0.5);
    max = Math.ceil(Math.max(dmax, T.onMax) + 0.5);
    band = [T.nearMax, T.onMax];
    ticks = axisTicks(min, max, 1);
    fmtTick = (v) => v.toFixed(0);
  } else {
    const dmin = vals.length ? Math.min(...vals) : 800;
    const dmax = vals.length ? Math.max(...vals) : 1500;
    min = Math.max(0, Math.min(dmin, 1000) - 300);
    max = Math.max(dmax, 1000) + 300;
    band = [min, 1000];
    const span = max - min;
    const step = span > 4000 ? 2000 : span > 2000 ? 1000 : 500;
    ticks = axisTicks(min, max, step);
    fmtTick = (v) => v >= 1000 ? (v / 1000).toFixed(v % 1000 ? 1 : 0) + 'k' : String(v);
  }
  const y = (v) => padT + (1 - (v - min) / (max - min || 1)) * (HT - padT - padB);
  const path = data.map((d, i) => `${i === 0 ? 'M' : 'L'} ${xs(i, data.length).toFixed(1)} ${y(d.value).toFixed(1)}`).join(' ');
  const color = isHb ? 'var(--sky-deep)' : 'var(--orange)';
  const bandTop = y(Math.min(band[1], max));
  const bandBot = y(Math.max(band[0], min));

  if (!data.length) return <div className="body" style={{ textAlign: 'center', padding: '50px 0' }}>No {isHb ? 'HB' : 'ferritin'} readings in this period.</div>;

  return (
    <svg viewBox={`0 0 ${W} ${HT}`} width="100%" style={{ display: 'block' }}>
      {/* gridlines + y labels */}
      {ticks.map((tv) =>
      <g key={'t' + tv}>
          <line x1={padL} y1={y(tv)} x2={W - padR} y2={y(tv)} stroke="var(--hairline)" strokeWidth="1" />
          <text x={padL - 5} y={y(tv) + 3} fontSize="8.5" fontWeight="700" textAnchor="end" fill="var(--ink-3)">{fmtTick(tv)}</text>
        </g>
      )}
      {/* green target zone band */}
      <rect x={padL} y={bandTop} width={W - padL - padR} height={Math.max(0, bandBot - bandTop)} fill="var(--green-wash)" />
      <line x1={padL} y1={bandTop} x2={W - padR} y2={bandTop} stroke="#9CD45A" strokeWidth="1.2" strokeDasharray="3 3" />
      {band[0] > min && <line x1={padL} y1={bandBot} x2={W - padR} y2={bandBot} stroke="#9CD45A" strokeWidth="1.2" strokeDasharray="3 3" />}
      <text x={W - padR - 2} y={bandTop + 11} fontSize="8.5" fontWeight="800" textAnchor="end" fill="var(--success)">Target zone</text>
      {/* line + uniform points */}
      {data.length > 1 && <path d={path} fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />}
      {data.map((d, i) =>
      <g key={i}>
          <circle cx={xs(i, data.length)} cy={y(d.value)} r="4" fill="var(--surface)" stroke={color} strokeWidth="2.2" />
        </g>
      )}
    </svg>);

}

/* ---- HB legend rows derived from current (custom) targets ---- */
function hbLegendRows(t) {
  const f = (n) => (Math.round(n * 10) / 10).toFixed(1);
  return [
  ['var(--danger)', 'Below target', `< ${f(t.belowMax)}`],
  ['var(--warning)', 'Near target', `${f(t.belowMax)}–${f(t.nearMax - 0.1)}`],
  ['var(--success)', 'On target', `${f(t.nearMax)}–${f(t.onMax)}`],
  ['#3E9AA0', 'Above target', `> ${f(t.onMax)}`]];

}

function HealthHbTrends({ store }) {
  const [range, setRange] = React.useState('180');
  const targets = TC.hbTargets(store.patient);
  const hbAll = TC.hbSeries(store.data); // unified hbLog — chart + snapshot
  const hbPre = TC.preTransfusionHb(store.data); // source:'transfusion' troughs — status headline

  return (
    <div>
      <HbSmartStatus store={store} rows={hbPre} targets={targets} />

      <div className="card" style={{ marginBottom: 14 }}>
        <div className="between" style={{ marginBottom: 12, gap: 8 }}>
          <span className="sec-title" style={{ whiteSpace: 'nowrap' }}><Icon name="chart" size={15} color="var(--sky-deep)" />Hb trend</span>
          <RangePicker value={range} onChange={setRange} />
        </div>
        <MetricChart rows={hbAll} metric="hb" range={range} targets={targets} />
        <HbTrendAnalysis rows={hbAll} targets={targets} range={range} bare />
      </div>

      <HbForecast store={store} data={store.data} targets={targets} />

      <div className="card-flat" style={{ padding: '13px 15px' }}>
        <div className="between" style={{ marginBottom: 10 }}>
          <span className="sec-title" style={{ fontSize: 12 }}>Hb targets</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '9px 14px' }}>
          {hbLegendRows(targets).map(([c, label, rng]) =>
          <div key={label} className="row" style={{ gap: 8 }}>
              <span style={{ width: 10, height: 10, borderRadius: 999, background: c, flex: 'none' }} />
              <span style={{ fontSize: 12.5, fontWeight: 800, color: 'var(--ink)' }}>{label}</span>
              <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)', marginLeft: 'auto' }}>{rng}</span>
            </div>
          )}
        </div>
        <div className="row" style={{ alignItems: 'flex-start', gap: 8, marginTop: 13, paddingTop: 12, borderTop: '1px solid var(--hairline)' }}>
          <Icon name="info" size={14} color="var(--sky-deep)" style={{ flex: 'none', marginTop: 1 }} />
          <span className="body" style={{ fontSize: 11.5, lineHeight: 1.5 }}>Keeping Hb above 9.5–10.5 g/dL substantially reduces the bone marrow’s overactivity, leading to fewer skeletal complications and better growth in children.</span>
        </div>
      </div>

    </div>);

}

/* ---- one transfusion row (shared between records + history popup) ---- */
function TransfusionRow({ store, t, latest }) {
  const hbBefore = TC.transfusionHb(store.data, t.id);
  return (
    <div className="drow" style={{ padding: '13px 0', cursor: 'pointer' }} onClick={() => store.openModal('logTransfusion', { edit: t })}>
      <div className="leaf" style={{ width: 42, height: 42, flex: 'none', background: t.reaction ? 'var(--yellow-wash)' : 'var(--green-wash)', color: t.reaction ? 'var(--waiting)' : 'var(--success)' }}>
        <Icon name="drop" size={20} color={t.reaction ? 'var(--waiting)' : 'var(--success)'} fill={t.reaction ? 'var(--waiting)' : 'var(--success)'} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="dname" style={{ fontSize: 14.5 }}>{t.units} unit{t.units === 1 ? '' : 's'} · {t.donorSource === 'camp' ? 'Camp' : 'Direct donor'}</div>
        <div className="dmeta muted">{TC.fmtDate(t.date)}{t.volumeMl ? ` · ${t.volumeMl} mL` : ''}{hbBefore != null ? ` · HB before ${hbBefore}` : ''}</div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 5, flex: 'none' }}>
        {latest && <span className="chip-status" style={{ background: 'var(--orange-wash)', color: 'var(--orange)' }}>Latest</span>}
        {t.reaction && <span className="chip-status" style={{ background: 'var(--yellow-wash)', color: 'var(--waiting)' }}>Reaction</span>}
      </div>
    </div>);

}

/* ---- HB / Ferritin level rows (colour-coded) ---- */
const HB_SOURCE = { transfusion: 'Transfusion', lab_report: 'Lab report', manual: 'Manual' };

function HbRow({ store, e }) {
  const day = TC.daysSinceTransfusion(store.data.transfusions, e.date);
  const st = TC.hbStatus(e.value, TC.hbTargets(store.patient));
  return (
    <div className="drow" style={{ padding: '12px 0', cursor: 'pointer' }} onClick={() => store.openModal('logHb', { edit: e })}>
      <div className="leaf" style={{ width: 40, height: 40, flex: 'none', background: st.wash, color: st.color, borderRadius: 13 }}><Icon name="drop" size={18} color={st.color} fill={st.color} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="dname" style={{ fontSize: 14.5 }}>{e.value} <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>g/dL</span></div>
        <div className="dmeta muted">{TC.fmtDate(e.date)} · {HB_SOURCE[e.source] || 'Manual'}{e.source !== 'transfusion' && e.preTransfusion ? ' · Pre-transfusion' : ''}{day != null ? ` · Day ${day}` : ''}</div>
      </div>
      <span className="chip-status" style={{ background: st.wash, color: st.color, flex: 'none' }}><span style={{ width: 7, height: 7, borderRadius: 999, background: st.color }} />{st.label}</span>
    </div>);

}

function FerritinRow({ store, e }) {
  const st = TC.ferritinStatus(e.value);
  const meta = [TC.fmtDate(e.date), e.lab, e.notes].filter(Boolean).join(' · ');
  return (
    <div className="drow" style={{ padding: '12px 0', cursor: 'pointer' }} onClick={() => store.openModal('logFerritin', { edit: e })}>
      <div className="leaf" style={{ width: 40, height: 40, flex: 'none', background: st.wash, color: st.color, borderRadius: 13 }}><Icon name="sparkle" size={17} color={st.color} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="dname" style={{ fontSize: 14.5 }}>{e.value.toLocaleString()} <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>ng/mL</span></div>
        <div className="dmeta muted">{meta}</div>
      </div>
      <span className="chip-status" style={{ background: st.wash, color: st.color, flex: 'none' }}><span style={{ width: 7, height: 7, borderRadius: 999, background: st.color }} />{st.label}</span>
    </div>);

}

/* ---- HEALTH RECORDS tab ---- */
function HealthRecords({ store }) {
  const trans = [...(store.data.transfusions || [])].sort((a, b) => TC.parse(b.date) - TC.parse(a.date));

  // scroll the transfusion forecast into view when arriving from the Home card
  React.useEffect(() => {
    if (store.healthFocus !== 'forecast') return;
    let tries = 0;
    const tick = () => {
      const el = document.getElementById('hb-forecast');
      const sc = el && el.closest('.tc-scroll');
      if (el && sc && sc.scrollHeight > sc.clientHeight + 20) {
        const scRect = sc.getBoundingClientRect();
        const elRect = el.getBoundingClientRect();
        const scale = sc.offsetHeight ? scRect.height / sc.offsetHeight : 1;
        const target = Math.max(0, sc.scrollTop + (elRect.top - scRect.top - 54) / (scale || 1));
        // animate manually — a smooth native scroll gets cancelled by the
        // re-render when we clear the focus flag below
        const start = sc.scrollTop;
        const t0 = performance.now();
        const dur = 460;
        const ease = (p) => 1 - Math.pow(1 - p, 3);
        const step = (now) => {
          const p = Math.min(1, (now - t0) / dur);
          sc.scrollTop = start + (target - start) * ease(p);
          if (p < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
        store.setHealthFocus(null);
        return;
      }
      if (tries++ < 12) setTimeout(tick, 80);else
      store.setHealthFocus(null);
    };
    const id = setTimeout(tick, 120);
    return () => clearTimeout(id);
  }, [store.healthFocus]);

  const viewAll = (label, onClick) =>
  <button className="link" style={{ width: '100%', justifyContent: 'center', padding: '13px 0 12px', borderTop: '1.5px solid var(--hairline)', fontSize: 13.5 }} onClick={onClick}>
      {label}<Icon name="chevR" size={14} color="var(--orange)" />
    </button>;

  return (
    <div>
      {/* ---- Transfusion log ---- */}
      <SectionHead title="Transfusion log" link="+ Log" onLink={() => store.openModal('logTransfusion', {})} />
      <div className="card" style={{ padding: '6px 16px', marginBottom: 14 }}>
        {trans.length === 0 ? <div className="body" style={{ padding: '14px 0' }}>No transfusions logged yet.</div> :
        trans.slice(0, 2).map((t, i) => <TransfusionRow key={t.id} store={store} t={t} latest={i === 0} />)}
        {trans.length > 2 && viewAll(`View all ${trans.length} transfusions`, () => store.openModal('transfusionHistory', {}))}
      </div>

      {/* ---- Pre-transfusion haemoglobin (moved here from Trends) ---- */}
      <HealthHbTrends store={store} />
    </div>);

}

/* ---- CHELATION tab (medications) ---- */
function ChelationScreen({ store }) {
  const meds = store.patient.medications || [];
  const [view, setView] = React.useState('main');
  const hasChel = meds.some((m) => TC.findChelator(m.brand));

  if (view === 'insights') return <InsightsScreen store={store} onBack={() => setView('main')} />;

  return (
    <div>
      {hasChel &&
      <>
          <TodayDosesCard store={store} />
          <StreakCard store={store} />
          <div className="adh-tools">
            <button className="adh-tool" onClick={() => store.openModal('reminders', {})}>
              <span className="adh-tool-leaf" style={{ background: 'var(--orange-wash)' }}><Icon name="bell" size={19} color="var(--orange)" /></span>
              <span className="adh-tool-l">Reminders</span>
            </button>
            <button className="adh-tool" onClick={() => setView('insights')}>
              <span className="adh-tool-leaf" style={{ background: 'var(--sky-wash)' }}><Icon name="trendUp" size={19} color="var(--sky-deep)" /></span>
              <span className="adh-tool-l">Insights</span>
            </button>
            <button className="adh-tool" onClick={() => store.openModal('shareAdherence', {})}>
              <span className="adh-tool-leaf" style={{ background: 'var(--green-wash)' }}><Icon name="share" size={18} color="var(--success)" /></span>
              <span className="adh-tool-l">Share</span>
            </button>
          </div>
        </>
      }
      <SectionHead title="Chelation medications" link="+ Add" onLink={() => store.openModal('addMed', {})} />
      {meds.length === 0 ?
      <div className="card"><div className="body">No chelation medication added yet. Tap “+ Add” to set up your regimen with weight-based dosing.</div></div> :

      <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
          {meds.map((m) => {
          const refillDays = m.nextRefill ? -TC.relDays(m.nextRefill) : null;
          const low = refillDays != null && refillDays <= 7;
          const daily = TC.medDailyMg(m);
          const chel = TC.findChelator(m.brand);
          const wKg = m.weightKg || store.patient.weightKg || 0;
          const mkd = daily && wKg ? daily / wKg : 0;
          const dc = mkd ? TC.doseCategory(mkd, m.brand) : null;
          return (
            <div key={m.id} className="card" style={{ padding: 16, cursor: 'pointer' }} onClick={() => store.openModal('addMed', { med: m })}>
                <div className="row" style={{ gap: 13 }}>
                  <div className="leaf" style={{ width: 46, height: 46, background: 'var(--orange-wash)', color: 'var(--orange)', borderRadius: '46% 54% 62% 38% / 54% 42% 58% 46%' }}><Icon name="pill" size={22} color="var(--orange)" /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="dname" style={{ fontSize: 15.5 }}>{m.brand || m.name}® {chel ? <span className="body" style={{ fontSize: 11.5 }}>({chel.abbr})</span> : ''}</div>
                    <div className="dmeta muted">{chel ? chel.form : m.form} · {chel ? chel.route : TC.medFreqLabel(m.frequency)}</div>
                  </div>
                  <div className="row" style={{ gap: 7, flex: 'none' }}>
                    <button className="icon-btn" style={{ width: 36, height: 36, background: 'var(--surface-2)' }} onClick={(e) => {e.stopPropagation();store.openModal('addMed', { med: m });}} aria-label="Edit medication"><Icon name="edit" size={16} /></button>
                    <button className="icon-btn" style={{ width: 36, height: 36, background: 'var(--surface-2)' }} onClick={(e) => {e.stopPropagation();store.openModal('confirm', { title: 'Remove this medication?', message: `${m.brand || m.name} will be removed from your chelation regimen. This cannot be undone.`, confirmLabel: 'Remove', onConfirm: () => {store.mutate((d) => {d.patient.medications = (d.patient.medications || []).filter((x) => x.id !== m.id);});store.showToast('Medication removed', '🗑️');} });}} aria-label="Delete medication"><Icon name="trash" size={16} color="var(--waiting)" /></button>
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 16px', marginTop: 14, padding: '12px 13px', background: 'var(--surface-2)', borderRadius: 14 }}>
                  <div>
                    <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 3 }}>Your dose</div>
                    <div style={{ fontWeight: 800, fontSize: 13, color: 'var(--ink)' }}>{daily ? `${daily.toLocaleString()} mg/day` : TC.medDoseLabel(m)}</div>
                    {mkd > 0 && <div className="body" style={{ fontSize: 11.5, marginTop: 1 }}>{mkd.toFixed(1)} mg/kg/day</div>}
                  </div>
                  {dc &&
                <div>
                      <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 3 }}>Category</div>
                      <span className="chip-status" style={{ background: dc.wash, color: dc.color, padding: '3px 9px', fontSize: 10.5 }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: dc.color, display: 'inline-block', marginRight: 5 }} />{dc.label}</span>
                    </div>
                }
                  {chel && chel.standardDoseLabel &&
                <div>
                      <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 3 }}>Standard</div>
                      <div style={{ fontWeight: 700, fontSize: 12, color: 'var(--success)' }}>{chel.standardDoseLabel}</div>
                    </div>
                }
                  {chel && chel.severeDoseLabel &&
                <div>
                      <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 3 }}>Severe overload</div>
                      <div style={{ fontWeight: 700, fontSize: 12, color: 'var(--warning)' }}>{chel.severeDoseLabel}</div>
                    </div>
                }
                </div>
                {chel && chel.bestFor &&
              <div style={{ marginTop: 10, fontSize: 12, fontWeight: 600, color: 'var(--ink-2)' }}>Best for: {chel.bestFor}</div>
              }
                {refillDays != null &&
              <div className="between" style={{ marginTop: 12, padding: '9px 12px', borderRadius: 12, background: low ? 'var(--yellow-wash)' : 'var(--surface-2)', gap: 10 }}>
                    <span className="body" style={{ fontWeight: 700, fontSize: 12.5, color: low ? 'var(--waiting)' : 'var(--ink-2)', whiteSpace: 'nowrap' }}>{low ? 'Refill soon' : 'Next refill'}</span>
                    <span className="body" style={{ fontWeight: 800, fontSize: 12.5, color: low ? 'var(--waiting)' : 'var(--ink)', whiteSpace: 'nowrap' }}>{refillDays <= 0 ? 'Today' : `in ${refillDays}d`} · {TC.fmtDate(m.nextRefill, { day: 'numeric', month: 'short' })}</span>
                  </div>
              }
              </div>);

        })}
        </div>
      }
    </div>);

}

function HealthScreen({ store }) {
  const tab = store.healthTab || 'records';
  const setTab = store.setHealthTab;
  return (
    <div className="tc-scroll"><div className="tc-page tc-page--top">
      <div className="h1" style={{ marginBottom: 14, color: "var(--ink)" }}>My Health</div>
      <div className="seg tri" style={{ gap: 3 }}>
        <button className={tab === 'records' ? 'on' : ''} style={{ fontSize: 12.5, padding: '9px 1px' }} onClick={() => setTab('records')}>Transfusion</button>
        <button className={tab === 'chelation' ? 'on' : ''} style={{ fontSize: 12.5, padding: '9px 1px' }} onClick={() => setTab('chelation')}>Chelation</button>
        <button className={tab === 'monitoring' ? 'on' : ''} style={{ fontSize: 12.5, padding: '9px 1px' }} onClick={() => setTab('monitoring')}>Monitoring</button>
      </div>
      <div key={tab} className="stagger" style={{ marginTop: 4 }}>
        {tab === 'chelation' ? <ChelationScreen store={store} /> : tab === 'monitoring' ? <MonitoringScreen store={store} /> : <HealthRecords store={store} />}
      </div>
    </div></div>);

}

Object.assign(window, { HealthScreen, TransfusionRow, HbRow, FerritinRow });