/* global React, RIcons, JOURNAL_SUMMARY */
// Night Watch — full overnight monitoring flow.
// Upsells from Rounds home when journal flags are present.
// Flow: Suggest → Context wizard → Package reveal → Activating ceremony → Active monitoring

const { useState: useStateN, useEffect: useEffectN, useRef: useRefN, useMemo: useMemoN } = React;

const DEFAULT_CONTEXT = {
  feeling: null,
  symptoms: [],
  meds: [],
  notes: '',
  band: 'calm',
};

const NW_BANDS = {
  calm: {
    id: 'calm', tier: 'Calm', dot: '#9de3cd', ink: '#9de3cd',
    tint: 'rgba(157,227,205,0.12)', border: 'rgba(157,227,205,0.3)',
    title: 'Owlet is watching tonight',
    sub: 'Your care team is one step away if anything changes.',
    aurora: 'radial-gradient(40% 30% at 25% 18%, rgba(157,227,205,0.16) 0%, transparent 70%), radial-gradient(40% 30% at 80% 28%, rgba(125,128,230,0.18) 0%, transparent 70%)',
  },
  watch: {
    id: 'watch', tier: 'Closer watch', dot: '#9a9cf0', ink: '#b4b6f5',
    tint: 'rgba(125,128,230,0.16)', border: 'rgba(125,128,230,0.38)',
    title: 'Keeping a closer eye on Nora',
    sub: 'Nothing urgent. We noticed a small change and we are watching it more closely.',
    aurora: 'radial-gradient(46% 32% at 30% 16%, rgba(125,128,230,0.30) 0%, transparent 72%), radial-gradient(40% 30% at 82% 30%, rgba(157,160,240,0.20) 0%, transparent 70%)',
  },
  action: {
    id: 'action', tier: 'Action needed', dot: '#f7a4a4', ink: '#f7a4a4',
    tint: 'rgba(240,68,56,0.16)', border: 'rgba(240,68,56,0.46)',
    title: 'Check on Nora now',
    sub: 'Owlet detected readings that need your attention.',
    aurora: 'radial-gradient(52% 38% at 50% 10%, rgba(240,68,56,0.28) 0%, transparent 72%)',
  },
};

const OWLET_RED_TRIAD = [
  'Is Baby breathing normally?',
  "Is Baby's skin color normal?",
  'Is Baby alert and responsive?',
];

// ─── Stars ────────────────────────────────────────────────
const NW_STARS = [
  { x: 8,  y: 22, d: 0.0 }, { x: 22, y: 110, d: 1.2 }, { x: 38, y: 38, d: 2.1 },
  { x: 56, y: 18, d: 0.6 }, { x: 72, y: 90, d: 3.0 },  { x: 86, y: 32, d: 1.0 },
  { x: 92, y: 60, d: 2.6 }, { x: 6,  y: 70, d: 1.7 },  { x: 48, y: 130, d: 0.4 },
  { x: 80, y: 150, d: 2.3 }, { x: 16, y: 200, d: 1.1 }, { x: 64, y: 230, d: 2.9 },
];
function NWStars({ count = 12 }) {
  return (
    <div className="nw-stars" aria-hidden="true">
      {NW_STARS.slice(0, count).map((s, i) => (
        <span key={i} style={{ left: s.x + '%', top: s.y + 'px', animationDelay: s.d + 's' }} />
      ))}
    </div>
  );
}

// ─── Shared layout pieces ──────────────────────────────────
function NWTopBar({ onBack, step, totalSteps, title, rightSlot }) {
  return (
    <div className="nw-top">
      <button className="nw-iconbtn" onClick={onBack} aria-label="Back">
        <RIcons.ChevronLeft size={20} />
      </button>
      {step ? (
        <div className="nw-step-pill">Step {step} of {totalSteps}</div>
      ) : title ? (
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--foreground)', whiteSpace: 'nowrap' }}>{title}</div>
      ) : <div />}
      <div style={{ width: 36 }}>{rightSlot}</div>
    </div>
  );
}

function NWFooterCTA({ children }) {
  return (
    <div className="nw-footer-cta">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, position: 'relative', zIndex: 1 }}>
        {children}
      </div>
    </div>
  );
}

