/* ============================================================
   MUIY 2.0 — Chelation adherence · insights · reminders · share
   InsightsScreen (sub-screen) · RemindersSheet · ShareAdherenceSheet
   Loads AFTER adherence.jsx, BEFORE shell.jsx. Exports to window.
   All numbers read scheduled-dose logic via TC.adherence — never
   calendar days. Tone: informational, supportive, never a grade.
   ============================================================ */

const ADHV = () => window.TC.adherence;

/* ============================================================
   ADHERENCE INSIGHTS  (reached from the Chelation tab)
   ============================================================ */
function InsightsScreen({ store, onBack }) {
  const meds = ADHV().chelationMeds(store.patient.medications);
  const log = store.data.chelationLog || {};
  const w7 = ADHV().windowStats(log, meds, 7);
  const w30 = ADHV().windowStats(log, meds, 30);
  const streak = ADHV().streak(log, meds);
  const best = ADHV().longestStreak(log, meds);
  const wk = ADHV().weekdayPattern(log, meds, 30);
  const skips = ADHV().skipBySlot(log, meds, 30);

  // most-skipped slot → gentle nudge
  let topSlot = null, topN = 0;
  Object.keys(skips).forEach((s) => { if (skips[s] > topN) { topN = skips[s]; topSlot = s; } });
  const nudgeTime = topSlot ? (ADHV().SLOT_DEFAULT_TIME[topSlot] || '20:00') : null;

  const barColor = (pct) => pct >= 80 ? 'var(--green)' : pct >= 50 ? 'var(--waiting)' : 'var(--waiting)';

  return (
    <div>
      <button className="sub-back" onClick={onBack}><Icon name="chevL" size={17} color="var(--ink-2)" />Chelation</button>
      <div className="h1" style={{ fontSize: 24, margin: '2px 0 4px' }}>Adherence insights</div>
      <p className="body" style={{ margin: '0 0 16px' }}>A calm look at your recent chelation — to notice patterns, not to grade yourself.</p>

      {/* headline metrics */}
      <div className="ins-grid" style={{ marginBottom: 10 }}>
        <div className="ins-metric">
          <div className="ins-metric-k">Last 7 days</div>
          <div className="ins-metric-v">{w7.taken}<span style={{ fontSize: 14, color: 'var(--ink-3)' }}> / {w7.scheduled}</span></div>
          <div className="ins-metric-sub" style={{ color: barColor(w7.pct) }}>{w7.pct}% of scheduled doses</div>
        </div>
        <div className="ins-metric">
          <div className="ins-metric-k">Last 30 days</div>
          <div className="ins-metric-v">{w30.taken}<span style={{ fontSize: 14, color: 'var(--ink-3)' }}> / {w30.scheduled}</span></div>
          <div className="ins-metric-sub" style={{ color: barColor(w30.pct) }}>{w30.pct}% of scheduled doses</div>
        </div>
        <div className="ins-metric">
          <div className="ins-metric-k">Consistency streak</div>
          <div className="ins-metric-v">{streak}</div>
          <div className="ins-metric-sub">{streak === 1 ? 'dose' : 'doses'} in a row</div>
        </div>
        <div className="ins-metric">
          <div className="ins-metric-k">Longest streak</div>
          <div className="ins-metric-v">{best}</div>
          <div className="ins-metric-sub">best run so far</div>
        </div>
      </div>

      {/* 30-day bar + plain line */}
      <div className="card" style={{ marginBottom: 11 }}>
        <div className="between" style={{ marginBottom: 9 }}>
          <div className="adh-today-k">30-day adherence</div>
          <div className="ins-pct" style={{ color: barColor(w30.pct) }}>{w30.pct}%</div>
        </div>
        <div className="ins-bar"><div className="ins-bar-fill" style={{ width: w30.pct + '%', background: barColor(w30.pct) }} /></div>
        <p className="body" style={{ margin: '11px 0 0', fontSize: 12.5 }}>
          You recorded {w30.taken} of {w30.scheduled} scheduled doses in the last month. This information may be useful to discuss with your care team.
        </p>
      </div>

      {/* weekday pattern */}
      <div className="card" style={{ marginBottom: 11 }}>
        <div className="adh-today-k" style={{ marginBottom: 12 }}>Weekday pattern · last 30 days</div>
        <div className="wk-bars">
          {wk.map((d) => (
            <div key={d.l} className="wk-col">
              <div className="wk-track"><div className="wk-fill" style={{ height: Math.max(6, Math.round(d.pct * 100)) + '%', background: d.scheduled ? barColor(Math.round(d.pct * 100)) : 'var(--hairline-2)' }} /></div>
              <span className="wk-lbl">{d.l[0]}</span>
            </div>
          ))}
        </div>
      </div>

      {/* most-skipped nudge */}
      <div className="card" style={{ marginBottom: 11 }}>
        <div className="row" style={{ gap: 12, alignItems: 'flex-start' }}>
          <span className="ins-leaf"><Icon name="clock" size={18} color="var(--sky-deep)" /></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="adh-today-k">Pattern to notice</div>
            <p className="body" style={{ margin: '5px 0 0', fontSize: 13, color: 'var(--ink)' }}>
              {topSlot
                ? `Your ${topSlot.toLowerCase()} dose is the one most often missed lately — a reminder around ${nudgeTime} may help.`
                : 'No clear pattern of missed doses lately — nicely steady.'}
            </p>
            {topSlot && <button className="ins-nudge" onClick={() => store.openModal('reminders', {})}>Set a reminder<Icon name="chevR" size={13} color="var(--orange)" /></button>}
          </div>
        </div>
      </div>

      <p className="ins-disclaimer">Informational only — not a compliance score.</p>
    </div>
  );
}

