// v8 "Bloom Dream" — faithful LIVE recreation of the real Daily Doula app
// (Today screen) for the hero phone trio. Authored at the REAL app width (390px)
// with the real font sizes/spacing from src/v2/V2Today.tsx + tokens.ts, then
// scaled to fit the phone by the trio (CSS zoom). Scrollable + sticky tab bar.

const RA_DESIGN_W = 390;

// Real brand tokens (verbatim from src/design/tokens.ts).
function realBrand(stage) {
  const base = {
    cream:'#F6EDDE', creamDeep:'#E5D3B0', card:'#FBF5E9',
    cardMint:'#DEEAD0', cardBlush:'#F2D6C7', cardLemon:'#F2E5A5', cardSky:'#D4DDDF', cardLilac:'#E3D5E3',
    ink:'#2A1B14', inkSoft:'#5B3E2E', inkMute:'#9B8670',
    butter:'#EDB94C', rose:'#E89AA1', pistachio:'#B8C89A',
    rule:'rgba(42,27,20,0.18)', ruleStrong:'rgba(42,27,20,0.25)',
    forest:'#2D4435', forestInk:'#E8DFC9',
  };
  if (stage === 'ttc') return { ...base, accent:'#D9A035', accentSoft:'#F0CB6F',
    period:'#C44A52', fertile:'#7C9569', ovulation:'#D9A035', luteal:'#C97A3D' };
  if (stage === 'postpartum') return { ...base, accent:'#7C9569', accentSoft:'#B8C89A', forest:'#3C3A2D' };
  return { ...base, accent:'#D9582C', accentSoft:'#F4A88F' };
}
const raF = { display:"'Fraunces', Georgia, serif", body:"'Instrument Sans', system-ui, sans-serif", mono:"'JetBrains Mono', ui-monospace, monospace" };

const RA_CONFIG = {
  ttc: {
    pill:'Trying · Cycle 1 · Day 13', greet:'Hey beautiful,', name:'Tess.', accent:'#D9A035',
    deck:[
      {img:'paint-ttc.png', title:'One good thing today', note:"You showed up for yourself today, even when it was hard. That counts. 🌸"},
      {img:'paint-postpartum.png', title:'A softer evening', note:"Slow down tonight — warm tea, early bed. I’ve got tomorrow’s plan. 🌙"},
      {img:'paint-pregnancy.png', title:'Something to hope for', note:"Name one thing you’re hopeful about. I’ll keep it safe for you. 💛"},
    ],
    chips:[['📋','Doctor questions'],['✨','Log a symptom'],['🌅','Test day plan'],['💜','How I feel']],
    tabs:[['Today','☀️'],['Cycle','◐'],['Della',null],['Facts','✦'],['Calendar','📅']],
  },
  pregnancy: {
    pill:'Pregnancy · Week 28 · 3rd Trimester', due:'Due Aug 26', greet:'Hey beautiful,', name:'Maya.', accent:'#D9582C',
    deck:[
      {img:'paint-pregnancy.png', title:'Name three good things today', note:"Three good things — even tiny ones — rewire how the day feels. Tell me yours? 💛"},
      {img:'paint-ttc.png', title:'A quiet win', note:"You drank water and rested. That’s real care. Proud of you. 🌸"},
      {img:'paint-postpartum.png', title:'Picture this', note:"Close your eyes and picture meeting them. I’ll be right here. 🌙"},
    ],
    chips:[['💞','Note to partner'],['🎀','How I feel'],['🔮','What to expect'],['✨','Baby names']],
    tabs:[['Today','☀️'],['Growth','📖'],['Della',null],['Journal','📓'],['Planner','📋']],
  },
  postpartum: {
    pill:'Postpartum · 2 Months', greet:'Hey gorgeous,', name:'Priya.', accent:'#7C9569',
    deck:[
      {img:'paint-postpartum.png', title:'One tiny thing about baby today', note:"Ila is tracking your face across the room now. She’s memorizing you. 🥹"},
      {img:'paint-pregnancy.png', title:'A gentle reminder', note:"You’re doing better than you think. Rest is productive too. 💛"},
      {img:'paint-ttc.png', title:'For you, not the baby', note:"What’s one small thing just for you today? Let’s plan it. 🌸"},
    ],
    chips:[['👶','Baby milestones'],['🍼','Feeding help'],['📷','Photo journal'],['🕯️','Self care']],
    tabs:[['Today','☀️'],['Growth','📖'],['Della',null],['Journal','📓'],['Planner','📋']],
  },
};

