/* ============================================================
   MUIY 2.0 — Me screen (profile · config · prefs)
   ============================================================ */

function Row({ icon, iconBg, iconColor, label, value, onClick, danger, last }) {
  return (
    <button className="me-row" onClick={onClick} style={{ borderBottom: last ? 'none' : '1.5px solid var(--hairline)' }}>
      <div className="me-ic" style={{ background: iconBg, color: iconColor }}><Icon name={icon} size={18} color={iconColor} /></div>
      <span style={{ flex: 1, textAlign: 'left', fontWeight: 700, fontSize: 14.5, color: danger ? 'var(--orange)' : 'var(--ink)' }}>{label}</span>
      {value && <span className="body" style={{ fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap', flex: 'none' }}>{value}</span>}
      {onClick && <Icon name="chevR" size={17} color="var(--ink-3)" />}
    </button>);

}

/* ---- Plain-language device-save state (honest: local-first, no server).
   "Sync" here just means the automatic local save + offline write queue. ---- */
function deviceSaveState(sync) {
  const online = sync ? sync.online !== false : true;
  const pending = sync && sync.pending || 0;
  if (!online) return { tag: pending > 0 ? `${pending} waiting` : 'Offline', color: 'var(--ink-2)', wash: 'var(--surface-2)', icon: 'cloud' };
  if (pending > 0) return { tag: 'Saving\u2026', color: 'var(--waiting)', wash: 'var(--yellow-wash)', icon: 'refresh' };
  return { tag: 'Automatic', color: 'var(--eligible)', wash: 'var(--eligible-wash)', icon: 'check' };
}

function tcRecordCount(d) {
  return (d.donors || []).length + (d.transfusions || []).length + (d.hbLog || []).length + (d.ferritinLog || []).length + (d.labReports || []).length + ((d.patient && d.patient.medications) || []).length + Object.keys(d.chelationLog || {}).length;
}

/* ---- Unified data-protection card — the single entry point for everything
   about where data lives, how it's saved, and the user's backup copy. It
   replaces the old Account "Backup & Restore" + "Synced" rows and the separate
   bottom "Back up your data" hero, so there's one clear source of truth. ---- */
function DataProtectionCard({ store }) {
  const s = store.settings || {};
  const d = store.data;
  const expDays = s.lastExportedAt ? Math.floor(TC.relDays(s.lastExportedAt)) : null;
  const backedUp = expDays != null && expDays < 14;
  const recordCount = tcRecordCount(d);
  const dev = deviceSaveState(store.sync);
  const headline = backedUp ? 'Your data is protected' : expDays == null ? 'Back up your data' : 'Time for a fresh backup';
  const accent = backedUp ? 'var(--eligible)' : 'var(--orange)';
  const accentWash = backedUp ? 'var(--eligible-wash)' : 'var(--orange-wash)';

  const StatusLine = ({ icon, iconWash, iconColor, label, sub, value, valueColor }) =>
    <div className="row" style={{ gap: 11, padding: '11px 0', alignItems: 'center' }}>
      <div className="me-ic" style={{ width: 30, height: 30, flex: 'none', background: iconWash, color: iconColor }}><Icon name={icon} size={15} color={iconColor} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--ink)' }}>{label}</div>
        <div className="body" style={{ fontSize: 11.5, marginTop: 1 }}>{sub}</div>
      </div>
      <span style={{ fontWeight: 800, fontSize: 12.5, color: valueColor || 'var(--ink-2)', whiteSpace: 'nowrap', flex: 'none' }}>{value}</span>
    </div>;

  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <button className="med-head" onClick={() => store.openModal('dataBackup', {})} style={{ alignItems: 'center' }}>
        <div className="me-ic" style={{ width: 46, height: 46, flex: 'none', background: accentWash, color: accent }}>
          <Icon name="shield" size={23} color={accent} />
        </div>
        <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 16, letterSpacing: '-.01em', color: 'var(--ink)' }}>{headline}</div>
          <div className="body" style={{ fontSize: 12.5, marginTop: 2, lineHeight: 1.4 }}>{recordCount} record{recordCount === 1 ? '' : 's'} · tap to manage &amp; restore</div>
        </div>
        <Icon name="chevR" size={18} color="var(--ink-3)" style={{ flex: 'none' }} />
      </button>
      <div style={{ padding: '0 16px 4px', borderTop: '1.5px solid var(--hairline)' }}>
        <StatusLine icon={dev.icon} iconWash={dev.wash} iconColor={dev.color} label="On this phone" sub="Saved automatically as you go" value={dev.tag} valueColor={dev.color} />
        <div style={{ height: 1.5, background: 'var(--hairline)' }} />
        <StatusLine icon="download" iconWash={backedUp ? 'var(--eligible-wash)' : 'var(--surface-2)'} iconColor={backedUp ? 'var(--eligible)' : 'var(--ink-3)'} label="Backup copy" sub="A file you keep somewhere safe" value={expDays == null ? 'None yet' : TC.relAgo(s.lastExportedAt)} valueColor={expDays == null ? 'var(--orange)' : 'var(--ink-2)'} />
      </div>
    </div>);
}

/* Caregivers / doctors entry — reflects how many have access */
function CaregiversRow({ store }) {
  const list = store.data.caregivers || [];
  const active = list.filter((c) => c.status === 'active').length;
  const invited = list.length - active;
  const sub = list.length === 0 ? 'Invite a parent or doctor' :
    `${active} with access${invited ? ` · ${invited} invited` : ''}`;
  return (
    <button className="me-row" onClick={() => store.openModal('caregivers', {})} style={{ borderBottom: 'none' }}>
      <div className="me-ic" style={{ background: 'var(--orange-wash)', color: 'var(--orange)' }}><Icon name="users" size={18} color="var(--orange)" /></div>
      <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
        <span style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>Caregivers &amp; doctors</span>
        <div className="body" style={{ fontSize: 12, marginTop: 1 }}>{sub}</div>
      </div>
      <Icon name="chevR" size={17} color="var(--ink-3)" />
    </button>);
}

/* Live signed-in identity from the Supabase session. The local store's
   patient.email is never populated by the cloud sign-in flow, so account UI
   must read the session, not the store. user: undefined = still loading,
   null = signed out, else { email, provider, name }. */
function useAuthUser() {
  const cloud = !!(window.TCsb && window.TCsb.isConfigured());
  const [user, setUser] = React.useState(undefined);
  React.useEffect(() => {
    if (!cloud) { setUser(null); return; }
    let alive = true;
    const read = () => {
      window.TCsb.getUser().then((u) => {
        if (!alive) return;
        setUser(u ? {
          email: u.email || '',
          provider: (u.app_metadata && u.app_metadata.provider) || 'email',
          name: (u.user_metadata && (u.user_metadata.full_name || u.user_metadata.name)) || '',
        } : null);
      }).catch(() => { if (alive) setUser(null); });
    };
    read();
    const unsub = window.TCsb.onAuthChange(() => read());
    return () => { alive = false; unsub(); };
  }, [cloud]);
  return { cloud, user };
}