/* ============================================================
   REMINDERS & NOTIFICATION SETTINGS  (modal sheet)
   One row per scheduled dose; independent times + on/off.
   Wires to TC.reminders (PWA local-notification layer); the
   Ramadan offset hook is called by the scheduler (no-op today).
   ============================================================ */
function defaultReminderRows(store) {
  const meds = ADHV().chelationMeds(store.patient.medications);
  const rows = [];
  meds.forEach((m) => {
    ADHV().medSlots(m).forEach((slot) => {
      rows.push({ medId: m.id, slot, time: ADHV().slotTime(m, slot), on: true });
    });
  });
  return rows;
}

function RemindersSheet({ store, close }) {
  const saved = store.reminders || {};
  const meds = ADHV().chelationMeds(store.patient.medications);
  const [on, setOn] = React.useState(saved.on !== false);
  const [rows, setRows] = React.useState(saved.rows && saved.rows.length ? saved.rows : defaultReminderRows(store));
  const [snooze, setSnooze] = React.useState(saved.snooze || 15);
  const [sound, setSound] = React.useState(saved.sound || 'chime');

  const setRow = (i, patch) => setRows((rs) => rs.map((r, k) => k === i ? { ...r, ...patch } : r));
  const medName = (id) => { const m = meds.find((x) => x.id === id); return m ? (m.brand || m.name) : 'Medication'; };

  const save = async () => {
    if (on && window.TC.reminders) { try { await window.TC.reminders.requestPermission(); } catch (e) {} }
    store.setReminders({ on, rows, snooze, sound });
    store.showToast(on ? 'Reminders updated' : 'Reminders paused', '🔔');
    close();
  };

  return (
    <MSheet title="Dose reminders" sub="Gentle nudges to log each scheduled dose." onClose={close}>
      <div className="rem-master">
        <span className="rem-leaf" style={{ background: 'var(--orange-wash)', color: 'var(--orange)' }}><Icon name="bell" size={17} color="var(--orange)" /></span>
        <div className="rem-master-tx">
          <div className="rem-master-t">Dose reminders</div>
          <div className="rem-master-d">{on ? `${rows.filter((r) => r.on).length} active` : 'All paused'}</div>
        </div>
        <Switch on={on} onChange={setOn} />
      </div>

      <div className={'rem-body' + (on ? '' : ' off')}>
        <div className="rem-eyebrow" style={{ marginTop: 6 }}>Per-dose times</div>
        {rows.map((r, i) => (
          <div key={r.medId + r.slot} className={'rem-row' + (r.on ? '' : ' muted')}>
            <span className="rem-leaf" style={{ background: 'var(--surface-2)', color: 'var(--orange)' }}><Icon name={ADHV().SLOT_ICON[r.slot] || 'pill'} size={16} color="var(--orange)" /></span>
            <div className="rem-mid">
              <div className="rem-name">{medName(r.medId)} · {r.slot}</div>
              <input className="rem-time" type="time" value={r.time} onChange={(e) => setRow(i, { time: e.target.value })} />
            </div>
            <Switch on={r.on} onChange={(v) => setRow(i, { on: v })} />
          </div>
        ))}

        <div className="rem-eyebrow" style={{ marginTop: 18 }}>Options</div>
        <div className="rem-opt">
          <span className="rem-leaf soft"><Icon name="clock" size={16} color="var(--ink-2)" /></span>
          <div className="rem-mid"><div className="rem-name">Snooze interval</div></div>
          <div className="rem-seg">
            {[5, 15, 30].map((m) => <button key={m} className={snooze === m ? 'on' : ''} onClick={() => setSnooze(m)}>{m}m</button>)}
          </div>
        </div>
        <div className="rem-opt">
          <span className="rem-leaf soft"><Icon name="bell" size={16} color="var(--ink-2)" /></span>
          <div className="rem-mid"><div className="rem-name">Sound</div></div>
          <div className="rem-seg">
            <button className={sound === 'chime' ? 'on' : ''} onClick={() => setSound('chime')}>Soft chime</button>
            <button className={sound === 'silent' ? 'on' : ''} onClick={() => setSound('silent')}>Silent</button>
          </div>
        </div>

        <div className="rem-copy">Reminders say: <b>“Time for your chelation medication.”</b> Tapping one opens today’s check-in.</div>
      </div>

      <button className="btn btn-primary" style={{ width: '100%', marginTop: 18 }} onClick={save}>Save reminders</button>
    </MSheet>
  );
}

