// Klairely app — the 9 screens. Exports Screens registry to window.
const { Icon, Avatar, PrimaryBtn, GhostBtn, Chip, SectionLabel, ScreenHead, TabBar, Toast } = window;
const K = window.K;

// ── local helpers ─────────────────────────────────────
function Screen({ children, bottom, bg, pad = 54 }) {
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', background:bg||K.paper, paddingTop:pad }}>
      <div style={{ flex:1, overflowY:'auto', overflowX:'hidden' }}>{children}</div>
      {bottom}
    </div>
  );
}
function Card({ children, onClick, style }) {
  return (
    <div onClick={onClick} style={{
      background:K.surface, border:`1px solid ${K.line2}`, borderRadius:20,
      boxShadow:'0 1px 2px rgba(43,39,34,.04)', cursor:onClick?'pointer':'default',
      transition:'transform .12s ease, box-shadow .2s', ...style,
    }}
    onMouseDown={onClick?(e=>e.currentTarget.style.transform='scale(.99)'):undefined}
    onMouseUp={onClick?(e=>e.currentTarget.style.transform='none'):undefined}
    onMouseLeave={onClick?(e=>e.currentTarget.style.transform='none'):undefined}>
      {children}
    </div>
  );
}
function Toggle({ on, onClick }) {
  return (
    <button onClick={onClick} aria-pressed={on} style={{
      width:46, height:28, borderRadius:999, border:'none', cursor:'pointer', flexShrink:0,
      background:on?K.sage:K.line, position:'relative', transition:'background .2s', padding:0,
    }}>
      <span style={{
        position:'absolute', top:3, left:on?21:3, width:22, height:22, borderRadius:'50%',
        background:'#fff', boxShadow:'0 1px 3px rgba(0,0,0,.22)', transition:'left .2s ease',
      }}/>
    </button>
  );
}

// shared data
const PEOPLE = {
  daniels: { initials:'MD', bg:K.sage, name:'Mrs. Daniels', org:'Lincoln Elementary' },
  soccer:  { initials:'CS', bg:K.coral, name:'City Soccer Club', org:'Activities' },
  office:  { initials:'LE', bg:'#7d8a9b', name:'Lincoln Office', org:'School bulletin' },
  pta:     { initials:'PT', bg:'#a78b6a', name:'PTA Newsletter', org:'Community' },
};

