/* Admin → Live Fleet Map: all buses on a stylized map + fleet status list. */
function FleetScreen() {
  const STATUS = {
    route:   { label:'On route', bg:'var(--success-100)', fg:'var(--success-600)', dot:'var(--success-500)' },
    delayed: { label:'Delayed',  bg:'var(--warning-100)', fg:'var(--warning-600)', dot:'var(--warning-500)' },
    idle:    { label:'At depot', bg:'var(--gray-100)',    fg:'var(--gray-600)',    dot:'var(--gray-400)' },
  };
  const baseBuses = [
    { id:'12', driver:'Marcus Reed', route:'KMS Loop 3', status:'route',   students:11, eta:'7:20 AM', x:34, y:58 },
    { id:'07', driver:'Dana Cole',   route:'Elm & Park',  status:'route',   students:14, eta:'7:24 AM', x:62, y:38 },
    { id:'19', driver:'Sam Ortiz',   route:'North Ridge', status:'delayed', students:9,  eta:'7:35 AM', x:20, y:30 },
    { id:'23', driver:'Priya Nair',  route:'Cinco West',  status:'route',   students:12, eta:'7:28 AM', x:78, y:64 },
    { id:'04', driver:'Leon Baptiste',route:'South Gate', status:'idle',    students:0,  eta:'—',       x:48, y:82 },
  ];
  const [sel, setSel] = React.useState('12');
  const [live, setLive] = React.useState({});
  const [assign, setAssign] = React.useState({});
  const [alerts, setAlerts] = React.useState([]);
  React.useEffect(() => {
    const read = () => { try { setLive(JSON.parse(localStorage.getItem('jl_fleet') || '{}')); setAssign(JSON.parse(localStorage.getItem('jl_routes') || '{}')); setAlerts(JSON.parse(localStorage.getItem('jl_alerts') || '[]')); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_fleet' || e.key === 'jl_routes' || e.key === 'jl_alerts') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, []);
  const clearAlerts = () => { try { localStorage.setItem('jl_alerts', '[]'); } catch(e){} setAlerts([]); jlToast('Alerts cleared', { icon:'check-check' }); };
  const setAlert = (id, patch, toast) => {
    setAlerts(prev => {
      const n = prev.map(a => a.id===id ? { ...a, ...patch } : a);
      try { localStorage.setItem('jl_alerts', JSON.stringify(n)); } catch(e){}
      if (patch.status==='resolved') {
        try {
          const a = prev.find(x=>x.id===id);
          if (a) { const log = JSON.parse(localStorage.getItem('jl_incidentlog') || '[]'); log.unshift({ id:a.id, kind:a.kind, label:a.label, bus:a.bus, driver:a.driver, reportedAt:a.at, resolvedAt:Date.now() }); localStorage.setItem('jl_incidentlog', JSON.stringify(log.slice(0,50))); }
        } catch(e){}
      }
      return n;
    });
    if (toast) jlToast(toast.msg, { icon:toast.icon, color:toast.color });
  };
  const ago = (t) => { const s = Math.round((Date.now()-t)/1000); return s<60?'just now':(s<3600?Math.floor(s/60)+'m ago':Math.floor(s/3600)+'h ago'); };
  const buses = baseBuses.map(b => {
    let out = { ...b };
    const a = assign[b.id];
    if (a) out = { ...out, route:a.route || out.route, driver:a.driver || out.driver, students:a.students };
    const l = live[b.id];
    if (l) out = { ...out, status:l.status, students:l.students, driver:l.driver || out.driver, route:l.route || out.route, next:l.next, isLive:true };
    return out;
  });
  const onRoute = buses.filter(b=>b.status==='route').length;
  const delayed = buses.filter(b=>b.status==='delayed').length;
  const aboard = buses.reduce((n,b)=>n+b.students,0);

  return (
    <div style={{ padding:'22px 28px 40px', height:'100%', overflowY:'auto', boxSizing:'border-box' }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16, marginBottom:16 }}>
        <StatTile icon="bus" tint="var(--blue-100)" ic="var(--blue-500)" value={buses.length} label="Buses tracked" />
        <StatTile icon="navigation" tint="var(--success-100)" ic="var(--success-600)" value={onRoute} label="On route" />
        <StatTile icon="clock" tint="var(--warning-100)" ic="var(--warning-600)" value={delayed} label="Delayed" />
        <StatTile icon="users" tint="var(--gold-100)" ic="var(--gold-600)" value={aboard} label="Students aboard" />
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:16 }}>
        {/* map */}
        <Panel title="Live Fleet Map" action={<Pill bg="var(--success-100)" fg="var(--success-600)"><span style={{ width:7, height:7, borderRadius:'999px', background:'var(--success-500)', display:'inline-block' }} />Live</Pill>} pad={false}>
          <div style={{ position:'relative', height:460, background:'linear-gradient(160deg,#E9EEF5 0%,#DCE4EF 100%)', overflow:'hidden', borderRadius:'0 0 16px 16px' }}>
            <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position:'absolute', inset:0, width:'100%', height:'100%' }}>
              {[16,34,52,70,88].map(y => <line key={'h'+y} x1="0" y1={y} x2="100" y2={y} stroke="rgba(120,140,170,.16)" strokeWidth=".4" />)}
              {[14,32,50,68,86].map(x => <line key={'v'+x} x1={x} y1="0" x2={x} y2="100" stroke="rgba(120,140,170,.16)" strokeWidth=".4" />)}
              <polyline points="8,88 34,58 62,38 88,20" fill="none" stroke="rgba(26,58,109,.25)" strokeWidth="1.5" strokeLinecap="round" />
              <polyline points="20,30 48,50 78,64" fill="none" stroke="rgba(26,58,109,.25)" strokeWidth="1.5" strokeLinecap="round" />
            </svg>
            {/* school */}
            <div style={{ position:'absolute', left:'50%', top:'8%', transform:'translate(-50%,-50%)' }}>
              <span style={{ display:'flex', alignItems:'center', justifyContent:'center', width:30, height:30, borderRadius:9, background:'var(--navy-600)', border:'2px solid #fff', boxShadow:'0 2px 6px rgba(0,0,0,.25)' }}><Icon name="school" size={16} color="#fff" /></span>
            </div>
            {buses.map(b => {
              const st = STATUS[b.status];
              const on = sel===b.id;
              return (
                <button key={b.id} onClick={()=>setSel(b.id)} title={'Bus #'+b.id} style={{ position:'absolute', left:b.x+'%', top:b.y+'%', transform:'translate(-50%,-50%)', border:0, background:'transparent', cursor:'pointer', padding:0, zIndex: on?5:3 }}>
                  <span className={b.status==='route'?'jl-pulse':''} style={{ display:'flex', alignItems:'center', justifyContent:'center', width: on?44:36, height: on?44:36, borderRadius:'999px', background:st.dot, border: on?'3px solid var(--navy-600)':'3px solid #fff', boxShadow:'0 3px 9px rgba(0,0,0,.28)', transition:'.15s' }}>
                    <Icon name="bus-front" size={on?22:18} color="#fff" />
                  </span>
                </button>
              );
            })}
          </div>
        </Panel>

        {/* fleet list */}
        <Panel title="Fleet Status" pad={false}>
          {buses.map((b,i) => {
            const st = STATUS[b.status];
            const on = sel===b.id;
            return (
              <button key={b.id} onClick={()=>setSel(b.id)} style={{ width:'100%', display:'flex', alignItems:'center', gap:12, padding:'13px 16px', borderTop: i>0?'1px solid var(--gray-100)':'0', border:'0', borderLeft: on?'3px solid var(--blue-500)':'3px solid transparent', background: on?'var(--blue-100)':'transparent', cursor:'pointer', fontFamily:'var(--font-sans)', textAlign:'left' }}>
                <span style={{ width:40, height:40, borderRadius:11, background:st.bg, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name="bus" size={19} color={st.fg} /></span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)' }}>Bus #{b.id} · {b.route}</div>
                  <div style={{ fontSize:12, color:'var(--gray-500)' }}>{b.driver} · {b.students} aboard</div>
                </div>
                <div style={{ textAlign:'right', flex:'0 0 auto' }}>
                  <Pill bg={st.bg} fg={st.fg}>{st.label}</Pill>
                  <div style={{ fontSize:11.5, color: b.isLive?'var(--success-600)':'var(--gray-400)', marginTop:3, fontFamily:'var(--font-mono)', display:'flex', alignItems:'center', gap:4, justifyContent:'flex-end' }}>{b.isLive && <span className="jl-pulse" style={{ width:6, height:6, borderRadius:'999px', background:'var(--success-500)' }} />}{b.isLive ? 'Live' : 'ETA ' + b.eta}</div>
                </div>
              </button>
            );
          })}
          <div style={{ padding:'12px 16px', borderTop:'1px solid var(--gray-100)' }}>
            <button onClick={()=>jlToast('Messaging all drivers', { icon:'radio' })} style={{ width:'100%', display:'flex', alignItems:'center', justifyContent:'center', gap:8, background:'var(--navy-600)', color:'#fff', border:0, borderRadius:10, padding:'11px', fontWeight:700, fontSize:13.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="radio" size={16} color="#fff" />Message All Drivers</button>
          </div>
        </Panel>
      </div>

      {/* live driver alerts */}
      <div style={{ marginTop:16 }}>
        <Panel title="Driver Alerts" action={alerts.length>0 && <button onClick={clearAlerts} style={{ background:'transparent', border:0, color:'var(--blue-500)', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}>Clear all</button>} pad={false}>
          {alerts.length===0 ? (
            <div style={{ display:'flex', alignItems:'center', gap:10, padding:'18px', color:'var(--gray-500)', fontSize:13.5 }}><Icon name="shield-check" size={18} color="var(--success-500)" />No active alerts — fleet running normally.</div>
          ) : alerts.map((a,i) => {
            const inc = a.kind==='incident';
            return (
              <div key={a.id} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 18px', borderTop: i>0?'1px solid var(--gray-100)':'0', opacity: a.status==='resolved'?.55:1 }}>
                <span style={{ width:38, height:38, borderRadius:10, background: inc?'var(--danger-100)':'var(--warning-100)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name={inc?'triangle-alert':'clock'} size={18} color={inc?'var(--danger-500)':'var(--warning-600)'} /></span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)' }}>{a.label} · Bus {a.bus}</div>
                  <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{a.driver} · {ago(a.at)}</div>
                </div>
                {a.status==='resolved' ? (
                  <Pill bg="var(--success-100)" fg="var(--success-600)"><Icon name="check" size={12} color="var(--success-600)" />Resolved</Pill>
                ) : (
                  <div style={{ display:'flex', alignItems:'center', gap:7 }}>
                    {a.status==='ack'
                      ? <Pill bg="var(--blue-100)" fg="var(--blue-600)">Acknowledged</Pill>
                      : <button onClick={()=>setAlert(a.id, { status:'ack' }, { msg:'Acknowledged · Bus '+a.bus, icon:'eye' })} style={feBtnGhost}>Acknowledge</button>}
                    <button onClick={()=>jlToast('Messaging '+a.driver, { icon:'radio' })} title="Message driver" style={feIcon}><Icon name="radio" size={15} color="var(--navy-600)" /></button>
                    <button onClick={()=>jlToast('Dispatching support to Bus '+a.bus, { icon:'ambulance', color: inc?'#E5484D':undefined })} title="Dispatch support" style={feIcon}><Icon name="ambulance" size={15} color="var(--danger-500)" /></button>
                    <button onClick={()=>setAlert(a.id, { status:'resolved' }, { msg:'Marked resolved · Bus '+a.bus, icon:'check-check', color:'#1F9D57' })} style={feBtnResolve}><Icon name="check" size={14} color="#fff" />Resolve</button>
                  </div>
                )}
              </div>
            );
          })}
        </Panel>
      </div>
    </div>
  );
}
const feBtnGhost = { background:'#fff', border:'1px solid var(--gray-200)', borderRadius:8, padding:'7px 12px', fontWeight:700, fontSize:12.5, color:'var(--navy-600)', cursor:'pointer', fontFamily:'var(--font-sans)' };
const feIcon = { width:32, height:32, borderRadius:8, border:'1px solid var(--gray-200)', background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' };
const feBtnResolve = { display:'flex', alignItems:'center', gap:5, background:'var(--success-500)', color:'#fff', border:0, borderRadius:8, padding:'7px 12px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' };
Object.assign(window, { FleetScreen });
