/* Admin → Reports: attendance, transport, finance */
function ReportsScreen() {
  const [log, setLog] = React.useState([]);
  React.useEffect(() => {
    const read = () => { try { setLog(JSON.parse(localStorage.getItem('jl_incidentlog') || '[]')); } catch(e){} };
    read();
    const onStore = (e) => { if (e.key === 'jl_incidentlog') read(); };
    window.addEventListener('storage', onStore);
    const iv = setInterval(read, 1500);
    return () => { window.removeEventListener('storage', onStore); clearInterval(iv); };
  }, []);
  const fmt = (t) => new Date(t).toLocaleString([], { month:'short', day:'numeric', hour:'numeric', minute:'2-digit' });
  const dur = (a,b) => { const m = Math.max(1, Math.round((b-a)/60000)); return m<60?m+'m':Math.floor(m/60)+'h '+(m%60)+'m'; };
  const downloadCSV = (name, rows) => {
    const csv = rows.map(r => r.map(c => { const s = String(c==null?'':c); return /[",\n]/.test(s) ? '"'+s.replace(/"/g,'""')+'"' : s; }).join(',')).join('\n');
    const blob = new Blob([csv], { type:'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove();
    setTimeout(()=>URL.revokeObjectURL(url), 1000);
    jlToast('Downloaded ' + name, { icon:'file-down', color:'#1F9D57' });
  };
  const CSVDATA = {
    'Attendance Summary': [['Day','Attendance %'], ...week.map(w=>[w.d, w.a]), ['Average', 93.4]],
    'Transport Utilization': [['Route','Bus','Riders'],['KMS Loop 3','#12',9],['Elm & Park','#07',14],['North Ridge','#19',9],['Cinco West','#23',12],['South Gate','#04',0]],
    'Financial Statement': [['Category','Collected','Outstanding'],['Lunch accounts','$18,240','$1,120'],['Field-trip fees','$4,560','$380'],['Fundraisers','$15,040','—']],
  };
  const genReport = (c) => {
    if (c.title === 'Incident Log') {
      if (!log.length) { jlToast('No incidents to export', { icon:'shield-check' }); return; }
      downloadCSV('incident-log.csv', [['Incident','Bus','Driver','Reported','Resolved','Response'], ...log.map(r=>[r.label, r.bus, r.driver, fmt(r.reportedAt), fmt(r.resolvedAt), dur(r.reportedAt, r.resolvedAt)])]);
      return;
    }
    downloadCSV(c.title.toLowerCase().replace(/[^a-z]+/g,'-').replace(/^-|-$/g,'') + '.csv', CSVDATA[c.title] || [['Report'],[c.title]]);
  };
  const week = [
    { d:'Mon', a:96 }, { d:'Tue', a:94 }, { d:'Wed', a:97 }, { d:'Thu', a:91 }, { d:'Fri', a:89 },
  ];
  const cards = [
    { title:'Attendance Summary', sub:'Daily & by grade', icon:'user-check', tint:'var(--blue-100)', ic:'var(--blue-500)' },
    { title:'Transport Utilization', sub:'Riders per route', icon:'bus', tint:'var(--gold-100)', ic:'var(--gold-600)' },
    { title:'Financial Statement', sub:'Collections & dues', icon:'banknote', tint:'var(--success-100)', ic:'var(--success-600)' },
    { title:'Incident Log', sub:'Safety & behavior', icon:'shield-alert', tint:'var(--danger-100)', ic:'var(--danger-500)' },
  ];
  return (
    <div style={{ padding:'22px 28px 40px', height:'100%', overflowY:'auto', boxSizing:'border-box' }}>
      <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:16, marginBottom:16 }}>
        <Panel title="Attendance — This Week" action={<Pill bg="var(--success-100)" fg="var(--success-600)">Avg 93.4%</Pill>}>
          <div style={{ padding:'10px 4px 2px' }}>
            <BarChart data={[96,94,97,91,89]} labels={['Mon','Tue','Wed','Thu','Fri']} color="var(--navy-600)" height={172} max={100} valueFmt={v=>v+'%'} />
          </div>
        </Panel>
        <Panel title="On-Time Performance">
          {[['Buses on time','91%','var(--success-500)'],['Pickups verified','99%','var(--success-500)'],['Messages opened','78%','var(--warning-500)']].map(([l,p,col],i)=>(
            <div key={i} style={{ padding:'11px 0', borderBottom: i<2?'1px solid var(--gray-100)':'0' }}>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:6 }}><span style={{ fontWeight:700, color:'var(--ink)' }}>{l}</span><span style={{ color:col, fontWeight:700 }}>{p}</span></div>
              <div style={{ height:7, background:'var(--gray-200)', borderRadius:'999px', overflow:'hidden' }}><div style={{ width:p, height:'100%', background:col, borderRadius:'999px' }} /></div>
            </div>
          ))}
        </Panel>
      </div>

      <Panel title="Generate a Report" action={<span style={{ fontSize:12.5, color:'var(--gray-500)' }}>Download CSV</span>}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, padding:'6px 0 4px' }}>
          {cards.map((c,i)=>(
            <button key={i} onClick={()=>genReport(c)} style={{ textAlign:'left', background:'#fff', border:'1px solid var(--gray-200)', borderRadius:12, padding:'16px', cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-xs)' }}>
              <span style={{ width:38, height:38, borderRadius:10, background:c.tint, display:'flex', alignItems:'center', justifyContent:'center', marginBottom:12 }}><Icon name={c.icon} size={18} color={c.ic} /></span>
              <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)' }}>{c.title}</div>
              <div style={{ fontSize:12.5, color:'var(--gray-500)', marginTop:2 }}>{c.sub}</div>
              <div style={{ display:'inline-flex', alignItems:'center', gap:5, marginTop:12, fontSize:12, fontWeight:700, color:'var(--blue-500)' }}><Icon name="file-down" size={13} color="var(--blue-500)" />CSV</div>
            </button>
          ))}
        </div>
      </Panel>

      {/* resolved incident log */}
      <div style={{ marginTop:16 }}>
        <Panel title="Incident Log" action={log.length ? <button onClick={()=>genReport({title:'Incident Log'})} style={{ display:'inline-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="file-down" size={14} color="var(--blue-500)" />Export CSV</button> : <Pill bg="var(--success-100)" fg="var(--success-600)">0 resolved</Pill>} pad={false}>
          {log.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 incidents logged — resolve driver alerts on the Fleet Map to log them here.</div>
          ) : (
            <React.Fragment>
              <div style={{ display:'grid', gridTemplateColumns:'1.4fr .7fr 1.1fr 1.1fr .8fr', padding:'11px 18px', background:'var(--gray-50)', fontSize:11, fontWeight:800, letterSpacing:'.05em', textTransform:'uppercase', color:'var(--gray-500)' }}>
                <span>Incident</span><span>Bus</span><span>Reported</span><span>Resolved</span><span style={{ textAlign:'right' }}>Response</span>
              </div>
              {log.map((r,i) => { const inc = r.kind==='incident'; return (
                <div key={r.id} style={{ display:'grid', gridTemplateColumns:'1.4fr .7fr 1.1fr 1.1fr .8fr', alignItems:'center', padding:'11px 18px', borderTop:'1px solid var(--gray-100)', fontSize:13 }}>
                  <span style={{ display:'flex', alignItems:'center', gap:9, minWidth:0 }}><Icon name={inc?'triangle-alert':'clock'} size={16} color={inc?'var(--danger-500)':'var(--warning-600)'} /><span style={{ fontWeight:700, color:'var(--ink)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{r.label}</span></span>
                  <span style={{ color:'var(--gray-600)', fontWeight:600 }}>{r.bus}</span>
                  <span style={{ color:'var(--gray-500)', fontSize:12.5 }}>{fmt(r.reportedAt)}</span>
                  <span style={{ color:'var(--gray-500)', fontSize:12.5 }}>{fmt(r.resolvedAt)}</span>
                  <span style={{ justifySelf:'end' }}><Pill bg="var(--success-100)" fg="var(--success-600)">{dur(r.reportedAt, r.resolvedAt)}</Pill></span>
                </div>
              ); })}
            </React.Fragment>
          )}
        </Panel>
      </div>
    </div>
  );
}
Object.assign(window, { ReportsScreen });