/* ============================================================
   CARE-TEAM SHARING SUMMARY  (modal sheet)
   Explicit, opt-in. Routes through the single existing export.
   ============================================================ */
// Dose-level adherence over a day window [from..to] days ago (inclusive).
function rangeStats(log, meds, from, to) {
  let taken = 0, scheduled = 0;
  const today = TC.todayIndex();
  for (let ago = from; ago <= to; ago++) {
    ADHV().scheduledFor(TC.dayIndexToStr(today - ago), meds).forEach((s) => {
      scheduled++;
      const e = log[s.key];
      if (e && e.status === 'taken') taken++;
    });
  }
  return { taken, scheduled, pct: scheduled ? Math.round((taken / scheduled) * 100) : 0 };
}

// Day-level view of the last `days`: which days had ≥1 scheduled dose, and of
// those which had ≥1 taken. Also the longest run of fully-missed scheduled days.
function dayStats(log, meds, days) {
  const today = TC.todayIndex();
  let scheduledDays = 0, loggedDays = 0, missedDays = 0, gap = 0, maxGap = 0;
  for (let ago = days; ago >= 1; ago--) {
    const sched = ADHV().scheduledFor(TC.dayIndexToStr(today - ago), meds);
    if (!sched.length) continue;
    scheduledDays++;
    const anyTaken = sched.some((s) => { const e = log[s.key]; return e && e.status === 'taken'; });
    if (anyTaken) { loggedDays++; gap = 0; }
    else { missedDays++; gap++; if (gap > maxGap) maxGap = gap; }
  }
  return { scheduledDays, loggedDays, missedDays, maxGap };
}

