/* Messages list + Chat thread */
const JL_CONVOS = [
  { id:1, initials:'MJ', color:'blue',  name:'Mrs. Johnson', role:'Math Teacher',    preview:'EJ did great today in class!',          time:'2m', unread:2, cat:'Teachers' },
  { id:2, initials:'MW', color:'cyan',  name:'Mr. Williams', role:'Science Teacher', preview:"Don't forget the quiz tomorrow.",        time:'1h', unread:0, cat:'Teachers' },
  { id:3, initials:'SA', color:'navy',  name:'School Admin', role:'Katy Middle School', preview:'Early dismissal this Friday at 1:00 PM.', time:'2h', unread:0, cat:'School' },
  { id:4, initials:'AP', color:'gold',  name:'Aftercare Program', role:'Katy Middle School', preview:'Reminder: Aftercare payment due.',     time:'1d', unread:0, cat:'School' },
  { id:5, initials:'CB', color:'red',   name:'Coach Brown', role:'Boys Basketball',  preview:'Practice tomorrow at 4:30 PM.',            time:'2d', unread:0, cat:'Groups' },
];
const JL_FILTERS = ['All','Teachers','School','Groups'];

function MessagesScreen({ onNav, onOpen, onBack }) {
  const [filter, setFilter] = React.useState('All');
  const list = JL_CONVOS.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 || JL_CONVOS[0];
  const [bubbles, setBubbles] = React.useState([
    { 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.' },
  ]);
  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)' }}>EJ had a great day. A fractions worksheet is due tonight at 11:59 PM — you confirmed it'll be done.</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, JL_CONVOS });