// ════════════════════════════════════════════════════════
// 1 · CONNECT GMAIL
// ════════════════════════════════════════════════════════
function ConnectGmail({ nav }) {
  return (
    <Screen bg={K.paper} bottom={
      <div style={{ padding:'0 22px 30px', background:K.paper }}>
        <PrimaryBtn onClick={()=>nav('senders')}>
          <Icon name="mail" size={20} stroke="#fff"/> Connect Gmail
        </PrimaryBtn>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'center', gap:7, marginTop:14 }}>
          <Icon name="lock" size={14} stroke={K.ink3}/>
          <span style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3 }}>Read-only access · revoke anytime</span>
        </div>
      </div>
    }>
      <div style={{ padding:'12px 26px 0', textAlign:'center', display:'flex', flexDirection:'column', alignItems:'center' }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, fontFamily:K.sans, fontWeight:700, fontSize:19, letterSpacing:'-.03em', color:K.ink }}>
          <span style={{ width:9, height:9, borderRadius:'50%', background:K.coral }}/> klairely
        </div>

        {/* calm visual — stacked cards */}
        <div style={{ position:'relative', width:200, height:170, margin:'34px 0 30px' }}>
          <div style={{ position:'absolute', inset:'40px 22px auto', height:64, borderRadius:16, background:K.sageTint, transform:'rotate(-6deg)' }}/>
          <div style={{ position:'absolute', inset:'30px 10px auto', height:64, borderRadius:16, background:K.coralTint, transform:'rotate(4deg)' }}/>
          <div style={{ position:'absolute', inset:'18px 0 auto', padding:'16px 18px', borderRadius:18, background:'#fff', boxShadow:'0 14px 30px rgba(43,39,34,.12)', textAlign:'left' }}>
            <div style={{ display:'flex', alignItems:'center', gap:9 }}>
              <Avatar initials="MD" bg={K.sage} size={30} />
              <div>
                <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:12.5, color:K.ink }}>Mrs. Daniels</div>
                <div style={{ fontFamily:K.sans, fontSize:10.5, color:K.ink3 }}>Picture Day + Form</div>
              </div>
              <div style={{ marginLeft:'auto', width:26, height:26, borderRadius:'50%', background:K.sage, display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="check" size={15} stroke="#fff" sw={2.4}/>
              </div>
            </div>
          </div>
        </div>

        <h1 style={{ fontFamily:K.serif, fontSize:29, fontWeight:500, lineHeight:1.12, letterSpacing:'-.015em', margin:'0 0 12px', color:K.ink }}>
          Let's quiet the school inbox.
        </h1>
        <p style={{ fontFamily:K.sans, fontSize:15, lineHeight:1.55, color:K.ink2, margin:'0 0 22px', maxWidth:'30ch' }}>
          Klairely watches only your school and activity mail — and never sends or schedules anything without your tap.
        </p>
        <div style={{ display:'flex', flexDirection:'column', gap:10, width:'100%', textAlign:'left' }}>
          {[
            ['eye','Read-only','Klairely reads, never writes to your inbox.'],
            ['flag','You stay in control','Every reply and event waits for approval.'],
            ['trash','Yours to remove','Delete data and disconnect in one tap.'],
          ].map(([ic,t,d])=>(
            <div key={t} style={{ display:'flex', gap:12, alignItems:'center', padding:'12px 14px', background:K.surfaceTint, border:`1px solid ${K.line2}`, borderRadius:14 }}>
              <div style={{ width:34, height:34, borderRadius:9, background:K.sageTint, color:K.sageInk, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name={ic} size={18} stroke={K.sageInk}/>
              </div>
              <div>
                <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:13.5, color:K.ink }}>{t}</div>
                <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3, lineHeight:1.4 }}>{d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════════════════════
// 2 · CONFIRM SENDERS
// ════════════════════════════════════════════════════════
function ConfirmSenders({ nav }) {
  const [on, setOn] = React.useState({ daniels:true, office:true, soccer:true, scouts:true, pta:false });
  const rows = [
    { id:'daniels', p:PEOPLE.daniels, sub:'Teacher · 12 emails' },
    { id:'office',  p:PEOPLE.office,  sub:'School office · 8 emails' },
    { id:'soccer',  p:PEOPLE.soccer,  sub:'Activity · 5 emails' },
    { id:'scouts',  p:{initials:'SP',bg:'#6a8a7e',name:'Scout Pack 312',org:'Activity'}, sub:'Activity · 3 emails' },
    { id:'pta',     p:PEOPLE.pta,     sub:'Newsletter · 21 emails' },
  ];
  const count = Object.values(on).filter(Boolean).length;
  return (
    <Screen bottom={
      <div style={{ padding:'14px 22px 30px', background:K.paper, borderTop:`1px solid ${K.line2}` }}>
        <PrimaryBtn onClick={()=>nav('inbox')}>Watch {count} senders <Icon name="chevron" size={17} stroke="#fff"/></PrimaryBtn>
      </div>
    }>
      <ScreenHead onBack={()=>nav('connect')} greet="Step 2 of 2" title="Confirm who to watch" />
      <div style={{ padding:'2px 22px 0' }}>
        <p style={{ fontFamily:K.sans, fontSize:14.5, color:K.ink2, lineHeight:1.5, margin:'0 0 18px' }}>
          We found these school and activity senders in your mail. Keep on the ones worth watching — Klairely ignores the rest.
        </p>
        <SectionLabel>Detected senders</SectionLabel>
        <Card style={{ overflow:'hidden', padding:0 }}>
          {rows.map((r,i)=>(
            <div key={r.id} style={{ display:'flex', alignItems:'center', gap:12, padding:'14px 16px', borderTop:i?`1px solid ${K.line2}`:'none' }}>
              <Avatar initials={r.p.initials} bg={r.p.bg} size={40}/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:15, color:K.ink }}>{r.p.name}</div>
                <div style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3 }}>{r.sub}</div>
              </div>
              <Toggle on={on[r.id]} onClick={()=>setOn(s=>({...s,[r.id]:!s[r.id]}))}/>
            </div>
          ))}
        </Card>
        <div style={{ display:'flex', alignItems:'center', gap:9, marginTop:16, padding:'0 4px 8px' }}>
          <Icon name="sparkle" size={15} stroke={K.sage}/>
          <span style={{ fontFamily:K.sans, fontSize:12.5, color:K.ink3, lineHeight:1.4 }}>Klairely keeps learning which senders matter as new mail arrives.</span>
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════════════════════
// 3 · INBOX TRIAGE
// ════════════════════════════════════════════════════════
function Inbox({ nav }) {
  const [filter, setFilter] = React.useState('action');
  const mails = [
    { id:'pd', p:PEOPLE.daniels, time:'7:02 AM', subj:'Picture Day + Permission Form',
      sum:'Picture day is Friday. The form is due Wednesday. No reply required.',
      tags:[['Form due Wed','coral'],['Add to calendar','sage']], action:true, unread:true, to:'detail' },
    { id:'sc', p:PEOPLE.soccer, time:'Yesterday', subj:'Practice moved to Tuesday 6 PM',
      sum:"Jackson's practice now overlaps with a calendar event on Tuesday.",
      tags:[['Calendar conflict','coral'],['Jackson','neutral']], action:true, unread:true, to:'calendar' },
    { id:'ft', p:PEOPLE.office, time:'Mon', subj:'Spring field trip — forms & fee',
      sum:'Field trip to the science museum. Form and $12 fee due next Friday.',
      tags:[['Deadline next Fri','coral']], action:true, to:'detail' },
    { id:'pta', p:PEOPLE.pta, time:'Sun', subj:'This week at Lincoln Elementary',
      sum:'Newsletter — book fair, spirit week, and a reminder about early pickup.',
      tags:[['FYI only','neutral']], action:false, to:'detail' },
  ];
  const shown = filter==='action' ? mails.filter(m=>m.action) : mails;
  return (
    <Screen bottom={<TabBar active="inbox" onNav={nav}/>}>
      <ScreenHead greet="Good morning, Maya" title="School inbox"
        right={<Avatar initials="M" bg={K.coral} size={34}/>}/>
      <div style={{ padding:'0 16px' }}>
        {/* summary */}
        <div style={{ background:K.sage, borderRadius:18, padding:'15px 17px', color:'#fff', boxShadow:'0 8px 20px rgba(73,97,80,.22)', marginBottom:16 }}>
          <div style={{ fontFamily:K.sans, fontWeight:700, fontSize:11, letterSpacing:'.1em', textTransform:'uppercase', opacity:.82 }}>Needs you today</div>
          <div style={{ fontFamily:K.serif, fontSize:18, lineHeight:1.32, marginTop:6 }}>1 form due Wednesday and 1 calendar conflict to resolve.</div>
        </div>
        {/* filters */}
        <div style={{ display:'flex', gap:8, marginBottom:14 }}>
          {[['action','Action needed'],['all','All mail']].map(([id,l])=>(
            <button key={id} onClick={()=>setFilter(id)} style={{
              fontFamily:K.sans, fontWeight:600, fontSize:13, padding:'8px 14px', borderRadius:999, cursor:'pointer',
              border:`1px solid ${filter===id?K.sage:K.line}`, background:filter===id?K.sage:'transparent',
              color:filter===id?'#fff':K.ink2,
            }}>{l}</button>
          ))}
        </div>
        {/* mail cards */}
        <div style={{ display:'flex', flexDirection:'column', gap:11, paddingBottom:14 }}>
          {shown.map(m=>(
            <Card key={m.id} onClick={()=>nav(m.to,{mail:m.id})} style={{ padding:'14px 15px' }}>
              <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                <Avatar initials={m.p.initials} bg={m.p.bg} size={36}/>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14.5, color:K.ink }}>{m.p.name}</div>
                  <div style={{ fontFamily:K.sans, fontSize:11.5, color:K.ink3 }}>{m.p.org} · {m.time}</div>
                </div>
                {m.unread && <span style={{ width:9, height:9, borderRadius:'50%', background:K.coral, flexShrink:0 }}/>}
              </div>
              <div style={{ fontFamily:K.sans, fontWeight:600, fontSize:14, color:K.ink, margin:'11px 0 4px' }}>{m.subj}</div>
              <div style={{ fontFamily:K.sans, fontSize:13, color:K.ink2, lineHeight:1.45 }}>{m.sum}</div>
              <div style={{ display:'flex', gap:7, marginTop:11, flexWrap:'wrap' }}>
                {m.tags.map(([t,tone])=><Chip key={t} tone={tone}>{t}</Chip>)}
              </div>
            </Card>
          ))}
        </div>
      </div>
    </Screen>
  );
}

