/* Admin → Messaging: broadcasts + parent threads */
function DispatchThread() {
  const SEED = [
    { from:'dispatch', t:'Morning Marcus — Elm Village Dr is closed for repairs. Use the Riverstone detour for stop 3.' },
    { from:'driver',   t:'Got it, taking the detour now.' },
    { from:'dispatch', t:'Thanks. Let us know if you fall behind schedule.' },
  ];
  const [thread, setThread] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  React.useEffect(() => {
    JLBackend.seed({ dispatch: SEED });
    setThread(JLBackend.get('dispatch', SEED));
    return JLBackend.subscribe('dispatch', v => setThread(v || []));
  }, []);
  const send = () => {
    const t = draft.trim(); if (!t) return;
    JLBackend.update('dispatch', prev => [...(prev||[]), { from:'dispatch', t }], SEED);
    setDraft('');
  };
  return (
    <Panel title="Dispatch · Bus #12 — Marcus Reed" action={<span style={{ display:'inline-flex', alignItems:'center', gap:6, fontSize:12.5, fontWeight:700, color:'var(--success-600)' }}><span style={{ width:8, height:8, borderRadius:'999px', background:'var(--success-500)' }} />Live</span>}>
      <div style={{ display:'flex', flexDirection:'column', gap:8, maxHeight:220, overflowY:'auto', padding:'4px 2px 10px' }}>
        {thread.map((b,i)=>{ const me = b.from==='dispatch'; return (
          <div key={i} style={{ alignSelf: me?'flex-end':'flex-start', maxWidth:'82%', background: me?'var(--navy-600)':'var(--gray-100)', color: me?'#fff':'var(--ink)', borderRadius:14, borderBottomRightRadius: me?4:14, borderBottomLeftRadius: me?14:4, padding:'9px 13px', fontSize:13.5, lineHeight:1.4 }}>{b.t}</div>
        ); })}
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:9, borderTop:'1px solid var(--gray-100)', paddingTop:11 }}>
        <input value={draft} onChange={e=>setDraft(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter') send(); }} placeholder="Message the driver…" style={{ flex:1, border:'1px solid var(--gray-200)', borderRadius:'999px', padding:'10px 15px', fontSize:13.5, fontFamily:'var(--font-sans)', outline:'none', color:'var(--ink)' }} />
        <button onClick={send} style={{ width:40, height:40, borderRadius:'999px', border:0, background:'var(--navy-600)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flex:'0 0 auto' }}><Icon name="send-horizontal" size={18} color="#fff" /></button>
      </div>
    </Panel>
  );
}
function NotifReachPanel() {
  const CATS = [
    { id:'alerts', label:'Emergency alerts', icon:'siren' },
    { id:'pickup', label:'Pickup & bus', icon:'car-front' },
    { id:'attend', label:'Attendance', icon:'calendar-check' },
    { id:'grades', label:'Grades', icon:'graduation-cap' },
    { id:'messages', label:'Messages', icon:'message-circle' },
    { id:'payments', label:'Payments', icon:'wallet' },
    { id:'events', label:'Events', icon:'calendar-days' },
  ];
  const [prefs, setPrefs] = React.useState(null);
  React.useEffect(() => {
    const read = () => { try { setPrefs(JSON.parse(localStorage.getItem('jl_notif') || 'null')); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_notif') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, []);
  const Dot = ({ on }) => <span style={{ display:'inline-flex', alignItems:'center', gap:5, fontSize:12, fontWeight:700, color: on?'var(--success-600)':'var(--gray-400)' }}><span style={{ width:8, height:8, borderRadius:'999px', background: on?'var(--success-500)':'var(--gray-300)' }} />{on?'On':'Off'}</span>;
  return (
    <Panel title="Notification Reach · Hatten Family" action={<Pill bg="var(--blue-100)" fg="var(--blue-600)">live from parent app</Pill>} pad={false}>
      {!prefs ? (
        <div style={{ padding:'18px', color:'var(--gray-500)', fontSize:13.5 }}>This family hasn't set notification preferences yet — defaults apply (push on).</div>
      ) : (
        <React.Fragment>
          <div style={{ display:'grid', gridTemplateColumns:'auto 80px 80px', padding:'11px 18px', background:'var(--gray-50)', fontSize:11, fontWeight:800, letterSpacing:'.05em', textTransform:'uppercase', color:'var(--gray-500)' }}>
            <span>Category</span><span>Push</span><span>SMS</span>
          </div>
          {CATS.map((c,i) => { const p = prefs[c.id] || {}; return (
            <div key={c.id} style={{ display:'grid', gridTemplateColumns:'auto 80px 80px', alignItems:'center', padding:'11px 18px', borderTop:'1px solid var(--gray-100)', fontSize:13.5 }}>
              <span style={{ display:'flex', alignItems:'center', gap:9 }}><Icon name={c.icon} size={16} color="var(--gray-500)" /><span style={{ fontWeight:600, color:'var(--ink)' }}>{c.label}</span></span>
              <Dot on={!!p.push} /><Dot on={!!p.sms} />
            </div>
          ); })}
        </React.Fragment>
      )}
    </Panel>
  );
}
function MessagingScreen() {
  const [tab, setTab] = React.useState('broadcasts');
  const broadcasts = [
    { t:'Early dismissal this Friday at 1:00 PM', aud:'All Parents · Katy Middle', time:'2h ago', reach:'1,248 sent', icon:'megaphone', tint:'var(--blue-100)', ic:'var(--blue-500)' },
    { t:'Bus #7 running late on Route 3', aud:'Route 3 Families', time:'3h ago', reach:'19 sent', icon:'bus', tint:'var(--danger-100)', ic:'var(--danger-500)' },
    { t:'Spring book fair next week', aud:'All Parents', time:'1d ago', reach:'1,248 sent', icon:'book-open', tint:'var(--gold-100)', ic:'var(--gold-600)' },
  ];
  const threads = [
    { n:'Jermaine Hatten', re:'Re: EJ pickup change', prev:'Thank you, that works for us.', time:'12m', c:'navy', unread:true },
    { n:'Ashley Brooks', re:'Bus stop question', prev:'Is the morning stop still at 7:40?', time:'1h', c:'blue', unread:true },
    { n:'Marcus Lee', re:'Lunch balance', prev:'Just added funds — thanks!', time:'4h', c:'green', unread:false },
  ];
  return (
    <div style={{ padding:'22px 28px 40px', height:'100%', overflowY:'auto', boxSizing:'border-box' }}>
      <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:16 }}>
        {/* composer */}
        <Panel title="New Broadcast">
          <div style={{ padding:'4px 0 8px' }}>
            <div style={{ display:'flex', gap:10, marginBottom:12 }}>
              <select style={selStyle}><option>All Parents · Katy Middle</option><option>Route 3 Families</option><option>Grade 6 Parents</option></select>
              <select style={{ ...selStyle, width:150 }}><option>Normal</option><option>Urgent</option></select>
            </div>
            <textarea placeholder="Write an announcement to families…" style={{ width:'100%', minHeight:96, resize:'vertical', border:'1px solid var(--gray-200)', borderRadius:10, padding:'12px 14px', fontSize:14, fontFamily:'var(--font-sans)', outline:'none', boxSizing:'border-box', color:'var(--ink)' }} defaultValue="" />
            <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:12 }}>
              <button onClick={()=>jlToast('Attach a file', { icon:'paperclip' })} style={{ display:'flex', alignItems:'center', gap:7, background:'#fff', border:'1px solid var(--gray-200)', borderRadius:9, padding:'9px 13px', fontWeight:700, fontSize:13, cursor:'pointer', color:'var(--gray-700)', fontFamily:'var(--font-sans)' }}><Icon name="paperclip" size={15} color="var(--gray-600)" />Attach</button>
              <button onClick={()=>jlToast('Schedule for later', { icon:'clock' })} style={{ display:'flex', alignItems:'center', gap:7, background:'#fff', border:'1px solid var(--gray-200)', borderRadius:9, padding:'9px 13px', fontWeight:700, fontSize:13, cursor:'pointer', color:'var(--gray-700)', fontFamily:'var(--font-sans)' }}><Icon name="clock" size={15} color="var(--gray-600)" />Schedule</button>
              <button onClick={()=>jlToast('Broadcast sent to 1,248 families', { icon:'send-horizontal' })} style={{ marginLeft:'auto', display:'flex', alignItems:'center', gap:7, background:'var(--gold-400)', color:'var(--on-gold)', border:0, borderRadius:9, padding:'10px 18px', fontWeight:700, fontSize:13.5, cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-gold)' }}><Icon name="send-horizontal" size={15} color="var(--on-gold)" />Send Broadcast</button>
            </div>
          </div>
        </Panel>

        {/* parent threads */}
        <Panel title="Parent Threads" action={<Pill bg="var(--blue-100)" fg="var(--blue-600)">2 new</Pill>}>
          {threads.map((t,i)=>(
            <div key={i} onClick={()=>jlToast('Opening thread with '+t.n, { icon:'message-circle' })} style={{ display:'flex', alignItems:'flex-start', gap:11, padding:'11px 0', borderBottom: i<threads.length-1?'1px solid var(--gray-100)':'0', cursor:'pointer' }}>
              <Avatar initials={t.n.split(' ').map(w=>w[0]).join('')} color={t.c} size={34} />
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>{t.n}</div>
                <div style={{ fontSize:12, color:'var(--gray-500)', marginBottom:2 }}>{t.re}</div>
                <div style={{ fontSize:12.5, color: t.unread?'var(--ink-soft)':'var(--gray-500)', fontWeight: t.unread?600:400, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{t.prev}</div>
              </div>
              <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:5 }}>
                <span style={{ fontSize:11, color:'var(--gray-400)' }}>{t.time}</span>
                {t.unread && <span style={{ width:8, height:8, borderRadius:'999px', background:'var(--blue-500)' }} />}
              </div>
            </div>
          ))}
        </Panel>
      </div>

      {/* live dispatch thread (wired to driver app) */}
      <div style={{ marginTop:16 }}>
        <DispatchThread />
      </div>

      <div style={{ marginTop:16 }}>
        <NotifReachPanel />
      </div>

      {/* sent broadcasts */}
      <div style={{ marginTop:16 }}>
        <Panel title="Recent Broadcasts" action={<span onClick={()=>jlToast('Showing all broadcasts', { icon:'megaphone' })} style={{ fontSize:12.5, fontWeight:700, color:'var(--blue-500)', cursor:'pointer' }}>View All</span>}>
          {broadcasts.map((b,i)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:13, padding:'12px 0', borderBottom: i<broadcasts.length-1?'1px solid var(--gray-100)':'0' }}>
              <span style={{ width:38, height:38, borderRadius:10, background:b.tint, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name={b.icon} size={18} color={b.ic} /></span>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)' }}>{b.t}</div>
                <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{b.aud}</div>
              </div>
              <div style={{ textAlign:'right' }}>
                <div style={{ fontSize:12.5, fontWeight:700, color:'var(--success-600)' }}>{b.reach}</div>
                <div style={{ fontSize:11.5, color:'var(--gray-400)' }}>{b.time}</div>
              </div>
            </div>
          ))}
        </Panel>
      </div>
    </div>
  );
}
const selStyle = { flex:1, border:'1px solid var(--gray-200)', borderRadius:10, padding:'10px 12px', fontSize:13.5, fontFamily:'var(--font-sans)', color:'var(--ink)', background:'#fff', outline:'none' };
Object.assign(window, { MessagingScreen });