function MeScreen({ store }) {
  const { patient, settings } = store;
  const auth = useAuthUser();
  const age = patient.dob ? Math.floor(TC.relDays(patient.dob) / 365) : null;
  const meds = patient.medications || [];
  const mon = patient.monitoring || {};
  const monSummary = `${mon.thalType || 'TDT'} · ${(mon.sex || patient.sex) === 'female' ? 'Female' : 'Male'}`;

  return (
    <div className="tc-scroll"><div className="tc-page tc-page--top">
      {/* profile header */}
      <div className="me-head stagger">
        <button className="me-id-edit" onClick={() => store.openModal('editProfile', {})} aria-label="Edit profile"><Icon name="edit" size={15} color="var(--ink-2)" /></button>
        <PatientAvatar patient={patient} size={64} />
        <div className="me-id-info">
          <div className="me-id-nrow">
            <span className="me-id-name">{patient.name}</span>
            <BloodBadge group={patient.bloodGroup} size={11} />
          </div>
          <div className="me-id-chips">
            <span className="chip-status" style={{ background: 'var(--surface-2)', color: 'var(--ink-2)' }}>{patient.thalType}</span>
            {age != null && <span className="chip-status" style={{ background: 'var(--surface-2)', color: 'var(--ink-2)' }}>{age} yrs</span>}
          </div>
        </div>
      </div>

      {/* account — identity comes from the live session (see useAuthUser) */}
      <SectionHead title="Account" spark={false} />
      <div className="card" style={{ padding: '4px 16px' }}>
        <button className="me-row" onClick={() => store.openModal('account', {})} style={{ borderBottom: 'none' }}>
          <span className="me-ic" style={{ background: 'var(--surface-2)' }}>
            {auth.user && auth.user.provider !== 'google'
              ? <Icon name="mail" size={19} color="var(--ink-2)" />
              : <GoogleG size={20} />}
          </span>
          <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
            <div className="row" style={{ gap: 7 }}>
              <span style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>
                {!auth.cloud ? 'Account'
                  : auth.user && auth.user.provider !== 'google' ? 'Email account'
                  : 'Google account'}
              </span>
              {auth.cloud && auth.user &&
                <span className="chip-status" style={{ background: 'var(--eligible-wash)', color: 'var(--eligible)' }}>Signed in</span>}
            </div>
            <div className="body" style={{ fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {!auth.cloud ? 'Local mode — data stays on this device'
                : auth.user === undefined ? 'Checking…'
                : auth.user ? (auth.user.email || auth.user.name)
                : 'Not signed in'}
            </div>
          </div>
          <Icon name="chevR" size={17} color="var(--ink-3)" />
        </button>
      </div>

      {/* your data — single source of truth for storage, saving & backup */}
      <SectionHead title="Your data" spark={false} />
      <DataProtectionCard store={store} />

      <MedicalProfileCard store={store} />

      <SectionHead title="Sharing & access" spark={false} />
      <div className="card" style={{ padding: '4px 16px' }}>
        <CaregiversRow store={store} />
      </div>

      <SectionHead title="Message templates" spark={false} />
      <div className="card" style={{ padding: '4px 16px' }}>
        <Row icon="chat" iconBg="var(--green-wash)" iconColor="var(--success)" label="Donation request" onClick={() => store.openModal('template', { which: 'donationRequest' })} />
        <Row icon="heart" iconBg="var(--orange-wash)" iconColor="var(--orange)" label="Thank-you message" onClick={() => store.openModal('template', { which: 'thankYou' })} last />
      </div>

      <SectionHead title="Preferences" spark={false} />
      <div className="card" style={{ padding: '4px 16px' }}>
        <Row icon="moon" iconBg="var(--slate-wash)" iconColor="var(--sky-deep)" label="Theme" value={TC.themeById(TC.resolveThemeId(settings)).name} onClick={() => store.openModal('themePicker', {})} />
        <Row icon="sun" iconBg="var(--orange-wash)" iconColor="var(--orange)" label="Home illustration" value={TC.sceneName ? TC.sceneName(settings.sceneVariant) : (SCENE_VARIANTS.find((v) => v.id === settings.sceneVariant) || SCENE_VARIANTS[0]).name} onClick={() => store.openModal('scenePicker', {})} />
        <ToggleRow icon="bell" iconBg="var(--yellow-wash)" iconColor="var(--waiting)" label="Notifications" sub="Refill, rest-day & transfusion reminders" value={settings.notificationsEnabled} onChange={(v) => store.mutate((d) => {d.settings.notificationsEnabled = v;})} />
        <Row icon="download" iconBg="var(--orange-wash)" iconColor="var(--orange)" label="Get the app & reminders" value={tcStandalone() ? 'Installed' : null} onClick={() => store.openModal('getApp', {})} last />
      </div>

      {/* support */}
      <SectionHead title="Support" spark={false} />
      <div className="card" style={{ padding: '4px 16px' }}>
        <Row icon="info" iconBg="var(--sky-wash)" iconColor="var(--sky-deep)" label="Help & FAQ" onClick={() => store.openModal('help', {})} />
        <Row icon="chat" iconBg="var(--green-wash)" iconColor="var(--success)" label="Send feedback" onClick={() => store.openModal('contactUs', {})} />
        <Row icon="shield" iconBg="var(--surface-2)" iconColor="var(--ink-2)" label="About MUIY" value={`v${TC.APP_VERSION}`} onClick={() => store.openModal('about', {})} last />
      </div>

      {/* sign out */}
      <button className="btn btn-ghost" style={{ width: '100%', marginTop: 16, color: 'var(--orange)', fontWeight: 800, gap: 8 }} onClick={() => store.openModal('confirm', { title: 'Sign out of MUIY?', message: (window.TCsb && window.TCsb.isConfigured())
        ? 'Your records are backed up to your account and will be here when you sign back in. To protect your privacy on shared devices, the copy on this phone is cleared.'
        : 'Your data stays saved on this device and will be here when you sign back in. Export a copy first if you’d like a backup somewhere else.', confirmLabel: 'Sign out', danger: true, onConfirm: () => {store.showToast('Signed out', '👋');store.signOut();} })}><Icon name="logout" size={17} color="var(--orange)" /> Sign out</button>

      <div className="me-foot">
        <div className="body" style={{ marginTop: 8, fontSize: 13, textAlign: 'center' }}>Made with <span style={{ color: 'var(--orange)' }}>♥</span> in 🇲🇻 for ThalFrndz<br />v{TC.APP_VERSION}</div>
      </div>
    </div></div>);

}

/* Google "G" mark — official four-colour, used in the account row */
function GoogleG({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.9 2.4 30.3 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.9 6.2C12.4 13.6 17.7 9.5 24 9.5z" />
      <path fill="#4285F4" d="M46.1 24.6c0-1.6-.1-3.1-.4-4.6H24v9.1h12.4c-.5 2.9-2.1 5.3-4.6 7l7.1 5.5C43.4 37.5 46.1 31.6 46.1 24.6z" />
      <path fill="#FBBC05" d="M10.5 19.4l-7.9-6.2C.9 16.5 0 20.1 0 24s.9 7.5 2.6 10.8l7.9-6.2C9.9 27 9.5 25.5 9.5 24s.4-3 1-4.6z" />
      <path fill="#34A853" d="M24 48c6.3 0 11.6-2.1 15.5-5.7l-7.1-5.5c-2 1.3-4.6 2.1-8.4 2.1-6.3 0-11.6-4.1-13.5-9.9l-7.9 6.2C6.5 42.6 14.6 48 24 48z" />
    </svg>);

}

function ToggleRow({ icon, iconBg, iconColor, label, sub, value, onChange, last }) {
  return (
    <div className="me-row" style={{ borderBottom: last ? 'none' : '1.5px solid var(--hairline)', cursor: 'default' }}>
      <div className="me-ic" style={{ background: iconBg, color: iconColor }}><Icon name={icon} size={18} color={iconColor} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <span style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>{label}</span>
        {sub && <div className="body" style={{ fontSize: 12, marginTop: 1 }}>{sub}</div>}
      </div>
      <button className={'switch' + (value ? ' on' : '')} onClick={() => onChange(!value)}><span className="knob" /></button>
    </div>);

}

/* ---------- live photo resolution (Storage ref → signed URL) ---------- */
// Resolves a stored photo reference (or legacy inline string) to a URL we can
// paint. Inline / already-cached images show on the first frame; a private
// Storage ref is signed asynchronously and swapped in when ready.
function usePhotoUrl(photo) {
  const [url, setUrl] = React.useState(() => window.TCFiles.immediateUrl(photo));
  const key = window.TCFiles.keyOf(photo);
  React.useEffect(() => {
    let live = true;
    window.TCFiles.resolveUrl(photo).then((u) => { if (live) setUrl(u); }).catch(() => {});
    return () => { live = false; };
  }, [key]);
  return url;
}
function PatientAvatar({ patient, size }) {
  const url = usePhotoUrl((patient && (patient.photo || patient.photoUrl)) || null);
  return <Avatar name={(patient && patient.name) || 'You'} size={size} photoUrl={url} />;
}

/* ---------- profile + template + confirm sheets ---------- */
function EditProfileSheet({ store, close }) {
  const p = store.patient;
  const [f, setF] = React.useState({ name: p.name, preferredName: p.preferredName || '', dob: p.dob, sex: p.sex || p.monitoring && p.monitoring.sex || 'female' });
  const existingPhoto = p.photo || p.photoUrl || null;
  const [preview, setPreview] = React.useState(() => window.TCFiles.immediateUrl(existingPhoto));
  const [picked, setPicked] = React.useState(undefined);   // undefined = unchanged · null = removed · File = new
  const [savingPhoto, setSavingPhoto] = React.useState(false);
  const fileRef = React.useRef(null);
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  // resolve a stored ref → signed URL for the live preview (once, on open)
  React.useEffect(() => {
    let live = true;
    window.TCFiles.resolveUrl(existingPhoto).then((u) => { if (live && picked === undefined) setPreview(u); }).catch(() => {});
    return () => { live = false; };
  }, []);
  const onPhoto = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setPicked(file);
    const r = new FileReader();
    r.onload = () => setPreview(String(r.result));
    r.readAsDataURL(file);
  };
  const removePhoto = () => { setPicked(null); setPreview(null); };
  const AV = { bucket: 'avatars', folder: 'profile', kind: 'avatar', name: 'profile.jpg', maxDim: 512, quality: 0.85 };
  const save = async () => {
    if (savingPhoto) return;
    let photoObj = existingPhoto;
    if (picked === null) {
      photoObj = null;                                  // photo removed
    } else if (picked) {
      setSavingPhoto(true);
      photoObj = await window.TCFiles.putImage(picked, AV);   // new photo → Storage (or inline fallback)
      setSavingPhoto(false);
    } else if (typeof existingPhoto === 'string' && existingPhoto && window.TCsb && window.TCsb.isConfigured()) {
      // migrate a legacy inlined base64 avatar up to Storage on next save
      setSavingPhoto(true);
      photoObj = await window.TCFiles.putImage(existingPhoto, AV);
      setSavingPhoto(false);
    }
    store.mutate((d) => {
      d.patient.name = f.name;
      d.patient.preferredName = (f.preferredName || '').trim() || (f.name || '').trim().split(/\s+/)[0];
      d.patient.dob = f.dob;
      d.patient.sex = f.sex;
      d.patient.monitoring = Object.assign({}, d.patient.monitoring, { sex: f.sex });
      d.patient.photo = photoObj || null;
      d.patient.photoUrl = null;                        // legacy base64 field retired
    });
    store.showToast('Profile updated', '🌱');
    close();
  };
  return (
    <Sheet title="Edit profile" onClose={close}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 20 }}>
        <div style={{ position: 'relative' }}>
          <Avatar name={f.name || 'You'} size={88} photoUrl={preview} />
          <button className="icon-btn" onClick={() => fileRef.current && fileRef.current.click()} style={{ position: 'absolute', right: -3, bottom: -3, width: 34, height: 34, borderRadius: '50%', background: 'var(--orange)', color: '#fff', border: '3px solid var(--surface)' }} aria-label="Change photo"><Icon name="edit" size={15} color="#fff" /></button>
        </div>
        <input ref={fileRef} type="file" accept="image/*" onChange={onPhoto} style={{ display: 'none' }} />
        <button className="link" style={{ marginTop: 10, fontSize: 12.5 }} onClick={() => preview ? removePhoto() : fileRef.current && fileRef.current.click()}>{savingPhoto ? 'Uploading…' : (preview ? 'Remove photo' : 'Upload a photo')}</button>
      </div>
      <div className="field"><label className="field-label">Full name</label><input className="input" value={f.name} onChange={(e) => set('name', e.target.value)} /></div>
      <div className="field"><label className="field-label">Preferred name</label><input className="input" value={f.preferredName} onChange={(e) => set('preferredName', e.target.value)} placeholder="What should we call you?" /></div>
      <div className="field"><label className="field-label">Date of birth</label><input className="input" type="date" value={f.dob} onChange={(e) => set('dob', e.target.value)} /></div>
      <div className="field"><label className="field-label">Sex</label>
        <Segmented value={f.sex} onChange={(v) => set('sex', v)} options={[{ value: 'female', label: 'Female' }, { value: 'male', label: 'Male' }]} />
      </div>
      <div className="card-flat row" style={{ padding: '11px 14px', margin: '4px 0 16px', gap: 10 }}>
        <Icon name="info" size={15} color="var(--sky-deep)" style={{ flex: 'none' }} />
        <span className="body" style={{ fontSize: 12 }}>Blood group, thalassaemia type and other medical details live in your <b>Medical Profile</b>.</span>
      </div>
      <div className="row" style={{ gap: 10, marginTop: 4 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1.4, opacity: savingPhoto ? 0.6 : 1 }} disabled={savingPhoto} onClick={save}>{savingPhoto ? 'Saving…' : 'Save'}</button>
      </div>
    </Sheet>);

}

