// Laporan HR & Payroll
const { useState: useStateLR } = React;

function Laporan({ dept, pushToast }) {
  const [range, setRange] = useStateLR('2026');
  const employees = dept === 'all' ? KARYAWAN : KARYAWAN.filter(k => k.deptId === dept);
  const slips = employees.map(k => slipGaji(k.id));
  const totalCost = slips.reduce((s, sl) => s + sl.takeHome, 0);
  const avgCost = Math.round(totalCost / Math.max(1, employees.length));
  const totalPph = slips.reduce((s, sl) => s + sl.potongan.pph21, 0);
  const totalBpjs = slips.reduce((s, sl) => s + sl.potongan.bpjsKes + sl.potongan.bpjsJht + sl.potongan.bpjsJp, 0);
  const turnover = 2.1;

  const trend = PAYROLL_RUNS.slice().reverse().map((r, i) => ({
    label: r.label.split(' ')[0].slice(0,3),
    total: r.total || KPI.payrollDraft,
    karyawan: r.karyawan,
    idx: i,
  }));
  const maxTrend = Math.max(...trend.map(t => t.total));

  return (
    <>
      <PageHeader
        eyebrow="Analitik HR"
        title="Laporan SDM & Payroll"
        subtitle={`Total biaya payroll filter aktif ${rupiah(totalCost, {sym:true})}, rata-rata ${rupiah(avgCost, {sym:true})} per karyawan. PPh21 estimasi ${rupiah(totalPph, {sym:true})}.`}
        actions={<>
          <select className="select" value={range} onChange={e=>setRange(e.target.value)} style={{width:'auto', minWidth:150, height:36}}>
            <option value="2026">Tahun 2026</option>
            <option value="q2">Q2 2026</option>
            <option value="apr">April 2026</option>
          </select>
          <Btn icon="download" tone="primary" onClick={()=>pushToast({msg:'Laporan HR PDF diunduh'})}>Unduh PDF</Btn>
          <Btn icon="upload" tone="outline">Kirim Email</Btn>
        </>}
      />

      <div className="grid g-4" style={{marginBottom:18}}>
        <Kpi label="Total Payroll" value={rupiah(totalCost, {sym:true, compact:true})} sub={`${employees.length} karyawan`} icon="creditCard" tone="accent" />
        <Kpi label="Average Cost" value={rupiah(avgCost, {sym:true, compact:true})} sub="per karyawan" icon="trending" tone="green" />
        <Kpi label="PPh21 + BPJS" value={rupiah(totalPph + totalBpjs, {sym:true, compact:true})} sub={`${rupiah(totalPph, {compact:true})} PPh21 · ${rupiah(totalBpjs, {compact:true})} BPJS`} icon="receipt" tone="violet" />
        <Kpi label="Turnover" value={`${turnover}%`} sub="YTD (rendah)" icon="users" tone="amber" />
      </div>

      <div className="grid" style={{gridTemplateColumns:'1.35fr 0.9fr', gap:18, marginBottom:18}}>
        <Card>
          <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}>
            <SectionHead title="Trend Payroll Run" hint="5 periode terakhir" />
          </div>
          <div style={{padding:'18px 16px 14px'}}>
            <div className="row" style={{gap:12, alignItems:'flex-end', height:210}}>
              {trend.map(t => (
                <div key={t.label + t.idx} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:6}}>
                  <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', fontVariantNumeric:'tabular-nums'}}>{rupiah(t.total, {compact:true})}</div>
                  <div title={`${t.label}: ${rupiah(t.total, {sym:true})}`} style={{
                    width:'100%', height:(t.total / maxTrend) * 100 + '%', minHeight:8,
                    borderRadius:'8px 8px 0 0',
                    background: t.idx === trend.length - 1 ? 'hsl(var(--accent-h) var(--accent-s) var(--accent-l))' : 'hsl(var(--accent-h) var(--accent-s) 78%)'
                  }} />
                  <div style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>{t.label}</div>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card>
          <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}>
            <SectionHead title="Headcount per Departemen" hint="Distribusi organisasi" />
          </div>
          <div style={{padding:'14px 16px'}}>
            {DEPT.map(d => {
              const count = KARYAWAN.filter(k => k.deptId === d.id).length;
              return (
                <div key={d.id} style={{padding:'9px 0', borderTop:'1px solid hsl(var(--border))'}}>
                  <div className="row between" style={{marginBottom:5}}>
                    <div style={{fontSize:12.5, fontWeight:700}}>{d.name}</div>
                    <div className="mono" style={{fontSize:12, fontWeight:800}}>{count}</div>
                  </div>
                  <div className="dept-bar"><div style={{width:(count / KARYAWAN.length) * 100 * 2.2 + '%'}} /></div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>

      <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:18}}>
        <Card>
          <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}>
            <SectionHead title="Cost Center Detail" hint="THP estimasi April" />
          </div>
          <table className="table">
            <thead><tr><th>Departemen</th><th>Manager</th><th style={{textAlign:'right'}}>Headcount</th><th style={{textAlign:'right'}}>Total THP</th><th style={{textAlign:'right'}}>Avg</th></tr></thead>
            <tbody>
              {COST_BREAKDOWN_DEPT.map(d => {
                const def = DEPT.find(x => x.id === d.deptId);
                return (
                  <tr key={d.deptId}>
                    <td style={{fontWeight:700}}>{d.dept}</td>
                    <td>{def.manager}</td>
                    <td style={{textAlign:'right'}}>{d.headcount}</td>
                    <td style={{textAlign:'right', fontWeight:800}}>{rupiah(d.total, {sym:true})}</td>
                    <td style={{textAlign:'right'}}>{rupiah(Math.round(d.total/d.headcount), {sym:true})}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>

        <Card>
          <div style={{padding:'14px 16px', borderBottom:'1px solid hsl(var(--border))'}}>
            <SectionHead title="Statutory Summary" hint="PPh21, BPJS, dan compliance" />
          </div>
          <div style={{padding:'16px 18px'}}>
            <div className="form-grid">
              <Field label="PPh21 Estimasi" value={rupiah(totalPph, {sym:true})} />
              <Field label="BPJS Employee" value={rupiah(totalBpjs, {sym:true})} />
              <Field label="NPWP Missing" value={`${KARYAWAN.filter(k => !k.npwp).length} karyawan`} />
              <Field label="Status SPT" value="Draft bulanan" />
              <Field label="BPJS TK Perusahaan" value={TENANT.bpjsTk} />
              <Field label="BPJS Kes Perusahaan" value={TENANT.bpjsKes} />
            </div>
            <div className="callout accent" style={{marginTop:16}}>
              <Icon name="info" size={14}/>
              <span>Nominal statutory di halaman ini adalah estimasi demo. Sistem produksi perlu integrasi aturan PTKP/PKP detail, JKK/JKM/JHT perusahaan, dan rekonsiliasi e-Bupot.</span>
            </div>
          </div>
        </Card>
      </div>
    </>
  );
}

window.Laporan = Laporan;