// Ferritin trend + plain-language reading. For ferritin, DOWN is the good
// direction (iron clearing); UP means iron is accumulating.
function ferritinTrend(store) {
  if (!window.MON) return null;
  const test = MON.testById ? MON.testById('ferritin') : null;
  if (!test) return null;
  const logs = store.data.testLogs || [];
  const list = MON.logsFor('ferritin', logs);
  if (!list.length) return null;
  const tr = MON.trendOf(test, logs);
  const last = list[0];
  const latest = MON.numVal(last);
  const dir = tr ? tr.dir : 'flat';
  const word = dir === 'up' ? 'rising' : dir === 'down' ? 'easing down' : 'holding steady';
  const prev = (tr && tr.delta != null) ? Math.round(latest - tr.delta) : null;
  const pctAbs = tr && tr.pct ? Math.round(Math.abs(tr.pct)) : 0;
  return { word, dir, latest, prev, pctAbs, unit: test.unit || 'ng/mL', date: last.date };
}

// Slot-level miss analysis over `days`: which slots get missed, why (skip
// reasons), and how the misses are distributed in time. This is what lets us
// tell a SCHEDULE problem (one slot, spread across the month) apart from a
// LIFE-DISRUPTION (clustered run, often a travel / supply reason).
function missAnalysis(log, meds, days) {
  const today = TC.todayIndex();
  const bySlot = {};        // slot -> { missed, scheduled }
  const reasons = {};       // skipReason -> count
  const missDays = new Set();
  let totalMissed = 0, totalSkips = 0;
  for (let ago = 1; ago <= days; ago++) {
    ADHV().scheduledFor(TC.dayIndexToStr(today - ago), meds).forEach((s) => {
      const slot = s.slot;
      bySlot[slot] = bySlot[slot] || { missed: 0, scheduled: 0 };
      bySlot[slot].scheduled++;
      const e = log[s.key];
      if (!(e && e.status === 'taken')) {
        bySlot[slot].missed++; totalMissed++; missDays.add(ago);
        if (e && e.status === 'skipped' && e.skipReason) { reasons[e.skipReason] = (reasons[e.skipReason] || 0) + 1; totalSkips++; }
      }
    });
  }
  let topSlot = null, topMissed = 0;
  Object.keys(bySlot).forEach((sl) => { if (bySlot[sl].missed > topMissed) { topMissed = bySlot[sl].missed; topSlot = sl; } });
  let topReason = null, topReasonN = 0;
  Object.keys(reasons).forEach((r) => { if (reasons[r] > topReasonN) { topReasonN = reasons[r]; topReason = r; } });
  const topShare = totalMissed ? topMissed / totalMissed : 0;
  const reasonShare = totalSkips ? topReasonN / totalSkips : 0;
  const travel = !!topReason && /away|travel|unavail|supply/i.test(topReason);
  return { bySlot, topSlot, topMissed, totalMissed, topShare, missDaySpread: missDays.size, topReason, reasonShare, travel };
}

