// Klairely app — screens 5–9
const { Icon, Avatar, PrimaryBtn, GhostBtn, Chip, SectionLabel, ScreenHead, TabBar, Toast } = window;
const K = window.K;
const { Screen, Card, Toggle, PEOPLE } = window.KHelpers;

// ════════════════════════════════════════════════════════
// 5 · EMAIL DETAIL
// ════════════════════════════════════════════════════════
function EmailDetail({ nav, toast }) {
  const [added, setAdded] = React.useState({ cal:false, rem:false });
  const [open, setOpen] = React.useState(false);
  const add = (k, label) => { setAdded(s=>({...s,[k]:true})); toast(label); };
  return (
    <Screen bottom={
      <div style={{ padding:'12px 22px 30px', background:K.paper, borderTop:`1px solid ${K.line2}`, display:'flex', gap:10 }}>
        <GhostBtn onClick={()=>nav('inbox')} style={{ flex:'0 0 52px', padding:14 }}><Icon name="back" size={18} stroke={K.ink}/></GhostBtn>
        <PrimaryBtn onClick={()=>nav('reply')}><Icon name="reply" size={18} stroke="#fff"/> Draft a reply</PrimaryBtn>
      </div>
    }>
      <ScreenHead onBack={()=>nav('inbox')} right={<Chip tone="coral"><Icon name="flag" size={12} stroke={K.coralInk}/> Action needed</Chip>}/>
      <div style={{ padding:'0 22px' }}>
        {/* sender */}
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:6 }}>
          <Avatar initials="MD" bg={K.sage} size={44}/>
          <div>
            <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:16, color:K.ink }}>Mrs. Daniels</div>
            <div style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3 }}>Lincoln Elementary · Today 7:02 AM</div>
          </div>
        </div>
        <h1 style={{ fontFamily:K.serif, fontSize:23, fontWeight:500, lineHeight:1.2, letterSpacing:'-.01em', margin:'14px 0 16px', color:K.ink }}>Picture Day + Permission Form</h1>

        {/* Klairely summary */}
        <Card style={{ padding:'15px 16px', background:K.surfaceTint, borderColor:K.line2 }}>
          <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:9 }}>
            <span style={{ width:9, height:9, borderRadius:'50%', background:K.coral }}/>
            <span style={{ fontFamily:K.sans, fontWeight:700, fontSize:11, letterSpacing:'.1em', textTransform:'uppercase', color:K.ink3 }}>Klairely summary</span>
          </div>
          <p style={{ fontFamily:K.serif, fontSize:16.5, lineHeight:1.5, color:K.ink, margin:0 }}>
            "Picture day is Friday. The form is due Wednesday. No reply required."
          </p>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:13, paddingTop:12, borderTop:`1px solid ${K.line2}` }}>
            <Icon name="eye" size={15} stroke={K.ink3}/>
            <span style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, lineHeight:1.4 }}>Flagged because it names a <b style={{color:K.ink2}}>deadline</b> and is from a watched teacher.</span>
          </div>
        </Card>

        {/* suggested actions */}
        <SectionLabel style={{ margin:'22px 0 11px' }}>Suggested actions</SectionLabel>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {[
            { k:'cal', ic:'calendar', t:'Add Picture Day to calendar', d:'Friday, May 16 · all day', label:'Picture Day added to calendar' },
            { k:'rem', ic:'bell', t:'Add form deadline reminder', d:'Wednesday, May 14 · 8:00 AM', label:'Form reminder added' },
          ].map(a=>(
            <Card key={a.k} style={{ padding:'13px 14px', display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:38, height:38, borderRadius:11, background:K.sageTint, color:K.sageInk, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name={a.ic} size={19} stroke={K.sageInk}/>
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>{a.t}</div>
                <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3 }}>{a.d}</div>
              </div>
              {added[a.k] ? (
                <span style={{ display:'flex', alignItems:'center', gap:5, fontFamily:K.sans, fontWeight:600, fontSize:12.5, color:K.sage }}><Icon name="check" size={15} stroke={K.sage} sw={2.2}/>Added</span>
              ) : (
                <button onClick={()=>add(a.k,a.label)} style={{ fontFamily:K.sans, fontWeight:600, fontSize:13, padding:'9px 15px', borderRadius:999, border:'none', background:K.sage, color:'#fff', cursor:'pointer', flexShrink:0 }}>Add</button>
              )}
            </Card>
          ))}
        </div>

        {/* original email */}
        <button onClick={()=>setOpen(o=>!o)} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', width:'100%', background:'none', border:'none', cursor:'pointer', padding:'20px 2px 8px' }}>
          <span style={{ fontFamily:K.sans, fontWeight:600, fontSize:13.5, color:K.ink2 }}>Original email</span>
          <Icon name={open?'chevDown':'chevron'} size={16} stroke={K.ink3}/>
        </button>
        {open && (
          <div style={{ fontFamily:K.sans, fontSize:13.5, lineHeight:1.6, color:K.ink2, background:K.surface, border:`1px solid ${K.line2}`, borderRadius:14, padding:'14px 16px', marginBottom:8 }}>
            Hi families,<br/><br/>A quick reminder that Picture Day is this <b>Friday</b>. Please return the signed permission form by <b>Wednesday</b> so we have everyone accounted for. No need to reply.<br/><br/>Warmly,<br/>Mrs. Daniels
          </div>
        )}
        <div style={{ height:8 }}/>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════════════════════