// ════════════════════════════════════════════════════════
// 4 · CHAT
// ════════════════════════════════════════════════════════
function ChatBubble({ from, children }) {
  const me = from==='me';
  return (
    <div style={{ display:'flex', justifyContent:me?'flex-end':'flex-start', marginBottom:10 }}>
      <div style={{
        maxWidth:'82%', padding:'11px 14px', borderRadius:18,
        borderBottomRightRadius:me?5:18, borderBottomLeftRadius:me?18:5,
        background:me?K.sage:K.surface, color:me?'#fff':K.ink,
        border:me?'none':`1px solid ${K.line2}`, boxShadow:me?'none':'0 1px 2px rgba(43,39,34,.04)',
        fontFamily:K.sans, fontSize:14.5, lineHeight:1.5,
      }}>{children}</div>
    </div>
  );
}
function Chat({ nav }) {
  const [msgs, setMsgs] = React.useState([
    { from:'k', t:'Morning, Maya. I went through the school inbox overnight — here\u2019s what needs you.' },
    { from:'k', card:'summary' },
    { from:'me', t:'What\u2019s the Tuesday conflict?' },
    { from:'k', t:'Jackson\u2019s soccer moved to Tuesday 6 PM, which overlaps Blake\u2019s work dinner. Want me to show both and propose a fix?' },
    { from:'k', card:'conflict' },
  ]);
  const suggestions = ['Scan a flyer','Paste a text message','Draft the reply to Mrs. Daniels','Add the form deadline','What\u2019s due this week?'];
  const scroller = React.useRef(null);
  React.useEffect(()=>{ if(scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight; },[msgs]);
  const ask = (q)=> {
    if(q === 'Scan a flyer') {
      nav('flyerscan');
      return;
    }
    if(q === 'Paste a text message') {
      nav('textimport');
      return;
    }
    setMsgs(m=>[...m,{from:'me',t:q},{from:'k',t:'On it — opening that for your approval now.'}]);
  };
  return (
    <Screen bottom={
      <div>
        <div style={{ display:'flex', gap:8, padding:'2px 14px 10px', overflowX:'auto' }}>
          {suggestions.map(s=>(
            <button key={s} onClick={()=>ask(s)} style={{
              whiteSpace:'nowrap', fontFamily:K.sans, fontWeight:500, fontSize:12.5, padding:'8px 13px',
              borderRadius:999, border:`1px solid ${K.line}`, background:K.surface, color:K.ink2, cursor:'pointer', flexShrink:0,
            }}>{s}</button>
          ))}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 16px', borderTop:`1px solid ${K.line2}`, background:K.surfaceSoft }}>
          <div style={{ flex:1, height:42, borderRadius:999, border:`1px solid ${K.line}`, background:'#fff', display:'flex', alignItems:'center', padding:'0 16px', fontFamily:K.sans, fontSize:14, color:K.ink3 }}>Ask Klairely anything…</div>
          <div style={{ width:42, height:42, borderRadius:'50%', background:K.sage, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name="send" size={19} stroke="#fff"/></div>
        </div>
        <TabBar active="chat" onNav={nav}/>
      </div>
    }>
      <div style={{ display:'flex', alignItems:'center', gap:11, padding:'4px 20px 12px', borderBottom:`1px solid ${K.line2}` }}>
        <div style={{ width:40, height:40, borderRadius:'50%', background:K.sageTint, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <span style={{ width:11, height:11, borderRadius:'50%', background:K.coral }}/>
        </div>
        <div>
          <div style={{ fontFamily:K.sans, fontWeight:700, fontSize:16, color:K.ink, letterSpacing:'-.01em' }}>Klairely</div>
          <div style={{ fontFamily:K.sans, fontSize:11.5, color:K.sage, display:'flex', alignItems:'center', gap:5 }}><span style={{ width:6, height:6, borderRadius:'50%', background:K.sage }}/>Caught up · 4 items this week</div>
        </div>
      </div>
      <div ref={scroller} style={{ padding:'16px 16px 8px' }}>
        {msgs.map((m,i)=>{
          if(m.card==='summary') return (
            <div key={i} style={{ marginBottom:12 }}>
              <Card style={{ padding:'14px 15px', borderLeft:`3px solid ${K.sage}` }}>
                <SectionLabel style={{ margin:'0 0 9px' }}>This week</SectionLabel>
                {[['3 school items',K.sage],['2 activity updates',K.sage],['1 calendar conflict',K.coral]].map(([t,c])=>(
                  <div key={t} style={{ display:'flex', alignItems:'center', gap:9, padding:'5px 0', fontFamily:K.sans, fontSize:13.5, color:K.ink }}>
                    <span style={{ width:7, height:7, borderRadius:'50%', background:c }}/>{t}
                  </div>
                ))}
              </Card>
            </div>
          );
          if(m.card==='conflict') return (
            <div key={i} style={{ marginBottom:12 }}>
              <Card onClick={()=>nav('calendar')} style={{ padding:'14px 15px' }}>
                <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, color:K.coralInk }}>Tuesday overlap</span>
                </div>
                <div style={{ display:'flex', gap:8 }}>
                  <div style={{ flex:1, background:K.sageTint, borderRadius:12, padding:'10px 12px' }}>
                    <div style={{ fontFamily:K.sans, fontSize:11, color:K.sageInk, fontWeight:600 }}>6:00 PM</div>
                    <div style={{ fontFamily:K.sans, fontSize:13, fontWeight:600, color:K.ink }}>Soccer · Jackson</div>
                  </div>
                  <div style={{ flex:1, background:K.coralTint, borderRadius:12, padding:'10px 12px' }}>
                    <div style={{ fontFamily:K.sans, fontSize:11, color:K.coralInk, fontWeight:600 }}>6:30 PM</div>
                    <div style={{ fontFamily:K.sans, fontSize:13, fontWeight:600, color:K.ink }}>Work dinner · Blake</div>
                  </div>
                </div>
                <div style={{ marginTop:11, fontFamily:K.sans, fontWeight:600, fontSize:13, color:K.sage, display:'flex', alignItems:'center', gap:5 }}>
                  Review &amp; resolve <Icon name="chevron" size={14} stroke={K.sage}/>
                </div>
              </Card>
            </div>
          );
          if(i === msgs.length - 1) {
            return (
              <React.Fragment key={i}>
                <ChatBubble from={m.from}>{m.t}</ChatBubble>
                <div style={{ marginBottom:12 }}>
                  <Card onClick={()=>nav('textimport')} style={{ padding:'14px 15px', borderLeft:`3px solid ${K.coral}` }}>
                    <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
                      <div style={{ width:34, height:34, borderRadius:10, background:K.coralTint, color:K.coralInk, display:'flex', alignItems:'center', justifyContent:'center' }}>
                        <Icon name="clip" size={17} stroke={K.coralInk}/>
                      </div>
                      <div>
                        <div style={{ fontFamily:K.sans, fontWeight:700, fontSize:13.5, color:K.ink }}>Paste a message</div>
                        <div style={{ fontFamily:K.sans, fontSize:12, color:K.ink3 }}>Texts, DMs, portals, or copied notes</div>
                      </div>
                    </div>
                    <div style={{ fontFamily:K.sans, fontSize:13.2, color:K.ink2, lineHeight:1.45 }}>
                      Copy a text about an appointment, birthday invite, or practice change. Klairely pulls out the date, time, and next steps.
                    </div>
                  </Card>
                </div>
              </React.Fragment>
            );
          }
          return <ChatBubble key={i} from={m.from}>{m.t}</ChatBubble>;
        })}
      </div>
    </Screen>
  );
}

window.Screens1 = { ConnectGmail, ConfirmSenders, Inbox, Chat };
window.KHelpers = { Screen, Card, Toggle, PEOPLE };