function buildAdherenceSummary(store) {
  const meds = ADHV().chelationMeds(store.patient.medications);
  const log = store.data.chelationLog || {};
  const w30 = ADHV().windowStats(log, meds, 30);
  const prev30 = rangeStats(log, meds, 31, 60);
  const streak = ADHV().streak(log, meds);
  const best = ADHV().longestStreak(log, meds);
  const ds = dayStats(log, meds, 30);
  const m = missAnalysis(log, meds, 30);
  const ferritin = ferritinTrend(store);

  // ---- per-drug regimen detail: what they take, the dose, and its adherence ----
  const wKg = store.patient.weightKg || 0;
  const regimen = ADHV().perMedStats(log, meds, 30).map((p) => {
    const med = p.med;
    const chel = TC.findChelator(med.brand) || {};
    const dailyMg = TC.medDailyMg(med);
    const mgPerKg = dailyMg && wKg ? Math.round((dailyMg / wKg) * 10) / 10 : null;
    return {
      generic: chel.chelator || med.name || med.brand,
      brand: med.brand || med.name,
      abbr: chel.abbr || '',
      route: chel.infusion ? 'Infusion' : (chel.route || 'Oral'),
      freqLabel: TC.medFreqLabel(med.frequency),
      doseLabel: TC.medDoseLabel(med),
      dailyMg, mgPerKg,
      doseCat: mgPerKg ? TC.doseCategory(mgPerKg, med.brand) : null,
      taken: p.taken, scheduled: p.scheduled, pct: p.pct,
    };
  });

  // ---- trajectory + pattern classification ----
  const comparable = prev30.scheduled >= 6;
  const improved = comparable && w30.pct - prev30.pct >= 4;
  const declined = comparable && prev30.pct - w30.pct >= 5;
  const high = w30.pct >= 85;
  const traj = improved ? 'up' : declined ? 'down' : 'steady';
  const multiSlot = Object.keys(m.bySlot).length >= 2;
  // systematic: with 2+ daily slots, one slot owns the misses across many days
  // → a timing/schedule problem the doctor can actually act on.
  const systematic = multiSlot && m.totalMissed >= 3 && m.topShare >= 0.55 && m.missDaySpread >= 4 && !!m.topSlot;
  // episodic: misses bunched into a run, or a travel/supply reason dominates.
  const episodic = (ds.maxGap >= 3 || (m.travel && m.reasonShare >= 0.5)) && !systematic;
  // forgetful: a single daily dose that slips evenly across the month (no slot to
  // blame, no single disruption) → a reminder, not a reschedule, is the lever.
  const forgetful = !systematic && !episodic && m.totalMissed >= 3 && m.missDaySpread >= 4;
  const slot = m.topSlot ? m.topSlot.toLowerCase() : null;

  // ---- the headline insight: correlate dosing with the iron trend ----
  let headline;
  if (ferritin && ferritin.dir === 'down') {
    headline = (improved || high)
      ? { tone: 'good', text: `Iron is **easing down** and dosing is the steadiest it's been — the routine is working.` }
      : { tone: 'good', text: `Iron is **easing down**, even with a few missed doses.` };
  } else if (ferritin && ferritin.dir === 'up') {
    if (systematic) headline = { tone: 'watch', text: `Iron is **creeping up**, and most missed doses fall in the ${slot} — timing, not motivation, looks like the gap.` };
    else if (episodic) headline = { tone: 'watch', text: `Iron **ticked up** after a ${m.travel ? 'stretch away from medication' : 'break in routine'} interrupted dosing.` };
    else if (forgetful) headline = { tone: 'watch', text: `Iron is **creeping up** and doses slip fairly evenly through the month — a daily reminder may be the simplest lever.` };
    else if (high) headline = { tone: 'watch', text: `Iron is **rising despite steady dosing** — this may be one to review with the dose, not just the routine.` };
    else headline = { tone: 'watch', text: `Iron is **rising** and dosing has been patchy — worth tightening before the next labs.` };
  } else if (ferritin) {
    headline = { tone: 'neutral', text: `Iron is **holding steady**${high ? ' on consistent dosing' : ''}.` };
  } else if (systematic) {
    headline = { tone: 'watch', text: `Doses mostly slip in the **${slot}** — a schedule that fits the day might close the gap.` };
  } else if (episodic) {
    headline = { tone: 'watch', text: `Routine held up well apart from a **${ds.maxGap}-day break**${m.travel ? ' away from medication' : ''}.` };
  } else if (forgetful) {
    headline = { tone: 'watch', text: `Doses slip **fairly evenly** across the month — a daily nudge might be the simplest fix.` };
  } else if (traj === 'up') {
    headline = { tone: 'good', text: `Dosing is **more consistent** than last month.` };
  } else if (high) {
    headline = { tone: 'good', text: `**Steady, consistent dosing** all month.` };
  } else {
    headline = { tone: 'neutral', text: `A mixed month — some steady stretches, some gaps.` };
  }

  // ---- supporting bullets (interpretive, not just descriptive) ----
  const wins = [];
  if (ds.scheduledDays) wins.push(`Took chelation on **${ds.loggedDays} of ${ds.scheduledDays}** days.`);
  if (improved) wins.push(`Dose adherence up from **${prev30.pct}%** the month before.`);
  if (ferritin && ferritin.dir === 'down') wins.push(`Ferritin is moving in the right direction.`);
  if (ds.maxGap <= 1 && ds.loggedDays) wins.push(`No long gaps between doses.`);
  if (wins.length < 2 && best >= 5) wins.push(`Best run of **${best}** doses in a row.`);

  const challenges = [];
  if (systematic) challenges.push(`Most missed doses (**${m.topMissed} of ${m.totalMissed}**) were in the ${slot} — more about timing than forgetting.`);
  else if (forgetful) challenges.push(`**${ds.missedDays} of ${ds.scheduledDays}** days slipped — spread evenly rather than one bad patch${m.topReason ? `, most often logged “${m.topReason.toLowerCase()}”` : ''}.`);
  else if (m.topSlot && m.totalMissed && multiSlot) challenges.push(`${m.topSlot} doses were the easiest to miss.`);
  if (episodic) challenges.push(`A **${ds.maxGap}-day gap**${m.travel ? ' lined up with being away from medication' : ''} broke an otherwise steady stretch.`);
  else if (!systematic && !forgetful && ds.missedDays > 0) challenges.push(`${ds.missedDays} ${ds.missedDays === 1 ? 'day was' : 'days were'} missed across the month.`);
  if (!challenges.length) challenges.push(`No notable gaps — steady all month.`);

  return { name: store.patient.name, w30, prev30, streak, best, ds, ferritin, regimen, headline, systematic, episodic, forgetful, multiSlot, traj, high, m, topSlot: m.topSlot, slot, wins: wins.slice(0, 3), challenges, meds };
}

