// Absensi — attendance recap
const { useState: useStateAB } = React;

function Absensi({ dept, pushToast }) {
  const [filter, setFilter] = useStateAB('all');
  const employees = dept === 'all' ? KARYAWAN : KARYAWAN.filter(k => k.deptId === dept);
  const ids = new Set(employees.map(k => k.id));
  let rows = ABSENSI.filter(a => ids.has(a.karyawanId));
  if (filter === 'exception') rows = rows.filter(a => a.alpha || a.telat || a.sakit || a.cuti);
  if (filter === 'overtime') rows = rows.filter(a => a.lemburJam > 0);

  const totals = rows.reduce((s, a) => ({
    hadir: s.hadir + a.hadir,
    sakit: s.sakit + a.sakit,
    cuti: s.cuti + a.cuti,
    izin: s.izin + a.izin,
    alpha: s.alpha + a.alpha,
    telat: s.telat + a.telat,
    lemburJam: s.lemburJam + a.lemburJam,
    total: s.total + a.total,
  }), { hadir:0, sakit:0, cuti:0, izin:0, alpha:0, telat:0, lemburJam:0, total:0 });

  const attendancePct = totals.total ? Math.round((totals.hadir / totals.total) * 100) : 0;

  return (
    <>
      <PageHeader
        eyebrow={`Periode ${PERIODE_LABEL}`}
        title="Absensi & Kehadiran"
        subtitle={`${employees.length} karyawan dalam filter aktif. Tingkat hadir periode berjalan ${attendancePct}% dengan ${totals.telat} kejadian terlambat dan ${totals.lemburJam} jam lembur.`}
        actions={<>
          <Btn icon="download" tone="primary" onClick={()=>pushToast({msg:'Rekap absensi XLS diunduh'})}>Ekspor Rekap</Btn>
          <Btn icon="upload" tone="outline">Impor Fingerprint</Btn>
        </>}
      />

      <div className="grid g-4" style={{marginBottom:18}}>
        <Kpi label="Hadir Periode" value={`${attendancePct}%`} sub={`${totals.hadir}/${totals.total} hari kerja`} icon="checkCircle" tone="green" progress={attendancePct} />
        <Kpi label="Telat" value={totals.telat} sub="kejadian terlambat" icon="clock" tone="amber" />
        <Kpi label="Cuti/Sakit/Izin" value={totals.cuti + totals.sakit + totals.izin} sub={`${totals.cuti} cuti · ${totals.sakit} sakit · ${totals.izin} izin`} icon="calendar" tone="accent" />
        <Kpi label="Jam Lembur" value={totals.lemburJam} sub="masuk perhitungan payroll" icon="trending" tone="violet" />
      </div>

      <div className="grid" style={{gridTemplateColumns:'0.9fr 1.35fr', gap:18, marginBottom:18}}>
        <Card>
          <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}>
            <SectionHead title="Clock-in Hari Ini" hint={formatDateID(TODAY)} />
          </div>
          <div style={{padding:'6px 0'}}>
            {ABSENSI_HARI_INI.map(a => {
              const k = KARYAWAN_BY_ID[a.karyawanId];
              return (
                <div key={a.karyawanId} className="row" style={{padding:'10px 16px', borderTop:'1px solid hsl(var(--border))', gap:10}}>
                  <EmpAvatar name={k.nama} size="sm" />
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontSize:12.5, fontWeight:700}}>{k.nama}</div>
                    <div style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>{k.dept} · {k.jabatan}</div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <StatusPill status={a.status}/>
                    <div className="mono" style={{fontSize:11, color:'hsl(var(--muted-foreground))', marginTop:3}}>{a.clockIn || a.keterangan || '-'}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        <Card>
          <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}>
            <SectionHead title="Kalender Kehadiran" hint={`${HARI_KERJA_APRIL.length} hari kerja sampai ${formatTanggalKerja(TODAY)}`} />
          </div>
          <div style={{padding:'16px'}}>
            <div className="grid" style={{gridTemplateColumns:'repeat(11, 1fr)', gap:6}}>
              {HARI_KERJA_APRIL.map((d, idx) => {
                const pct = 88 + ((idx * 7) % 12);
                return (
                  <div key={d} title={`${formatDateID(d)}: ${pct}% hadir`} style={{padding:'8px 5px', border:'1px solid hsl(var(--border))', borderRadius:8, background:pct < 92 ? 'hsl(38 90% 96%)' : 'hsl(152 58% 96%)', textAlign:'center'}}>
                    <div className="mono" style={{fontSize:11, fontWeight:800}}>{d.slice(8)}</div>
                    <div style={{fontSize:10.5, color:'hsl(var(--muted-foreground))', marginTop:2}}>{pct}%</div>
                  </div>
                );
              })}
            </div>
            <div className="callout accent" style={{marginTop:14}}>
              <Icon name="info" size={14}/>
              <span>Absensi 23-30 April belum terkunci. Payroll draft mengambil cut-off sampai 22 April dan akan refresh otomatis sebelum run.</span>
            </div>
          </div>
        </Card>
      </div>

      <Card>
        <div className="row between" style={{padding:'12px 16px', borderBottom:'1px solid hsl(var(--border))', flexWrap:'wrap', gap:8}}>
          <div className="row gap-2">
            {[
              {id:'all', label:'Semua'},
              {id:'exception', label:'Exception'},
              {id:'overtime', label:'Ada Lembur'},
            ].map(f => <button key={f.id} className={'btn ' + (filter === f.id ? '' : 'outline') + ' sm'} onClick={()=>setFilter(f.id)}>{f.label}</button>)}
          </div>
          <div className="text-sm muted">{rows.length} baris rekap</div>
        </div>
        <div style={{maxHeight:'54vh', overflowY:'auto'}}>
          <table className="table">
            <thead style={{position:'sticky', top:0, background:'hsl(var(--card))', zIndex:1}}>
              <tr>
                <th>Karyawan</th><th>Departemen</th><th style={{textAlign:'right'}}>Hadir</th><th style={{textAlign:'right'}}>Cuti</th><th style={{textAlign:'right'}}>Sakit</th><th style={{textAlign:'right'}}>Telat</th><th style={{textAlign:'right'}}>Alpha</th><th style={{textAlign:'right'}}>Lembur</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(a => {
                const k = KARYAWAN_BY_ID[a.karyawanId];
                return (
                  <tr key={a.karyawanId}>
                    <td><div className="row gap-2"><EmpAvatar name={k.nama} size="sm"/><div><div style={{fontWeight:700}}>{k.nama}</div><div className="mono" style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>{k.id}</div></div></div></td>
                    <td style={{fontSize:12.5}}>{k.dept}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{a.hadir}/{a.total}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{a.cuti}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{a.sakit}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', color:a.telat ? 'hsl(38 80% 36%)' : undefined}}>{a.telat}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', color:a.alpha ? 'hsl(var(--destructive))' : undefined}}>{a.alpha}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:a.lemburJam ? 700 : 400}}>{a.lemburJam} jam</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </>
  );
}

window.Absensi = Absensi;