function RealToday({ stage }) {
  const b = realBrand(stage);
  const c = RA_CONFIG[stage];
  return (
    <div style={{ width: RA_DESIGN_W, fontFamily: raF.body, color:b.ink, background:b.cream, minHeight:'100%', paddingBottom:30 }}>
      {/* header */}
      <div style={{ padding:'26px 22px 0', display:'flex', alignItems:'center', gap:7 }}>
        <DDMark size={22} />
        <span style={{ fontFamily:raF.display, fontSize:16, fontWeight:500, letterSpacing:'-0.01em' }}>My Daily Doula</span>
        <span style={{ marginLeft:'auto', width:34, height:34, borderRadius:'50%', background:'#2A1B14',
          color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, fontWeight:600 }}>{c.name[0]}</span>
      </div>
      {/* stage pill + due */}
      <div style={{ padding:'16px 22px 0', display:'flex', flexDirection:'column', alignItems:'flex-start', gap:8 }}>
        <span style={{ display:'inline-flex', alignItems:'center', gap:8, padding:'6px 14px', borderRadius:20,
          background:b.creamDeep, fontSize:13.5, fontWeight:600 }}>
          <span style={{ width:8, height:8, borderRadius:'50%', background:b.accent }} />{c.pill}
        </span>
        {c.due && (
          <span style={{ position:'relative', display:'inline-flex', alignItems:'center', gap:6, padding:'6px 14px',
            borderRadius:20, background:b.creamDeep, fontSize:13, fontWeight:600, border:`1.5px dashed ${b.rule}` }}>
            <span aria-hidden="true" style={{ position:'absolute', top:-6, left:-4, width:30, height:11,
              background:'repeating-linear-gradient(135deg,#F0A57D 0 8px,#FBC9A8 8px 16px)', transform:'rotate(-12deg)', opacity:0.9 }} />
            📅 {c.due}
          </span>
        )}
      </div>
      {/* greeting */}
      <div style={{ padding:'14px 22px 0', fontFamily:raF.display, fontSize:34, fontWeight:600, lineHeight:1, letterSpacing:'-0.03em' }}>
        {c.greet}<br /><em style={{ color:b.accent, fontStyle:'italic', fontWeight:500 }}>{c.name}</em>
      </div>

      {/* album stack — tap to flip, swipe to browse, gentle auto-flip */}
      <RealAlbum b={b} c={c} />

      {/* widgets */}
      <div style={{ padding:'16px 22px 0', display:'flex', flexDirection:'column', gap:10 }}>
        {stage === 'ttc' && <RAStack b={b} blocks={['cycle','partner','vitamin','distraction','todos8']} />}
        {stage === 'pregnancy' && <RAStack b={b} blocks={['ritualPreg','gender','names','partnerArjun','mood','todos0']} />}
        {stage === 'postpartum' && <RAStack b={b} blocks={['ritualPost','week','milestones','partnerArjun','mood','todos0']} />}
      </div>
    </div>
  );
}

function RAStack({ b, blocks }) { return <>{blocks.map((k,i) => <RAWidget key={i} b={b} k={k} />)}</>; }

function RAWidget({ b, k }) {
  if (k === 'cycle') return <RACycleBar b={b} />;
  if (k === 'partner') return <RAPartner b={b} label="Loop Your Partner In?" />;
  if (k === 'partnerArjun') return <RAPartner b={b} label="Loop Arjun In?" />;
  if (k === 'vitamin') return <RARitual b={b} bg={b.cardSky} icon="💊" title="Prenatal vitamin"
    body="Folic acid plus your daily multi — take with food and water." pill="30 SEC" rest="Tap When Done" dashed />;
  if (k === 'distraction') return <RARitual b={b} bg={b.cardMint} icon="💻" title="A Small Distraction"
    body="Make yourself a warm tea or golden milk, find a comfortable spot, and lie down for five minutes while you sip it slowly." pill="5 MIN" rest="Tap To Start" dashed />;
  if (k === 'ritualPreg') return <RARitual b={b} bg={b.cardMint} icon="🌿" title="Warm drink, phones down"
    body="Make yourself tea or warm water with lemon, find a quiet spot, and sit with it for three minutes without checking anything." pill="3 MIN" rest="Tap When Done" dashed />;
  if (k === 'ritualPost') return <RARitual b={b} bg={b.cardMint} icon="🍵" title="Sit with something warm"
    body="Make tea or broth, find a spot where you can see Ila, and just breathe for five minutes." pill="5 MIN" rest="Tap When Done" dashed />;
  if (k === 'gender') return <RAGender b={b} />;
  if (k === 'names') return <RANames b={b} />;
  if (k === 'week') return <RAWeek b={b} />;
  if (k === 'milestones') return <RAMilestones b={b} />;
  if (k === 'mood') return <RAMood b={b} />;
  if (k === 'todos0') return <RATodos b={b} count={0} items={[]} />;
  if (k === 'todos8') return <RATodos b={b} count={8} items={[
    ['💊','Start prenatal vitamins','Folic acid is the big one — start now.','Soon'],
    ['📋','Schedule a preconception checkup','Review your health history and concerns.','Soon'],
    ['📅','Learn your fertile window','Ovulation usually happens 12 to 16 days before your period.'],
    ['💊','Review your medications','Some common meds are not safe for early pregnancy.'],
  ]} />;
  return null;
}