// "I'd like help with" prompts, in the patient's voice, seeded from the pattern.
function helpSuggestions(s) {
  const out = [];
  if (s.systematic && s.slot) out.push(`Whether a schedule without a ${s.slot} dose would suit me`);
  else if (s.forgetful) out.push(`A daily reminder that actually gets me to take it`);
  else if (s.slot && s.multiSlot) out.push(`Remembering my ${s.slot} dose`);
  if (s.episodic || s.m.travel) out.push(`A plan for keeping doses going while travelling`);
  if (s.ferritin && s.ferritin.dir === 'up') out.push(`What my rising ferritin means for my chelation`);
  out.push(`Whether my current dose is still right for me`);
  return [...new Set(out)].slice(0, 4);
}

function ferritinLine(f) {
  return `Ferritin ${f.word} — ${f.latest} ${f.unit}${f.prev ? `, from ${f.prev}` : ''}${f.pctAbs ? ` (${f.dir === 'down' ? '−' : f.dir === 'up' ? '+' : '±'}${f.pctAbs}%)` : ''}.`;
}

function regimenLine(r) {
  const dose = [r.doseLabel, r.dailyMg ? `${r.dailyMg} mg/day` : null, r.mgPerKg ? `${r.mgPerKg} mg/kg` : null].filter(Boolean).join(' · ');
  const cat = r.doseCat ? ` (${r.doseCat.label})` : '';
  const name = r.brand && r.brand !== r.generic ? `${r.generic} (${r.brand})` : r.generic;
  return `${name} — ${dose}${cat} — ${r.pct}% taken (${r.taken}/${r.scheduled})`;
}

function summaryText(store) {
  const s = buildAdherenceSummary(store);
  const name = s.name || 'I';
  const strip = (t) => t.replace(/\*\*/g, '');
  const L = [
    `My Chelation Journey — last 30 days`,
    `${name} · ${TC.fmtDate(TC.now())}`,
    ``,
    strip(s.headline.text),
    ``,
    `What went well`,
    ...s.wins.map((w) => `  • ${strip(w)}`),
    ``,
    `Challenges`,
    ...s.challenges.map((c) => `  • ${strip(c)}`),
  ];
  if (s.regimen.length) L.push(``, `My chelation`, ...s.regimen.map((r) => `  • ${regimenLine(r)}`));
  if (s.ferritin) L.push(``, `Iron marker`, `  • ${ferritinLine(s.ferritin)}`);
  return L.join('\n');
}