function TemplateSheet({ store, close, which }) {
  const labels = { donationRequest: 'Donation request', thankYou: 'Thank-you message' };
  const [val, setVal] = React.useState((store.patient.messageTemplates || {})[which] || '');
  const save = () => {store.mutate((d) => {d.patient.messageTemplates[which] = val;});store.showToast('Template saved', '✅');close();};
  return (
    <Sheet title={labels[which]} sub="Use [Donor Name] and [Patient Name] as placeholders." onClose={close}>
      <textarea className="input textarea" rows={6} value={val} onChange={(e) => setVal(e.target.value)} />
      <div className="row" style={{ gap: 10, marginTop: 12 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1.4 }} onClick={save}>Save</button>
      </div>
    </Sheet>);

}

function ScenePickerSheet({ store, close }) {
  const current = (store.settings || {}).sceneVariant || 'sprout';
  const [sel, setSel] = React.useState(current);
  const save = () => {store.mutate((d) => {d.settings.sceneVariant = sel;});store.showToast('Home illustration updated', '🎨');close();};
  return (
    <Sheet title="Home illustration" sub="Pick the backdrop for your Today screen." onClose={close}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {SCENE_VARIANTS.map((v) => {
          const on = sel === v.id;
          return (
            <button key={v.id} onClick={() => setSel(v.id)} style={{ border: on ? '2.5px solid var(--orange)' : '2.5px solid transparent', borderRadius: 18, padding: 0, background: 'none', cursor: 'pointer', overflow: 'hidden', textAlign: 'left' }}>
              <div className={'scene scene--' + v.id} style={{ height: 112, borderRadius: '14px 14px 0 0', position: 'relative', overflow: 'hidden' }}>
                {v.id === 'living' ? <LivingSky phase={skyPhase(TC.now().getHours())} /> : <SceneArt variant={v.id} />}
              </div>
              <div style={{ padding: '9px 11px', background: 'var(--surface-2)' }}>
                <div className="row" style={{ justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontWeight: 800, fontSize: 13.5 }}>{v.name}</span>
                  {on && <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--orange)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}><Icon name="check" size={11} color="#fff" sw={3} /></span>}
                </div>
                <div className="body" style={{ fontSize: 11, marginTop: 1 }}>{v.desc}</div>
              </div>
            </button>);

        })}
      </div>
      <div className="row" style={{ gap: 10, marginTop: 16 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1.4 }} onClick={save}>Apply</button>
      </div>
    </Sheet>);

}

/* ---------- theme picker (light/dark palettes) ---------- */
function ThemePickerSheet({ store, close }) {
  const current = TC.resolveThemeId(store.settings || {});
  const [sel, setSel] = React.useState(current);
  const save = () => {store.mutate((d) => {d.settings.theme = sel;d.settings.sceneVariant = TC.themeById(sel).scene || 'living';});if (TC.persistThemeNow) TC.persistThemeNow(sel);store.showToast('Theme updated', '🎨');close();};
  return (
    <Sheet title="Theme" sub="Choose the colour mood of the whole app." onClose={close}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
        {TC.THEMES.map((t) => {
          const on = sel === t.id;
          return (
            <button key={t.id} onClick={() => setSel(t.id)} className="wf-opt" style={on ? { borderColor: 'var(--orange)', background: 'var(--orange-wash)', boxShadow: '0 0 0 3px var(--orange-wash)' } : null}>
              <span style={{ position: 'relative', width: 52, height: 52, flex: 'none', borderRadius: 15, overflow: 'hidden', background: t.sw[2], boxShadow: 'inset 0 0 0 1.5px rgba(0,0,0,.06)' }}>
                <span style={{ position: 'absolute', left: 9, top: 9, width: 20, height: 20, borderRadius: '50%', background: t.sw[0] }} />
                <span style={{ position: 'absolute', right: 8, bottom: 9, width: 16, height: 16, borderRadius: 5, background: t.sw[1] }} />
              </span>
              <span style={{ flex: 1, minWidth: 0 }}>
                <span className="wf-opt-t" style={{ display: 'block' }}>{t.name}</span>
                <span className="wf-opt-d" style={{ display: 'block' }}>{t.desc}</span>
              </span>
              <span className="wf-opt-tick" style={on ? { borderColor: 'var(--orange)', background: 'var(--orange)' } : null}>
                {on && <Icon name="check" size={13} color="#fff" sw={3} />}
              </span>
            </button>);

        })}
      </div>
      <div className="row" style={{ gap: 10, marginTop: 16 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1.4 }} onClick={save}>Apply</button>
      </div>
    </Sheet>);

}

