/* Messages list + Chat thread — threads are per-child. */
const JL_CONVO_SETS = {
  ej: [
    { id:'ej-1', initials:'MJ', color:'blue', name:'Mrs. Johnson', role:'Math Teacher', cat:'Teachers', time:'2m', unread:2,
      preview:'EJ did great today in class!',
      bubbles:[{me:false,t:'Hi! Just wanted to share that EJ did great today in class.'},{me:false,t:'Reminder: the fractions worksheet is due tonight at 11:59 PM.'},{me:true,t:'Thank you so much! We\u2019ll get it done tonight.'}],
      summary:'EJ had a great day. A fractions worksheet is due tonight at 11:59 PM — you confirmed it\u2019ll be done.' },
    { id:'ej-2', initials:'MW', color:'cyan', name:'Mr. Williams', role:'Science Teacher', cat:'Teachers', time:'1h', unread:0,
      preview:"Don't forget the quiz tomorrow.",
      bubbles:[{me:false,t:'EJ\u2019s lab report was excellent work.'},{me:false,t:'Don\u2019t forget the quiz on ecosystems tomorrow.'},{me:true,t:'Thanks for the heads-up — we\u2019ll review tonight.'}],
      summary:'Praise for EJ\u2019s lab report; an ecosystems quiz is tomorrow.' },
    { id:'ej-3', initials:'SA', color:'navy', name:'School Admin', role:'Katy Middle School', cat:'School', time:'2h', unread:0,
      preview:'Early dismissal this Friday at 1:00 PM.',
      bubbles:[{me:false,t:'Reminder: early dismissal this Friday at 1:00 PM.'},{me:false,t:'Please confirm your pickup plan in the app.'}],
      summary:'Early dismissal Friday at 1:00 PM — confirm your pickup plan.' },
    { id:'ej-4', initials:'CB', color:'red', name:'Coach Brown', role:'Boys Basketball', cat:'Groups', time:'2d', unread:0,
      preview:'Practice tomorrow at 4:30 PM.',
      bubbles:[{me:false,t:'Practice tomorrow at 4:30 PM in the main gym.'},{me:true,t:'Got it, EJ will be there.'}],
      summary:'Basketball practice tomorrow at 4:30 PM in the main gym.' },
  ],
  maya: [
    { id:'maya-1', initials:'RC', color:'gold', name:'Ms. Carter', role:'4th Grade Teacher', cat:'Teachers', time:'15m', unread:1,
      preview:'Maya was so kind to a new student today.',
      bubbles:[{me:false,t:'Maya was so kind to a new student today — I wanted you to know.'},{me:false,t:'Spelling test is Friday; the word list is in her folder.'},{me:true,t:'That\u2019s wonderful to hear, thank you!'}],
      summary:'Kindness praise for Maya; spelling test Friday, list in her folder.' },
    { id:'maya-2', initials:'LP', color:'green', name:'Ms. Park', role:'Reading Specialist', cat:'Teachers', time:'3h', unread:0,
      preview:'Maya moved up a reading level!',
      bubbles:[{me:false,t:'Great news — Maya moved up a reading level this week.'},{me:true,t:'She\u2019ll be thrilled — thank you for the support.'}],
      summary:'Maya advanced a reading level this week.' },
    { id:'maya-3', initials:'SA', color:'navy', name:'School Admin', role:'Katy Elementary', cat:'School', time:'2h', unread:0,
      preview:'Early dismissal this Friday at 1:00 PM.',
      bubbles:[{me:false,t:'Reminder: early dismissal this Friday at 1:00 PM.'},{me:false,t:'Walkers will be released from the front entrance.'}],
      summary:'Early dismissal Friday at 1:00 PM — walkers released from the front.' },
    { id:'maya-4', initials:'AG', color:'red', name:'Art Club', role:'Katy Elementary', cat:'Groups', time:'1d', unread:0,
      preview:'Bring a smock on Thursday.',
      bubbles:[{me:false,t:'Art Club meets Thursday — please send a smock with Maya.'},{me:true,t:'Will do, thanks!'}],
      summary:'Art Club Thursday; send a smock with Maya.' },
  ],
};
function jlConvos(){ return JL_CONVO_SETS[jlChild().id] || JL_CONVO_SETS.ej; }
const JL_FILTERS = ['All','Teachers','School','Groups'];