// ─── Context wizard ────────────────────────────────────────
function NWContextScreen({ onBack, onNext, context, setContext }) {
  const FEELINGS = [
    { id: 'normal',     label: 'Normal',       blurb: 'Same as usual' },
    { id: 'off',        label: 'A little off', blurb: 'Hard to put my finger on it' },
    { id: 'sick',       label: 'Sick',         blurb: 'Something is clearly going on' },
    { id: 'recovering', label: 'Recovering',   blurb: 'Bouncing back after illness' },
  ];
  const SYMPTOMS = [
    { id: 'fever', label: 'Fever' }, { id: 'cough', label: 'Cough' },
    { id: 'congestion', label: 'Congestion' }, { id: 'fussy', label: 'Unusual fussiness' },
    { id: 'vomit', label: 'Vomiting' }, { id: 'diaper', label: 'Diaper rash' },
    { id: 'tummy', label: 'Upset tummy' }, { id: 'sleep', label: 'Sleep change' },
  ];
  const MEDS = [
    { id: 'tylenol', label: 'Tylenol' }, { id: 'motrin', label: 'Motrin' },
    { id: 'breath', label: 'Breathing tx' }, { id: 'abx', label: 'Antibiotic' },
    { id: 'vitd', label: 'Vitamin D' }, { id: 'none', label: 'None today' },
  ];

  const [step, setStep] = useStateN(0);
  const [dir, setDir] = useStateN('right');
  const [slidePhase, setSlidePhase] = useStateN(0);
  const totalSteps = 4;

  useEffectN(() => {
    setSlidePhase(1);
    const t = setTimeout(() => setSlidePhase(0), 20);
    return () => clearTimeout(t);
  }, [step]);

  function toggleArr(key, id) {
    setContext(prev => {
      const set = new Set(prev[key]);
      set.has(id) ? set.delete(id) : set.add(id);
      if (key === 'meds' && id === 'none') return { ...prev, meds: set.has('none') ? ['none'] : [] };
      if (key === 'meds' && set.has('none') && id !== 'none') set.delete('none');
      return { ...prev, [key]: [...set] };
    });
  }

  function next() {
    if (step === totalSteps - 1) { onNext(); return; }
    setDir('right'); setStep(step + 1);
  }
  function back() {
    if (step === 0) { onBack(); return; }
    setDir('left'); setStep(step - 1);
  }

  const canContinue = step === 0 ? !!context.feeling : true;

  return (
    <div className="nw-page nw-page--footer">
      <NWStars count={6} />
      <NWTopBar onBack={back} step={step + 1} totalSteps={totalSteps} />
      <div className="wizard-progress">
        <span style={{ width: `${((step + 1) / totalSteps) * 100}%` }} />
      </div>

      <div style={{ position: 'relative', zIndex: 1, padding: '20px 20px 0' }}>
        <div key={step} style={{
          opacity: slidePhase ? 0 : 1,
          transform: slidePhase ? `translateX(${dir === 'right' ? 28 : -28}px)` : 'translateX(0)',
          transition: slidePhase ? 'none' : 'opacity 380ms cubic-bezier(.2,.8,.25,1), transform 380ms cubic-bezier(.2,.8,.25,1)',
        }}>
          {step === 0 && <StepFeeling options={FEELINGS} value={context.feeling} onChange={(id) => setContext(p => ({ ...p, feeling: id }))} />}
          {step === 1 && <StepSymptoms options={SYMPTOMS} selected={context.symptoms} onToggle={(id) => toggleArr('symptoms', id)} />}
          {step === 2 && <StepMeds options={MEDS} selected={context.meds} onToggle={(id) => toggleArr('meds', id)} />}
          {step === 3 && <StepNotes value={context.notes} onChange={(v) => setContext(p => ({ ...p, notes: v }))} />}
        </div>
      </div>

      <NWFooterCTA>
        <button className="nw-cta" onClick={next} disabled={!canContinue}
          style={{ opacity: canContinue ? 1 : 0.5, cursor: canContinue ? 'pointer' : 'default' }}>
          {step === totalSteps - 1 ? "See tonight's package" : 'Continue'}
          <RIcons.ChevronRight size={18} />
        </button>
        {step > 0 && step < totalSteps - 1 && (
          <button className="nw-cta-text" onClick={next}>Skip this step →</button>
        )}
        {step === 0 && !canContinue && (
          <div className="muted" style={{ fontSize: 12, textAlign: 'center' }}>Pick how Nora is feeling to continue.</div>
        )}
      </NWFooterCTA>
    </div>
  );
}