/* ---------- weight (feeds chelation dosing) ---------- */
function WeightSheet({ store, close }) {
  const p = store.patient;
  const [w, setW] = React.useState(p.weightKg ? String(p.weightKg) : '');
  const wKg = parseFloat(w);
  const meds = (p.medications || []).filter((m) => TC.findChelator(m.brand));
  const valid = wKg > 0 && wKg < 250;
  const save = () => {if (!valid) return;store.mutate((d) => {d.patient.weightKg = Math.round(wKg * 10) / 10;});store.showToast('Weight updated', '⚖️');close();};
  return (
    <Sheet title="Body weight" sub="Used to calculate your weight-based chelation dose targets." onClose={close}>
      <div className="field">
        <label className="field-label">Weight</label>
        <div className="row" style={{ gap: 8 }}>
          <input className="input" type="number" inputMode="decimal" step="0.5" value={w} onChange={(e) => setW(e.target.value)} placeholder="e.g. 58" autoFocus />
          <span className="input" style={{ width: 56, flex: 'none', textAlign: 'center', fontWeight: 800, color: 'var(--ink-2)' }}>kg</span>
        </div>
      </div>

      {valid && meds.length > 0 &&
      <div className="card-flat" style={{ padding: '13px 15px', marginBottom: 16 }}>
          <div style={{ fontSize: 11, fontWeight: 900, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--orange)', marginBottom: 10 }}>Target dose at {Math.round(wKg * 10) / 10} kg</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {meds.map((m) => {
            const t = TC.targetDose(m.brand, wKg);
            return (
              <div key={m.id} className="between" style={{ gap: 10 }}>
                  <span className="row" style={{ gap: 9, minWidth: 0 }}><Icon name="pill" size={15} color="var(--orange)" /><span style={{ fontWeight: 700, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.brand}</span></span>
                  <span style={{ fontWeight: 800, fontSize: 13.5, color: 'var(--ink)', whiteSpace: 'nowrap' }}>{t ? `${t.min}–${t.max} mg/day` : '—'}</span>
                </div>);

          })}
          </div>
          <div className="body" style={{ fontSize: 11.5, marginTop: 10 }}>Guideline ranges only — your haematologist sets the actual dose.</div>
        </div>
      }
      {valid && meds.length === 0 &&
      <div className="card-flat" style={{ padding: '11px 14px', marginBottom: 16, display: 'flex', gap: 9, alignItems: 'center' }}>
          <Icon name="info" size={16} color="var(--sky-deep)" />
          <span className="body" style={{ fontSize: 12 }}>Add a chelation medication and we’ll show weight-based dose targets here.</span>
        </div>
      }

      <div className="row" style={{ gap: 10, marginTop: 4 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1.4, opacity: valid ? 1 : 0.5 }} onClick={save}>Save</button>
      </div>
    </Sheet>);

}

/* ---------- account ---------- */
function AccountSheet({ store, close }) {
  const p = store.patient;
  const auth = useAuthUser();
  const email = (auth.user && auth.user.email) || p.email || '';
  const google = !auth.user || auth.user.provider === 'google';
  return (
    <Sheet title="Account" onClose={close}>
      <div className="card-flat" style={{ padding: 16, marginBottom: 16, display: 'flex', gap: 13, alignItems: 'center' }}>
        <PatientAvatar patient={p} size={48} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 15 }}>{p.name}</div>
          <div className="row" style={{ gap: 6, marginTop: 2 }}>
            {google ? <GoogleG size={14} /> : <Icon name="mail" size={14} color="var(--ink-2)" />}
            <span className="body" style={{ fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{email}</span>
          </div>
        </div>
      </div>
      <div className="between" style={{ padding: '4px 0 16px' }}>
        <span className="body" style={{ fontSize: 13.5 }}>Signed in with</span>
        <span className="row" style={{ gap: 6, fontWeight: 700, fontSize: 13.5, color: 'var(--ink)' }}>
          {google ? <React.Fragment><GoogleG size={15} /> Google</React.Fragment>
            : <React.Fragment><Icon name="mail" size={15} color="var(--ink-2)" /> Email code</React.Fragment>}
        </span>
      </div>
      <button className="btn btn-ghost" style={{ width: '100%', marginBottom: 10, gap: 8 }} onClick={() => {close();store.openModal('dataBackup', {});}}><Icon name="shield" size={17} color="var(--sky-deep)" /> Your data &amp; backup</button>
      <button className="btn btn-ghost" style={{ width: '100%', color: 'var(--orange)', fontWeight: 800, gap: 8 }} onClick={() => {close();store.openModal('confirm', { title: 'Sign out of MUIY?', message: (window.TCsb && window.TCsb.isConfigured())
        ? 'Your records are backed up to your account and will be here when you sign back in. To protect your privacy on shared devices, the copy on this phone is cleared.'
        : 'Your data stays saved on this device and will be here when you sign back in. Export a copy first if you’d like a backup somewhere else.', confirmLabel: 'Sign out', danger: true, onConfirm: () => {store.showToast('Signed out', '👋');store.signOut();} });}}><Icon name="logout" size={17} color="var(--orange)" /> Sign out</button>
    </Sheet>);

}

