/* ============================================================
   DashboardView.jsx — สรุปการลาของครูแต่ละท่าน รายภาคเรียน
   ============================================================ */

function DashboardView({assignments, approvals}){
  const defSem = (semesterOf(BASE_DATE) || SEMESTERS[0]).id;
  const [semId, setSemId] = React.useState(defSem);
  const sem = SEMESTERS.find(s=>s.id===semId);

  const groups = Object.values(groupAssignments(assignments))
    .filter(g=>{ const s=semesterOf(g[0].date); return s && s.id===semId; });

  // รวมต่อครู
  const byTeacher = {};
  groups.forEach(g=>{
    const tid = g[0].leaveTeacherId;
    const rec = byTeacher[tid] || (byTeacher[tid]={kit:0,sick:0,gov:0,early:0,occ:0,periods:0, approved:0, pending:0, rejected:0});
    rec[g[0].reason] = (rec[g[0].reason]||0)+1;
    rec.occ++; rec.periods += g.length;
    const ap = approvals[g[0].groupId];
    if(ap){ rec[ap.final]++; } else { rec.pending++; }
  });
  const rows = Object.entries(byTeacher).map(([tid,rec])=>({t:teacherById(tid), ...rec}))
    .filter(r=>r.t).sort((a,b)=> b.occ-a.occ || b.periods-a.periods);

  // ยอดรวมภาพรวม
  const tot = {kit:0,sick:0,gov:0,early:0,occ:0,periods:0,teachers:rows.length};
  rows.forEach(r=>{ tot.kit+=r.kit; tot.sick+=r.sick; tot.gov+=r.gov; tot.early+=r.early; tot.occ+=r.occ; tot.periods+=r.periods; });
  const reasonMax = Math.max(1, ...rows.map(r=>r.occ));

  return (
    <div>
      <div className="flex ac jb wrap gap12" style={{marginBottom:18}}>
        <div>
          <h1 style={{fontSize:22,color:'var(--brand-900)'}}>แดชบอร์ดสรุปการลา</h1>
          <p style={{margin:'4px 0 0',color:'var(--ink-2)',fontSize:14}}>สรุปสถิติการลาของครูแต่ละท่าน แยกตามภาคเรียน</p>
        </div>
        <div className="flex ac gap8">
          <Icon name="calendar" size={16} style={{color:'var(--ink-3)'}}/>
          <select className="sel" value={semId} onChange={e=>setSemId(e.target.value)} style={{minWidth:190}}>
            {SEMESTERS.map(s=><option key={s.id} value={s.id}>{s.label}</option>)}
          </select>
        </div>
      </div>

      <div className="stats">
        <Stat k="ครูที่มีการลา" v={tot.teachers} unit="ท่าน" tone="blue" icon="users"/>
        <Stat k="การลารวม" v={tot.occ} unit="ครั้ง" tone="amber" icon="calendar"/>
        <Stat k="คาบที่ต้องจัดสอนแทน" v={tot.periods} unit="คาบ" tone="green" icon="layers"/>
        <Stat k="ขอออกก่อนเวลา" v={tot.early} unit="ครั้ง" tone="red" icon="clock"/>
      </div>

      {/* สัดส่วนตามประเภท */}
      <Card className="mb0" >
        <CardHead icon="filter" title="สัดส่วนการลาตามประเภท" sub={sem?sem.label:''}/>
        <div className="card-pad">
          <div className="rsn-bars">
            {[['kit','ลากิจ','rt-kit'],['sick','ลาป่วย','rt-sick'],['gov','ไปราชการ','rt-gov'],['early','ขอออกก่อนเวลา','rt-early']].map(([k,l,cls])=>{
              const v = tot[k]||0; const pct = tot.occ? Math.round(v/tot.occ*100):0;
              return (
                <div key={k} className="rsn-row">
                  <span className={`reason-tag ${cls}`} style={{minWidth:120,justifyContent:'center'}}>{l}</span>
                  <div className="rsn-track"><div className={`rsn-fill ${cls}`} style={{width:pct+'%'}}></div></div>
                  <span className="num rsn-val">{v} ครั้ง · {pct}%</span>
                </div>
              );
            })}
          </div>
        </div>
      </Card>

      {/* ตารางรายครู */}
      <div className="flex ac gap8" style={{margin:'24px 0 10px'}}>
        <Icon name="users" size={17} style={{color:'var(--brand-600)',flex:'none'}}/>
        <b style={{fontFamily:'Kanit',fontSize:15,color:'var(--brand-900)',whiteSpace:'nowrap'}}>สรุปรายครู</b>
      </div>
      <div className="scroll-x-hint">← เลื่อนตารางแนวนอนเพื่อดูทุกคอลัมน์ →</div>
      <div className="tbl-wrap">
        <table className="tbl" style={{minWidth:760}}>
          <thead>
            <tr>
              <th>ครู</th><th>กลุ่มสาระ</th>
              <th style={{textAlign:'center'}}>ลากิจ</th><th style={{textAlign:'center'}}>ลาป่วย</th>
              <th style={{textAlign:'center'}}>ไปราชการ</th><th style={{textAlign:'center'}}>ออกก่อนเวลา</th>
              <th style={{textAlign:'center'}}>รวม (ครั้ง)</th><th style={{textAlign:'center'}}>รวม (คาบ)</th>
              <th style={{textAlign:'center'}}>อนุญาตแล้ว</th>
            </tr>
          </thead>
          <tbody>
            {rows.length===0 && <tr><td colSpan={9}><Empty icon="inbox" title="ยังไม่มีข้อมูลการลาในภาคเรียนนี้"/></td></tr>}
            {rows.map(r=>(
              <tr key={r.t.id}>
                <td><div className="flex ac gap8"><Avatar t={r.t} size="sm"/><span style={{fontWeight:500,whiteSpace:'nowrap'}}>{fullTitle(r.t)}</span></div></td>
                <td style={{whiteSpace:'nowrap'}} className="muted">{r.t.primary}</td>
                <td className="num" style={{textAlign:'center'}}>{r.kit||'–'}</td>
                <td className="num" style={{textAlign:'center'}}>{r.sick||'–'}</td>
                <td className="num" style={{textAlign:'center'}}>{r.gov||'–'}</td>
                <td className="num" style={{textAlign:'center'}}>{r.early||'–'}</td>
                <td className="num" style={{textAlign:'center',fontWeight:600,color:'var(--brand-700)'}}>{r.occ}</td>
                <td className="num" style={{textAlign:'center'}}>{r.periods}</td>
                <td style={{textAlign:'center'}}>
                  <span className="num" style={{fontWeight:600,color:'var(--green)'}}>{r.approved}</span>
                  <span className="tiny"> / {r.occ}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="note-box mt16">
        <Icon name="info" size={18} style={{flex:'none'}}/>
        <div>“รวม (ครั้ง)” นับจำนวนครั้งที่แจ้งลา · “รวม (คาบ)” นับจำนวนคาบที่ต้องจัดครูสอนแทน · “อนุญาตแล้ว” คือจำนวนครั้งที่ผ่านการอนุญาตจากผู้อำนวยการครบขั้นตอน</div>
      </div>
    </div>
  );
}

window.DashboardView = DashboardView;