function StepHeader({ kicker, title, sub }) {
  return (
    <>
      <div style={{ color: 'var(--primary)', fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', marginBottom: 8 }}>{kicker}</div>
      <h1 className="nw-hero-title" style={{ fontSize: 26, lineHeight: '32px' }}>{title}</h1>
      {sub && <p className="nw-hero-sub" style={{ marginTop: 8 }}>{sub}</p>}
    </>
  );
}

function FeelingGlyph({ id, selected }) {
  const color = selected ? 'var(--primary)' : 'rgba(212,212,249,0.5)';
  const glyphs = {
    normal:     <circle cx="14" cy="14" r="6" />,
    off:        <path d="M8 12 Q14 8 20 12 M14 18 v0.1" strokeLinecap="round" />,
    sick:       <path d="M8 11 L12 15 L16 11 L20 15 M14 18 v0.1" strokeLinecap="round" />,
    recovering: <path d="M8 16 Q14 12 20 16" strokeLinecap="round" />,
  };
  return (
    <div style={{
      width: 36, height: 36, borderRadius: 999,
      background: selected ? 'rgba(157,227,205,0.14)' : 'rgba(212,212,249,0.05)',
      border: '1px solid ' + (selected ? 'rgba(157,227,205,0.35)' : 'rgba(212,212,249,0.08)'),
      display: 'flex', alignItems: 'center', justifyContent: 'center', transition: '200ms ease-out',
    }}>
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke={color} strokeWidth="1.8" strokeLinejoin="round">
        <circle cx="14" cy="14" r="12" stroke={selected ? 'var(--primary)' : 'rgba(212,212,249,0.2)'} strokeWidth="1" fill="none" />
        {glyphs[id]}
      </svg>
    </div>
  );
}

function StepFeeling({ options, value, onChange }) {
  return (
    <>
      <StepHeader kicker="Tonight" title="How is Nora feeling?" sub="Tap the closest match — we'll tune the watch around it." />
      <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {options.map(o => (
          <button key={o.id} className={`mood-card ${value === o.id ? 'on' : ''}`} onClick={() => onChange(value === o.id ? null : o.id)}>
            <FeelingGlyph id={o.id} selected={value === o.id} />
            <div style={{ fontSize: 15, fontWeight: 600, color: '#fff', whiteSpace: 'nowrap' }}>{o.label}</div>
            <div className="muted" style={{ fontSize: 12, lineHeight: '17px' }}>{o.blurb}</div>
          </button>
        ))}
      </div>
    </>
  );
}

function StepSymptoms({ options, selected, onToggle }) {
  return (
    <>
      <StepHeader kicker="Step 2" title="Anything to watch for?" sub="Pick anything you noticed today. None is a fine answer too." />
      <div style={{ marginTop: 20, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {options.map(o => (
          <button key={o.id} onClick={() => onToggle(o.id)} className={`nw-chip ${selected.includes(o.id) ? 'on' : ''}`}>{o.label}</button>
        ))}
      </div>
      {selected.length > 0 && (
        <div className="muted" style={{ fontSize: 12, marginTop: 16, padding: '8px 12px', borderRadius: 8, background: 'rgba(201,168,146,0.08)', border: '1px solid rgba(201,168,146,0.18)', color: '#e8c8ad' }}>
          Noted {selected.length} {selected.length === 1 ? 'thing' : 'things'} for tonight's watch.
        </div>
      )}
    </>
  );
}

function StepMeds({ options, selected, onToggle }) {
  return (
    <>
      <StepHeader kicker="Step 3" title="Any medication today?" sub="Helpful for the provider if we end up looping one in tonight." />
      <div style={{ marginTop: 20, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {options.map(o => (
          <button key={o.id} onClick={() => onToggle(o.id)} className={`nw-chip ${selected.includes(o.id) ? 'on' : ''}`}>{o.label}</button>
        ))}
      </div>
    </>
  );
}

function StepNotes({ value, onChange }) {
  return (
    <>
      <StepHeader kicker="Last step" title="Anything different about tonight?" sub="A few words is plenty — it goes straight into the care package." />
      <div style={{ marginTop: 20 }}>
        <textarea value={value} onChange={(e) => onChange(e.target.value)}
          placeholder="e.g. late bedtime, new food, slept in our room" rows={5}
          style={{ width: '100%', resize: 'none', background: 'var(--surface)', border: '1px solid rgba(212,212,249,0.06)', borderRadius: 14, padding: 16, fontFamily: 'inherit', fontSize: 14.5, lineHeight: '22px', color: 'var(--foreground)', outline: 'none' }}
        />
      </div>
    </>
  );
}

// ─── Package reveal ────────────────────────────────────────
function NWPackageScreen({ onBack, onActivate, context }) {
  const S_MAP = { fever: 'Fever', cough: 'Cough', congestion: 'Congestion', fussy: 'Fussy', vomit: 'Vomiting', diaper: 'Diaper rash', tummy: 'Upset tummy', sleep: 'Sleep change' };
  const M_MAP = { tylenol: 'Tylenol', motrin: 'Motrin', breath: 'Breathing treatment', abx: 'Antibiotic', vitd: 'Vitamin D', none: 'None' };
  const F_MAP = { normal: 'Normal', off: 'A little off', sick: 'Sick', recovering: 'Recovering' };

  const symptomLabel = context.symptoms.length ? context.symptoms.map(s => S_MAP[s]).join(', ') : 'None tonight';
  const medsLabel = context.meds.length ? context.meds.map(m => M_MAP[m]).join(', ') : '—';
  const feelingLabel = F_MAP[context.feeling] || '—';

  const rows = [
    { icon: <RIcons.Heart size={18} />,       title: 'Live Sock vitals',     sub: 'Pulse, oxygen, motion · sampled continuously' },
    { icon: <RIcons.Bell size={18} />,        title: 'Owlet alert system',   sub: 'Independent of AI — established clinical alerts' },
    { icon: <RIcons.Journal size={18} />,     title: "Tonight's context",    sub: `Feeling: ${feelingLabel} · Symptoms: ${symptomLabel}` },
    { icon: <RIcons.Pill size={18} />,        title: 'Medication noted',     sub: medsLabel },
    { icon: <RIcons.TrendUp size={18} />,     title: 'Care profile context', sub: 'Last 7 nights of sleep and vitals' },
    { icon: <RIcons.Stethoscope size={18} />, title: 'OnCall escalation',    sub: 'Pediatric provider on standby with full context' },
  ];

  const [revealedRows, setRevealedRows] = useStateN(0);
  const [done, setDone] = useStateN(false);

  useEffectN(() => {
    let timer = setInterval(() => {
      setRevealedRows(prev => {
        const next = prev + 1;
        if (next >= rows.length) { clearInterval(timer); setTimeout(() => setDone(true), 400); }
        return next;
      });
    }, 220);
    return () => clearInterval(timer);
  }, []); // eslint-disable-line

  const status = done ? "Tonight's care package" : 'Preparing tonight\'s package…';

  return (
    <div className="nw-page nw-page--footer">
      <div className="nw-aurora" />
      <NWStars count={8} />
      <NWTopBar onBack={onBack} step={2} totalSteps={2} />

      <div style={{ position: 'relative', zIndex: 1, padding: '14px 20px 0' }}>
        <div style={{ color: done ? 'var(--primary)' : 'var(--foreground-muted)', fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8, transition: '300ms ease-out' }}>
          {!done && <span style={{ width: 12, height: 12, borderRadius: 999, border: '2px solid currentColor', borderTopColor: 'transparent', animation: 'owlet-spin 700ms linear infinite' }} />}
          {done && (
            <span className="check-pop" style={{ width: 14, height: 14, borderRadius: 999, background: 'var(--primary)', color: 'var(--on-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </span>
          )}
          {status}
        </div>
        <h1 className="nw-hero-title" style={{ fontSize: 24, lineHeight: '30px' }}>Here's what Owlet will do tonight</h1>

        <div style={{ marginTop: 18, background: 'rgba(17,19,63,0.7)', border: '1px solid rgba(157,227,205,0.18)', borderRadius: 18, padding: '6px 4px', backdropFilter: 'blur(12px)' }}>
          {rows.map((r, i) => (
            <PackageRow key={i} icon={r.icon} title={r.title} sub={r.sub} last={i === rows.length - 1} revealed={i < revealedRows} />
          ))}
        </div>

        <div style={{ marginTop: 16, opacity: done ? 1 : 0, transform: done ? 'translateY(0)' : 'translateY(8px)', transition: '420ms cubic-bezier(.2,.8,.25,1)', display: 'flex', alignItems: 'center', gap: 12, background: 'rgba(157,227,205,0.06)', border: '1px solid rgba(157,227,205,0.18)', borderRadius: 14, padding: '14px 16px' }}>
          <span style={{ width: 30, height: 30, borderRadius: 9, flexShrink: 0, background: 'rgba(157,227,205,0.10)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <RIcons.Sunrise size={18} />
          </span>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>Owlet watches until morning</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 1, lineHeight: '17px' }}>Your summary will be ready when you wake.</div>
          </div>
        </div>
      </div>

      <NWFooterCTA>
        <div style={{ opacity: done ? 1 : 0, transform: done ? 'translateY(0)' : 'translateY(8px)', transition: '420ms cubic-bezier(.2,.8,.25,1)', display: 'flex', flexDirection: 'column', gap: 10, pointerEvents: done ? 'auto' : 'none' }}>
          <button className="nw-cta glow" onClick={onActivate}>
            Activate Night Watch <RIcons.ChevronRight size={18} />
          </button>
          <div className="muted" style={{ fontSize: 12, textAlign: 'center', lineHeight: '17px' }}>Emergency alerts from your Owlet Sock continue to run as normal.</div>
        </div>
      </NWFooterCTA>
    </div>
  );
}

function PackageRow({ icon, title, sub, last, revealed }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '12px 14px', borderBottom: last ? 'none' : '1px solid rgba(212,212,249,0.05)', opacity: revealed ? 1 : 0, transform: revealed ? 'translateY(0)' : 'translateY(8px)', transition: 'opacity 420ms cubic-bezier(.2,.8,.25,1), transform 420ms cubic-bezier(.2,.8,.25,1)' }}>
      <div style={{ width: 30, height: 30, borderRadius: 9, background: 'rgba(157,227,205,0.10)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{title}</div>
        <div className="muted" style={{ fontSize: 12.5, lineHeight: '17px', marginTop: 1 }}>{sub}</div>
      </div>
      <div style={{ width: 22, height: 22, borderRadius: 999, background: revealed ? 'var(--primary)' : 'rgba(212,212,249,0.08)', color: 'var(--on-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'background 300ms ease-out' }}>
        {revealed && <svg className="check-pop" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>}
      </div>
    </div>
  );
}

// ─── Quick arm (returning nights) ─────────────────────────
const QA_LABEL = {
  feeling: { normal: 'Normal', off: 'A little off', sick: 'Sick', recovering: 'Recovering' },
  meds: { tylenol: 'Tylenol', motrin: 'Motrin', breath: 'Breathing tx', abx: 'Antibiotic', vitd: 'Vitamin D', none: 'No meds' },
  symptoms: { fever: 'Fever', cough: 'Cough', congestion: 'Congestion', fussy: 'Fussy', vomit: 'Vomiting', diaper: 'Diaper rash', tummy: 'Upset tummy', sleep: 'Sleep change' },
};
const QA_FEELINGS = [
  { id: 'normal', label: 'Normal' }, { id: 'off', label: 'A little off' },
  { id: 'sick', label: 'Sick' }, { id: 'recovering', label: 'Recovering' },
];
const QA_MEDS = [
  { id: 'tylenol', label: 'Tylenol' }, { id: 'motrin', label: 'Motrin' },
  { id: 'breath', label: 'Breathing tx' }, { id: 'abx', label: 'Antibiotic' },
  { id: 'vitd', label: 'Vitamin D' }, { id: 'none', label: 'None today' },
];

function NWQuickArm({ onBack, onActivate, context, setContext, lastNight }) {
  const [expanded, setExpanded] = useStateN(false);
  const ln = lastNight || {};

  useEffectN(() => {
    setContext(p => ({
      ...p,
      feeling:  p.feeling  || ln.feeling  || 'normal',
      symptoms: (p.symptoms && p.symptoms.length) ? p.symptoms : (ln.symptoms || []),
      meds:     (p.meds && p.meds.length) ? p.meds : (ln.meds || []),
    }));
  }, []); // eslint-disable-line

  function toggleMed(id) {
    setContext(prev => {
      const set = new Set(prev.meds);
      set.has(id) ? set.delete(id) : set.add(id);
      if (id === 'none') return { ...prev, meds: set.has('none') ? ['none'] : [] };
      if (set.has('none') && id !== 'none') set.delete('none');
      return { ...prev, meds: [...set] };
    });
  }

  const feelingTxt = QA_LABEL.feeling[context.feeling] || 'Normal';
  const medsTxt = (!context.meds || !context.meds.length || (context.meds.length === 1 && context.meds[0] === 'none'))
    ? 'no meds'
    : context.meds.filter(m => m !== 'none').map(m => QA_LABEL.meds[m]).join(', ').toLowerCase();
  const sympTxt = (context.symptoms && context.symptoms.length)
    ? context.symptoms.map(s => QA_LABEL.symptoms[s]).join(', ')
    : null;

  return (
    <div className="nw-page nw-page--footer screen-enter">
      <div className="nw-aurora" />
      <NWStars count={8} />
      <NWTopBar onBack={onBack} title="Night Watch" />

      <div style={{ position: 'relative', zIndex: 1, padding: '24px 20px 0' }}>
        <div style={{ color: 'var(--primary)', fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', marginBottom: 10 }}>Tonight's watch</div>
        <h1 className="nw-hero-title">Arm Night Watch for Nora?</h1>

        {!expanded ? (
          <div style={{ marginTop: 22, background: 'rgba(17,19,63,0.7)', border: '1px solid rgba(157,227,205,0.18)', borderRadius: 18, padding: 18, backdropFilter: 'blur(12px)' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--foreground-muted)', marginBottom: 12 }}>Same as last night</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              <QARecapRow icon={<RIcons.Heart size={16} />} text={
                sympTxt ? <><strong style={{ color: '#fff' }}>{feelingTxt}</strong> · {sympTxt}</>
                        : <><strong style={{ color: '#fff' }}>{feelingTxt}</strong>, {medsTxt}</>
              } />
              {sympTxt && <QARecapRow icon={<RIcons.Pill size={16} />} text={medsTxt.charAt(0).toUpperCase() + medsTxt.slice(1)} />}
              <QARecapRow icon={<RIcons.Sunrise size={16} />} text={<>Watching until <strong style={{ color: '#fff' }}>morning</strong></>} />
            </div>
          </div>
        ) : (
          <div style={{ marginTop: 18 }}>
            <NWSection label="Tonight she's feeling">
              <div style={{ width: '100%', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {QA_FEELINGS.map(o => (
                  <button key={o.id} onClick={() => setContext(p => ({ ...p, feeling: o.id }))}
                    className={`nw-chip ${context.feeling === o.id ? 'on' : ''}`}
                    style={{ justifyContent: 'center', textAlign: 'center' }}>{o.label}</button>
                ))}
              </div>
            </NWSection>
            <NWSection label="Medication today">
              {QA_MEDS.map(o => (
                <button key={o.id} onClick={() => toggleMed(o.id)}
                  className={`nw-chip ${(context.meds || []).includes(o.id) ? 'on' : ''}`}>{o.label}</button>
              ))}
            </NWSection>
            <NWSection label="Anything different tonight?">
              <textarea value={context.notes} onChange={(e) => setContext(p => ({ ...p, notes: e.target.value }))}
                placeholder="e.g. late bedtime, new food" rows={3}
                style={{ width: '100%', resize: 'none', background: 'var(--surface)', border: '1px solid rgba(212,212,249,0.06)', borderRadius: 14, padding: 14, fontFamily: 'inherit', fontSize: 14, lineHeight: '21px', color: 'var(--foreground)', outline: 'none' }} />
            </NWSection>
          </div>
        )}
      </div>

      <NWFooterCTA>
        <button className="nw-cta glow" onClick={onActivate}>
          {expanded ? 'Arm Night Watch' : 'Arm now'} <RIcons.ChevronRight size={18} />
        </button>
        {!expanded && <button className="nw-cta-text" onClick={() => setExpanded(true)}>Adjust tonight →</button>}
        <div className="muted" style={{ fontSize: 12, textAlign: 'center', lineHeight: '17px' }}>Emergency alerts from your Owlet Sock run as normal.</div>
      </NWFooterCTA>
    </div>
  );
}

function QARecapRow({ icon, text }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <span style={{ width: 28, height: 28, borderRadius: 8, flexShrink: 0, background: 'rgba(157,227,205,0.10)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</span>
      <div style={{ fontSize: 14, lineHeight: '19px', color: 'var(--foreground)' }}>{text}</div>
    </div>
  );
}

function NWSection({ label, children }) {
  return (
    <div style={{ marginTop: 22 }}>
      <h2 className="nw-section-label" style={{ marginLeft: 4 }}>{label}</h2>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>{children}</div>
    </div>
  );
}

// ─── Activating ceremony ───────────────────────────────────
const RITUAL_STARS = [
  { x: 12, y: 14, r: 2, d: 0.0 }, { x: 28, y: 26, r: 1.5, d: 1.4 }, { x: 48, y: 10, r: 1.5, d: 2.1 },
  { x: 72, y: 22, r: 2, d: 0.4 }, { x: 86, y: 38, r: 1.5, d: 1.6 }, { x: 18, y: 78, r: 1.5, d: 2.0 },
  { x: 36, y: 88, r: 2, d: 0.2 }, { x: 64, y: 82, r: 1.5, d: 1.0 }, { x: 82, y: 92, r: 1.5, d: 0.6 },
  { x: 92, y: 70, r: 1.5, d: 1.8 },
];

function NWActivatingScreen({ onDone }) {
  const [phase, setPhase] = useStateN(0);

  useEffectN(() => {
    const timings = [1200, 1500, 1500, 2200, 700];
    const timers = [];
    let acc = 0;
    timings.forEach((t, i) => {
      acc += t;
      timers.push(setTimeout(() => {
        if (i === timings.length - 1) onDone();
        else setPhase(i + 1);
      }, acc));
    });
    return () => timers.forEach(clearTimeout);
  }, []); // eslint-disable-line

  const lines = [
    { kicker: 'Tonight', title: 'Settling in',             sub: 'Owlet is taking the watch.' },
    { kicker: 'Tonight', title: 'Locking in baseline',     sub: 'Pulse · oxygen · sleep — last 7 nights.' },
    { kicker: 'Tonight', title: 'Care team coming online',  sub: 'A pediatric provider is on standby.' },
    { kicker: 'Tonight', title: 'Night Watch',             sub: 'Activated · watching now' },
  ];
  const line = lines[Math.min(phase, lines.length - 1)];
  const isFinal = phase >= 3;

  return (
    <div className={`nw-ritual-stage ${isFinal ? 'nw-ritual--final' : ''}`}>
      <div className="nw-ritual-stars" aria-hidden="true">
        {RITUAL_STARS.map((s, i) => (
          <span key={i} style={{ left: s.x + '%', top: s.y + '%', width: s.r + 'px', height: s.r + 'px', animationDelay: s.d + 's' }} />
        ))}
      </div>
      <div className="nw-ritual-copy">
        <span className="nw-ritual-star" aria-hidden="true" />
        <div key={`k-${phase}`} className="nw-ritual-kicker">{line.kicker}</div>
        {!isFinal && (
          <>
            <div key={`t-${phase}`} className="nw-ritual-title">{line.title}</div>
            <div key={`s-${phase}`} className="nw-ritual-subline">{line.sub}</div>
          </>
        )}
        {isFinal && (
          <>
            <div key="hr-top" className="nw-ritual-rule nw-ritual-rule--top" />
            <h1 key="hl" className="nw-ritual-headline">{line.title}</h1>
            <div key="hr-bot" className="nw-ritual-rule nw-ritual-rule--bot" />
            <div key="badge" className="nw-ritual-badge">
              <span className="nw-ritual-dot" />{line.sub}
            </div>
          </>
        )}
      </div>
      {!isFinal && (
        <div className="nw-ritual-pips" aria-hidden="true">
          {[0, 1, 2, 3].map(i => <span key={i} className={i <= phase ? 'on' : ''} />)}
        </div>
      )}
    </div>
  );
}

// ─── Alert: clinician auto-connects on red ─────────────────
function NWAlertConnecting({ onConnected }) {
  const [phase, setPhase] = useStateN(0);

  useEffectN(() => {
    const t1 = setTimeout(() => setPhase(1), 1500);
    const t2 = setTimeout(() => onConnected && onConnected(), 2700);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []); // eslint-disable-line

  return (
    <div className="nw-page screen-enter" style={{ paddingBottom: 24, background: 'radial-gradient(60% 42% at 50% 0%, rgba(240,68,56,0.22) 0%, transparent 70%), #060727' }}>
      <NWStars count={8} />
      <div style={{ position: 'relative', zIndex: 1, padding: '46px 24px 0' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px', borderRadius: 9999, background: 'rgba(240,68,56,0.16)', border: '1px solid rgba(240,68,56,0.46)', color: '#f7a4a4', fontSize: 12, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase' }}>
            <span style={{ width: 7, height: 7, borderRadius: 999, background: '#f04438', boxShadow: '0 0 0 4px rgba(240,68,56,0.18)', animation: 'sock-pulse 1.2s ease-in-out infinite' }} />
            Owlet alert
          </div>
        </div>
        <h1 style={{ fontFamily: 'var(--font-heading)', fontWeight: 600, fontSize: 26, lineHeight: '32px', color: '#fff', margin: '0 0 8px', textAlign: 'center' }}>Connecting you to a clinician</h1>
        <p className="muted" style={{ fontSize: 14, lineHeight: '20px', textAlign: 'center', margin: '0 0 22px' }}>Owlet flagged Nora's readings and is bringing a pediatric provider on now.</p>
        <div style={{ textAlign: 'left', background: 'rgba(240,68,56,0.08)', border: '1px solid rgba(240,68,56,0.45)', borderRadius: 18, padding: '16px 16px 14px' }}>
          <div style={{ color: '#f7a4a4', fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', marginBottom: 12 }}>While we connect, check on Nora</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            {OWLET_RED_TRIAD.map((q, i) => (
              <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', fontSize: 14.5, lineHeight: '20px', color: '#fff' }}>
                <span style={{ color: '#f7a4a4', flexShrink: 0, marginTop: 1 }}>•</span>{q}
              </div>
            ))}
          </div>
        </div>
        <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 12, background: 'rgba(17,19,63,0.7)', border: '1px solid rgba(212,212,249,0.08)', borderRadius: 14, padding: '14px 16px' }}>
          {phase === 0 ? (
            <span style={{ width: 18, height: 18, borderRadius: 999, flexShrink: 0, border: '2px solid #f7a4a4', borderTopColor: 'transparent', animation: 'owlet-spin 700ms linear infinite' }} />
          ) : (
            <span className="check-pop" style={{ width: 20, height: 20, borderRadius: 999, flexShrink: 0, background: 'var(--primary)', color: 'var(--on-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </span>
          )}
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{phase === 0 ? "Dr. Mehta is reviewing Nora's readings…" : 'Connected — opening call…'}</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 1, lineHeight: '17px' }}>Owlet shared Nora's vitals and tonight's context.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Active monitoring ─────────────────────────────────────
function NWActiveScreen({ onBack, onStartVisit, onEditContext, onEnd, context, activatedAt }) {
  const [bpm, setBpm] = useStateN(127);
  const [ox, setOx] = useStateN(97);
  const [lastSec, setLastSec] = useStateN(2);

  useEffectN(() => {
    const id = setInterval(() => {
      setBpm(v => Math.max(115, Math.min(135, Math.round(v + (Math.random() - 0.5) * 4))));
      setOx(v => Math.max(95, Math.min(99, Math.round(v + (Math.random() - 0.5)))));
      setLastSec(s => (s + 2) % 30);
    }, 2000);
    return () => clearInterval(id);
  }, []);

  const band = NW_BANDS[context.band] || NW_BANDS.calm;

  if (band.id === 'action') {
    return <NWAlertConnecting onConnected={onStartVisit} />;
  }

  return (
    <div className="nw-page screen-enter" style={{ paddingBottom: 24 }}>
      <div className="nw-aurora" style={{ background: band.aurora }} />
      <NWStars count={12} />
      <NWTopBar onBack={onBack} title="Night Watch" rightSlot={
        <button className="nw-iconbtn" onClick={onEditContext} aria-label="Edit context">
          <RIcons.Journal size={16} />
        </button>
      } />

      <div style={{ position: 'relative', zIndex: 1, padding: '10px 20px 0', textAlign: 'center' }}>
        <div style={{ position: 'relative', marginBottom: 14, display: 'inline-block' }}>
          <div style={{ width: 84, height: 84, borderRadius: 999, background: "#1a1c4a url('assets/baby-nora.png') center/cover no-repeat", boxShadow: `0 0 0 3px ${band.border}, 0 0 0 8px ${band.tint}, 0 12px 28px rgba(0,0,0,0.4)` }} />
          <span style={{ position: 'absolute', right: -2, bottom: -2, width: 30, height: 30, borderRadius: 999, background: band.dot, color: '#060727', border: '3px solid #060727', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <RIcons.ShieldCheck size={15} />
          </span>
        </div>

        <h1 style={{ fontFamily: 'var(--font-heading)', fontWeight: 600, fontSize: 25, lineHeight: '31px', color: '#fff', margin: '0 0 6px', letterSpacing: '-0.01em' }}>
          {band.id === 'calm' ? 'Nora is protected' : band.title}
        </h1>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: band.ink, whiteSpace: 'nowrap' }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, background: band.dot, animation: 'sock-pulse 1.5s ease-in-out infinite' }} />
          Owlet is watching · {band.tier}
        </div>

        <div style={{ marginTop: 16 }}>
          <CompactLiveReadings bpm={bpm} ox={ox} lastSec={lastSec} />
        </div>
      </div>

      <div style={{ padding: '12px 16px 0', position: 'relative', zIndex: 1 }}>
        <CareTeamCard onStartVisit={onStartVisit} />
      </div>

      <div style={{ padding: '0 16px', position: 'relative', zIndex: 1 }}>
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button className="nw-cta" onClick={onEditContext} style={{ background: 'transparent', color: 'var(--foreground)', border: '1px solid rgba(212,212,249,0.12)', boxShadow: 'none', height: 48 }}>
            <RIcons.Journal size={18} /> What the clinician sees
          </button>
        </div>
        <div style={{ marginTop: 18, padding: '12px 14px', background: 'rgba(125,128,230,0.06)', border: '1px solid rgba(125,128,230,0.16)', borderRadius: 12, fontSize: 12.5, lineHeight: '17px', color: 'rgba(212,212,249,0.78)' }}>
          <b style={{ color: '#fff', fontWeight: 600 }}>Owlet's alert system runs independently.</b>
          {' '}If a clinical alert fires on the Sock, you'll be notified the way you always have been.
        </div>
        <button className="nw-cta-text" onClick={onEnd} style={{ marginTop: 14 }}>End tonight's watch → Morning Summary</button>
      </div>
    </div>
  );
}

function CompactLiveReadings({ bpm, ox, lastSec }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '10px 14px', background: 'rgba(17,19,63,0.55)', border: '1px solid rgba(212,212,249,0.06)', borderRadius: 14, backdropFilter: 'blur(8px)' }}>
      <CompactReading icon={<RIcons.Heart size={15} />} value={bpm} unit="bpm" />
      <span style={{ width: 1, height: 22, background: 'rgba(212,212,249,0.08)' }} />
      <CompactReading icon={<RIcons.Lungs size={15} />} value={ox} unit="%" />
      <span style={{ width: 1, height: 22, background: 'rgba(212,212,249,0.08)' }} />
      <CompactReading icon={<RIcons.Sleep size={15} />} value="Light" />
      <span style={{ width: 1, height: 22, background: 'rgba(212,212,249,0.08)' }} />
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--foreground-muted)', fontSize: 11, fontWeight: 500, whiteSpace: 'nowrap' }}>
        <span style={{ width: 5, height: 5, borderRadius: 999, background: 'var(--primary)', animation: 'sock-pulse 1.5s ease-in-out infinite' }} />
        {lastSec}s
      </div>
    </div>
  );
}

function CompactReading({ icon, value, unit }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6, flex: 1, justifyContent: 'center', minWidth: 0 }}>
      <span style={{ color: 'var(--primary)', opacity: 0.85, display: 'inline-flex', alignSelf: 'center' }}>{icon}</span>
      <span style={{ fontFamily: 'var(--font-heading)', fontWeight: 600, fontSize: 17, color: '#fff', letterSpacing: '-0.01em', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{value}</span>
      {unit && <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--foreground-muted)', whiteSpace: 'nowrap' }}>{unit}</span>}
    </div>
  );
}

function CareTeamCard({ onStartVisit }) {
  return (
    <div style={{ background: 'rgba(17,19,63,0.7)', border: '1px solid rgba(212,212,249,0.06)', borderRadius: 18, padding: 18, backdropFilter: 'blur(12px)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
        <div style={{ display: 'flex', flexShrink: 0 }}>
          {["url('assets/doc-mehta.png')", "url('assets/doc-senior.png')", "url('assets/doc-okafor.png')"].map((g, i) => (
            <div key={i} style={{ width: 36, height: 36, borderRadius: 999, background: `#1a1c4a ${g} center/cover no-repeat`, border: '2px solid #11133f', marginLeft: i === 0 ? 0 : -12, boxShadow: '0 4px 12px rgba(0,0,0,0.3)', position: 'relative', zIndex: 3 - i }} />
          ))}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 600, fontSize: 16, color: '#fff', whiteSpace: 'nowrap' }}>Care team</div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 2, fontSize: 11.5, fontWeight: 600, letterSpacing: '0.06em', color: 'var(--primary)', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--primary)', animation: 'sock-pulse 1.5s ease-in-out infinite' }} />
            On standby · ~2 min
          </div>
        </div>
      </div>
      <button onClick={onStartVisit} style={{ width: '100%', height: 44, borderRadius: 12, background: 'rgba(157,227,205,0.12)', color: 'var(--primary)', border: '1px solid rgba(157,227,205,0.32)', fontSize: 14, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
        <RIcons.Chat size={15} /> Chat with care team
      </button>
      <div className="hint muted" style={{ marginTop: 12, fontSize: 11.5, fontWeight: 500, lineHeight: '16px', display: 'flex', alignItems: 'center', gap: 6 }}>
        <RIcons.Doctor size={12} />
        A pediatric provider picks up with full context if you reach out.
      </div>
    </div>
  );
}

// ─── Tab screen — value prop + paywall entry ─────────────────

const NW_TAB_PILLARS = [
  {
    id: 'telehealth',
    badge: '24/7',
    icon: (s) => <RIcons.Doctor size={s} />,
    title: 'Pediatric visits, anytime',
    sub: 'Morning rounds come twice a day — your signed check-ins on a schedule. Care+ is for when you can\'t wait: chat or video with a pediatric provider and get answers now, not at the next round.',
    points: ['No waiting for the next round', 'Sock + journal context in every visit', 'Same-day sick visits'],
  },
  {
    id: 'nightwatch',
    badge: 'Overnight',
    icon: (s) => <RIcons.Watch size={s} />,
    title: 'Night Watch',
    sub: 'Owlet\'s branded overnight watch for fever nights and fragile sleep. Vitals stream, a care package builds in the background, and you wake to a signed morning round.',
    points: ['Live Sock monitoring', 'Doctor-ready care package', 'Morning round in your inbox'],
    branded: true,
  },
  {
    id: 'autonightwatch',
    badge: 'Care+',
    icon: (s) => <RIcons.Sparkles size={s} />,
    title: 'Auto Night Watch',
    sub: 'After 30 nights, Owlet learns what normal looks like for Nora specifically — not just for babies in general. When her readings drift meaningfully from her pattern, Night Watch arms itself before you\'d even notice.',
    points: [
      'Arms before you go to bed',
      'Calibrated to Nora\'s baseline, not generic thresholds',
      'Activates after your first month',
    ],
    branded: true,
    careplus: true,
  },
];

function NightWatchTabDock({ nwActive, onGetStarted, onOpenActive }) {
  return (
    <div className="nw-tab-dock-fixed" aria-label="Care+ actions">
      <button
        type="button"
        className="nw-cta glow"
        onClick={nwActive ? onOpenActive : onGetStarted}
      >
        {nwActive ? 'View tonight\'s watch' : 'Get Care+'}
        <RIcons.ChevronRight size={18} />
      </button>
      <p className="nw-tab-fine">
        Emergency Sock alerts always run on their own. Care+ adds clinicians, context, and Night Watch backup.
      </p>
    </div>
  );
}

function NightWatchTabScreen({ onGetStarted, nwActive, onOpenActive }) {
  return (
    <div className="nw-page nw-tab-page screen-enter" data-screen-label="Night Watch tab">
      <div className="nw-aurora" />
      <NWStars count={12} />

      <div className="nw-tab-scroll">
        <div className="nw-tab-hero">
          <div className="nw-tab-clock-ring" aria-hidden="true">
            <RIcons.Clock size={22} />
          </div>
          <div className="nw-tab-kicker">Care+ · Round-the-clock</div>
          <h1 className="nw-tab-headline">Care that doesn&apos;t clock out</h1>
          <p className="nw-tab-lede">
            Telehealth when you need a clinician. <strong>Night Watch</strong> when you need the night watched. One membership, built around Nora.
          </p>
        </div>

        {nwActive && (
          <button type="button" className="nw-tab-active-pill" onClick={onOpenActive}>
            <span className="nw-tab-active-dot" />
            <span style={{ flex: 1, textAlign: 'left' }}>
              <span className="nw-tab-active-title">Night Watch is on tonight</span>
              <span className="nw-tab-active-sub">Live vitals · care package building</span>
            </span>
            <RIcons.ChevronRight size={16} />
          </button>
        )}

        <div className="nw-tab-included">
          <div className="nw-tab-included-head">
            <span className="nw-tab-included-plan">Care+</span>
            <h2 className="nw-tab-included-title">All included — one membership</h2>
            <p className="nw-tab-included-lede">Day, night, and overtime between rounds. No tiers to pick.</p>
          </div>
          <div className="nw-tab-included-list">
            {NW_TAB_PILLARS.map((p, i) => (
              <div
                key={p.id}
                className={`nw-tab-included-row ${i < NW_TAB_PILLARS.length - 1 ? 'nw-tab-included-row--divided' : ''} ${p.branded ? 'nw-tab-included-row--gold' : ''}`}
              >
                <div className="nw-tab-included-row-head">
                  <span className="nw-tab-included-icon">{p.icon(18)}</span>
                  <div className="nw-tab-included-row-titles">
                    <span className="nw-tab-included-tag">{p.badge}</span>
                    <h3 className="nw-tab-included-row-title">{p.title}</h3>
                  </div>
                </div>
                <p className="nw-tab-included-row-sub">{p.sub}</p>
                <ul className="nw-tab-included-points">
                  {p.points.map((pt) => (
                    <li key={pt}>
                      <RIcons.Check size={11} />
                      {pt}
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        <div className="nw-tab-bridge">
          <div className="nw-tab-bridge-icon" aria-hidden="true">
            <RIcons.Moon size={18} />
          </div>
          <p className="nw-tab-bridge-copy">
            <strong>Permission to sleep.</strong> Most nights you may only need 24/7 access. When something feels off, arm Night Watch — vitals, context, and backup without repeating the story.
          </p>
        </div>

        <div className="nw-tab-careplus">
          <div className="nw-tab-careplus-badge">Care+</div>
          <p className="nw-tab-careplus-copy">
            Unlimited telehealth visits, Night Watch nights, Talk to a doctor, and morning rounds — <strong>$12.99/mo</strong>.
            Or arm <strong>tonight only</strong> for $4.99.
          </p>
        </div>
      </div>
    </div>
  );
}

// ─── Upsell surfaces ───────────────────────────────────────

// Ghost card — shown to non-Care+ parents the morning after a night with notable vitals deviation.
// Shows what Auto Night Watch would have caught, making the upsell personal and counterfactual.
function AutoNWGhostCard({ onUpgrade }) {
  return (
    <div className="nw-ghost-card" onClick={onUpgrade}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div className="nw-ghost-card-icon">
          <RIcons.ShieldCheck size={18} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="nw-ghost-card-eyebrow">Night Watch · Care+</div>
          <div className="nw-ghost-card-title">Last night, you would&apos;ve benefited from Night Watch</div>
          <div className="nw-ghost-card-sub">
            Nora&apos;s heart rate ran higher than her usual overnight baseline — the kind of night Care+ is built for. We would&apos;ve armed a watch, packaged the context, and had a pediatric provider on standby while you slept.
          </div>
          <div className="nw-ghost-card-cta">
            See what Care+ includes <RIcons.ChevronRight size={12} />
          </div>
        </div>
      </div>
    </div>
  );
}

// Suggest card — triggered by journal flags on home screen.
function NightWatchSuggestCard({ onActivate }) {
  const hasTempFlag = JOURNAL_SUMMARY && JOURNAL_SUMMARY.tempFlag;
  if (!hasTempFlag) return null;

  return (
    <div onClick={onActivate} style={{
      margin: '0 16px 14px', padding: '14px 16px',
      background: 'linear-gradient(135deg, rgba(247,200,123,0.10) 0%, var(--surface) 70%)',
      border: '1px solid rgba(247,200,123,0.28)', borderRadius: 18,
      cursor: 'pointer', transition: '160ms ease-out',
      boxShadow: '0 8px 20px rgba(0,0,0,0.2)',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, flexShrink: 0, background: 'rgba(247,200,123,0.14)', color: '#f7c87b', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <RIcons.Watch size={18} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#fff', marginBottom: 2 }}>Consider Night Watch tonight</div>
          <div style={{ fontSize: 12, color: 'var(--foreground-muted)', lineHeight: '17px' }}>
            Nora had a 100.4°F logged today. Activate for extra peace of mind overnight.
          </div>
        </div>
        <div style={{ color: 'var(--foreground-muted)', flexShrink: 0, marginTop: 2 }}>
          <RIcons.ChevronRight size={15} />
        </div>
      </div>
      <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, color: '#f7c87b' }}>
        <RIcons.Watch size={13} /> Set up Night Watch →
      </div>
    </div>
  );
}

// Home banner — replaces SockStatus when Night Watch is armed.
function NightWatchActiveBanner({ onTap, context }) {
  const band = NW_BANDS[context.band] || NW_BANDS.calm;
  return (
    <div className="nw-home-banner" onClick={onTap}>
      <div style={{ position: 'relative', zIndex: 1, display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 36, height: 36, borderRadius: 999, background: band.tint, border: `1px solid ${band.border}`, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: band.dot }}>
          <RIcons.ShieldCheck size={18} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#fff' }}>Night Watch · Active</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2, fontSize: 12, color: band.ink, fontWeight: 600 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: band.dot, animation: 'sock-pulse 1.5s ease-in-out infinite' }} />
            {band.tier} · Owlet is watching
          </div>
        </div>
        <RIcons.ChevronRight size={15} style={{ color: 'var(--foreground-muted)', flexShrink: 0 }} />
      </div>
    </div>
  );
}

const RNightWatch = {
  NWContextScreen, NWPackageScreen, NWQuickArm, NWActivatingScreen, NWActiveScreen,
  NightWatchTabScreen, NightWatchTabDock, NightWatchSuggestCard, NightWatchActiveBanner, AutoNWGhostCard, DEFAULT_CONTEXT,
};