/* ---------- data & backups hub (real export + restore) ---------- */
function DataBackupSheet({ store, close }) {
  const s = store.settings || {};
  const d = store.data;
  const lastExp = s.lastExportedAt ? TC.relAgo(s.lastExportedAt) : 'Never';
  const expDays = s.lastExportedAt ? Math.floor(TC.relDays(s.lastExportedAt)) : null;
  const backedUp = expDays != null && expDays < 14;
  const dev = deviceSaveState(store.sync);
  const fileRef = React.useRef(null);
  const [restore, setRestore] = React.useState(null);

  // every area that lives on this device — what a backup actually protects
  const tiles = [
    { label: 'Donors', n: (d.donors || []).length, icon: 'users', color: 'var(--orange)', wash: 'var(--orange-wash)' },
    { label: 'Transfusions', n: (d.transfusions || []).length, icon: 'drop', color: 'var(--alert)', wash: 'var(--orange-wash)' },
    { label: 'Hb readings', n: (d.hbLog || []).length, icon: 'trendUp', color: 'var(--sky-deep)', wash: 'var(--sky-wash)' },
    { label: 'Ferritin', n: (d.ferritinLog || []).length, icon: 'chart', color: 'var(--success)', wash: 'var(--green-wash)' },
    { label: 'Lab reports', n: (d.labReports || []).length, icon: 'clipboard', color: 'var(--sky-deep)', wash: 'var(--slate-wash)' },
    { label: 'Medications', n: ((d.patient && d.patient.medications) || []).length, icon: 'pill', color: 'var(--orange)', wash: 'var(--orange-wash)' },
    { label: 'Dose logs', n: Object.keys(d.chelationLog || {}).length, icon: 'checkCircle', color: 'var(--success)', wash: 'var(--green-wash)' },
    { label: 'Profile', n: 1, icon: 'user', color: 'var(--ink-2)', wash: 'var(--surface-2)' },
  ];
  const totalRecords = tiles.reduce((a, t) => a + t.n, 0);

  const Cap = ({ children }) => <div style={{ fontSize: 11, fontWeight: 900, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)', margin: '2px 2px 9px' }}>{children}</div>;
  const OptRow = ({ icon, color, wash, label, sub, onClick, danger }) => (
    <button className="me-row" onClick={onClick} style={{ padding: '12px 0', borderBottom: 'none' }}>
      <div className="me-ic" style={{ background: wash, color }}><Icon name={icon} size={18} color={color} /></div>
      <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 14, color: danger ? 'var(--orange)' : 'var(--ink)' }}>{label}</div>
        <div className="body" style={{ fontSize: 12, marginTop: 1, lineHeight: 1.4 }}>{sub}</div>
      </div>
      <Icon name="chevR" size={17} color="var(--ink-3)" style={{ flex: 'none' }} />
    </button>);

  const onFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const r = new FileReader();
    r.onload = () => setRestore(Object.assign({ name: file.name }, store.parseBackup(String(r.result || ''))));
    r.readAsText(file);
    e.target.value = '';
  };
  const doRestore = () => {
    if (!restore || !restore.ok) return;
    const when = restore.meta && restore.meta.exportedAt ? ` (exported ${TC.relAgo(restore.meta.exportedAt)})` : '';
    store.openModal('confirm', { title: 'Restore this backup?', message: `This replaces everything currently in MUIY with the contents of “${restore.name}”${when}. This can’t be undone.`, confirmLabel: 'Restore', danger: true, onConfirm: () => store.restoreData(restore.data) });
  };

  return (
    <Sheet title="Your data" sub="Everything you log is saved on this phone. A backup copy keeps it safe if the phone is ever lost." onClose={close}>
      {/* two clear, separate states: what's saved on the phone vs. your backup copy */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
        {/* 1 — on this phone (automatic, always on) */}
        <div className="card-flat" style={{ padding: '14px 15px', display: 'flex', gap: 13, alignItems: 'center' }}>
          <div className="me-ic" style={{ width: 44, height: 44, flex: 'none', background: dev.wash, color: dev.color }}><Icon name={dev.icon} size={22} color={dev.color} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="row" style={{ gap: 7 }}>
              <span style={{ fontWeight: 800, fontSize: 14.5, color: 'var(--ink)' }}>On this phone</span>
              <span className="chip-status" style={{ background: dev.wash, color: dev.color, flex: 'none' }}>{dev.tag}</span>
            </div>
            <div className="body" style={{ fontSize: 12.5, marginTop: 2, lineHeight: 1.4 }}>Every record is saved here automatically as you go.</div>
          </div>
        </div>

        {/* 2 — backup copy (the file you keep elsewhere) */}
        <div className="card-flat" style={{ padding: '15px 16px', border: `1.5px solid ${backedUp ? 'var(--eligible)' : 'var(--orange)'}`, background: backedUp ? 'var(--eligible-wash)' : 'var(--orange-wash)' }}>
          <div className="row" style={{ gap: 13, alignItems: 'flex-start' }}>
            <div className="me-ic" style={{ width: 44, height: 44, flex: 'none', background: '#fff', color: backedUp ? 'var(--eligible)' : 'var(--orange)' }}>
              <Icon name="shield" size={22} color={backedUp ? 'var(--eligible)' : 'var(--orange)'} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row" style={{ gap: 7 }}>
                <span style={{ fontWeight: 800, fontSize: 14.5, letterSpacing: '-.01em', color: 'var(--ink)' }}>Backup copy</span>
                <span className="chip-status" style={{ background: '#fff', color: backedUp ? 'var(--eligible)' : 'var(--orange)', flex: 'none' }}>{backedUp ? `Saved ${lastExp.toLowerCase()}` : expDays == null ? 'None yet' : 'Out of date'}</span>
              </div>
              <div className="body" style={{ fontSize: 12.5, marginTop: 3, lineHeight: 1.5 }}>{backedUp ? 'A safe copy for a new phone. Make a fresh one whenever you add a lot of records.' : 'If this phone is lost or cleared, anything not backed up is gone. Keep a copy in Drive, iCloud or Downloads.'}</div>
            </div>
          </div>
          <button className="btn btn-primary" style={{ width: '100%', gap: 8, marginTop: 13 }} onClick={() => store.exportData()}><Icon name="download" size={17} color="#fff" /> {expDays == null ? 'Back up now' : 'Back up again'}</button>
        </div>
      </div>

      {/* what's stored */}
      <Cap>On this device · {totalRecords} record{totalRecords === 1 ? '' : 's'}</Cap>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 10 }}>
        {tiles.map((t) =>
        <div key={t.label} className="card-flat" style={{ padding: '11px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div className="me-ic" style={{ width: 32, height: 32, flex: 'none', background: t.wash, color: t.color }}><Icon name={t.icon} size={16} color={t.color} /></div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 800, fontSize: 16, lineHeight: 1, color: 'var(--ink)' }} className="num">{t.n}</div>
              <div className="body" style={{ fontSize: 11.5, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.label}</div>
            </div>
          </div>
        )}
      </div>
      <div className="row" style={{ gap: 8, marginBottom: 18, padding: '0 2px', alignItems: 'flex-start' }}>
        <Icon name="check" size={14} color="var(--eligible)" style={{ flex: 'none', marginTop: 2 }} />
        <span className="body" style={{ fontSize: 11.5, lineHeight: 1.45 }}>All of this — plus your preferences and message templates — is saved automatically and included in every backup.</span>
      </div>

      {/* export */}
      <Cap>Export</Cap>
      <div className="card" style={{ padding: '2px 14px', marginBottom: 18 }}>
        <OptRow icon="download" color="var(--sky-deep)" wash="var(--sky-wash)" label="Full backup (JSON)" sub="Everything above — for a new phone or safe-keeping" onClick={() => store.exportData()} />
        <div style={{ height: 1.5, background: 'var(--hairline)' }} />
        <OptRow icon="grid" color="var(--success)" wash="var(--green-wash)" label="Donor list (CSV)" sub="A spreadsheet of your blood pool to print or share" onClick={() => store.openModal('exportDonors', {})} />
      </div>

      {/* bring data in */}
      <Cap>Bring data in</Cap>
      <div className="card" style={{ padding: '2px 14px', marginBottom: 8 }}>
        <input ref={fileRef} type="file" accept="application/json,.json" onChange={onFile} style={{ display: 'none' }} />
        <OptRow icon="refresh" color="var(--orange)" wash="var(--orange-wash)" label="Restore from a backup" sub="Replace everything here with an exported file" onClick={() => fileRef.current && fileRef.current.click()} />
        <div style={{ height: 1.5, background: 'var(--hairline)' }} />
        <OptRow icon="upload" color="var(--ink-2)" wash="var(--surface-2)" label="Import donors (CSV)" sub="Add donors in bulk from a spreadsheet" onClick={() => store.openModal('import', {})} />
      </div>
      {restore && !restore.ok &&
      <div className="row" style={{ gap: 8, margin: '4px 2px 14px', alignItems: 'flex-start' }}><Icon name="warn" size={15} color="var(--orange)" style={{ flex: 'none', marginTop: 1 }} /><span className="body" style={{ fontSize: 12.5, color: 'var(--orange)' }}>{restore.error}</span></div>}
      {restore && restore.ok &&
      <div style={{ margin: '10px 0 16px' }}>
          <div className="card-flat row" style={{ padding: '11px 13px', marginBottom: 11, gap: 10, alignItems: 'center', background: 'var(--eligible-wash)' }}>
            <Icon name="checkCircle" size={18} color="var(--eligible)" style={{ flex: 'none' }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{restore.name}</div>
              <div className="body" style={{ fontSize: 11.5, marginTop: 1 }}>{restore.meta.donors} donor{restore.meta.donors === 1 ? '' : 's'} · {restore.meta.transfusions} transfusion{restore.meta.transfusions === 1 ? '' : 's'}{restore.meta.exportedAt ? ` · ${TC.relAgo(restore.meta.exportedAt)}` : ''}</div>
            </div>
          </div>
          <button className="btn" style={{ width: '100%', background: 'var(--orange)', color: '#fff', gap: 8 }} onClick={doRestore}><Icon name="refresh" size={16} color="#fff" /> Restore this backup</button>
        </div>}
      <div style={{ height: 10 }} />

      {/* truthful disclosure */}
      <div className="card-flat row" style={{ padding: '11px 14px', gap: 10, alignItems: 'flex-start' }}>
        <Icon name="info" size={15} color="var(--ink-3)" style={{ flex: 'none', marginTop: 1 }} />
        <span className="body" style={{ fontSize: 12, lineHeight: 1.5 }}>MUIY keeps your records on this device only — there’s no MUIY account holding a copy. A backup you’ve actually restored once is the only backup you can trust.</span>
      </div>
    </Sheet>);

}

/* ---------- contact us · feedback ---------- */
const FB_RATINGS = [
{ e: '😠', l: 'Terrible' },
{ e: '🙁', l: 'Bad' },
{ e: '😐', l: 'Okay' },
{ e: '🙂', l: 'Good' },
{ e: '😍', l: 'Awesome!' }];

const FB_LIKES = [
{ icon: 'check', l: 'Easy to use' },
{ icon: 'bell', l: 'Helpful reminders' },
{ icon: 'chart', l: 'Clear lab tracking' },
{ icon: 'sparkle', l: 'Great features' },
{ icon: 'heart', l: 'Calm & caring' }];

function ContactUsSheet({ store, close }) {
  const [rating, setRating] = React.useState(-1);
  const [likes, setLikes] = React.useState([]);
  const [note, setNote] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const toggleLike = (l) => setLikes((s) => s.includes(l) ? s.filter((x) => x !== l) : [...s, l]);

  const submit = async () => {
    if (rating < 0 || sending) return;
    setSending(true);
    const res = window.TCFeedback ? await window.TCFeedback.submit({
      rating,
      ratingLabel: FB_RATINGS[rating] && FB_RATINGS[rating].l,
      likes,
      comment: note,
      googleSubId: store.patient && store.patient.googleSubId,
      appVersion: window.TC && window.TC.APP_VERSION || null
    }) : { ok: true, queued: true };
    close();
    store.showToast(
      res.queued ? 'Saved — we’ll send it once you’re online' : 'Thank you for your feedback!',
      res.queued ? '🤍' : '💛');
  };

  const SectionLabel = ({ icon, children, optional }) =>
  <div className="row" style={{ gap: 9, alignItems: 'center', marginBottom: 12 }}>
      <Icon name={icon} size={19} color="var(--ink-2)" />
      <span style={{ fontWeight: 800, fontSize: 16, letterSpacing: '-.01em', color: 'var(--ink)', flex: 1 }}>{children}</span>
      {optional && <span className="body" style={{ fontSize: 12.5, fontStyle: 'italic' }}>Optional</span>}
    </div>;

  return (
    <Sheet onClose={close}>
      {/* hero banner */}
      <div style={{ background: 'linear-gradient(135deg, var(--green) 0%, var(--success) 100%)', borderRadius: 18, padding: '18px 18px', display: 'flex', alignItems: 'center', gap: 15, boxShadow: '0 8px 22px -10px rgba(77,138,19,.55)' }}>
        <div style={{ width: 54, height: 54, flex: 'none', borderRadius: 15, background: 'rgba(255,255,255,.2)', display: 'grid', placeItems: 'center' }}>
          <Icon name="chat" size={26} color="#fff" />
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 20, letterSpacing: '-.015em', color: '#fff', lineHeight: 1.15 }}>Share your feedback</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,.85)', marginTop: 2 }}>Help us improve MUIY</div>
        </div>
      </div>

      {/* rate */}
      <div style={{ marginTop: 22 }}>
        <SectionLabel icon="heart">Rate your experience</SectionLabel>
        <div style={{ display: 'flex', gap: 6, justifyContent: 'space-between' }}>
          {FB_RATINGS.map((r, i) => {
            const on = rating === i;
            return (
              <button key={i} onClick={() => setRating(i)} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit' }}>
                <span style={{ width: '100%', maxWidth: 56, aspectRatio: '1', borderRadius: '50%', display: 'grid', placeItems: 'center', fontSize: 26, background: on ? 'var(--green-wash)' : 'var(--surface-2)', border: on ? '2px solid var(--green)' : '1.5px solid var(--hairline)', transform: on ? 'scale(1.06)' : 'none', transition: 'all .15s ease' }}>{r.e}</span>
                <span style={{ fontSize: 11.5, fontWeight: 700, color: on ? 'var(--success)' : 'var(--ink-3)' }}>{r.l}</span>
              </button>);
          })}
        </div>
      </div>

      {/* likes */}
      <div style={{ marginTop: 24 }}>
        <SectionLabel icon="check">What did you like?</SectionLabel>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
          {FB_LIKES.map((c) => {
            const on = likes.includes(c.l);
            return (
              <button key={c.l} onClick={() => toggleLike(c.l)} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '11px 16px', borderRadius: 999, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 14, background: on ? 'var(--green-wash)' : 'var(--surface-2)', border: on ? '1.5px solid var(--green)' : '1.5px solid var(--hairline)', color: on ? 'var(--success)' : 'var(--ink)', transition: 'all .15s ease' }}>
                <Icon name={c.icon} size={17} color={on ? 'var(--success)' : 'var(--ink-2)'} />
                {c.l}
              </button>);
          })}
        </div>
      </div>

      {/* comments */}
      <div style={{ marginTop: 24 }}>
        <SectionLabel icon="chat" optional>Additional comments</SectionLabel>
        <textarea className="input textarea" rows={4} maxLength={250} value={note} onChange={(e) => setNote(e.target.value)} placeholder="Tell us more about your experience…" style={{ width: '100%', resize: 'none' }} />
        <div className="body num" style={{ fontSize: 12, textAlign: 'right', marginTop: 4 }}>{note.length}/250</div>
      </div>

      <button className="btn" style={{ width: '100%', marginTop: 18, background: 'var(--green)', color: '#fff', fontSize: 15.5, padding: '15px', opacity: rating < 0 || sending ? 0.55 : 1 }} disabled={rating < 0 || sending} onClick={submit}>{sending ? 'Sending…' : 'Submit feedback'}</button>
    </Sheet>);

}

