/* Admin → Dashboard overview */
function Sparkline({ data, color }) {
  const w = 96, h = 30, max = Math.max(...data), min = Math.min(...data);
  const rng = max - min || 1;
  const pts = data.map((v, i) => [ (i/(data.length-1))*w, h - ((v-min)/rng)*(h-4) - 2 ]);
  const d = pts.map((p,i)=> (i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
  const area = d + ` L${w} ${h} L0 ${h} Z`;
  const gid = 'sg' + color.replace(/[^a-z0-9]/gi,'');
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display:'block', overflow:'visible' }}>
      <defs><linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={color} stopOpacity="0.18" /><stop offset="100%" stopColor={color} stopOpacity="0" />
      </linearGradient></defs>
      <path d={area} fill={`url(#${gid})`} />
      <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.6" fill={color} />
    </svg>
  );
}

function StatTile({ icon, tint, ic, value, label, delta, deltaColor, trend, spark, onClick }) {
  const [hover, setHover] = React.useState(false);
  const up = trend === 'up', down = trend === 'down';
  const pillBg = up ? 'var(--success-100)' : down ? 'var(--danger-100)' : 'var(--gray-100)';
  const pillFg = up ? 'var(--success-600)' : down ? 'var(--danger-600)' : 'var(--gray-600)';
  return (
    <div onClick={onClick} onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)} style={{
      background:'#fff', border:'1px solid var(--gray-200)', borderRadius:16, padding:'18px',
      boxShadow: hover ? 'var(--shadow-md)' : 'var(--shadow-sm)', cursor: onClick?'pointer':'default',
      transform: hover ? 'translateY(-2px)' : 'none', transition:'transform .16s ease, box-shadow .16s ease',
      position:'relative', overflow:'hidden',
    }}>
      <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between' }}>
        <span style={{ width:40, height:40, borderRadius:11, background:tint, display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name={icon} size={20} color={ic} /></span>
        {delta && (
          <span style={{ display:'inline-flex', alignItems:'center', gap:3, background:pillBg, color:pillFg, fontSize:11.5, fontWeight:700, padding:'4px 9px', borderRadius:'999px' }}>
            {(up||down) && <Icon name={up?'trending-up':'trending-down'} size={12} color={pillFg} stroke={2.4} />}
            {delta}
          </span>
        )}
      </div>
      <div style={{ fontSize:28, fontWeight:800, letterSpacing:'-.02em', color:'var(--ink)', marginTop:14 }}>{value}</div>
      <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:8 }}>
        <div style={{ fontSize:13, color:'var(--gray-500)', marginTop:3 }}>{label}</div>
        {spark && <div style={{ opacity:.95 }}><Sparkline data={spark} color={ic} /></div>}
      </div>
    </div>
  );
}

function Panel({ title, action, children, pad=true }) {
  return (
    <div style={{ background:'#fff', border:'1px solid var(--gray-200)', borderRadius:14, boxShadow:'var(--shadow-sm)', overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'15px 18px', borderBottom:'1px solid var(--gray-200)' }}>
        <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)' }}>{title}</div>
        {action}
      </div>
      <div style={{ padding: pad ? '6px 18px 12px' : 0 }}>{children}</div>
    </div>
  );
}