function RACard({ b, bg, dashed, children, style={} }) {
  return <div style={{ background:bg||b.card, borderRadius:18, padding:14,
    border:`1.5px ${dashed?'dashed':'solid'} ${b.rule}`, ...style }}>{children}</div>;
}

function RARitual({ b, bg, icon, title, body, pill, rest, dashed }) {
  return (
    <RACard b={b} bg={bg} dashed={dashed} style={{ display:'flex', gap:12, alignItems:'flex-start' }}>
      <div style={{ width:40, height:40, borderRadius:'50%', background:b.pistachio, flexShrink:0,
        display:'flex', alignItems:'center', justifyContent:'center', fontSize:18 }}>{icon}</div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontFamily:raF.display, fontSize:15.5, fontWeight:500, lineHeight:1.25 }}>{title}</div>
        <div style={{ fontSize:12.5, color:b.inkSoft, marginTop:4, lineHeight:1.4 }}>{body}</div>
        <div style={{ marginTop:6, display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontFamily:raF.mono, fontSize:9.5, letterSpacing:'0.14em', padding:'3px 8px', background:b.accent, color:b.cream, borderRadius:10, fontWeight:600 }}>{pill}</span>
          <span style={{ fontFamily:raF.mono, fontSize:9.5, letterSpacing:'0.14em', color:b.inkMute, textTransform:'uppercase' }}>{rest}</span>
        </div>
      </div>
    </RACard>
  );
}

function RACycleBar({ b }) {
  return (
    <RACard b={b} bg={b.cardBlush} dashed>
      <div style={{ display:'flex', justifyContent:'space-between', fontFamily:raF.mono, fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:b.inkMute }}>
        <span>Cycle 1 · Day 13</span><span>28 Days</span>
      </div>
      <div style={{ position:'relative', height:9, borderRadius:5, marginTop:9,
        background:`linear-gradient(90deg, ${b.period} 0 18%, ${b.luteal} 18% 32%, ${b.fertile} 32% 64%, ${b.ovulation} 64% 72%, ${b.luteal} 72% 100%)` }}>
        <span style={{ position:'absolute', left:'46%', top:'50%', transform:'translate(-50%,-50%)', width:18, height:18, borderRadius:'50%', background:'#fff', border:`3px solid ${b.ink}` }} />
      </div>
      <div style={{ fontFamily:raF.display, fontSize:17, fontWeight:600, marginTop:10 }}>Fertile Window · Open</div>
      <div style={{ fontSize:12.5, color:b.inkSoft, marginTop:3, lineHeight:1.4 }}>Test Day Friday, June 19, 2026. 2 Days To Peak. Window Is Open.</div>
    </RACard>
  );
}

function RAPartner({ b, label }) {
  return (
    <RACard b={b} bg={b.cardLilac} dashed>
      <div style={{ fontFamily:raF.mono, fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:b.inkMute }}>{label}</div>
      <div style={{ fontSize:12.5, color:b.inkSoft, margin:'8px 0 11px', lineHeight:1.45 }}>
        Add a WhatsApp number and you'll be able to send quick notes — a meal, a walk, a hand with the baby, or a soft "thinking of you."
      </div>
      <span style={{ display:'inline-block', padding:'9px 18px', borderRadius:20, background:b.accent, color:b.cream, fontSize:13, fontWeight:600 }}>Set up partner</span>
    </RACard>
  );
}

function RAGender({ b }) {
  const opts = [['Girl','🎀','#F2C7D2'],['Boy','🧸','#C9DCEB'],['Surprise','✨','#E3D5E3']];
  return (
    <RACard b={b} bg={b.cardLemon} dashed>
      <div style={{ fontFamily:raF.display, fontSize:16.5, fontWeight:600, marginBottom:10 }}>Do You Know The Gender Yet?</div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:9 }}>
        {opts.map(([l,e,bg]) => (
          <div key={l} style={{ background:bg, borderRadius:14, padding:'14px 6px', textAlign:'center' }}>
            <div style={{ fontSize:20 }}>{e}</div>
            <div style={{ fontSize:13, fontWeight:600, marginTop:5, color:b.ink }}>{l}</div>
          </div>
        ))}
      </div>
    </RACard>
  );
}