/* ---------- help & faq · the Help Center now lives in src/help.jsx ---------- */

/* ---------- platform detection (for store-aware rating) ---------- */
function tcPlatform() {
  if (typeof navigator === 'undefined') return 'web';
  const ua = (navigator.userAgent || '').toLowerCase();
  const iOS = /iphone|ipad|ipod/.test(ua) ||
  navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1; // iPadOS
  if (iOS) return 'ios';
  if (/android/.test(ua)) return 'android';
  return 'web';
}

/* ---------- rate MUIY (in-app rating sheet · web/PWA + fallback) ---------- */
const RATE_LABELS = ['', 'Needs work', 'Could be better', 'It’s okay', 'Really good', 'Love it'];
function RateSheet({ store, close }) {
  const [rating, setRating] = React.useState(0); // 1..5
  const [hover, setHover] = React.useState(0);
  const [note, setNote] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const shown = hover || rating;

  const submit = async () => {
    if (rating < 1 || sending) return;
    setSending(true);
    const res = window.TCFeedback ? await window.TCFeedback.submit({
      rating: rating - 1, // 1..5 → 0..4, matching the feedback scale
      ratingLabel: RATE_LABELS[rating],
      likes: [],
      comment: note,
      googleSubId: store.patient && store.patient.googleSubId,
      appVersion: window.TC && window.TC.APP_VERSION || null
    }) : { ok: true, queued: true };
    close();
    store.showToast(
      res.queued ? 'Saved — we’ll send it once you’re online' : 'Thank you for rating MUIY!',
      res.queued ? '🤍' : '💛');
  };

  return (
    <Sheet title="Rate MUIY" sub="Your rating helps us make MUIY better for everyone in the community." onClose={close}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '8px 0 4px' }}>
        <div role="radiogroup" aria-label="Rating" style={{ display: 'flex', gap: 6 }}>
          {[1, 2, 3, 4, 5].map((n) => {
            const on = n <= shown;
            return (
              <button key={n} role="radio" aria-checked={rating === n} aria-label={`${n} star${n > 1 ? 's' : ''}`}
              onClick={() => setRating(n)} onMouseEnter={() => setHover(n)} onMouseLeave={() => setHover(0)}
              style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, lineHeight: 0, fontFamily: 'inherit' }}>
                <span style={{ fontSize: 38, color: on ? 'var(--orange)' : 'var(--hairline)', transition: 'color .12s, transform .12s', transform: on ? 'scale(1.04)' : 'none' }}>★</span>
              </button>);
          })}
        </div>
        <div className="body" style={{ fontSize: 14, fontWeight: 700, minHeight: 20, marginTop: 6, color: shown ? 'var(--orange)' : 'var(--ink-3)' }}>
          {shown ? RATE_LABELS[shown] : 'Tap a star to rate'}
        </div>
      </div>

      <div style={{ marginTop: 14 }}>
        <label className="field-label">Add a review <span className="body" style={{ fontStyle: 'italic', fontWeight: 400 }}>· optional</span></label>
        <textarea className="input textarea" rows={4} maxLength={250} value={note} onChange={(e) => setNote(e.target.value)} placeholder="What’s working well, or what would you change?" style={{ width: '100%', resize: 'none' }} />
        <div className="body num" style={{ fontSize: 12, textAlign: 'right', marginTop: 4 }}>{note.length}/250</div>
      </div>

      <button className="btn" style={{ width: '100%', marginTop: 16, background: 'var(--orange)', color: '#fff', fontSize: 15.5, padding: '15px', opacity: rating < 1 || sending ? 0.55 : 1 }} disabled={rating < 1 || sending} onClick={submit}>{sending ? 'Sending…' : 'Submit rating'}</button>
    </Sheet>);
}

