/* Admin → Bus Routes editor: manage routes, stops, and bus/driver assignment. */
function RoutesScreen() {
  const DRIVERS = ['Marcus Reed', 'Dana Cole', 'Sam Ortiz', 'Priya Nair', 'Leon Baptiste', 'Unassigned'];
  const BUSES = ['#12', '#07', '#19', '#23', '#04', 'Unassigned'];
  const [routes, setRoutes] = React.useState([
    { id:'r3', name:'KMS Loop 3', period:'AM', bus:'#12', driver:'Marcus Reed', stops:[
      { id:1, name:'Oak & 3rd', time:'6:52 AM', students:2 },
      { id:2, name:'Maple Court', time:'6:58 AM', students:1 },
      { id:3, name:'Katy Elm Village', time:'7:05 AM', students:3 },
      { id:4, name:'Riverstone Gate', time:'7:12 AM', students:1 },
      { id:5, name:'Cinco Ranch Pkwy', time:'7:20 AM', students:2 },
    ]},
    { id:'r1', name:'Elm & Park', period:'AM', bus:'#07', driver:'Dana Cole', stops:[
      { id:1, name:'Park Place', time:'6:48 AM', students:4 },
      { id:2, name:'Elm & 5th', time:'6:55 AM', students:5 },
      { id:3, name:'Grand Vista', time:'7:04 AM', students:5 },
    ]},
    { id:'r2', name:'North Ridge', period:'AM', bus:'#19', driver:'Sam Ortiz', stops:[
      { id:1, name:'Ridge Top', time:'6:40 AM', students:3 },
      { id:2, name:'Summit Way', time:'6:50 AM', students:6 },
    ]},
    { id:'r4', name:'South Gate', period:'PM', bus:'Unassigned', driver:'Unassigned', stops:[
      { id:1, name:'Gateway Blvd', time:'3:45 PM', students:0 },
    ]},
  ]);
  const [selId, setSelId] = React.useState('r3');
  const [dirty, setDirty] = React.useState(false);
  const sel = routes.find(r => r.id === selId);

  // Publish route→bus assignments so the Fleet Map reflects them live.
  React.useEffect(() => {
    try {
      const map = {};
      routes.forEach(r => {
        if (r.bus && r.bus !== 'Unassigned') {
          const key = r.bus.replace('#','');
          map[key] = { route:r.name, driver:r.driver, students:r.stops.reduce((m,s)=>m+(parseInt(s.students)||0),0), stops:r.stops.length };
        }
      });
      localStorage.setItem('jl_routes', JSON.stringify(map));
    } catch(e) {}
  }, [routes]);

  const patch = (fn) => { setRoutes(rs => rs.map(r => r.id===selId ? fn(r) : r)); setDirty(true); };
  const setField = (k, v) => patch(r => ({ ...r, [k]:v }));
  const setStop = (sid, k, v) => patch(r => ({ ...r, stops:r.stops.map(s => s.id===sid ? { ...s, [k]:v } : s) }));
  const addStop = () => patch(r => ({ ...r, stops:[...r.stops, { id:Date.now(), name:'New stop', time:'—', students:0 }] }));
  const rmStop = (sid) => patch(r => ({ ...r, stops:r.stops.filter(s => s.id!==sid) }));

  const totalStops = routes.reduce((n,r)=>n+r.stops.length,0);
  const totalStudents = routes.reduce((n,r)=>n+r.stops.reduce((m,s)=>m+ (parseInt(s.students)||0),0),0);
  const unassigned = routes.filter(r=>r.bus==='Unassigned'||r.driver==='Unassigned').length;

  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="route" tint="var(--blue-100)" ic="var(--blue-500)" value={routes.length} label="Routes" />
        <StatTile icon="map-pin" tint="var(--gold-100)" ic="var(--gold-600)" value={totalStops} label="Stops" />
        <StatTile icon="users" tint="var(--success-100)" ic="var(--success-600)" value={totalStudents} label="Students routed" />
        <StatTile icon="triangle-alert" tint="var(--warning-100)" ic="var(--warning-600)" value={unassigned} label="Need assignment" />
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'.8fr 1.6fr', gap:16 }}>
        {/* route list */}
        <Panel title="Routes" action={<button onClick={()=>{ const id='r'+Date.now(); setRoutes(rs=>[...rs, { id, name:'New Route', period:'AM', bus:'Unassigned', driver:'Unassigned', stops:[] }]); setSelId(id); setDirty(true); }} style={{ display:'flex', alignItems:'center', gap:6, background:'var(--navy-600)', color:'#fff', border:0, borderRadius:9, padding:'8px 13px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="plus" size={14} color="#fff" />Add</button>} pad={false}>
          {routes.map((r,i) => {
            const on = r.id===selId;
            const needs = r.bus==='Unassigned'||r.driver==='Unassigned';
            return (
              <button key={r.id} onClick={()=>setSelId(r.id)} style={{ width:'100%', display:'flex', alignItems:'center', gap:11, 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:36, height:36, borderRadius:10, background: on?'var(--blue-500)':'var(--gray-100)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name="route" size={17} color={on?'#fff':'var(--gray-500)'} /></span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)' }}>{r.name}</div>
                  <div style={{ fontSize:12, color:'var(--gray-500)' }}>{r.period} · {r.stops.length} stops · Bus {r.bus}</div>
                </div>
                {needs && <span title="Needs assignment" style={{ width:8, height:8, borderRadius:'999px', background:'var(--warning-500)', flex:'0 0 auto' }} />}
              </button>
            );
          })}
        </Panel>

        {/* editor */}
        <Panel title={sel ? 'Edit · ' + sel.name : 'Select a route'} action={dirty && <button onClick={()=>{ setDirty(false); jlToast(sel.name + ' saved', { icon:'check-check' }); }} style={{ display:'flex', alignItems:'center', gap:6, background:'var(--gold-400)', color:'var(--on-gold)', border:0, borderRadius:9, padding:'8px 13px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-gold)' }}><Icon name="save" size={14} color="var(--on-gold)" />Save Route</button>}>
          {sel && (
            <div style={{ padding:'4px 0 2px' }}>
              {/* route meta */}
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12, marginBottom:16 }}>
                <label style={{ display:'block' }}><span style={rtLbl}>Route name</span><input value={sel.name} onChange={e=>setField('name', e.target.value)} style={rtField} /></label>
                <label style={{ display:'block' }}><span style={rtLbl}>Bus</span><select value={sel.bus} onChange={e=>setField('bus', e.target.value)} style={{ ...rtField, cursor:'pointer' }}>{BUSES.map(b=><option key={b}>{b}</option>)}</select></label>
                <label style={{ display:'block' }}><span style={rtLbl}>Driver</span><select value={sel.driver} onChange={e=>setField('driver', e.target.value)} style={{ ...rtField, cursor:'pointer' }}>{DRIVERS.map(d=><option key={d}>{d}</option>)}</select></label>
              </div>
              <div style={{ display:'flex', gap:8, marginBottom:18 }}>
                {['AM','PM'].map(p => (
                  <button key={p} onClick={()=>setField('period', p)} style={{ padding:'8px 18px', borderRadius:9, cursor:'pointer', fontFamily:'var(--font-sans)', fontWeight:700, fontSize:13, border: sel.period===p?'0':'1px solid var(--gray-200)', background: sel.period===p?'var(--navy-600)':'#fff', color: sel.period===p?'#fff':'var(--gray-600)' }}>{p} Route</button>
                ))}
              </div>

              {/* stops */}
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:9 }}>
                <span style={{ fontSize:11, fontWeight:800, letterSpacing:'.06em', textTransform:'uppercase', color:'var(--gray-500)' }}>Stops ({sel.stops.length})</span>
                <button onClick={addStop} style={{ display:'flex', alignItems:'center', gap:6, background:'transparent', border:0, color:'var(--blue-500)', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="plus" size={14} color="var(--blue-500)" />Add stop</button>
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {sel.stops.length===0 && <div style={{ fontSize:13, color:'var(--gray-400)', padding:'14px', textAlign:'center', border:'1.5px dashed var(--gray-200)', borderRadius:10 }}>No stops yet — add the first stop.</div>}
                {sel.stops.map((s, idx) => (
                  <div key={s.id} style={{ display:'flex', alignItems:'center', gap:10, background:'var(--gray-50)', borderRadius:10, padding:'9px 11px' }}>
                    <span style={{ width:26, height:26, borderRadius:'999px', background:'var(--navy-600)', color:'#fff', fontSize:12, fontWeight:800, fontFamily:'var(--font-mono)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}>{idx+1}</span>
                    <input value={s.name} onChange={e=>setStop(s.id,'name',e.target.value)} style={{ ...rtField, flex:2, marginTop:0 }} />
                    <input value={s.time} onChange={e=>setStop(s.id,'time',e.target.value)} style={{ ...rtField, width:90, marginTop:0 }} />
                    <div style={{ display:'flex', alignItems:'center', gap:5, flex:'0 0 auto' }}>
                      <Icon name="users" size={14} color="var(--gray-400)" />
                      <input value={s.students} onChange={e=>setStop(s.id,'students',e.target.value.replace(/[^0-9]/g,''))} style={{ ...rtField, width:46, marginTop:0, textAlign:'center', fontFamily:'var(--font-mono)' }} />
                    </div>
                    <button onClick={()=>rmStop(s.id)} title="Remove stop" style={{ width:32, height:32, borderRadius:8, border:'1px solid var(--gray-200)', background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flex:'0 0 auto' }}><Icon name="trash-2" size={15} color="var(--danger-500)" /></button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </Panel>
      </div>
    </div>
  );
}
const rtLbl = { display:'block', fontSize:11.5, fontWeight:700, color:'var(--gray-500)', marginBottom:5 };
const rtField = { width:'100%', boxSizing:'border-box', border:'1px solid var(--gray-200)', borderRadius:9, padding:'9px 11px', fontSize:13.5, fontFamily:'var(--font-sans)', color:'var(--ink)', outline:'none', background:'#fff' };
Object.assign(window, { RoutesScreen });