function RANames({ b }) {
  const names = [['Lira','lyre, musical harmony'],['Soleil','sun, warmth and light'],['Kaia','sea, flowing and free']];
  return (
    <RACard b={b} bg={b.cardBlush} dashed>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <div><div style={{ fontFamily:raF.mono, fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:b.inkMute }}>Name Ideas Today</div>
          <div style={{ fontFamily:raF.display, fontSize:16.5, fontWeight:600 }}>Fresh Picks For <em style={{ color:b.accent, fontStyle:'italic' }}>You</em></div></div>
        <span style={{ fontSize:16 }}>🏷️</span>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, margin:'12px 0' }}>
        {names.map(([n,m],i) => (
          <div key={n} style={{ background:b.card, borderRadius:12, padding:'11px 7px', textAlign:'center', border:i===0?`1px solid ${b.accent}`:`1px solid ${b.rule}` }}>
            <div style={{ fontFamily:raF.display, fontSize:15.5, fontWeight:600 }}>{n}</div>
            <div style={{ fontSize:9, color:b.inkMute, marginTop:4, lineHeight:1.3 }}>{m}</div>
          </div>
        ))}
      </div>
      <div style={{ background:b.card, borderRadius:12, padding:'11px 13px', fontSize:12.5, color:b.inkMute, border:`1px solid ${b.rule}` }}>try 'cute short girl names'…</div>
    </RACard>
  );
}

function RAWeek({ b }) {
  return (
    <RACard b={b} bg={`linear-gradient(135deg, ${b.rose}22, ${b.butter}22)`} dashed style={{ display:'flex', gap:12, alignItems:'center' }}>
      <div style={{ width:52, height:52, borderRadius:'50%', background:b.card, flexShrink:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
        <div style={{ fontFamily:raF.display, fontSize:22, fontWeight:600, color:b.accent, lineHeight:1 }}>2</div>
        <div style={{ fontFamily:raF.mono, fontSize:7, letterSpacing:'0.1em', color:b.inkMute, textTransform:'uppercase' }}>Months</div>
      </div>
      <div style={{ flex:1 }}>
        <div style={{ fontFamily:raF.display, fontSize:13.5, fontStyle:'italic', lineHeight:1.25 }}>Holding their head steady</div>
        <div style={{ fontSize:11, color:b.inkSoft, marginTop:3, lineHeight:1.35 }}>Watching them lift and hold their head during tummy time feels like…</div>
      </div>
      <span style={{ fontFamily:raF.mono, fontSize:8, letterSpacing:'0.14em', color:b.accent, textTransform:'uppercase', fontWeight:600 }}>Read More →</span>
    </RACard>
  );
}

function RAMilestones({ b }) {
  const items = [['First real smile','Month 2',true],['Holding their head steady','Month 3','cur'],['First genuine laugh','Month 4',false],['Sleeping through the night','Month 4–6',false]];
  return (
    <RACard b={b} bg={b.cardSky}>
      <div style={{ fontFamily:raF.mono, fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:b.inkMute }}>Milestones · June</div>
      <div style={{ fontSize:14, marginTop:3 }}>Next: <em style={{ fontFamily:raF.display, fontStyle:'italic', fontWeight:600, color:b.ink }}>Holding their head steady</em></div>
      <div style={{ display:'flex', flexDirection:'column', gap:8, margin:'11px 0' }}>
        {items.map(([t,m,st]) => (
          <div key={t} style={{ display:'flex', alignItems:'center', gap:10, padding:st==='cur'?'8px 9px':'0 9px',
            background:st==='cur'?'rgba(255,255,255,0.5)':'transparent', borderRadius:10, border:st==='cur'?`1px dashed ${b.ruleStrong}`:'none' }}>
            <span style={{ width:20, height:20, borderRadius:'50%', flexShrink:0, border:`2px solid ${st===true?b.accent:b.ruleStrong}`, background:st===true?b.accent:'transparent',
              display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontSize:11 }}>{st===true?'✓':''}</span>
            <span style={{ flex:1, fontSize:13.5, color:st===true?b.inkMute:b.ink, textDecoration:st===true?'line-through':'none' }}>{t}</span>
            <span style={{ fontFamily:raF.mono, fontSize:8.5, letterSpacing:'0.1em', color:b.inkMute, textTransform:'uppercase' }}>{m}</span>
          </div>
        ))}
      </div>
      <div style={{ textAlign:'center', padding:'10px', borderRadius:20, background:b.accent, color:b.cream, fontSize:13, fontWeight:600, fontFamily:raF.mono, letterSpacing:'0.1em' }}>TALK TO DELLA →</div>
    </RACard>
  );
}

function RAMood({ b }) {
  const m = [['😊','Great'],['🙂','Good'],['😐','Meh'],['😕','Low'],['🥺','Rough']];
  return (
    <RACard b={b} bg={b.card}>
      <div style={{ fontSize:15, fontWeight:600, marginBottom:11 }}>How Are You Feeling Today?</div>
      <div style={{ display:'flex', justifyContent:'space-between' }}>
        {m.map(([e,l]) => (
          <div key={l} style={{ textAlign:'center' }}>
            <div style={{ width:44, height:44, borderRadius:'50%', background:b.cardLemon, display:'flex', alignItems:'center', justifyContent:'center', fontSize:22 }}>{e}</div>
            <div style={{ fontSize:11, color:b.inkMute, marginTop:5 }}>{l}</div>
          </div>
        ))}
      </div>
    </RACard>
  );
}

function RATodos({ b, count, items }) {
  return (
    <RACard b={b} bg={b.card}>
      <div style={{ display:'flex', gap:20, borderBottom:`1px solid ${b.rule}`, paddingBottom:10, marginBottom:items.length?11:10 }}>
        <span style={{ fontSize:14, fontWeight:700, color:b.ink, borderBottom:`2px solid ${b.accent}`, paddingBottom:7 }}>📋 To Do ({count})</span>
        <span style={{ fontSize:14, fontWeight:600, color:b.inkMute }}>📝 Notes (0)</span>
      </div>
      {items.map(([e,t,d,tag],i) => (
        <div key={i} style={{ display:'flex', gap:10, alignItems:'flex-start', padding:'9px 0', borderBottom:i<items.length-1?`1px solid ${b.rule}`:'none' }}>
          <span style={{ width:18, height:18, borderRadius:4, border:`2px solid ${b.ruleStrong}`, flexShrink:0, marginTop:1 }} />
          <div style={{ flex:1 }}>
            <div style={{ fontSize:13.5, fontWeight:600 }}>{e} {t} {tag && <span style={{ fontFamily:raF.mono, fontSize:8, color:b.accent, letterSpacing:'0.1em' }}>{tag.toUpperCase()}</span>}</div>
            <div style={{ fontSize:11, color:b.inkMute, marginTop:2, lineHeight:1.35 }}>{d}</div>
          </div>
        </div>
      ))}
      <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:items.length?11:0, padding:'11px 13px', border:`1.5px dashed ${b.rule}`, borderRadius:14 }}>
        <span style={{ fontSize:13, color:b.inkMute }}>Add a to-do…</span>
        <span style={{ marginLeft:'auto', fontSize:12, fontWeight:600, color:b.inkMute, padding:'5px 14px', border:`1px solid ${b.rule}`, borderRadius:14 }}>Add</span>
      </div>
    </RACard>
  );
}