// 6 · DRAFT REPLY
// ════════════════════════════════════════════════════════
const DRAFTS = {
  base:'Hi Mrs. Daniels, thanks for the reminder. We\u2019ll send the form in by Wednesday.',
  Warmer:'Hi Mrs. Daniels, thank you so much for the reminder — we really appreciate you keeping us on track! We\u2019ll have the form sent in by Wednesday.',
  Shorter:'Thanks Mrs. Daniels — form coming by Wednesday.',
  'More formal':'Dear Mrs. Daniels, thank you for the reminder. We will ensure the permission form is returned by Wednesday. Kind regards.',
};
function DraftReply({ nav, toast }) {
  const [tone, setTone] = React.useState('base');
  const [text, setText] = React.useState(DRAFTS.base);
  const pick = (t)=>{ setTone(t); setText(DRAFTS[t]); };
  return (
    <Screen bottom={
      <div style={{ padding:'12px 22px 30px', background:K.paper, borderTop:`1px solid ${K.line2}`, display:'flex', gap:10 }}>
        <GhostBtn onClick={()=>nav('detail')} style={{ flex:'0 0 78px' }}>Edit</GhostBtn>
        <PrimaryBtn onClick={()=>{ toast('Reply sent to Mrs. Daniels'); setTimeout(()=>nav('inbox'),900); }}><Icon name="send" size={18} stroke="#fff"/> Approve &amp; send</PrimaryBtn>
      </div>
    }>
      <ScreenHead onBack={()=>nav('detail')} greet="Re: Picture Day + Permission Form" title="Reply to Mrs. Daniels"/>
      <div style={{ padding:'4px 22px 0' }}>
        <div style={{ display:'inline-flex', alignItems:'center', gap:7, fontFamily:K.sans, fontWeight:600, fontSize:12, color:K.sageInk, background:K.sageTint, padding:'6px 12px', borderRadius:999, marginBottom:14 }}>
          <Icon name="sparkle" size={13} stroke={K.sageInk}/> Drafted in your tone
        </div>
        {/* editable draft */}
        <div style={{ background:K.surface, border:`1px solid ${K.line2}`, borderRadius:18, boxShadow:'0 1px 2px rgba(43,39,34,.04)', overflow:'hidden' }}>
          <div style={{ padding:'13px 16px', borderBottom:`1px solid ${K.line2}`, display:'flex', alignItems:'center', gap:9 }}>
            <Avatar initials="M" bg={K.coral} size={28}/>
            <span style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3 }}>From you · maya@gmail.com</span>
          </div>
          <textarea value={text} onChange={e=>{setText(e.target.value); setTone('base');}} style={{
            width:'100%', border:'none', outline:'none', resize:'none', minHeight:128, padding:'16px',
            fontFamily:K.serif, fontSize:16.5, lineHeight:1.6, color:K.ink, background:'transparent', boxSizing:'border-box',
          }}/>
        </div>
        {/* tone */}
        <SectionLabel style={{ margin:'22px 0 11px' }}>Adjust the tone</SectionLabel>
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {['Warmer','Shorter','More formal'].map(t=>{
            const on = tone===t;
            return <button key={t} onClick={()=>pick(t)} style={{
              fontFamily:K.sans, fontWeight:600, fontSize:13.5, padding:'10px 16px', borderRadius:999, cursor:'pointer',
              border:`1px solid ${on?K.sage:K.line}`, background:on?K.sage:K.surface, color:on?'#fff':K.ink2, transition:'all .15s',
            }}>{t}</button>;
          })}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:9, marginTop:20, padding:'12px 14px', background:K.surfaceTint, border:`1px solid ${K.line2}`, borderRadius:14 }}>
          <Icon name="lock" size={16} stroke={K.ink3}/>
          <span style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3, lineHeight:1.4 }}>Nothing sends until you tap <b style={{color:K.ink2}}>Approve &amp; send</b>.</span>
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════════════════════
// 7 · CALENDAR PROPOSAL
// ════════════════════════════════════════════════════════
function CalendarProposal({ nav, toast }) {
  const [choice, setChoice] = React.useState(null);
  const hours = ['5 PM','6 PM','7 PM','8 PM'];
  return (
    <Screen bottom={
      <div style={{ padding:'12px 22px 30px', background:K.paper, borderTop:`1px solid ${K.line2}`, display:'flex', gap:10 }}>
        <GhostBtn onClick={()=>nav('inbox')} style={{ flex:'0 0 96px' }}>Not now</GhostBtn>
        <PrimaryBtn onClick={()=>{ toast('Calendar updated · Blake notified'); setTimeout(()=>nav('inbox'),900); }}><Icon name="check" size={18} stroke="#fff" sw={2.2}/> Approve change</PrimaryBtn>
      </div>
    }>
      <ScreenHead onBack={()=>nav('inbox')} greet="Tuesday, May 13" title="Calendar conflict"/>
      <div style={{ padding:'2px 22px 0' }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, padding:'11px 14px', background:K.coralTint, borderRadius:14, marginBottom:18 }}>
          <Icon name="alert" size={18} stroke={K.coralInk}/>
          <span style={{ fontFamily:K.sans, fontSize:13, color:K.coralInk, fontWeight:600, lineHeight:1.4 }}>Two events overlap on Tuesday evening.</span>
        </div>

        {/* timeline */}
        <div style={{ position:'relative', paddingLeft:54, marginBottom:8 }}>
          {hours.map((h,i)=>(
            <div key={h} style={{ position:'relative', height:54, borderTop:`1px solid ${K.line2}` }}>
              <span style={{ position:'absolute', left:-54, top:-8, fontFamily:K.sans, fontSize:11, color:K.ink3, width:44, textAlign:'right' }}>{h}</span>
            </div>
          ))}
          {/* soccer block */}
          <div style={{ position:'absolute', left:54, right:'48%', top:60, height:74, background:K.sage, borderRadius:12, padding:'9px 11px', color:'#fff' }}>
            <div style={{ fontFamily:K.sans, fontWeight:700, fontSize:12.5 }}>Soccer</div>
            <div style={{ fontFamily:K.sans, fontSize:11, opacity:.85 }}>Jackson</div>
            <div style={{ fontFamily:K.sans, fontSize:10.5, opacity:.85, marginTop:3 }}>6:00–7:30</div>
          </div>
          {/* dinner block */}
          <div style={{ position:'absolute', left:'53%', right:0, top:74, height:80, background:K.coral, borderRadius:12, padding:'9px 11px', color:'#fff' }}>
            <div style={{ fontFamily:K.sans, fontWeight:700, fontSize:12.5 }}>Work dinner</div>
            <div style={{ fontFamily:K.sans, fontSize:11, opacity:.9 }}>Blake</div>
            <div style={{ fontFamily:K.sans, fontSize:10.5, opacity:.9, marginTop:3 }}>6:30–8:30</div>
          </div>
        </div>

        {/* proposal */}
        <SectionLabel style={{ margin:'18px 0 11px' }}>Klairely proposes</SectionLabel>
        <Card style={{ padding:'15px 16px', borderColor:K.sageTint2 }}>
          <div style={{ display:'flex', gap:11 }}>
            <div style={{ width:36, height:36, borderRadius:10, background:K.sageTint, color:K.sageInk, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name="sparkle" size={18} stroke={K.sageInk}/></div>
            <div>
              <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14.5, color:K.ink, lineHeight:1.4 }}>Blake takes soccer drop-off; you cover pickup at 7:30.</div>
              <div style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3, marginTop:4, lineHeight:1.45 }}>Keeps both events. I’ll add the split to Jackson’s soccer and notify Blake.</div>
            </div>
          </div>
        </Card>

        <SectionLabel style={{ margin:'20px 0 11px' }}>Or reschedule soccer reminder</SectionLabel>
        <div style={{ display:'flex', gap:8, flexWrap:'wrap', paddingBottom:8 }}>
          {hours.map(h=>{
            const on=choice===h;
            return <button key={h} onClick={()=>setChoice(h)} style={{
              fontFamily:K.sans, fontWeight:600, fontSize:13, padding:'9px 15px', borderRadius:999, cursor:'pointer',
              border:`1px solid ${on?K.sage:K.line}`, background:on?K.sage:K.surface, color:on?'#fff':K.ink2,
            }}>{h}</button>;
          })}
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════════════════════
// 8 · SUNDAY BRIEFING
// ════════════════════════════════════════════════════════
function Briefing({ nav }) {
  return (
    <Screen bottom={<TabBar active="briefing" onNav={nav}/>}>
      {/* header band */}
      <div style={{ background:K.night, padding:'4px 22px 22px', borderRadius:'0 0 26px 26px' }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', paddingTop:6 }}>
          <span style={{ fontFamily:K.sans, fontWeight:700, fontSize:11.5, letterSpacing:'.1em', textTransform:'uppercase', color:'#C9A88F' }}>Sunday briefing</span>
          <span style={{ fontFamily:K.sans, fontSize:12, color:'rgba(247,244,238,.55)' }}>Sun · 6:00 PM</span>
        </div>
        <h1 style={{ fontFamily:K.serif, fontSize:28, fontWeight:500, color:'#fff', letterSpacing:'-.015em', margin:'12px 0 4px', lineHeight:1.1 }}>Your week ahead</h1>
        <p style={{ fontFamily:K.sans, fontSize:13.5, color:'rgba(247,244,238,.66)', margin:0, lineHeight:1.5 }}>3 school items, 2 activity updates, and 1 conflict to settle before Monday.</p>
        <div style={{ display:'flex', gap:8, marginTop:16 }}>
          {[['3','School'],['2','Activities'],['1','Conflict']].map(([n,l],i)=>(
            <div key={l} style={{ flex:1, textAlign:'center', padding:'12px 4px', borderRadius:14, background:i===2?'rgba(206,111,79,.18)':'rgba(247,244,238,.08)' }}>
              <div style={{ fontFamily:K.serif, fontSize:24, fontWeight:600, color:i===2?'#E8A98C':'#fff', lineHeight:1 }}>{n}</div>
              <div style={{ fontFamily:K.sans, fontSize:10.5, color:'rgba(247,244,238,.6)', marginTop:5, fontWeight:600 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ padding:'20px 22px 14px' }}>
        <SectionLabel>School items</SectionLabel>
        {[
          { ic:'calendar', who:'Emma', t:'Picture day is Friday', d:'No reply needed · on calendar' },
          { ic:'bell', who:'Form', t:'Field trip form due Wednesday', d:'$12 fee · reminder set' },
          { ic:'doc', who:'Lincoln', t:'Book fair runs all week', d:'FYI · spirit week Thursday' },
        ].map((r,i)=>(
          <div key={i} style={{ display:'flex', gap:12, alignItems:'center', padding:'12px 0', borderTop:i?`1px solid ${K.line2}`:'none' }}>
            <div style={{ width:36, height:36, borderRadius:10, background:K.sageTint, color:K.sageInk, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name={r.ic} size={18} stroke={K.sageInk}/></div>
            <div style={{ flex:1 }}>
              <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>{r.t}</div>
              <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3 }}>{r.d}</div>
            </div>
          </div>
        ))}

        <SectionLabel style={{ margin:'22px 0 0' }}>The conflict</SectionLabel>
        <Card onClick={()=>nav('calendar')} style={{ padding:'14px 15px', marginTop:12, borderColor:K.coralTint }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10 }}>
            <Icon name="alert" size={17} stroke={K.coral}/>
            <span style={{ fontFamily:K.sans, fontWeight:700, fontSize:13.5, color:K.coralInk, whiteSpace:'nowrap' }}>Tuesday at 6 PM</span>
          </div>
          <p style={{ fontFamily:K.sans, fontSize:13.5, color:K.ink2, lineHeight:1.5, margin:'0 0 11px' }}>
            Jackson’s soccer overlaps with Blake’s work dinner. Klairely has a fix ready.
          </p>
          <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:13, color:K.sage, display:'flex', alignItems:'center', gap:5 }}>Resolve now <Icon name="chevron" size={14} stroke={K.sage}/></div>
        </Card>

        <div style={{ textAlign:'center', padding:'22px 0 8px' }}>
          <span style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, display:'inline-flex', alignItems:'center', gap:7 }}>
            <span style={{ width:7, height:7, borderRadius:'50%', background:K.coral }}/> Delivered every Sunday at 6 PM
          </span>
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════════════════════
// 9 · PRIVACY / SETTINGS
// ════════════════════════════════════════════════════════
function TextMessageImport({ nav, toast }) {
  const [text, setText] = React.useState("Hi, this is Bright Smiles Dental. Liam has an appointment with Dr. Patel on Tuesday, June 18 at 3:30 PM. Please arrive 10 minutes early and bring updated insurance cards. Reply C to confirm.");
  const [added, setAdded] = React.useState({ cal:false, rem:false, reply:false });
  const add = (k, msg) => { setAdded(s=>({...s,[k]:true})); toast(msg); };
  return (
    <Screen bottom={
      <div style={{ padding:'12px 22px 30px', background:K.paper, borderTop:`1px solid ${K.line2}`, display:'flex', gap:10 }}>
        <GhostBtn onClick={()=>nav('chat')} style={{ flex:'0 0 82px' }}>Back</GhostBtn>
        <PrimaryBtn onClick={()=>{ toast('Appointment added · reminder set'); setTimeout(()=>nav('chat'),900); }}>
          <Icon name="check" size={18} stroke="#fff" sw={2.2}/> Approve
        </PrimaryBtn>
      </div>
    }>
      <ScreenHead onBack={()=>nav('chat')} greet="Copy from Messages" title="Paste a family text"/>
      <div style={{ padding:'2px 22px 0' }}>
        <Card style={{ padding:'14px 15px', background:K.surfaceTint }}>
          <div style={{ display:'flex', gap:11, alignItems:'flex-start' }}>
            <div style={{ width:38, height:38, borderRadius:11, background:K.coralTint, color:K.coralInk, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <Icon name="clip" size={19} stroke={K.coralInk}/>
            </div>
            <div>
              <div style={{ fontFamily:K.sans, fontWeight:700, fontSize:14.5, color:K.ink }}>Paste any copied message</div>
              <div style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3, lineHeight:1.45, marginTop:3 }}>
                Texts from doctors, coaches, birthday hosts, camps, or parent groups. Klairely extracts dates and asks before adding anything.
              </div>
            </div>
          </div>
        </Card>

        <SectionLabel style={{ margin:'20px 0 11px' }}>Copied text</SectionLabel>
        <div style={{ background:K.surface, border:`1px solid ${K.line2}`, borderRadius:18, boxShadow:'0 1px 2px rgba(43,39,34,.04)', overflow:'hidden' }}>
          <textarea value={text} onChange={e=>setText(e.target.value)} style={{
            width:'100%', border:'none', outline:'none', resize:'none', minHeight:122, padding:'15px 16px',
            fontFamily:K.sans, fontSize:14.5, lineHeight:1.5, color:K.ink, background:'transparent', boxSizing:'border-box',
          }}/>
        </div>

        <SectionLabel style={{ margin:'22px 0 11px' }}>Klairely found</SectionLabel>
        <Card style={{ padding:'15px 16px', borderColor:K.sageTint2 }}>
          <div style={{ display:'flex', alignItems:'center', gap:9, marginBottom:11 }}>
            <Chip tone="sage"><Icon name="calendar" size={12} stroke={K.sageInk}/> Appointment</Chip>
            <Chip tone="coral"><Icon name="alert" size={12} stroke={K.coralInk}/> Needs confirmation</Chip>
          </div>
          <h2 style={{ fontFamily:K.serif, fontSize:22, fontWeight:500, lineHeight:1.18, margin:'0 0 8px', color:K.ink }}>Liam dentist appointment</h2>
          <div style={{ display:'grid', gap:9 }}>
            {[
              ['calendar','Tuesday, June 18 · 3:30 PM'],
              ['clock','Arrive 10 minutes early'],
              ['doc','Bring updated insurance cards'],
              ['reply','Reply “C” to confirm'],
            ].map(([ic,t])=>(
              <div key={t} style={{ display:'flex', alignItems:'center', gap:9, fontFamily:K.sans, fontSize:13.5, color:K.ink2 }}>
                <Icon name={ic} size={16} stroke={K.ink3}/>{t}
              </div>
            ))}
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:13, paddingTop:12, borderTop:`1px solid ${K.line2}` }}>
            <Icon name="eye" size={15} stroke={K.ink3}/>
            <span style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, lineHeight:1.4 }}>Saved as a private appointment by default. You can rename it before adding.</span>
          </div>
        </Card>

        <SectionLabel style={{ margin:'20px 0 11px' }}>Suggested actions</SectionLabel>
        <div style={{ display:'flex', flexDirection:'column', gap:10, paddingBottom:10 }}>
          {[
            { k:'cal', ic:'calendar', t:'Add private appointment', d:'Tuesday, June 18 · 3:30 PM', msg:'Private appointment added' },
            { k:'rem', ic:'bell', t:'Add reminder', d:'1 day before and 45 minutes before', msg:'Reminders added' },
            { k:'reply', ic:'reply', t:'Draft confirmation text', d:'C', msg:'Confirmation draft ready' },
          ].map(a=>(
            <Card key={a.k} style={{ padding:'13px 14px', display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:38, height:38, borderRadius:11, background:K.sageTint, color:K.sageInk, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name={a.ic} size={18} stroke={K.sageInk}/>
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>{a.t}</div>
                <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3 }}>{a.d}</div>
              </div>
              {added[a.k] ? (
                <span style={{ display:'flex', alignItems:'center', gap:5, fontFamily:K.sans, fontWeight:600, fontSize:12.5, color:K.sage }}><Icon name="check" size={15} stroke={K.sage} sw={2.2}/>Added</span>
              ) : (
                <button onClick={()=>add(a.k,a.msg)} style={{ fontFamily:K.sans, fontWeight:600, fontSize:13, padding:'9px 15px', borderRadius:999, border:'none', background:K.sage, color:'#fff', cursor:'pointer', flexShrink:0 }}>Add</button>
              )}
            </Card>
          ))}
        </div>
      </div>
    </Screen>
  );
}