function AdminMap() {
  const BUSES = [
    { id:'12', driver:'Mark Thompson', route:'Route 1 · East', riders:24, eta:'5 min', status:'On Route', color:'var(--success-500)', x:22, y:30, path:'M40 200 L40 120 L150 120 L150 60 L300 60' },
    { id:'7',  driver:'Carla Reyes',   route:'Route 3 · West Loop', riders:19, eta:'8 min late', status:'Delayed', color:'var(--danger-500)', x:60, y:56, path:'M300 60 L300 150 L180 150 L180 220' },
    { id:'15', driver:'Maya Okafor',   route:'Route 4 · South', riders:17, eta:'On time', status:'On Route', color:'var(--success-500)', x:42, y:74, path:'M120 230 L120 150 L60 150 L60 60' },
  ];
  const [sel, setSel] = React.useState('12');
  const [hoverPin, setHoverPin] = React.useState(null);
  const cur = BUSES.find(b => b.id === sel);
  return (
    <div style={{ position:'relative' }}>
      <div style={{ position:'relative', height:300, background:'#E8EEF0', overflow:'hidden' }}>
        {/* terrain */}
        <div style={{ position:'absolute', inset:0, background:
          'radial-gradient(circle at 22% 32%, #DCEAD9 0 96px, transparent 97px),'+
          'radial-gradient(circle at 78% 64%, #DCEAD9 0 116px, transparent 117px),'+
          'radial-gradient(circle at 60% 12%, #D6E6F0 0 70px, transparent 71px),'+
          'linear-gradient(180deg,#EAF0F1,#E2E9EB)' }} />
        {/* water */}
        <div style={{ position:'absolute', right:0, bottom:0, width:150, height:110, background:'#CFE4EE', borderRadius:'60px 0 0 0' }} />
        {/* roads */}
        <div style={{ position:'absolute', top:'40%', left:0, right:0, height:18, background:'#fff', boxShadow:'0 0 0 1px #D5DEE0' }} />
        <div style={{ position:'absolute', top:0, bottom:0, left:'55%', width:15, background:'#fff', boxShadow:'0 0 0 1px #D5DEE0' }} />
        <div style={{ position:'absolute', top:0, bottom:0, left:'28%', width:11, background:'#F2F5F6', boxShadow:'0 0 0 1px #DFE6E8' }} />
        <div style={{ position:'absolute', top:'72%', left:0, right:0, height:9, background:'#F2F5F6', boxShadow:'0 0 0 1px #DFE6E8' }} />

        {/* selected route line */}
        <svg viewBox="0 0 360 300" preserveAspectRatio="none" style={{ position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none' }}>
          <path d={cur.path} fill="none" stroke={cur.color} strokeWidth="5" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="2 9" opacity="0.85">
            <animate attributeName="stroke-dashoffset" from="22" to="0" dur="0.7s" repeatCount="indefinite" />
          </path>
        </svg>

        {/* school marker */}
        <div style={{ position:'absolute', left:'55%', top:'40%', transform:'translate(-50%,-50%)', display:'flex', flexDirection:'column', alignItems:'center', gap:2, zIndex:2 }}>
          <div style={{ width:30, height:30, borderRadius:9, background:'var(--navy-600)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 3px 8px rgba(0,0,0,.2)', border:'2px solid #fff' }}><Icon name="school" size={15} color="#fff" /></div>
        </div>

        {/* bus pins */}
        {BUSES.map(b => {
          const on = b.id === sel, hov = hoverPin === b.id;
          return (
            <button key={b.id} onClick={()=>setSel(b.id)} onMouseEnter={()=>setHoverPin(b.id)} onMouseLeave={()=>setHoverPin(null)}
              style={{ position:'absolute', left:b.x+'%', top:b.y+'%', transform:`translate(-50%,-50%) scale(${on||hov?1.12:1})`, transition:'transform .16s ease', display:'flex', flexDirection:'column', alignItems:'center', gap:3, border:0, background:'transparent', cursor:'pointer', zIndex: on?5:3, padding:0 }}>
              <span className={on?'jl-pulse':''} style={{ width:38, height:38, borderRadius:'999px', background: on?'var(--gold-400)':'#fff', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 4px 12px rgba(0,0,0,.28)', border:`2.5px solid ${on?'#fff':b.color}` }}>
                <Icon name="bus-front" size={18} color={on?'var(--navy-700)':b.color} />
              </span>
              <span style={{ fontSize:10, fontWeight:800, color:'var(--navy-700)', background:'#fff', padding:'1px 7px', borderRadius:'999px', boxShadow:'var(--shadow-xs)' }}>Bus #{b.id}</span>
            </button>
          );
        })}

        {/* live chip */}
        <div style={{ position:'absolute', top:12, left:12, display:'inline-flex', alignItems:'center', gap:6, background:'rgba(255,255,255,.92)', borderRadius:'999px', padding:'5px 11px', boxShadow:'var(--shadow-sm)', fontSize:11.5, fontWeight:700, color:'var(--success-600)' }}>
          <span className="jl-pulse" style={{ width:7, height:7, borderRadius:'999px', background:'var(--success-500)' }} />{BUSES.length} buses live
        </div>
      </div>

      {/* selected bus detail bar */}
      <div style={{ display:'flex', alignItems:'center', gap:12, padding:'13px 18px', borderTop:'1px solid var(--gray-200)', background:'#fff' }}>
        <span style={{ width:38, height:38, borderRadius:10, background:'var(--gold-100)', display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name="bus-front" size={19} color="var(--gold-600)" /></span>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)' }}>Bus #{cur.id} · {cur.driver}</div>
          <div style={{ fontSize:12.5, color:'var(--gray-500)' }}>{cur.route} · {cur.riders} riders</div>
        </div>
        <Pill bg={cur.status==='Delayed'?'var(--danger-100)':'var(--success-100)'} fg={cur.status==='Delayed'?'var(--danger-600)':'var(--success-600)'}>{cur.status==='Delayed'?<Icon name="alert-triangle" size={12} color="var(--danger-600)" />:<Icon name="check" size={12} color="var(--success-600)" stroke={2.5} />}{cur.eta}</Pill>
      </div>
    </div>
  );
}

function DashboardScreen({ onNav }) {
  const [alerts, setAlerts] = React.useState([
    { id:1, icon:'bus', tint:'var(--danger-100)', ic:'var(--danger-500)', t:'EJ Hatten missed Bus #12', s:'Self-reported · Stayed after class', time:'just now' },
    { id:2, icon:'alert-triangle', tint:'var(--danger-100)', ic:'var(--danger-500)', t:'Bus #7 running 8 min late', s:'Route 3 · West Loop', time:'3m ago' },
    { id:3, icon:'user-x', tint:'var(--warning-100)', ic:'var(--warning-600)', t:'Unverified pickup attempt', s:'Katy Middle · Sophia P.', time:'12m ago' },
  ]);
  const dismissAlert = (id) => { setAlerts(a => a.filter(x => x.id !== id)); jlToast('Alert resolved', { icon:'check' }); };

  const [queue, setQueue] = React.useState([
    { n:'EJ Hatten', g:'Grade 6', ty:'Car Rider', t:'3:30 PM', st:'Waiting' },
    { n:'James Walker', g:'Grade 7', ty:'Car Rider', t:'3:31 PM', st:'Waiting' },
    { n:'Sophia Perez', g:'Grade 6', ty:'Walker', t:'3:31 PM', st:'Picked Up' },
    { n:'Liam Carter', g:'Grade 8', ty:'Bus #12', t:'3:32 PM', st:'On Bus' },
  ]);
  const ST = {
    'Waiting':   { bg:'var(--gray-200)',    fg:'var(--gray-600)' },
    'Picked Up': { bg:'var(--success-100)',  fg:'var(--success-600)' },
    'On Bus':    { bg:'var(--blue-100)',     fg:'var(--blue-600)' },
  };
  const release = (i) => { setQueue(q => q.map((r,idx)=> idx===i ? { ...r, st:'Picked Up' } : r)); jlToast(queue[i].n + ' marked picked up', { icon:'check-circle-2' }); };
  const waiting = queue.filter(r => r.st==='Waiting').length;

  return (
    <div style={{ padding:'26px 32px 48px', overflowY:'auto', height:'100%', boxSizing:'border-box' }}>
      {/* stat row */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:20, marginBottom:22 }}>
        <StatTile icon="users" tint="var(--blue-100)" ic="var(--blue-500)" value="1,248" label="Total Students" delta="+12" trend="up" spark={[1180,1195,1202,1210,1224,1236,1248]} onClick={()=>onNav && onNav('students')} />
        <StatTile icon="bus" tint="var(--gold-100)" ic="var(--gold-600)" value="25" label="Active Buses · 12 routes" delta="20 live" spark={[18,22,19,24,21,23,25]} onClick={()=>onNav && onNav('transportation')} />
        <StatTile icon="car-front" tint="var(--warning-100)" ic="var(--warning-600)" value="37" label="Pending Pickups" delta="As of 3:15" spark={[120,98,76,61,52,44,37]} onClick={()=>onNav && onNav('pickup')} />
        <StatTile icon="banknote" tint="var(--success-100)" ic="var(--success-600)" value="$24,650" label="Collected this month" delta="+8%" trend="up" spark={[14,17,16,20,19,22,24.65]} onClick={()=>onNav && onNav('payments')} />
      </div>

      {/* two columns */}
      <div style={{ display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:20 }}>
        <Panel title="Live Bus Map" action={<span style={{ display:'inline-flex', alignItems:'center', gap:6, fontSize:12.5, fontWeight:700, color:'var(--success-600)' }}><span className="jl-pulse" style={{ width:8, height:8, borderRadius:'999px', background:'var(--success-500)' }} />Live</span>} pad={false}>
          <AdminMap />
        </Panel>

        <Panel title="Recent Alerts" action={<span onClick={()=>jlToast('Showing all alerts', { icon:'bell' })} style={{ fontSize:12.5, fontWeight:700, color:'var(--blue-500)', cursor:'pointer' }}>View All</span>}>
          {alerts.length === 0 && (
            <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:8, padding:'26px 0', color:'var(--gray-400)' }}>
              <Icon name="check-circle-2" size={26} color="var(--success-500)" />
              <span style={{ fontSize:13, fontWeight:600, color:'var(--gray-500)' }}>All caught up — no active alerts</span>
            </div>
          )}
          {alerts.map((a,i)=>(
            <div key={a.id} className="jl-alert-row" style={{ display:'flex', alignItems:'flex-start', gap:11, padding:'11px 0', borderBottom: i<alerts.length-1?'1px solid var(--gray-100)':'0' }}>
              <span style={{ width:34, height:34, borderRadius:9, background:a.tint, display:'flex', alignItems:'center', justifyContent:'center', flex:'0 0 auto' }}><Icon name={a.icon} size={17} color={a.ic} /></span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>{a.t}</div>
                <div style={{ fontSize:12, color:'var(--gray-500)' }}>{a.s}</div>
              </div>
              <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:6 }}>
                <span style={{ fontSize:11, color:'var(--gray-400)', whiteSpace:'nowrap' }}>{a.time}</span>
                <button onClick={()=>dismissAlert(a.id)} title="Resolve" style={{ border:0, background:'var(--gray-100)', borderRadius:'999px', width:24, height:24, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}><Icon name="check" size={14} color="var(--success-600)" stroke={2.5} /></button>
              </div>
            </div>
          ))}
        </Panel>
      </div>

      {/* charts row */}
      <div style={{ display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:20, marginTop:20 }}>
        <Panel title="Weekly Ridership" action={<span style={{ display:'inline-flex', alignItems:'center', gap:6, fontSize:12.5, fontWeight:700, color:'var(--success-600)' }}><Icon name="trending-up" size={14} color="var(--success-600)" />+6% vs last week</span>}>
          <div style={{ padding:'8px 4px 2px' }}>
            <AreaChart data={[412,438,455,447,468,430,402]} labels={['Mon','Tue','Wed','Thu','Fri','Sat','Sun']} color="var(--blue-500)" height={170} />
          </div>
        </Panel>
        <Panel title="Pickup Methods">
          <div style={{ padding:'14px 4px 8px' }}>
            <DonutChart
              centerTop="1,248" centerSub="students"
              segments={[
                { label:'Bus rider', value:58, suffix:'%', color:'var(--gold-500)' },
                { label:'Car rider', value:29, suffix:'%', color:'var(--blue-500)' },
                { label:'Walker', value:13, suffix:'%', color:'var(--success-500)' },
              ]} />
          </div>
        </Panel>
      </div>

      {/* pickup queue table */}
      <div style={{ marginTop:20 }}>
        <Panel title={`Pickup Queue · ${waiting} waiting`} action={<span onClick={()=>onNav && onNav('pickup')} style={{ fontSize:12.5, fontWeight:700, color:'var(--blue-500)', cursor:'pointer' }}>Open Pickup Manager</span>} pad={false}>
          <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr 1.2fr 1fr 1.3fr', padding:'11px 18px', background:'var(--gray-50)', fontSize:11, fontWeight:800, letterSpacing:'.05em', textTransform:'uppercase', color:'var(--gray-500)' }}>
            <span>Student</span><span>Grade</span><span>Method</span><span>Time</span><span style={{ textAlign:'right' }}>Status</span>
          </div>
          {queue.map((r,i)=>(
            <div key={i} style={{ display:'grid', gridTemplateColumns:'2fr 1fr 1.2fr 1fr 1.3fr', alignItems:'center', padding:'12px 18px', borderTop:'1px solid var(--gray-100)', fontSize:13.5 }}>
              <span style={{ display:'flex', alignItems:'center', gap:10 }}><Avatar initials={r.n.split(' ').map(w=>w[0]).join('')} color={['blue','navy','gold','green'][i%4]} size={30} /><span style={{ fontWeight:700, color:'var(--ink)' }}>{r.n}</span></span>
              <span style={{ color:'var(--gray-600)' }}>{r.g}</span>
              <span style={{ color:'var(--gray-600)' }}>{r.ty}</span>
              <span style={{ color:'var(--gray-600)' }}>{r.t}</span>
              <span style={{ justifySelf:'end' }}>
                {r.st === 'Waiting'
                  ? <button onClick={()=>release(i)} style={{ display:'inline-flex', alignItems:'center', gap:6, background:'var(--navy-600)', color:'#fff', border:0, borderRadius:8, padding:'7px 12px', fontWeight:700, fontSize:12, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="check" size={13} color="#fff" stroke={2.5} />Mark Picked Up</button>
                  : <Pill bg={ST[r.st].bg} fg={ST[r.st].fg}>{r.st}</Pill>}
              </span>
            </div>
          ))}
        </Panel>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardScreen, StatTile, Panel, AdminMap });