/* ---------- privacy & data (real, architecture-accurate) ---------- */
function PrivacyPoint({ q, children }) {
  return (
    <div style={{ padding: '13px 0', borderBottom: '1.5px solid var(--hairline)' }}>
      <div style={{ fontWeight: 800, fontSize: 14, letterSpacing: '-.01em', marginBottom: 5 }}>{q}</div>
      <div className="body" style={{ fontSize: 13, lineHeight: 1.55 }}>{children}</div>
    </div>);
}
function PrivacyDataSheet({ store, close }) {
  const lastUpdated = 'June 2026';
  const contact = (window.MUI_PRIVACY_CONTACT || '').trim();
  const openContact = () => {
    if (contact) {window.location.href = `mailto:${contact}?subject=${encodeURIComponent('MUIY privacy question')}`;return;}
    close();store.openModal('contactUs', {});
  };

  // honest at-rest line for the local-first build
  const atRest = 'Your data is stored in this device’s local storage. This build does not encrypt it on disk, so keep your device protected with its own screen lock.';

  return (
    <Sheet title="Privacy & data" onClose={close}>
      {/* summary banner */}
      <div style={{ background: 'var(--slate-wash)', borderRadius: 16, padding: '15px 16px', display: 'flex', gap: 13, alignItems: 'flex-start' }}>
        <div style={{ width: 42, height: 42, flex: 'none', borderRadius: 12, background: 'var(--surface)', display: 'grid', placeItems: 'center', boxShadow: 'var(--sh-sm)' }}>
          <Icon name="shield" size={22} color="var(--sky-deep)" />
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 15, letterSpacing: '-.01em' }}>Your health data stays on your device</div>
          <div className="body" style={{ fontSize: 12.5, marginTop: 3, lineHeight: 1.5 }}>MUIY is a local-first app. Your records are not uploaded to a MUIY account — they live in this device’s storage and only leave it if you export a copy yourself.</div>
        </div>
      </div>

      <div style={{ marginTop: 6 }}>
        <PrivacyPoint q="What personal information we collect">
          Only what you enter to set up your profile: your name and preferred name, date of birth and sex, and — if you sign in with Google — your Google account email and ID. There is no tracking, advertising, or background data collection.
        </PrivacyPoint>

        <PrivacyPoint q="What health information is stored">
          Everything you log: your medical profile (thalassaemia type, transfusion pattern, blood group, splenectomy status, body weight, treatment centre), your transfusion records, haemoglobin and ferritin results, chelation medications and dose history, lab results across the monitoring panel, and any lab-report files you import.
        </PrivacyPoint>

        <PrivacyPoint q="How lab reports, transfusions, ferritin, donors & your profile are handled">
          Lab-report photos and PDFs are read on your device to pull out values — the files and the numbers are saved locally, never sent to a MUIY server. Transfusion records, ferritin and other results, your medical profile, and your donor pool (donor names, phone numbers, blood groups and donation history) are all stored together in this device’s local storage. Donor details are other people’s information that you hold — see your responsibilities below.
        </PrivacyPoint>

        <PrivacyPoint q="Where your data is stored">
          In your device’s browser storage (local-first). There is no cloud account syncing your health records in this version, so your data lives on this one device. If you clear the browser’s data, uninstall, or lose the device, anything you haven’t exported is gone — so keep a backup (see below).
        </PrivacyPoint>

        <PrivacyPoint q="Is my data encrypted — in transit and at rest?">
          <b>At rest:</b> {atRest}<br /><br />
          <b>In transit:</b> MUIY doesn’t transmit your health records at all. The only thing that ever leaves your device is feedback you choose to send (your rating, what you liked, your written comment, the app version and your browser/device type) — and that is sent over an encrypted HTTPS connection. It never includes your health records, donors, or lab data.
        </PrivacyPoint>

        <PrivacyPoint q="Who can access your data">
          Only you, on this device. No MUIY staff can see your health records, donors, or labs — we have no copy of them. The only information our team can see is feedback you deliberately submit through the app.
        </PrivacyPoint>

        <PrivacyPoint q="Do we share data with third parties?">
          No. MUIY does not sell, rent, or share your information, and contains no third-party advertising or analytics trackers. The only third party involved is the secure database that stores the feedback you submit; it receives nothing else.
        </PrivacyPoint>

        <PrivacyPoint q="Exporting or deleting your data">
          You’re in full control. <b>Me → Data → Export a copy</b> saves a complete JSON file you can keep as a backup or move to another phone. <b>Me → Data → Clear all data</b> permanently erases everything on this device — this can’t be undone.
        </PrivacyPoint>

        <PrivacyPoint q="Your responsibilities">
          MUIY is a self-management companion, not a medical device — it doesn’t replace your care team, and dosing or eligibility figures are estimates to discuss with your clinician. Please keep your details accurate, and only add a donor’s contact information with their agreement, removing it if they ask.
        </PrivacyPoint>

        <div style={{ padding: '13px 0 2px' }}>
          <div style={{ fontWeight: 800, fontSize: 14, letterSpacing: '-.01em', marginBottom: 5 }}>Questions about privacy?</div>
          <div className="body" style={{ fontSize: 13, lineHeight: 1.55, marginBottom: 11 }}>
            {contact ?
            <>Email us at <b>{contact}</b>, or reach the team through the in-app feedback form.</> :
            <>Reach the team through the in-app feedback form and we’ll get back to you.</>}
          </div>
          <button className="btn btn-ghost" style={{ width: '100%', gap: 8 }} onClick={openContact}>
            <Icon name="chat" size={17} color="var(--green)" /> {contact ? 'Contact us about privacy' : 'Send a privacy question'}
          </button>
        </div>
      </div>

      <div className="body" style={{ fontSize: 11.5, textAlign: 'center', marginTop: 16, color: 'var(--ink-3)' }}>Last updated {lastUpdated} · MUIY v{TC.APP_VERSION}</div>
    </Sheet>);
}

/* ---------- about ---------- */
function AboutSheet({ store, close }) {
  const Link = ({ icon, label, sub, onClick, last }) =>
  <button className="me-row" onClick={onClick} style={{ borderBottom: last ? 'none' : '1.5px solid var(--hairline)', paddingLeft: 4, paddingRight: 4 }}>
      <div className="me-ic" style={{ background: 'var(--surface-2)', color: 'var(--ink-2)' }}><Icon name={icon} size={18} color="var(--ink-2)" /></div>
      <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
        <span style={{ fontWeight: 700, fontSize: 14.5 }}>{label}</span>
        {sub && <div className="body" style={{ fontSize: 12 }}>{sub}</div>}
      </div>
      <Icon name="chevR" size={16} color="var(--ink-3)" />
    </button>;

  // Store-aware rating: open the platform store's review page when published,
  // otherwise (web/PWA, no listing yet, or a blocked/failed open) fall back to
  // the in-app rating sheet so the button always does something useful.
  const rate = () => {
    const cfg = window.MUI_STORE || {};
    const plat = tcPlatform();
    const url = plat === 'ios' ? cfg.ios || '' : plat === 'android' ? cfg.android || '' : '';
    if (url) {
      try {
        const win = window.open(url, '_blank', 'noopener,noreferrer');
        if (win) {store.showToast('Opening the app store…', '💛');close();return;}
      } catch (e) {/* fall through to in-app rating */}
    }
    close();
    store.openModal('rate', {});
  };

  return (
    <Sheet title="About MUIY" onClose={close}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', padding: '2px 0 18px' }}>
        <Pearl size={100} />
        <div className="h2" style={{ marginTop: 8, color: 'var(--ink)', opacity: 0.7 }} aria-label="MUIY">MUIY</div>
        <div className="body" style={{ fontSize: 13 }}>Version {TC.APP_VERSION}</div>
        <div className="body" style={{ fontSize: 12.5, marginTop: 6, color: 'var(--ink-3)' }}>Muiy (މުތް) — Dhivehi for 'pearl.'<br />Named in memory of our friend Muiz (Mui)</div>
        <div className="body" style={{ fontSize: 13, marginTop: 12, lineHeight: 1.6, maxWidth: 290 }}>A self-management companion for people living with transfusion-dependent thalassaemia — manage donors, transfusions, iron and labs in one calm place.</div>
      </div>
      <div style={{ marginBottom: 4 }}>
        <Link icon="heart" label="Rate MUIY" sub="Tell us how we’re doing" onClick={rate} />
        <Link icon="candle" label="In memory" sub="Muiz &amp; our remembrance wall" onClick={() => {close();store.openModal('tribute', {});}} />
        <Link icon="chat" label="Send feedback" sub="Share an idea or report a problem" onClick={() => {close();store.openModal('contactUs', {});}} />
        <Link icon="shield" label="Privacy & data" sub="What we store and how it’s protected" onClick={() => {close();store.openModal('privacyData', {});}} />
        <Link icon="clipboard" label="Terms of Service" sub="The agreement for using MUIY" onClick={() => {close();store.openModal('terms', {});}} last />
      </div>
      <div className="body" style={{ fontSize: 12, textAlign: 'center', marginTop: 16 }}>Made with <span style={{ color: 'var(--orange)' }}>♥</span> in 🇲🇻 for ThalFrndz<br />v{TC.APP_VERSION}</div>
      <button type="button" onClick={() => {close();store.openModal('tribute', {});}} className="body" style={{ display: 'block', width: '100%', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, textAlign: 'center', marginTop: 10, color: 'var(--ink-3)', lineHeight: 1.5 }}>Dedicated to our thal friends who left us too soon.<br />Forever part of our story. ❤️</button>
    </Sheet>);

}

/* ============================================================
   MEDICAL PROFILE — single source of truth (consolidated card)
   ============================================================ */
function medProfileFields(p) {
  const mon = p.monitoring || {};
  const nMed = (p.medications || []).length;
  return [
  { key: 'thalType', icon: 'drop', iconBg: 'var(--orange-wash)', iconColor: 'var(--orange)', label: 'Thalassaemia type', value: p.thalType ? p.thalType.replace('-thalassaemia', '-thal') : null, done: !!p.thalType },
  { key: 'transfusionStatus', icon: 'drop', iconBg: 'var(--sky-wash)', iconColor: 'var(--sky-deep)', label: 'Transfusion pattern', value: mon.thalType || null, done: !!mon.thalType },
  { key: 'bloodGroup', icon: 'heart', iconBg: 'var(--orange-wash)', iconColor: 'var(--orange)', label: 'Blood group', value: p.bloodGroup || null, done: !!p.bloodGroup },
  { key: 'splenectomy', icon: 'shield', iconBg: 'var(--slate-wash)', iconColor: 'var(--sky-deep)', label: 'Splenectomy', value: mon.splenectomy != null ? mon.splenectomy ? 'Yes' : 'No' : null, done: mon.splenectomy != null },
  { key: 'weight', icon: 'chart', iconBg: 'var(--green-wash)', iconColor: 'var(--success)', label: 'Body weight', value: p.weightKg ? `${p.weightKg} kg` : null, done: !!p.weightKg },
  { key: 'treatmentCenter', icon: 'clipboard', iconBg: 'var(--sky-wash)', iconColor: 'var(--sky-deep)', label: 'Transfusion centre', value: p.treatmentCenter || null, done: !!p.treatmentCenter, opt: true },
  { key: 'interval', icon: 'calendar', iconBg: 'var(--yellow-wash)', iconColor: 'var(--waiting)', label: 'Usual interval', value: p.usualTransfusionInterval || null, done: !!p.usualTransfusionInterval, opt: true },
  { key: 'medications', icon: 'pill', iconBg: 'var(--yellow-wash)', iconColor: 'var(--waiting)', label: 'Chelation therapy', value: nMed ? `${nMed} med${nMed > 1 ? 's' : ''}` : null, done: nMed > 0, opt: true }];

}