function FlyerScan({ nav, toast }) {
  const [added, setAdded] = React.useState({ cal:false, rem:false, ask:false });
  const add = (k, msg) => { setAdded(s=>({...s,[k]:true})); toast(msg); };
  return (
    <Screen bottom={
      <div style={{ padding:'12px 22px 30px', background:K.paper, borderTop:`1px solid ${K.line2}`, display:'flex', gap:10 }}>
        <GhostBtn onClick={()=>nav('chat')} style={{ flex:'0 0 82px' }}>Back</GhostBtn>
        <PrimaryBtn onClick={()=>{ toast('Flyer actions saved'); setTimeout(()=>nav('chat'),900); }}>
          <Icon name="check" size={18} stroke="#fff" sw={2.2}/> Approve
        </PrimaryBtn>
      </div>
    }>
      <ScreenHead onBack={()=>nav('chat')} greet="Camera or photo upload" title="Scan a flyer"/>
      <div style={{ padding:'2px 22px 0' }}>
        <Card style={{ padding:'13px', background:K.surfaceTint }}>
          <div style={{
            minHeight:236, borderRadius:17, border:`1px dashed ${K.line}`, background:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center', overflow:'hidden', position:'relative'
          }}>
            <img
              src="../assets/science-night-flyer.png"
              alt="Uploaded school flyer"
              style={{ width:'100%', height:'100%', minHeight:236, objectFit:'cover', display:'block' }}
            />
            <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg, rgba(255,255,255,.06), rgba(43,39,34,.18))' }}/>
            <div style={{ position:'absolute', bottom:13, right:13, width:46, height:46, borderRadius:'50%', background:K.sage, display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 8px 18px rgba(73,97,80,.25)' }}>
              <Icon name="camera" size={22} stroke="#fff"/>
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:12, fontFamily:K.sans, fontSize:12.5, color:K.ink3 }}>
            <Icon name="sparkle" size={14} stroke={K.sage}/>
            Klairely reads the flyer and separates confirmed details from guesses.
          </div>
        </Card>

        <SectionLabel style={{ margin:'22px 0 11px' }}>Klairely found</SectionLabel>
        <Card style={{ padding:'15px 16px', borderColor:K.sageTint2 }}>
          <div style={{ display:'flex', alignItems:'center', gap:9, marginBottom:11 }}>
            <Chip tone="sage"><Icon name="calendar" size={12} stroke={K.sageInk}/> School event</Chip>
            <Chip tone="coral"><Icon name="doc" size={12} stroke={K.coralInk}/> Supplies needed</Chip>
          </div>
          <h2 style={{ fontFamily:K.serif, fontSize:22, fontWeight:500, lineHeight:1.18, margin:'0 0 8px', color:K.ink }}>Science Night</h2>
          <div style={{ display:'grid', gap:9 }}>
            {[
              ['calendar','Thursday, June 20 · 6:00–7:30 PM'],
              ['pin','Lincoln Elementary gym'],
              ['user','For Emma and Jackson'],
              ['doc','Bring a labeled water bottle'],
            ].map(([ic,t])=>(
              <div key={t} style={{ display:'flex', alignItems:'center', gap:9, fontFamily:K.sans, fontSize:13.5, color:K.ink2 }}>
                <Icon name={ic} size={16} stroke={K.ink3}/>{t}
              </div>
            ))}
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:13, paddingTop:12, borderTop:`1px solid ${K.line2}` }}>
            <Icon name="eye" size={15} stroke={K.ink3}/>
            <span style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, lineHeight:1.4 }}>Unclear whether RSVP is required. Klairely will keep this as a parent-check item.</span>
          </div>
        </Card>

        <SectionLabel style={{ margin:'20px 0 11px' }}>Suggested actions</SectionLabel>
        <div style={{ display:'flex', flexDirection:'column', gap:10, paddingBottom:10 }}>
          {[
            { k:'cal', ic:'calendar', t:'Add Science Night to calendar', d:'Thursday, June 20 · 6:00 PM', msg:'Science Night added' },
            { k:'rem', ic:'bell', t:'Remind us to pack water bottles', d:'Thursday at 4:30 PM', msg:'Water bottle reminder added' },
            { k:'ask', ic:'user', t:'Ask Blake who is taking them', d:'Send co-parent handoff', msg:'Blake handoff drafted' },
          ].map(a=>(
            <Card key={a.k} style={{ padding:'13px 14px', display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:38, height:38, borderRadius:11, background:K.sageTint, color:K.sageInk, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name={a.ic} size={18} stroke={K.sageInk}/>
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>{a.t}</div>
                <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3 }}>{a.d}</div>
              </div>
              {added[a.k] ? (
                <span style={{ display:'flex', alignItems:'center', gap:5, fontFamily:K.sans, fontWeight:600, fontSize:12.5, color:K.sage }}><Icon name="check" size={15} stroke={K.sage} sw={2.2}/>Added</span>
              ) : (
                <button onClick={()=>add(a.k,a.msg)} style={{ fontFamily:K.sans, fontWeight:600, fontSize:13, padding:'9px 15px', borderRadius:999, border:'none', background:K.sage, color:'#fff', cursor:'pointer', flexShrink:0 }}>Add</button>
              )}
            </Card>
          ))}
        </div>
      </div>
    </Screen>
  );
}