function MessagesScreen({ onNav, onOpen, onBack }) {
  const [filter, setFilter] = React.useState('All');
  const list = jlConvos().filter(c => filter==='All' || c.cat===filter);
  return (
    <div style={{ background:'#fff', minHeight:'100%' }}>
      <TitleBar title="Messages" onBack={onBack} action={<button onClick={()=>jlToast('New message', { icon:'square-pen' })} style={{ width:38, height:38, borderRadius:'999px', border:'1px solid var(--gray-200)', background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}><Icon name="square-pen" size={18} color="var(--navy-600)" /></button>} />
      <div style={{ padding:'8px 18px 6px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, background:'var(--gray-100)', border:'1px solid var(--gray-200)', borderRadius:'999px', padding:'11px 15px' }}>
          <Icon name="search" size={18} color="var(--gray-500)" />
          <input placeholder="Search messages" style={{ flex:1, border:0, background:'transparent', outline:'none', fontSize:14, fontFamily:'var(--font-sans)', color:'var(--ink)' }} />
        </div>
      </div>
      <div style={{ display:'flex', gap:8, padding:'8px 18px 4px', overflowX:'auto' }}>
        {JL_FILTERS.map(f => (
          <button key={f} onClick={()=>setFilter(f)} style={{
            padding:'7px 16px', borderRadius:'999px', border:0, cursor:'pointer',
            fontWeight:700, fontSize:13, fontFamily:'var(--font-sans)', whiteSpace:'nowrap',
            background: filter===f ? 'var(--navy-600)' : 'var(--gray-100)',
            color: filter===f ? '#fff' : 'var(--gray-600)',
          }}>{f}</button>
        ))}
      </div>
      <div style={{ padding:'4px 8px 110px' }}>
        {list.map(c => (
          <button key={c.id} onClick={()=>onOpen(c)} style={{
            width:'100%', display:'flex', alignItems:'center', gap:12, padding:'12px 12px',
            border:0, borderRadius:14, background:'transparent', cursor:'pointer',
            fontFamily:'var(--font-sans)', textAlign:'left',
          }}>
            <Avatar initials={c.initials} color={c.color} size={46} />
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:14.5, fontWeight:700, color:'var(--ink)' }}>{c.name}</div>
              <div style={{ fontSize:12, color:'var(--gray-400)', fontWeight:600, marginBottom:1 }}>{c.role}</div>
              <div style={{ fontSize:13, color: c.unread? 'var(--ink-soft)':'var(--gray-500)', fontWeight: c.unread?600:400, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{c.preview}</div>
            </div>
            <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:6, flex:'0 0 auto' }}>
              <span style={{ fontSize:11, color:'var(--gray-400)' }}>{c.time}</span>
              {c.unread>0 && <span style={{ minWidth:19, height:19, padding:'0 5px', borderRadius:'999px', background:'var(--blue-500)', color:'#fff', fontSize:11, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center' }}>{c.unread}</span>}
            </div>
          </button>
        ))}
      </div>
      <BottomNav active="messages" onNav={onNav} />
    </div>
  );
}

function ChatScreen({ convo, onBack }) {
  const c = convo || jlConvos()[0];
  const [bubbles, setBubbles] = React.useState(c.bubbles || []);
  const [draft, setDraft] = React.useState('');
  const [showSummary, setShowSummary] = React.useState(false);
  const endRef = React.useRef(null);
  const send = () => {
    const t = draft.trim();
    if (!t) return;
    setBubbles(b => [...b, { me:true, t }]);
    setDraft('');
    setTimeout(() => endRef.current && endRef.current.scrollIntoView({ behavior:'smooth' }), 50);
  };
  return (
    <div style={{ background:'var(--gray-50)', minHeight:'100%', display:'flex', flexDirection:'column' }}>
      <div style={{ paddingTop:54, padding:'54px 14px 12px', display:'flex', alignItems:'center', gap:10, background:'#fff', borderBottom:'1px solid var(--gray-200)' }}>
        <button onClick={onBack} style={{ width:36, height:36, border:0, background:'transparent', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}><Icon name="arrow-left" size={22} color="var(--ink)" /></button>
        <Avatar initials={c.initials} color={c.color} size={36} />
        <div style={{ flex:1 }}>
          <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)' }}>{c.name}</div>
          <div style={{ fontSize:11.5, color:'var(--gray-500)' }}>{c.role}</div>
        </div>
      </div>

      {/* AI Summary chip */}
      <div style={{ padding:'12px 16px 4px' }}>
        <button onClick={()=>setShowSummary(s=>!s)} style={{ display:'inline-flex', alignItems:'center', gap:7, whiteSpace:'nowrap', background: showSummary?'var(--blue-700)':'var(--blue-100)', color: showSummary?'#fff':'var(--blue-700)', border:0, borderRadius:'999px', padding:'8px 14px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}>
          <Icon name="sparkles" size={14} color={showSummary?'#fff':'var(--blue-700)'} />AI Summary
        </button>
        {showSummary && (
          <div style={{ marginTop:10, background:'var(--blue-100)', border:'1px solid #C9DBF5', borderRadius:12, padding:'12px 14px' }}>
            <div style={{ fontSize:11, fontWeight:800, letterSpacing:'.08em', color:'var(--blue-700)', marginBottom:4 }}>SUMMARY</div>
            <div style={{ fontSize:13, lineHeight:1.5, color:'var(--ink-soft)' }}>{c.summary}</div>
          </div>
        )}
      </div>

      <div style={{ flex:1, padding:'8px 16px 16px', display:'flex', flexDirection:'column', gap:9 }}>
        {bubbles.map((b,i)=>(
          <div key={i} style={{ alignSelf: b.me?'flex-end':'flex-start', maxWidth:'78%', background: b.me?'var(--navy-600)':'#fff', color: b.me?'#fff':'var(--ink)', border: b.me?'0':'1px solid var(--gray-200)', borderRadius:16, padding:'11px 14px', fontSize:14, lineHeight:1.4, boxShadow:'var(--shadow-xs)' }}>{b.t}</div>
        ))}
        <div ref={endRef} />
      </div>

      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 14px 30px', background:'#fff', borderTop:'1px solid var(--gray-200)' }}>
        <div style={{ flex:1, display:'flex', alignItems:'center', background:'var(--gray-100)', borderRadius:'999px', padding:'11px 16px' }}>
          <input value={draft} onChange={e=>setDraft(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter') send(); }} placeholder="Type message..." style={{ flex:1, border:0, background:'transparent', outline:'none', fontSize:14, fontFamily:'var(--font-sans)' }} />
        </div>
        <button onClick={send} style={{ width:44, height:44, borderRadius:'999px', border:0, background:'var(--gold-400)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', boxShadow:'var(--shadow-gold)' }}><Icon name="send-horizontal" size={20} color="var(--on-gold)" /></button>
      </div>
    </div>
  );
}

Object.assign(window, { MessagesScreen, ChatScreen, jlConvos });