function CompletionRing({ pct, size = 54, stroke = 5 }) {
  const r = (size - stroke) / 2,c = 2 * Math.PI * r,off = c * (1 - pct / 100);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flex: 'none' }}>
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--hairline)" strokeWidth={stroke} />
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--orange)" strokeWidth={stroke} strokeLinecap="round"
      strokeDasharray={c} strokeDashoffset={off} transform={`rotate(-90 ${size / 2} ${size / 2})`}
      style={{ transition: 'stroke-dashoffset .55s cubic-bezier(.22,1,.36,1)' }} />
      <text x="50%" y="50%" dominantBaseline="central" textAnchor="middle" style={{ fontSize: 14.5, fontWeight: 800, fill: 'var(--ink)', fontFamily: 'inherit' }}>{pct}%</text>
    </svg>);

}

function MedicalProfileCard({ store }) {
  const p = store.patient;
  const fields = medProfileFields(p);
  const done = fields.filter((x) => x.done).length;
  const pct = Math.round(done / fields.length * 100);
  const open = (field) => store.openModal('medicalProfile', { field });
  const rowClick = (fk) => fk === 'medications' ? store.goHealth('chelation') : fk === 'weight' ? store.openModal('weight', {}) : open(fk);
  const [expanded, setExpanded] = React.useState(false);
  return (
    <React.Fragment>
      <SectionHead title="Medical profile" spark={false} />
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <button className="med-head" onClick={() => setExpanded((v) => !v)} aria-expanded={expanded}>
          <CompletionRing pct={pct} />
          <div style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
            <div style={{ fontWeight: 800, fontSize: 16, letterSpacing: '-.01em', color: 'var(--ink)' }}>Medical Profile</div>
            <div className="body" style={{ fontSize: 12.5, marginTop: 2, lineHeight: 1.4 }}>{pct === 100 ? 'Complete · your single source of truth' : `${pct}% complete · ${done} of ${fields.length} details added`}</div>
          </div>
          <span
            role="button" tabIndex={0}
            className="chip-status"
            style={{ background: 'var(--orange-wash)', color: 'var(--orange)', flex: 'none', gap: 5 }}
            onClick={(e) => { e.stopPropagation(); open(null); }}
            onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); open(null); } }}>
            <Icon name="edit" size={12} color="var(--orange)" /> Edit
          </span>
          <Icon name="chevD" size={18} color="var(--ink-3)" style={{ flex: 'none', marginLeft: 2, transition: 'transform .22s cubic-bezier(.22,1,.36,1)', transform: expanded ? 'rotate(180deg)' : 'none' }} />
        </button>
        {expanded &&
        <div style={{ padding: '0 16px', borderTop: '1.5px solid var(--hairline)' }}>
          {fields.map((fld, i) =>
          <Row key={fld.key} icon={fld.icon} iconBg={fld.iconBg} iconColor={fld.iconColor} label={fld.label}
          value={fld.value || 'Add'} onClick={() => rowClick(fld.key)} last={i === fields.length - 1} />
          )}
        </div>
        }
      </div>
    </React.Fragment>);

}

/* full medical-profile editor — opened from the card or any of its rows */
function MedicalProfileSheet({ store, close, field }) {
  const p = store.patient;
  const mon = p.monitoring || {};
  const [f, setF] = React.useState({
    thalType: p.thalType || '', transfusionStatus: mon.thalType || 'TDT',
    bloodGroup: p.bloodGroup || '', splenectomy: !!mon.splenectomy,
    weight: p.weightKg ? String(p.weightKg) : '', treatmentCenter: p.treatmentCenter || '',
    interval: p.usualTransfusionInterval || ''
  });
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  const THAL = WF_THAL.map((t) => t.v);
  const save = () => {
    store.mutate((d) => {
      const pt = d.patient;
      pt.thalType = f.thalType;
      pt.bloodGroup = f.bloodGroup;
      const w = parseFloat(f.weight);if (w > 0) pt.weightKg = Math.round(w * 10) / 10;
      pt.treatmentCenter = (f.treatmentCenter || '').trim() || null;
      pt.usualTransfusionInterval = f.interval || null;
      const im = WF_INTERVALS.find((it) => it.v === f.interval);if (im && im.w) pt.transfusionFrequencyWeeks = im.w;
      pt.monitoring = Object.assign({}, pt.monitoring, { thalType: f.transfusionStatus, splenectomy: f.splenectomy });
    });
    store.showToast('Medical profile updated', '🌱');close();
  };
  return (
    <MSheet title="Medical Profile" sub="Your single source of truth — this powers reminders, forecasts and insights." onClose={close}>
      <div className="field"><label className="field-label">Thalassaemia type</label>
        <div style={{ position: 'relative' }}>
          <select className="input" value={f.thalType} onChange={(e) => set('thalType', e.target.value)} style={{ paddingRight: 38 }} autoFocus={field === 'thalType'}>
            <option value="" disabled>Select your type</option>
            {THAL.map((t) => <option key={t} value={t}>{t}</option>)}
          </select>
          <Icon name="chevD" size={18} color="var(--ink-3)" style={{ position: 'absolute', right: 13, top: 15, pointerEvents: 'none' }} />
        </div>
      </div>
      <div className="field"><label className="field-label">Transfusion pattern</label>
        <Segmented value={f.transfusionStatus} onChange={(v) => set('transfusionStatus', v)} options={[{ value: 'TDT', label: 'Transfusion-dependent' }, { value: 'NTDT', label: 'Non-dependent' }]} />
      </div>
      <div className="field"><label className="field-label">Blood group</label>
        <BloodGrid value={f.bloodGroup} onChange={(v) => set('bloodGroup', v)} />
      </div>
      <div className="field"><label className="field-label">Splenectomy</label>
        <Segmented value={f.splenectomy} onChange={(v) => set('splenectomy', v)} options={[{ value: false, label: 'No' }, { value: true, label: 'Yes' }]} />
      </div>
      <div className="field"><label className="field-label">Body weight</label>
        <div className="row" style={{ gap: 8 }}>
          <input className="input" type="number" inputMode="decimal" step="0.5" value={f.weight} onChange={(e) => set('weight', e.target.value)} placeholder="e.g. 58" autoFocus={field === 'weight'} />
          <span className="input" style={{ width: 56, flex: 'none', textAlign: 'center', fontWeight: 800, color: 'var(--ink-2)' }}>kg</span>
        </div>
      </div>
      <div className="field"><label className="field-label">Transfusion centre <span style={{ color: 'var(--ink-3)', fontWeight: 700 }}>· optional</span></label>
        <input className="input" value={f.treatmentCenter} onChange={(e) => set('treatmentCenter', e.target.value)} placeholder="e.g. Maldivian Blood Services" autoFocus={field === 'treatmentCenter'} />
      </div>
      <div className="field"><label className="field-label">Usual transfusion interval <span style={{ color: 'var(--ink-3)', fontWeight: 700 }}>· optional</span></label>
        <div style={{ position: 'relative' }}>
          <select className="input" value={f.interval} onChange={(e) => set('interval', e.target.value)} style={{ paddingRight: 38 }} autoFocus={field === 'interval'}>
            <option value="">Not set</option>
            {WF_INTERVALS.map((it) => <option key={it.v} value={it.v}>{it.v}</option>)}
          </select>
          <Icon name="chevD" size={18} color="var(--ink-3)" style={{ position: 'absolute', right: 13, top: 15, pointerEvents: 'none' }} />
        </div>
      </div>
      <div className="card-flat row" style={{ padding: '11px 14px', marginBottom: 16, gap: 10 }}>
        <Icon name="pill" size={15} color="var(--orange)" style={{ flex: 'none' }} />
        <span className="body" style={{ fontSize: 12 }}>Manage chelation medication &amp; dosing under <b>Health → Chelation</b>.</span>
      </div>
      <div className="row" style={{ gap: 10, marginTop: 4 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1.4 }} onClick={save}>Save</button>
      </div>
    </MSheet>);

}

Object.assign(window, { MeScreen, EditProfileSheet, TemplateSheet, ScenePickerSheet, ThemePickerSheet, WeightSheet, AccountSheet, DataBackupSheet, ContactUsSheet, AboutSheet, RateSheet, PrivacyDataSheet, GoogleG, MedicalProfileCard, MedicalProfileSheet, CompletionRing });