function Settings({ nav, toast }) {
  const [tg, setTg] = React.useState({ why:true, cosync:true, weekly:true });
  return (
    <Screen bottom={<TabBar active="settings" onNav={nav}/>}>
      <ScreenHead greet="You're in control" title="Privacy &amp; control"/>
      <div style={{ padding:'2px 22px 18px' }}>
        {/* connection */}
        <Card style={{ padding:'15px 16px', display:'flex', alignItems:'center', gap:12 }}>
          <div style={{ width:42, height:42, borderRadius:12, background:K.sageTint, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name="mail" size={21} stroke={K.sageInk}/></div>
          <div style={{ flex:1 }}>
            <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14.5, color:K.ink }}>Gmail connected</div>
            <div style={{ fontFamily:K.sans, fontSize:12, color:K.sage, display:'flex', alignItems:'center', gap:5 }}><Icon name="lock" size={12} stroke={K.sage}/> Read-only · maya@gmail.com</div>
          </div>
          <span style={{ width:9, height:9, borderRadius:'50%', background:K.sage }}/>
        </Card>

        {/* locked approval */}
        <SectionLabel style={{ margin:'22px 0 11px' }}>Approval-first</SectionLabel>
        <Card style={{ padding:'14px 16px', display:'flex', alignItems:'center', gap:12, background:K.surfaceTint }}>
          <div style={{ width:36, height:36, borderRadius:10, background:K.sage, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name="shield" size={19} stroke="#fff"/></div>
          <div style={{ flex:1 }}>
            <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>Nothing sends without you</div>
            <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, lineHeight:1.4 }}>Replies &amp; calendar changes always need a tap.</div>
          </div>
          <Chip tone="sage"><Icon name="lock" size={11} stroke={K.sageInk}/> Always on</Chip>
        </Card>

        {/* toggles */}
        <SectionLabel style={{ margin:'22px 0 11px' }}>Preferences</SectionLabel>
        <Card style={{ padding:0, overflow:'hidden' }}>
          {[
            { k:'why', ic:'eye', t:'Show why items were flagged', d:'See the sender and reason on each item' },
            { k:'cosync', ic:'user', t:'Sync with Blake (co-parent)', d:'Share briefings and approvals' },
            { k:'weekly', ic:'calendar', t:'Sunday briefing', d:'Delivered every Sunday at 6 PM' },
          ].map((r,i)=>(
            <div key={r.k} style={{ display:'flex', alignItems:'center', gap:12, padding:'14px 16px', borderTop:i?`1px solid ${K.line2}`:'none' }}>
              <div style={{ width:34, height:34, borderRadius:9, background:K.paper2, color:K.ink2, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name={r.ic} size={17} stroke={K.ink2}/></div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>{r.t}</div>
                <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, lineHeight:1.35 }}>{r.d}</div>
              </div>
              <Toggle on={tg[r.k]} onClick={()=>setTg(s=>({...s,[r.k]:!s[r.k]}))}/>
            </div>
          ))}
        </Card>

        {/* watched senders link */}
        <Card onClick={()=>nav('senders')} style={{ padding:'14px 16px', display:'flex', alignItems:'center', gap:12, marginTop:14 }}>
          <div style={{ width:34, height:34, borderRadius:9, background:K.paper2, color:K.ink2, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name="user" size={17} stroke={K.ink2}/></div>
          <div style={{ flex:1 }}><div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>Watched senders</div><div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3 }}>4 on · 1 muted</div></div>
          <Icon name="chevron" size={17} stroke={K.ink3}/>
        </Card>

        {/* data controls */}
        <SectionLabel style={{ margin:'22px 0 11px' }}>Your data</SectionLabel>
        <Card style={{ padding:0, overflow:'hidden' }}>
          <button onClick={()=>toast('Export started — we\u2019ll email you')} style={{ width:'100%', display:'flex', alignItems:'center', gap:12, padding:'14px 16px', background:'none', border:'none', cursor:'pointer', textAlign:'left' }}>
            <Icon name="doc" size={19} stroke={K.ink2}/>
            <span style={{ flex:1, fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink }}>Export my data</span>
            <Icon name="chevron" size={16} stroke={K.ink3}/>
          </button>
          <button onClick={()=>toast('Data deleted · Gmail disconnected')} style={{ width:'100%', display:'flex', alignItems:'center', gap:12, padding:'14px 16px', background:'none', border:'none', borderTop:`1px solid ${K.line2}`, cursor:'pointer', textAlign:'left' }}>
            <Icon name="trash" size={19} stroke={K.coralDeep}/>
            <span style={{ flex:1, fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.coralDeep }}>Delete data &amp; disconnect</span>
            <Icon name="chevron" size={16} stroke={K.coralTint2}/>
          </button>
        </Card>
        <p style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, textAlign:'center', lineHeight:1.5, margin:'18px 8px 8px' }}>
          Klairely keeps only what it needs to brief you. Disconnecting removes everything within 24 hours.
        </p>
      </div>
    </Screen>
  );
}

window.Screens2 = { EmailDetail, DraftReply, CalendarProposal, Briefing, TextMessageImport, FlyerScan, Settings };