// Sticky bottom tab bar (the Today/Growth/Della pill). Rendered at phone scale.
function RATabBar({ stage }) {
  const b = realBrand(stage);
  const c = RA_CONFIG[stage];
  return (
    <div style={{ position:'absolute', left:9, right:9, bottom:9, zIndex:22,
      background:'rgba(255,253,246,0.94)', backdropFilter:'blur(10px)', borderRadius:20,
      border:`1px solid ${b.rule}`, boxShadow:'0 10px 24px -12px rgba(42,27,20,0.4)',
      display:'flex', alignItems:'center', justifyContent:'space-around', padding:'7px 5px' }}>
      {c.tabs.map(([label,icon],i) => {
        const active = i === 0;
        if (label === 'Della') return (
          <span key={label} style={{ fontFamily:raF.display, fontStyle:'italic', fontSize:13.5, fontWeight:600,
            color:b.accent, background: stage==='postpartum'?'#E7EFD9':'#F3E4DA', padding:'5px 13px', borderRadius:15 }}>Della</span>
        );
        return (
          <span key={label} style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:3 }}>
            <span style={{ fontSize:15, opacity:active?1:0.5, filter:active?'none':'grayscale(1)' }}>{icon}</span>
            <span style={{ fontFamily:raF.mono, fontSize:6.5, letterSpacing:'0.08em', textTransform:'uppercase', color:active?b.ink:b.inkMute, fontWeight:active?700:500 }}>{label}</span>
          </span>
        );
      })}
    </div>
  );
}