function ShareAdherenceSheet({ store, close }) {
  const s = React.useMemo(() => buildAdherenceSummary(store), [store]);
  const [copied, setCopied] = React.useState(false);
  const [picker, setPicker] = React.useState(false);

  const writeClip = async (text) => {
    // Try the async Clipboard API, but it rejects in cross-origin iframes /
    // without permission — fall back to a hidden textarea + execCommand.
    if (navigator.clipboard && navigator.clipboard.writeText) {
      try { await navigator.clipboard.writeText(text); return; } catch (e) { /* fall through */ }
    }
    const ta = document.createElement('textarea');
    ta.value = text; ta.style.position = 'fixed'; ta.style.top = '0'; ta.style.opacity = '0';
    document.body.appendChild(ta); ta.focus(); ta.select();
    let ok = false;
    try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
    ta.remove();
    if (!ok) throw new Error('copy-failed');
  };
  const doCopy = async () => {
    try {
      await writeClip(summaryText(store));
      setCopied(true); store.showToast('Summary copied', '📋'); setTimeout(() => setCopied(false), 1800);
    } catch (e) { store.showToast('Couldn’t copy', '⚠️'); }
  };
  const SUBJECT = 'My Chelation Journey — last 30 days';
  // Open a specific messaging channel pre-filled with the summary.
  const openChannel = (kind) => {
    const text = summaryText(store);
    let url;
    if (kind === 'whatsapp') url = `https://wa.me/?text=${encodeURIComponent(text)}`;
    else if (kind === 'sms') url = `sms:?&body=${encodeURIComponent(text)}`;
    else if (kind === 'email') url = `mailto:?subject=${encodeURIComponent(SUBJECT)}&body=${encodeURIComponent(text)}`;
    try {
      if (kind === 'whatsapp') window.open(url, '_blank', 'noopener');
      else window.location.href = url;
      setPicker(false);
    } catch (e) { store.showToast('Couldn’t open that app', '⚠️'); }
  };
  // Native OS share sheet (real phones) — offers every installed app.
  const doNative = async () => {
    try { if (navigator.share) await navigator.share({ title: SUBJECT, text: summaryText(store) }); }
    catch (e) { /* dismissed */ }
    setPicker(false);
  };

  const Section = ({ icon, color, wash, label, children }) => (
    <div className="jsec">
      <div className="jsec-head">
        <span className="jsec-ic" style={{ background: wash }}><Icon name={icon} size={14} color={color} /></span>
        <span className="jsec-t" style={{ color }}>{label}</span>
      </div>
      {children}
    </div>
  );
  const bold = (t) => t.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>');
  const Bullet = ({ color, html, children }) => (
    <div className="jbul">
      <span className="jbul-dot" style={{ background: color }} />
      {html
        ? <span className="jbul-tx" dangerouslySetInnerHTML={{ __html: html }} />
        : <span className="jbul-tx">{children}</span>}
    </div>
  );
  const TONE = {
    good:    { icon: 'sparkle', color: 'var(--success)',  wash: 'var(--green-wash)' },
    watch:   { icon: 'info',    color: 'var(--warning)',  wash: 'var(--warning-wash)' },
    neutral: { icon: 'info',    color: 'var(--sky-deep)', wash: 'var(--sky-wash)' },
  };
  const tone = TONE[s.headline.tone] || TONE.neutral;

  return (
    <MSheet title="Share with your care team" sub="A short, human summary of your last month to bring to your care team." onClose={close}>
      <div className="jcard">
        <div className="jhead">
          <div className="jhead-row">
            <span className="jhead-leaf"><Icon name="heart" size={18} color="var(--success)" /></span>
            <div>
              <div className="jhead-t">{s.name ? `${s.name}’s` : 'My'} Chelation Journey</div>
              <div className="jhead-d">Last 30 days · {TC.fmtDate(TC.now(), { day: 'numeric', month: 'short' })}</div>
            </div>
          </div>
        </div>

        <div className="jbanner" style={{ background: tone.wash }}>
          <span className="jbanner-ic" style={{ background: 'var(--surface)' }}><Icon name={tone.icon} size={17} color={tone.color} /></span>
          <div className="jbanner-t" dangerouslySetInnerHTML={{ __html: bold(s.headline.text) }} />
        </div>

        <Section icon="check" color="var(--success)" wash="var(--green-wash)" label="What went well">
          {s.wins.map((w, i) => <Bullet key={i} color="var(--success)" html={bold(w)} />)}
        </Section>

        <Section icon="info" color="var(--warning)" wash="var(--warning-wash)" label="Challenges">
          {s.challenges.map((c, i) => <Bullet key={i} color="var(--warning)" html={bold(c)} />)}
        </Section>

        <Section icon="pill" color="var(--orange)" wash="var(--orange-wash)" label="My chelation">
          {s.regimen.map((r, i) => (
            <div className="jmed" key={i}>
              <div className="jmed-top">
                <span className="jmed-name">{r.generic}{r.brand && r.brand !== r.generic ? ` · ${r.brand}` : ''}</span>
                {r.abbr && <span className="jmed-abbr">{r.abbr}</span>}
                <span className="jmed-route">{r.route} · {r.freqLabel}</span>
              </div>
              <div className="jmed-dose">
                <b>{r.doseLabel}</b>{r.dailyMg ? ` · ${r.dailyMg} mg/day` : ''}{r.mgPerKg ? ` · ${r.mgPerKg} mg/kg` : ''}
                {r.doseCat && <span className="jdosepill" style={{ background: r.doseCat.wash, color: r.doseCat.color }}>{r.doseCat.label}</span>}
              </div>
              <div className="jmed-adh">
                <span className="jmed-bar"><i style={{ width: r.pct + '%', background: r.pct >= 80 ? 'var(--success)' : 'var(--warning)' }} /></span>
                <span className="jmed-pct">{r.pct}% · {r.taken}/{r.scheduled}</span>
              </div>
            </div>
          ))}
          {s.ferritin && (
            <div className="jmed-dose" style={{ marginTop: 12, paddingTop: 11, borderTop: '1px solid var(--hairline)', color: 'var(--ink-3)' }}>
              <span dangerouslySetInnerHTML={{ __html: bold(`Iron marker — ${ferritinLine(s.ferritin)}`) }} />
            </div>
          )}
        </Section>
      </div>

      {!picker ? (
        <div className="row" style={{ gap: 10, marginTop: 16 }}>
          <button className="btn btn-ghost" style={{ flex: 1 }} onClick={doCopy}><Icon name="copy" size={17} color="var(--ink-2)" />{copied ? 'Copied' : 'Copy'}</button>
          <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => setPicker(true)}><Icon name="share" size={17} color="#fff" />Share…</button>
        </div>
      ) : (
        <div className="jshare">
          <div className="jshare-h">Share with your care team via…</div>
          <div className="jshare-row">
            <button className="jshare-opt" onClick={() => openChannel('whatsapp')}>
              <span className="jshare-ic" style={{ background: '#25D3661F' }}><Icon name="whatsapp" size={23} color="#1FA855" /></span>WhatsApp
            </button>
            <button className="jshare-opt" onClick={() => openChannel('sms')}>
              <span className="jshare-ic" style={{ background: 'var(--sky-wash)' }}><Icon name="sms" size={23} color="var(--sky-deep)" /></span>SMS
            </button>
            <button className="jshare-opt" onClick={() => openChannel('email')}>
              <span className="jshare-ic" style={{ background: 'var(--orange-wash)' }}><Icon name="mail" size={23} color="var(--orange)" /></span>Email
            </button>
            {typeof navigator !== 'undefined' && navigator.share && (
              <button className="jshare-opt" onClick={doNative}>
                <span className="jshare-ic" style={{ background: 'var(--surface-2)' }}><Icon name="share" size={21} color="var(--ink-2)" /></span>More…
              </button>
            )}
          </div>
          <button className="btn btn-ghost" style={{ width: '100%' }} onClick={() => setPicker(false)}>Back</button>
        </div>
      )}
      <p className="ins-disclaimer" style={{ marginTop: 14 }}>Shared only when you choose. Intended to support conversations with your care team — not for ranking or scoring.</p>
    </MSheet>
  );
}

Object.assign(window, { InsightsScreen, RemindersSheet, ShareAdherenceSheet, buildAdherenceSummary, summaryText });
