
// CoParent — Flow screens: Journal, Health log, Travel notice, Tone check,
// Reimbursement, House rules, Onboarding, App lock.

// ─── Journal — shared photo & note log ───────────────────────────────────────
function JournalScreen({ t, base, onBack }) {
  const items = COPARENT_DATA.journal;
  const [filter, setFilter] = React.useState('all');
  const [composing, setComposing] = React.useState(false);
  const [draft, setDraft] = React.useState('');
  const [draftChild, setDraftChild] = React.useState('Emma');
  const visible = filter === 'all' ? items : items.filter(i => i.child === filter);

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 24px', position: 'relative' }}>
      <BackHeader title="Journal" subtitle="Shared moments · 4 entries" t={t} base={base} onBack={onBack} />

      {/* Child filter */}
      <div style={{ padding: '14px 22px 0', display: 'flex', gap: 8 }}>
        {['all', 'Emma', 'Liam'].map(f => (
          <div key={f} onClick={() => setFilter(f)} style={{
            padding: '7px 14px', borderRadius: 16, fontSize: 13, fontWeight: 600,
            background: filter === f ? t.text : t.bgSecondary,
            color: filter === f ? t.bg : t.subtext, cursor: 'pointer' }}>
            {f === 'all' ? 'Both' : f}
          </div>
        ))}
      </div>

      {/* Timeline */}
      <div style={{ padding: '24px 22px 0', position: 'relative' }}>
        <div style={{ position: 'absolute', left: 32, top: 24, bottom: 0, width: 1, background: t.divider }} />
        {visible.map((j, i) => {
          const child = COPARENT_DATA.children.find(c => c.name === j.child);
          return (
            <div key={j.id} style={{ position: 'relative', display: 'flex', gap: 16, paddingBottom: 24 }}>
              <div style={{ width: 22, height: 22, borderRadius: 11, background: child.color,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 800, color: '#fff', flexShrink: 0,
                marginLeft: -1, zIndex: 1, boxShadow: `0 0 0 4px ${t.bg}` }}>
                {j.child[0]}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{j.author}</div>
                  <div style={{ fontSize: 12, color: t.subtext }}>{j.date}</div>
                </div>
                <div style={{ background: t.bgSecondary, borderRadius: 14, padding: '14px 16px' }}>
                  <div style={{ fontSize: 14, color: t.text, lineHeight: 1.55 }}>
                    <span style={{ marginRight: 6 }}>{j.mood}</span>{j.text}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {!composing && <FloatingPlus base={base} onClick={() => setComposing(true)} />}

      {composing && (
        <CalmBottomSheet t={t} onClose={() => setComposing(false)}>
          <div style={{ fontSize: 22, fontWeight: 800, color: t.text, marginBottom: 4, letterSpacing: -0.3 }}>New entry</div>
          <div style={{ fontSize: 13, color: t.subtext, marginBottom: 18 }}>Shared with Jordan</div>
          <CalmSectionLabel label="About" t={t} />
          <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
            {COPARENT_DATA.children.map(c => {
              const sel = c.name === draftChild;
              return (
                <div key={c.id} onClick={() => setDraftChild(c.name)} style={{
                  flex: 1, padding: '12px 0', textAlign: 'center', borderRadius: 12,
                  background: sel ? t.bgSecondary : 'transparent',
                  border: `1px solid ${sel ? t.text : t.divider}`,
                  color: t.text, fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>{c.name}</div>
              );
            })}
          </div>
          <textarea value={draft} onChange={e => setDraft(e.target.value)}
            placeholder="A moment, a milestone, a quick note…"
            style={{ width: '100%', minHeight: 110, background: t.bgSecondary, border: 'none',
              outline: 'none', padding: 14, borderRadius: 12, fontSize: 15, color: t.text,
              fontFamily: 'inherit', resize: 'none', lineHeight: 1.5, marginBottom: 14 }} />
          <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
            {['📷 Photo', '🎤 Voice', '🎉', '🩺', '🎨', '⚽'].map(a => (
              <div key={a} style={{ padding: '8px 12px', borderRadius: 10, background: t.bgSecondary,
                fontSize: 13, color: t.text, cursor: 'pointer' }}>{a}</div>
            ))}
          </div>
          <PrimaryButton label="Post to journal" base={base} onClick={() => setComposing(false)} />
        </CalmBottomSheet>
      )}
    </div>
  );
}

// ─── Health log ──────────────────────────────────────────────────────────────
function HealthLogScreen({ t, base, onBack }) {
  const items = COPARENT_DATA.healthLog;
  const [sheet, setSheet] = React.useState(null);
  const sevColor = (s) => s === 'high' ? base.red : s === 'med' ? base.amber : base.green;
  const kindLabel = { med: 'Medication', visit: 'Visit', fever: 'Fever', allergy: 'Allergy' };

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 24px', position: 'relative' }}>
      <BackHeader title="Health log" subtitle={`${items.length} entries · last 30 days`} t={t} base={base} onBack={onBack} />

      {/* Stat row */}
      <div style={{ padding: '20px 22px 0', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
        {[
          { l: 'Meds given', v: '7' },
          { l: 'Doctor visits', v: '2' },
          { l: 'Sick days', v: '3' },
        ].map(s => (
          <div key={s.l} style={{ background: t.bgSecondary, borderRadius: 14, padding: 14 }}>
            <div style={{ fontSize: 11, color: t.subtext, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>{s.l}</div>
            <div style={{ fontSize: 22, fontWeight: 800, color: t.text, marginTop: 4 }}>{s.v}</div>
          </div>
        ))}
      </div>

      {/* Entries */}
      <div style={{ padding: '24px 22px 0' }}>
        <CalmSectionLabel label="Recent" t={t} action="Filter" />
        <div>
          {items.map((h, i) => {
            const child = COPARENT_DATA.children.find(c => c.name === h.child);
            return (
              <ListRow key={h.id} t={t} last={i === items.length - 1}
                onClick={() => setSheet(h)}
                left={<CalmAvatar name={h.child} color={child.color} size={32} />}
                primary={h.label}
                secondary={`${kindLabel[h.kind]} · ${h.date}`}
                right={<div style={{ width: 10, height: 10, borderRadius: 5, background: sevColor(h.severity), flexShrink: 0 }} />}
              />
            );
          })}
        </div>
      </div>

      <FloatingPlus base={base} onClick={() => setSheet({ add: true })} />

      {sheet && (
        <CalmBottomSheet t={t} onClose={() => setSheet(null)}>
          {sheet.add ? (
            <>
              <div style={{ fontSize: 22, fontWeight: 800, color: t.text, marginBottom: 4 }}>Log a health event</div>
              <div style={{ fontSize: 13, color: t.subtext, marginBottom: 22 }}>Visible to Jordan</div>
              <div>
                {[{l:'Medication given',k:'med'},{l:'Symptom or fever',k:'fever'},{l:'Doctor visit',k:'visit'},{l:'Allergy event',k:'allergy'}].map((opt, i, arr) => (
                  <ListRow key={opt.k} t={t} last={i === arr.length - 1}
                    onClick={() => setSheet(null)} primary={opt.l}
                    right={<span style={{ fontSize: 18, color: t.subtext }}>›</span>} />
                ))}
              </div>
            </>
          ) : (
            <>
              <div style={{ fontSize: 13, color: t.subtext, marginBottom: 8 }}>{kindLabel[sheet.kind]} · {sheet.child} · {sheet.date}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: t.text, marginBottom: 8 }}>{sheet.label}</div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7,
                padding: '4px 10px', borderRadius: 10,
                background: sevColor(sheet.severity) + '22',
                color: sevColor(sheet.severity), fontSize: 12, fontWeight: 700,
                textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 16 }}>
                {sheet.severity} severity
              </div>
              <div style={{ fontSize: 14, color: t.subtext, lineHeight: 1.55, marginBottom: 22 }}>{sheet.notes}</div>
              <div style={{ display: 'flex', gap: 10 }}>
                <SecondaryButton label="Edit" t={t} onClick={() => setSheet(null)} />
                <PrimaryButton label="Mark resolved" base={base} onClick={() => setSheet(null)} />
              </div>
            </>
          )}
        </CalmBottomSheet>
      )}
    </div>
  );
}

// ─── Travel notice ───────────────────────────────────────────────────────────
function TravelScreen({ t, base, onBack }) {
  const items = COPARENT_DATA.travelNotices;
  const [composing, setComposing] = React.useState(false);
  const [step, setStep] = React.useState(0);
  const [sheet, setSheet] = React.useState(null);

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 24px', position: 'relative' }}>
      <BackHeader title="Travel" subtitle="Out-of-state notice · per custody agreement" t={t} base={base} onBack={onBack} />

      {!composing && (
        <>
          <div style={{ padding: '14px 22px 0' }}>
            <AmberBanner kicker="Reminder" t={t} base={base}
              title="Out-of-state trips need 14 days notice. Submit early to avoid friction."
              onClick={() => setComposing(true)} />
          </div>

          <div style={{ padding: '24px 22px 0' }}>
            <CalmSectionLabel label="Upcoming trips" t={t} />
            <div>
              {items.map((tr, i) => (
                <ListRow key={tr.id} t={t} last={i === items.length - 1}
                  onClick={() => setSheet(tr)}
                  primary={tr.dest}
                  secondary={`${tr.dates} · ${tr.who}`}
                  right={
                    <span style={{ fontSize: 11, fontWeight: 700,
                      color: tr.status === 'approved' ? base.green : base.amber,
                      letterSpacing: 0.5, textTransform: 'uppercase' }}>{tr.status}</span>
                  } />
              ))}
            </div>
          </div>

          <div style={{ padding: '32px 22px 0' }}>
            <PrimaryButton label="Submit a travel notice" base={base} onClick={() => setComposing(true)} />
          </div>
        </>
      )}

      {composing && (
        <div style={{ padding: '20px 22px 0' }}>
          <CalmSectionLabel label={`Step ${step + 1} of 3`} t={t} action="Cancel" onAction={() => { setComposing(false); setStep(0); }} />
          {step === 0 && (
            <div>
              <div style={{ fontSize: 13, color: t.subtext, fontWeight: 600, marginBottom: 8 }}>Destination</div>
              <input placeholder="City, state" defaultValue="Austin, TX"
                style={{ width: '100%', background: t.bgSecondary, border: 'none', outline: 'none',
                  padding: '14px 16px', borderRadius: 12, fontSize: 15, color: t.text, marginBottom: 14 }} />
              <div style={{ fontSize: 13, color: t.subtext, fontWeight: 600, marginBottom: 8 }}>Reason</div>
              <textarea placeholder="Wedding, family visit, vacation…" defaultValue="Cousin's wedding"
                style={{ width: '100%', minHeight: 80, background: t.bgSecondary, border: 'none',
                  outline: 'none', padding: 14, borderRadius: 12, fontSize: 15, color: t.text,
                  fontFamily: 'inherit', resize: 'none', lineHeight: 1.5 }} />
            </div>
          )}
          {step === 1 && (
            <div>
              <div style={{ fontSize: 13, color: t.subtext, fontWeight: 600, marginBottom: 8 }}>Dates</div>
              <ListRow t={t} primary="Departure" right={<span style={{ fontSize: 13, color: t.text, fontWeight: 600 }}>Fri Jun 14</span>} />
              <ListRow t={t} primary="Return" right={<span style={{ fontSize: 13, color: t.text, fontWeight: 600 }}>Sun Jun 16</span>} />
              <ListRow t={t} last primary="Children traveling" right={<span style={{ fontSize: 13, color: t.text, fontWeight: 600 }}>Both</span>} />
            </div>
          )}
          {step === 2 && (
            <div>
              <div style={{ fontSize: 13, color: t.subtext, fontWeight: 600, marginBottom: 8 }}>Itinerary & contact</div>
              <ListRow t={t} primary="Flight info" right={<span style={{ fontSize: 13, color: t.subtext }}>Add</span>} />
              <ListRow t={t} primary="Hotel / address" right={<span style={{ fontSize: 13, color: t.subtext }}>Add</span>} />
              <ListRow t={t} last primary="Emergency contact" right={<span style={{ fontSize: 13, color: t.text, fontWeight: 600 }}>Mom · 555-0144</span>} />
              <div style={{ marginTop: 16, padding: 14, background: t.bgSecondary, borderRadius: 12,
                fontSize: 13, color: t.subtext, lineHeight: 1.5 }}>
                Jordan has 7 days to respond. No response = approved per your agreement.
              </div>
            </div>
          )}
          <div style={{ marginTop: 22, display: 'flex', gap: 10 }}>
            {step > 0 && <SecondaryButton label="Back" t={t} onClick={() => setStep(s => s - 1)} />}
            <PrimaryButton label={step < 2 ? 'Continue' : 'Submit notice'} base={base}
              onClick={() => step < 2 ? setStep(s => s + 1) : (setComposing(false), setStep(0))} />
          </div>
        </div>
      )}

      {sheet && (
        <CalmBottomSheet t={t} onClose={() => setSheet(null)}>
          <div style={{ fontSize: 13, color: t.subtext, marginBottom: 8 }}>Travel · {sheet.status}</div>
          <div style={{ fontSize: 22, fontWeight: 800, color: t.text, marginBottom: 4 }}>{sheet.dest}</div>
          <div style={{ fontSize: 14, color: t.subtext, marginBottom: 22 }}>{sheet.dates} · {sheet.who}</div>
          <div style={{ display: 'flex', gap: 10 }}>
            <SecondaryButton label="View details" t={t} onClick={() => setSheet(null)} />
            <PrimaryButton label="Message Jordan" base={base} onClick={() => setSheet(null)} />
          </div>
        </CalmBottomSheet>
      )}
    </div>
  );
}

// ─── Tone check ──────────────────────────────────────────────────────────────
function ToneCheckScreen({ t, base, onBack }) {
  const original = "If you can't be on time for once just tell me, I'm tired of waiting around guessing whether you'll show up.";
  const suggested = "Hi Jordan — when pickup runs late, it's hard for me to plan around it. Could we agree to text by the start time if you're going to be more than 10 minutes off? Thanks for hearing me out.";
  const [picked, setPicked] = React.useState('suggested');
  const flags = [
    { tone: 'Accusatory', phrase: '"can\u2019t be on time for once"', color: base.red },
    { tone: 'Frustrated', phrase: '"tired of waiting"', color: base.amber },
  ];

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 24px' }}>
      <BackHeader title="Tone check" subtitle="Before sending" t={t} base={base} onBack={onBack} />

      {/* Score card */}
      <div style={{ padding: '20px 22px 0' }}>
        <div style={{ background: base.amberBg, borderRadius: 18, padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
            <div style={{ width: 56, height: 56, borderRadius: 28, background: base.amber + '33',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 24, fontWeight: 800, color: base.amber }}>!</div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, color: base.amber, letterSpacing: 1.2, textTransform: 'uppercase' }}>Heads up</div>
              <div style={{ fontSize: 17, fontWeight: 700, color: t.text, marginTop: 2 }}>This message reads as confrontational</div>
            </div>
          </div>
          <div style={{ fontSize: 13, color: t.subtext, lineHeight: 1.55 }}>
            We rewrote it to be clearer about your need without escalating. You can send either version — or edit yours.
          </div>
        </div>
      </div>

      {/* Flags */}
      <div style={{ padding: '20px 22px 0' }}>
        <CalmSectionLabel label="What we noticed" t={t} />
        <div>
          {flags.map((f, i) => (
            <div key={f.tone} style={{ display: 'flex', alignItems: 'center', gap: 14,
              padding: '14px 0', borderBottom: i < flags.length - 1 ? `1px solid ${t.divider}` : 'none' }}>
              <div style={{ width: 8, height: 8, borderRadius: 4, background: f.color, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{f.tone}</div>
                <div style={{ fontSize: 13, color: t.subtext, marginTop: 2, fontStyle: 'italic' }}>{f.phrase}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Versions */}
      <div style={{ padding: '24px 22px 0' }}>
        <CalmSectionLabel label="Choose a version" t={t} />
        {[
          { id: 'original', label: 'Your message', body: original },
          { id: 'suggested', label: 'Suggested rewrite', body: suggested },
        ].map(v => {
          const sel = v.id === picked;
          return (
            <div key={v.id} onClick={() => setPicked(v.id)} style={{
              padding: 16, marginBottom: 10, borderRadius: 14,
              background: sel ? t.bgSecondary : 'transparent',
              border: `1.5px solid ${sel ? t.text : t.divider}`, cursor: 'pointer' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{v.label}</div>
                {sel && <div style={{ fontSize: 11, fontWeight: 700, color: base.green, letterSpacing: 0.5, textTransform: 'uppercase' }}>Selected</div>}
              </div>
              <div style={{ fontSize: 14, color: t.text, lineHeight: 1.55 }}>{v.body}</div>
            </div>
          );
        })}
      </div>

      <div style={{ padding: '24px 22px 0', display: 'flex', gap: 10 }}>
        <SecondaryButton label="Edit more" t={t} onClick={onBack} />
        <PrimaryButton label="Send" base={base} onClick={onBack} />
      </div>
      <div style={{ fontSize: 12, color: t.subtext, textAlign: 'center', marginTop: 12, padding: '0 22px' }}>
        Tone check is private. Jordan only sees what you send.
      </div>
    </div>
  );
}

// ─── Reimbursement request ───────────────────────────────────────────────────
function ReimbursementScreen({ t, base, onBack }) {
  const [amount, setAmount] = React.useState('320');
  const [reason, setReason] = React.useState('Daycare \u2014 April balance');
  const [method, setMethod] = React.useState('venmo');
  const [step, setStep] = React.useState(0);

  if (step === 1) return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 24px' }}>
      <BackHeader title="Request sent" t={t} base={base} onBack={onBack} />
      <div style={{ padding: '40px 28px 0', textAlign: 'center' }}>
        <div style={{ width: 72, height: 72, borderRadius: 36, background: base.greenBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '20px auto 24px' }}>
          <svg width="32" height="32" viewBox="0 0 32 32"><path d="M8 16l5 5 11-11" stroke={base.green} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none"/></svg>
        </div>
        <div style={{ fontSize: 24, fontWeight: 800, color: t.text, letterSpacing: -0.4 }}>${amount} requested</div>
        <div style={{ fontSize: 14, color: t.subtext, marginTop: 12, lineHeight: 1.55 }}>
          Jordan will get a notification. Once accepted, payment goes through {method === 'venmo' ? 'Venmo' : method === 'zelle' ? 'Zelle' : 'a linked bank account'} automatically.
        </div>
      </div>
      <div style={{ padding: '32px 22px 0' }}>
        <PrimaryButton label="Done" base={base} onClick={onBack} />
      </div>
    </div>
  );

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 24px' }}>
      <BackHeader title="Request reimbursement" subtitle="Direct payment from Jordan" t={t} base={base} onBack={onBack} />

      {/* Amount */}
      <div style={{ padding: '24px 22px 0', textAlign: 'center' }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: t.subtext, letterSpacing: 1.2, textTransform: 'uppercase' }}>Amount</div>
        <div style={{ fontSize: 56, fontWeight: 800, color: t.text, letterSpacing: -2, marginTop: 6 }}>
          $<input value={amount} onChange={e => setAmount(e.target.value)}
            style={{ background: 'transparent', border: 'none', outline: 'none',
              color: t.text, fontSize: 56, fontWeight: 800, letterSpacing: -2,
              width: '4ch', textAlign: 'left' }} />
        </div>
      </div>

      {/* Reason */}
      <div style={{ padding: '20px 22px 0' }}>
        <input value={reason} onChange={e => setReason(e.target.value)} placeholder="What is this for?"
          style={{ width: '100%', background: t.bgSecondary, border: 'none', outline: 'none',
            padding: '14px 16px', borderRadius: 12, fontSize: 15, color: t.text }} />
      </div>

      {/* Tied to expense */}
      <div style={{ padding: '24px 22px 0' }}>
        <CalmSectionLabel label="Tied to expense" t={t} action="Change" />
        <div style={{ background: t.bgSecondary, borderRadius: 14, padding: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Daycare — April</div>
          <div style={{ fontSize: 13, color: t.subtext, marginTop: 2 }}>$640 total · Jordan's share $320 · Settled record</div>
        </div>
      </div>

      {/* Method */}
      <div style={{ padding: '24px 22px 0' }}>
        <CalmSectionLabel label="Payment method" t={t} />
        <div>
          {[
            { id: 'venmo', label: 'Venmo', sub: '@alex-morgan', linked: true },
            { id: 'zelle', label: 'Zelle', sub: 'alex@morgan.example', linked: true },
            { id: 'bank', label: 'Direct bank (Plaid)', sub: 'Connect to enable', linked: false },
          ].map((m, i, arr) => {
            const sel = m.id === method;
            return (
              <div key={m.id} onClick={() => m.linked && setMethod(m.id)}
                style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 0',
                  borderBottom: i < arr.length - 1 ? `1px solid ${t.divider}` : 'none',
                  cursor: m.linked ? 'pointer' : 'default', opacity: m.linked ? 1 : 0.55 }}>
                <div style={{ width: 22, height: 22, borderRadius: 11,
                  border: `2px solid ${sel ? base.primary : t.divider}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  {sel && <div style={{ width: 10, height: 10, borderRadius: 5, background: base.primary }} />}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{m.label}</div>
                  <div style={{ fontSize: 13, color: t.subtext, marginTop: 2 }}>{m.sub}</div>
                </div>
                {!m.linked && <span style={{ fontSize: 12, fontWeight: 700, color: base.primary }}>Connect</span>}
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ padding: '32px 22px 0' }}>
        <PrimaryButton label={`Request $${amount}`} base={base} onClick={() => setStep(1)} />
        <div style={{ fontSize: 12, color: t.subtext, textAlign: 'center', marginTop: 12 }}>
          Jordan can accept, decline, or counter. We log it either way.
        </div>
      </div>
    </div>
  );
}

// ─── House rules ─────────────────────────────────────────────────────────────
function HouseRulesScreen({ t, base, onBack }) {
  const items = COPARENT_DATA.houseRules;
  const [sheet, setSheet] = React.useState(null);
  const pending = items.filter(r => !r.agreed);

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '0 0 24px', position: 'relative' }}>
      <BackHeader title="House rules" subtitle="Shared agreements" t={t} base={base} onBack={onBack} />

      {pending.length > 0 && (
        <div style={{ padding: '14px 22px 0' }}>
          <AmberBanner kicker="Discussion" t={t} base={base}
            title={`${pending[0].topic} — ${pending[0].note}`}
            onClick={() => setSheet(pending[0])} />
        </div>
      )}

      <div style={{ padding: '24px 22px 0' }}>
        <CalmSectionLabel label="Rules in effect" t={t} action="Add" />
        <div>
          {items.map((r, i) => (
            <ListRow key={r.id} t={t} last={i === items.length - 1}
              onClick={() => setSheet(r)}
              primary={r.topic}
              secondary={`Emma: ${r.emma}${r.liam !== '\u2014' ? ' · Liam: ' + r.liam : ''}`}
              right={
                <span style={{ fontSize: 11, fontWeight: 700,
                  color: r.agreed ? base.green : base.amber,
                  letterSpacing: 0.5, textTransform: 'uppercase' }}>
                  {r.agreed ? 'Agreed' : 'Open'}
                </span>
              } />
          ))}
        </div>
      </div>

      <div style={{ padding: '32px 22px 0' }}>
        <SecondaryButton label="Print as one-pager" t={t} onClick={() => {}} />
      </div>

      {sheet && (
        <CalmBottomSheet t={t} onClose={() => setSheet(null)}>
          <div style={{ fontSize: 13, color: t.subtext, marginBottom: 8 }}>{sheet.agreed ? 'Agreed' : 'Open for discussion'}</div>
          <div style={{ fontSize: 22, fontWeight: 800, color: t.text, marginBottom: 16 }}>{sheet.topic}</div>
          <div style={{ background: t.bgSecondary, borderRadius: 12, padding: 14, marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: t.subtext, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Emma</div>
            <div style={{ fontSize: 14, color: t.text, marginTop: 4 }}>{sheet.emma}</div>
          </div>
          <div style={{ background: t.bgSecondary, borderRadius: 12, padding: 14, marginBottom: 18 }}>
            <div style={{ fontSize: 12, color: t.subtext, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Liam</div>
            <div style={{ fontSize: 14, color: t.text, marginTop: 4 }}>{sheet.liam}</div>
          </div>
          {sheet.note && (
            <div style={{ background: base.amberBg, borderRadius: 12, padding: 14, marginBottom: 18,
              fontSize: 13, color: t.text, lineHeight: 1.5 }}>{sheet.note}</div>
          )}
          <div style={{ display: 'flex', gap: 10 }}>
            <SecondaryButton label="Edit" t={t} onClick={() => setSheet(null)} />
            <PrimaryButton label={sheet.agreed ? 'Open for discussion' : 'Mark agreed'} base={base} onClick={() => setSheet(null)} />
          </div>
        </CalmBottomSheet>
      )}
    </div>
  );
}

// ─── Calm onboarding (first-run) ─────────────────────────────────────────────
function CalmOnboardingScreen({ t, base, onBack }) {
  const [step, setStep] = React.useState(0);
  const slides = [
    { kicker: 'Welcome', title: 'A calmer way to co-parent.',
      body: 'Track schedules, expenses, and conversations in one place — built to reduce friction, not amplify it.',
      art: <CircleArt color={base.primary} bg={base.primaryLight} glyph="✦" /> },
    { kicker: 'Built around your kids', title: 'Each child gets their own world.',
      body: 'School, medical, activities, and care notes — kept in sync so the right info is there when you need it.',
      art: <CircleArt color={base.accent} bg={base.accentLight} glyph="◐" /> },
    { kicker: 'Court-ready by default', title: 'Every action is timestamped.',
      body: 'Messages, expenses, and handoffs are logged with verification. Generate a PDF anytime — free, forever.',
      art: <CircleArt color={base.green} bg={base.greenBg} glyph="✓" /> },
    { kicker: 'Get started', title: 'Add your kids, then invite Jordan.',
      body: "We'll walk you through it. Takes about three minutes.",
      art: <CircleArt color={base.primary} bg={base.primaryLight} glyph="→" /> },
  ];
  const s = slides[step];

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '0 0 24px' }}>
      <BackHeader title="" t={t} base={base} onBack={onBack} />

      <div style={{ flex: 1, padding: '20px 28px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
        {s.art}
        <div style={{ fontSize: 12, fontWeight: 700, color: base.primary, letterSpacing: 1.5, textTransform: 'uppercase', marginTop: 32 }}>{s.kicker}</div>
        <div style={{ fontSize: 30, fontWeight: 800, color: t.text, letterSpacing: -0.6, lineHeight: 1.15, marginTop: 12 }}>{s.title}</div>
        <div style={{ fontSize: 16, color: t.subtext, lineHeight: 1.55, marginTop: 16, maxWidth: 320 }}>{s.body}</div>
      </div>

      {/* Dots */}
      <div style={{ display: 'flex', justifyContent: 'center', gap: 8, padding: '24px 0' }}>
        {slides.map((_, i) => (
          <div key={i} style={{
            width: i === step ? 24 : 6, height: 6, borderRadius: 3,
            background: i === step ? t.text : t.divider, transition: 'all 0.2s' }} />
        ))}
      </div>

      <div style={{ padding: '0 22px' }}>
        <PrimaryButton label={step < slides.length - 1 ? 'Continue' : 'Add your first child'} base={base}
          onClick={() => step < slides.length - 1 ? setStep(s => s + 1) : onBack()} />
        {step < slides.length - 1 && (
          <div onClick={onBack} style={{ fontSize: 13, color: t.subtext, textAlign: 'center', marginTop: 14, fontWeight: 600, cursor: 'pointer' }}>Skip</div>
        )}
      </div>
    </div>
  );
}
function CircleArt({ color, bg, glyph }) {
  return (
    <div style={{ width: 200, height: 200, position: 'relative', marginTop: 8 }}>
      <div style={{ position: 'absolute', inset: 0, borderRadius: 100, background: bg }} />
      <div style={{ position: 'absolute', inset: 30, borderRadius: 70, background: 'transparent',
        border: `1.5px dashed ${color}`, opacity: 0.4 }} />
      <div style={{ position: 'absolute', inset: 56, borderRadius: 44, background: color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontSize: 40, fontWeight: 800 }}>{glyph}</div>
    </div>
  );
}

// ─── App lock / Face ID gate ─────────────────────────────────────────────────
function AppLockScreen({ t, base, onBack }) {
  const [unlocking, setUnlocking] = React.useState(false);
  const [unlocked, setUnlocked] = React.useState(false);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column',
      background: t.bgSecondary, padding: '0 0 24px' }}>
      <BackHeader title="" t={t} base={base} onBack={onBack} />

      <div style={{ flex: 1, padding: '40px 28px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
        {/* Lock visual */}
        <div style={{ width: 120, height: 120, borderRadius: 60, background: t.bg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: t.shadow, marginTop: 30, position: 'relative' }}>
          {unlocked ? (
            <svg width="44" height="44" viewBox="0 0 44 44">
              <path d="M12 22l7 7 13-15" stroke={base.green} strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
            </svg>
          ) : (
            <>
              <div style={{ width: 28, height: 22, border: `3px solid ${t.text}`, borderRadius: 5, position: 'absolute', top: 50 }} />
              <div style={{ width: 18, height: 18, border: `3px solid ${t.text}`, borderTopLeftRadius: 9, borderTopRightRadius: 9, borderBottom: 'none', position: 'absolute', top: 36 }} />
            </>
          )}
          {unlocking && !unlocked && (
            <div style={{ position: 'absolute', inset: -8, borderRadius: 64,
              border: `2px solid ${base.primary}`, animation: 'pulse 1.4s ease-out infinite' }} />
          )}
        </div>
        <div style={{ fontSize: 26, fontWeight: 800, color: t.text, letterSpacing: -0.5, marginTop: 36 }}>
          {unlocked ? 'Welcome back' : unlocking ? 'Looking…' : 'CoParent is locked'}
        </div>
        <div style={{ fontSize: 14, color: t.subtext, marginTop: 12, lineHeight: 1.55, maxWidth: 280 }}>
          {unlocked ? 'Opening your private space.' : 'Your data stays private. Use Face ID or your passcode to continue.'}
        </div>
      </div>

      <div style={{ padding: '0 22px' }}>
        {!unlocked && (
          <PrimaryButton label={unlocking ? 'Authenticating…' : 'Unlock with Face ID'} base={base}
            onClick={() => { setUnlocking(true); setTimeout(() => { setUnlocking(false); setUnlocked(true); }, 900); }} />
        )}
        <div onClick={onBack} style={{ fontSize: 13, color: t.subtext, textAlign: 'center', marginTop: 14, fontWeight: 600, cursor: 'pointer' }}>
          {unlocked ? 'Tap to enter' : 'Use passcode'}
        </div>
      </div>

      <style>{`@keyframes pulse {
        0% { transform: scale(1); opacity: 0.8; }
        100% { transform: scale(1.4); opacity: 0; }
      }`}</style>
    </div>
  );
}

Object.assign(window, {
  JournalScreen, HealthLogScreen, TravelScreen, ToneCheckScreen,
  ReimbursementScreen, HouseRulesScreen, CalmOnboardingScreen, AppLockScreen
});