// Album stack — tap center to flip to Della's note, tap a side card to bring it
// forward, swipe to browse. A gentle auto-flip runs (also on background phones)
// to mirror the real app's living deck. Reduced motion → static, no auto-flip.
function RealAlbum({ b, c }) {
  const reduced = useReducedMotion();
  const deck = c.deck;
  const [idx, setIdx] = React.useState(0);
  const [flipped, setFlipped] = React.useState(null);
  const idxRef = React.useRef(0);
  React.useEffect(() => { idxRef.current = idx; }, [idx]);
  React.useEffect(() => {
    if (reduced) return;
    let t = [];
    const loop = () => {
      t.push(setTimeout(() => setFlipped(idxRef.current), 3000));
      t.push(setTimeout(() => setFlipped(null), 5600));
      t.push(setTimeout(() => { setIdx(i => (i + 1) % deck.length); loop(); }, 7600));
    };
    loop();
    return () => t.forEach(clearTimeout);
  }, [reduced, deck.length]);

  const start = React.useRef(null), moved = React.useRef(false);
  const down = (e) => { start.current = { x:e.clientX, y:e.clientY }; moved.current = false; };
  const move = (e) => { if (!start.current) return; if (Math.abs(e.clientX - start.current.x) > 8) moved.current = true; };
  const up = (e) => { const s = start.current; start.current = null; if (!s) return;
    const dx = e.clientX - s.x; if (Math.abs(dx) < 36) return; setFlipped(null);
    if (dx < 0) setIdx(i => Math.min(deck.length - 1, i + 1)); else setIdx(i => Math.max(0, i - 1)); };

  return (
    <>
      <div onPointerDown={down} onPointerMove={move} onPointerUp={up}
        style={{ position:'relative', height:310, marginTop:20, display:'flex', alignItems:'center', justifyContent:'center', perspective:1400, touchAction:'pan-y' }}>
        {deck.map((card, i) => {
          const off = i - idx, abs = Math.abs(off); if (abs > 2) return null;
          const isCenter = i === idx, isFlipped = flipped === i;
          // Pastel tone derived from the painting (front tint + flip-back colour) —
          // the website is warm pastels, never green.
          const tone = card.img.includes('ttc') ? { base:'#F3D7DC', back:'#EAC9D2', ink:'#76313E' } :
            card.img.includes('postpartum') ? { base:'#F8DAC9', back:'#F2CDBB', ink:'#8E4330' } :
            { base:'#F1E4C7', back:'#E8D6B6', ink:'#6E531D' };
          return (
            <div key={i} onClick={() => { if (moved.current) return; if (isCenter) setFlipped(f => f === i ? null : i); else { setIdx(i); setFlipped(null); } }}
              style={{ position:'absolute', width:200, height:270,
                transform:`translateX(${off*58}px) translateY(${abs*6}px) rotate(${off*3.5}deg) scale(${1-abs*0.07})`,
                zIndex:10-abs, transition:'transform 0.5s cubic-bezier(.2,.8,.2,1)', transformStyle:'preserve-3d', cursor:'pointer' }}>
              <div style={{ position:'absolute', inset:0, transformStyle:'preserve-3d',
                transition:'transform 0.7s cubic-bezier(.2,.8,.2,1)', transform: isFlipped ? 'rotateY(180deg)' : 'rotateY(0)' }}>
                {/* FRONT — full-bleed painting with the header overlaid + title below (matches the real app) */}
                <div style={{ position:'absolute', inset:0, backfaceVisibility:'hidden', WebkitBackfaceVisibility:'hidden',
                  background:b.card, borderRadius:14, padding:'10px 10px 12px', boxShadow:'0 16px 32px -12px rgba(42,27,20,0.3), 0 2px 0 rgba(42,27,20,0.05)', display:'flex', flexDirection:'column' }}>
                  <div style={{ flex:1, position:'relative', borderRadius:8, overflow:'hidden', background:tone.base }}>
                    <img src={`assets/realapp/${card.img}`} alt="" style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', mixBlendMode:'multiply', opacity:0.92 }} />
                    <div aria-hidden="true" style={{ position:'absolute', inset:0, background:tone.base, mixBlendMode:'soft-light', opacity:0.5 }} />
                    <span style={{ position:'absolute', top:8, left:10, fontFamily:raF.mono, fontSize:9, letterSpacing:'0.15em', color:b.ink, opacity:0.95, textTransform:'uppercase', textShadow:'0 1px 2px rgba(255,255,255,0.4)', zIndex:2 }}>Today</span>
                    <span style={{ position:'absolute', top:8, right:10, fontFamily:raF.mono, fontSize:9, letterSpacing:'0.15em', color:b.cream, background:b.ink, padding:'2px 6px', borderRadius:8, textTransform:'uppercase', zIndex:2 }}>Check In</span>
                  </div>
                  <div style={{ padding:'8px 4px 0', fontFamily:raF.display, fontSize:17, fontWeight:500, letterSpacing:'-0.01em', color:b.ink }}>{card.title}</div>
                  {i === 0 && <div aria-hidden="true" style={{ position:'absolute', top:-5, left:-8, width:56, height:14, background:b.butter, opacity:0.85, transform:'rotate(-8deg)' }} />}
                  {i === 1 && <div aria-hidden="true" style={{ position:'absolute', top:-5, right:-8, width:56, height:14, background:b.pistachio, opacity:0.85, transform:'rotate(10deg)' }} />}
                </div>
                {/* BACK — Della's note (pastel, derived from the painting — never green) */}
                <div style={{ position:'absolute', inset:0, backfaceVisibility:'hidden', WebkitBackfaceVisibility:'hidden', transform:'rotateY(180deg)',
                  background:tone.back, borderRadius:14, padding:14, color:tone.ink, display:'flex', flexDirection:'column', boxShadow:'0 16px 32px -12px rgba(42,27,20,0.35)' }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}>
                    <DDMark size={20} />
                    <div><div style={{ fontFamily:raF.display, fontSize:13, fontWeight:500 }}>Della</div>
                      <div style={{ fontSize:9, opacity:0.65, letterSpacing:'0.1em' }}>Today</div></div>
                  </div>
                  <div style={{ flex:1, fontSize:13, lineHeight:1.5, padding:'10px 12px', background:b.cream, color:b.ink, borderRadius:'14px 14px 14px 4px' }}>{card.note}</div>
                  <div style={{ marginTop:10, padding:'9px', background:b.accent, color:b.cream, textAlign:'center', fontFamily:raF.body, fontSize:12, fontWeight:600, borderRadius:20 }}>Write Back →</div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      {/* stepper */}
      <div style={{ display:'flex', justifyContent:'center', gap:5, marginTop:8 }}>
        {deck.map((_, i) => <span key={i} style={{ width:i===idx?20:6, height:6, borderRadius:3, background:i===idx?b.accent:b.ruleStrong, transition:'width 0.3s' }} />)}
      </div>
      <div style={{ textAlign:'center', marginTop:10, fontFamily:raF.mono, fontSize:9, letterSpacing:'0.22em', textTransform:'uppercase', color:b.inkMute }}>
        {flipped != null ? 'Tap To Flip Back · Swipe →' : 'Tap Center Card · Swipe To Browse'}
      </div>
    </>
  );
}

// The Della chat screen (postpartum phone), matching the real app's Della tab.
// A living thread between Priya and Della — pinned to the latest exchange, with
// a gentle typing reveal of the final message so it reads as alive, not static.
const DELLA_THREAD = [
  { date:'Yesterday' },
  { who:'me', at:'11:52 PM', text:"she woke every 90 min last night. i don't know how to keep doing this 😮‍💨" },
  { who:'della', at:'11:53 PM', text:"this isn't a forever-thing — it's a 4-month thing. and you don't have to be cheerful about it, love ♡" },
  { date:'Today' },
  { who:'della', at:'8:01 AM', text:"morning, mama. how are YOU — not mom-you, you-you?" },
  { who:'me', at:'8:03 AM', text:"she slept 5 hours straight!!! i feel almost human" },
  { who:'della', at:'8:04 AM', text:"FIVE HOURS?! that's massive — your body needed that. want me to text Sam your debrief so you don't have to retell it?", save:"Saved to journal · Ila slept 5h" },
  { who:'me', at:'8:05 AM', text:"yes please ♡" },
];

function DellaBubble({ b, m }) {
  const isDella = m.who === 'della';
  return (
    <div style={{ display:'flex', flexDirection:'column', alignItems:isDella?'flex-start':'flex-end', marginBottom:13 }}>
      <div style={{ display:'flex', alignItems:'flex-end', gap:7, maxWidth:'82%', flexDirection:isDella?'row':'row-reverse' }}>
        {isDella && <div style={{ flexShrink:0, marginBottom:2 }}><DDMark size={18} /></div>}
        <div style={{
          padding:'10px 13px', fontSize:13.5, lineHeight:1.42,
          background: isDella ? b.card : b.accent,
          color: isDella ? b.ink : b.cream,
          border: isDella ? `1px solid ${b.rule}` : 'none',
          borderRadius: isDella ? '16px 16px 16px 5px' : '16px 16px 5px 16px',
          boxShadow: isDella ? 'none' : '0 8px 18px -10px rgba(124,149,105,0.6)' }}>
          {m.text}
        </div>
      </div>
      <div style={{ fontFamily:raF.mono, fontSize:8, letterSpacing:'0.12em', color:b.inkMute, marginTop:4,
        padding: isDella ? '0 0 0 29px' : '0 2px 0 0', textTransform:'uppercase' }}>
        {isDella ? 'Della · ' : ''}{m.at}
      </div>
      {m.save && (
        <div style={{ marginTop:6, marginLeft:29, display:'inline-flex', alignItems:'center', gap:6, alignSelf:'flex-start',
          padding:'5px 10px', borderRadius:12, background:b.cardMint, border:`1px dashed ${b.rule}`,
          fontFamily:raF.mono, fontSize:8.5, letterSpacing:'0.1em', textTransform:'uppercase', color:b.inkSoft }}>
          <span>🔖</span>{m.save}
        </div>
      )}
    </div>
  );
}

function RealDella({ stage }) {
  const b = realBrand(stage);
  const c = RA_CONFIG[stage];
  const reduced = useReducedMotion();
  const scrollRef = React.useRef(null);
  // Reveal the last user reply after a beat so the thread feels live.
  const full = DELLA_THREAD.length;
  const [shown, setShown] = React.useState(reduced ? full : full - 1);
  const [typing, setTyping] = React.useState(false);
  React.useEffect(() => {
    if (reduced) return;
    const t1 = setTimeout(() => setTyping(true), 1400);
    const t2 = setTimeout(() => { setTyping(false); setShown(full); }, 2600);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [reduced, full]);
  React.useEffect(() => {
    const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight;
  }, [shown, typing]);

  return (
    <div style={{ width: RA_DESIGN_W, height: 844, fontFamily: raF.body, color:b.ink, background:b.cream, display:'flex', flexDirection:'column' }}>
      {/* top bar */}
      <div style={{ padding:'26px 20px 12px', display:'flex', alignItems:'flex-start', gap:10, borderBottom:`1px solid ${b.rule}`, flexShrink:0 }}>
        <span style={{ fontSize:20, color:b.inkMute, marginTop:2 }}>‹</span>
        <div style={{ flex:1 }}>
          <div style={{ fontFamily:raF.mono, fontSize:9, letterSpacing:'0.2em', textTransform:'uppercase', color:b.inkMute, lineHeight:1.4 }}>Ongoing · Your Thread With Della</div>
          <div style={{ fontFamily:raF.display, fontSize:22, fontWeight:600, letterSpacing:'-0.02em', marginTop:2 }}>
            <em style={{ color:b.accent, fontStyle:'italic', fontWeight:500 }}>Della</em> is here.
          </div>
        </div>
        <div style={{ display:'flex', background:b.creamDeep, borderRadius:16, padding:3, marginTop:2 }}>
          <span style={{ fontSize:11, fontWeight:700, padding:'5px 11px', borderRadius:13, background:'#2A1B14', color:b.cream }}>chat</span>
          <span style={{ fontSize:11, fontWeight:600, padding:'5px 11px', color:b.inkSoft }}>voice</span>
        </div>
      </div>
      {/* thread */}
      <div ref={scrollRef} style={{ flex:1, overflowY:'auto', overflowX:'hidden', padding:'18px 18px 8px', display:'flex', flexDirection:'column' }}>
        <div style={{ marginTop:'auto' }}>
          {DELLA_THREAD.slice(0, shown).map((m, i) => (
            m.date
              ? <div key={i} style={{ textAlign:'center', margin:'8px 0 14px', fontFamily:raF.mono, fontSize:8.5, letterSpacing:'0.22em', textTransform:'uppercase', color:b.inkMute }}>{m.date}</div>
              : <DellaBubble key={i} b={b} m={m} />
          ))}
          {typing && (
            <div style={{ display:'flex', alignItems:'flex-end', gap:7, marginBottom:13 }}>
              <DDMark size={18} />
              <div style={{ display:'flex', gap:4, padding:'12px 14px', background:b.card, border:`1px solid ${b.rule}`, borderRadius:'16px 16px 16px 5px' }}>
                {[0,1,2].map(n => <span key={n} className="v5-pulse-dot" style={{ width:6, height:6, borderRadius:'50%', background:b.inkMute, animationDelay:`${n*0.18}s` }} />)}
              </div>
            </div>
          )}
        </div>
      </div>
      {/* input bar */}
      <div style={{ padding:'12px 18px', borderTop:`1px solid ${b.rule}`, display:'flex', alignItems:'center', gap:10, flexShrink:0 }}>
        <div style={{ width:38, height:38, borderRadius:'50%', border:`1px solid ${b.rule}`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:15, color:b.inkMute }}>🖼️</div>
        <div style={{ flex:1, padding:'11px 16px', borderRadius:22, border:`1.5px dashed ${b.rule}`, color:b.inkMute, fontSize:13.5 }}>Write back to Della…</div>
        <div style={{ width:38, height:38, borderRadius:'50%', border:`1px solid ${b.rule}`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:15, color:b.inkMute }}>🎙️</div>
        <div style={{ width:38, height:38, borderRadius:'50%', background:b.accent, display:'flex', alignItems:'center', justifyContent:'center', fontSize:16, color:b.cream }}>→</div>
      </div>
    </div>
  );
}

Object.assign(window, { RealToday, RealAlbum, RealDella, RATabBar, realBrand, RA_DESIGN_W });
