// Laporan Penjualan — penjualan per kategori, slow-moving, ringkasan periode
function Laporan({ period, cabang }) {
  const totalOmzet  = CATEGORY_SALES.reduce((s, c) => s + c.omzet, 0);
  const totalMargin = CATEGORY_SALES.reduce((s, c) => s + c.margin, 0);
  const marginPct = (totalMargin / totalOmzet) * 100;
  const periodSales = DAILY_SALES.reduce((s, d) => s + d.total, 0);
  const avgDaily = periodSales / DAILY_SALES.length;

  return (
    <div className="stack-6">
      <PageHeader
        title="Laporan Penjualan"
        subtitle={`Periode ${periodLabel(period)}`}
        meta={`${CABANG_LIST.find(c => c.id === cabang)?.name || 'Semua cabang'} · Dicetak ${formatDateID(TODAY)}`}
        actions={<>
          <Btn icon="print" size="sm">Cetak</Btn>
          <Btn icon="download" size="sm">Export PDF</Btn>
        </>}
      />

      <div className="grid-4">
        <Kpi label="Omzet Periode"   value={rupiah(periodSales, { sym: true, compact: true })} hint={`${DAILY_SALES.length} hari`} icon="trending" />
        <Kpi label="Rata-rata Harian" value={rupiah(avgDaily, { sym: true, compact: true })} hint={`Target ${rupiah(SALES_TARGET_DAILY, { sym: true, compact: true })}/hari`} icon="cashbox" />
        <Kpi label="Margin Kotor"    value={rupiah(totalMargin, { sym: true, compact: true })} hint={`${marginPct.toFixed(1)}% dari omzet`} icon="trending" tone="success" />
        <Kpi label="Slow Moving"     value={SLOW_MOVING.length.toString()} hint="SKU > 7 hari tanpa penjualan" icon="alert" tone="warn" />
      </div>

      <div className="grid-2">
        <Card>
          <div className="card-pad">
            <SectionHead title="Penjualan per Kategori" hint="Kontribusi omzet & margin per kategori" />
            <table className="table">
              <thead><tr><th>Kategori</th><th style={{textAlign:'right'}}>Omzet</th><th style={{textAlign:'right'}}>Margin</th><th style={{textAlign:'right'}}>%</th><th>Share</th></tr></thead>
              <tbody>
                {CATEGORY_SALES.map(c => (
                  <tr key={c.cat}>
                    <td style={{fontWeight:500}}>{CATEGORIES.find(x => x.id === c.cat)?.label || c.cat}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(c.omzet)}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', color:'hsl(152 65% 35%)'}}>{rupiah(c.margin)}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{(c.margin / c.omzet * 100).toFixed(1)}%</td>
                    <td>
                      <div className="bar-h" style={{width:120}}><div style={{width: (c.share * 100) + '%'}} /></div>
                    </td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr>
                  <td style={{fontWeight:600}}>Total</td>
                  <td style={{textAlign:'right', fontWeight:600, fontVariantNumeric:'tabular-nums'}}>{rupiah(totalOmzet)}</td>
                  <td style={{textAlign:'right', fontWeight:600, fontVariantNumeric:'tabular-nums', color:'hsl(152 65% 35%)'}}>{rupiah(totalMargin)}</td>
                  <td style={{textAlign:'right', fontWeight:600, fontVariantNumeric:'tabular-nums'}}>{marginPct.toFixed(1)}%</td>
                  <td></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </Card>

        <Card>
          <div className="card-pad">
            <SectionHead title="Slow-Moving Stock" hint="SKU dengan perputaran lambat — pertimbangkan promo / clearance" action={<Pill tone="warn">Aksi diperlukan</Pill>} />
            <table className="table">
              <thead><tr><th>SKU</th><th>Produk</th><th style={{textAlign:'right'}}>Hari Idle</th><th style={{textAlign:'right'}}>Stok</th><th style={{textAlign:'right'}}>Nilai</th></tr></thead>
              <tbody>
                {SLOW_MOVING.map(s => {
                  const p = PROD[s.sku];
                  return (
                    <tr key={s.sku}>
                      <td><span className="mono">{s.sku}</span></td>
                      <td>{p?.name}</td>
                      <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', color:'hsl(var(--destructive))'}}>{s.daysSinceLastSale} hari</td>
                      <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{s.stockOnHand}</td>
                      <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{rupiah(s.stockOnHand * (p?.hpp || 0))}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            <div style={{marginTop:14, padding:12, background:'hsl(152 60% 96%)', border:'1px solid hsl(152 50% 85%)', borderRadius:6, fontSize:12}}>
              <strong>Rekomendasi:</strong> Buat promo bundling atau diskon 15-20% untuk SKU dengan idle &gt; 14 hari agar tidak menumpuk di gudang.
            </div>
          </div>
        </Card>
      </div>

      <Card>
        <div className="card-pad">
          <SectionHead title="Ringkasan Penjualan Harian" hint={`Detail per hari · ${periodLabel(period)}`} />
          <table className="table compact">
            <thead><tr><th>Tanggal</th><th>Hari</th><th style={{textAlign:'right'}}>Omzet</th><th style={{textAlign:'right'}}>vs Target</th><th>Status</th></tr></thead>
            <tbody>
              {DAILY_SALES.map(d => {
                const day = ['Min','Sen','Sel','Rab','Kam','Jum','Sab'][new Date(d.date).getDay()];
                const pct = (d.total / SALES_TARGET_DAILY) * 100;
                const status = pct >= 100 ? 'tercapai' : pct >= 80 ? 'mendekati' : 'di bawah';
                const tone = pct >= 100 ? 'success' : pct >= 80 ? 'warn' : 'danger';
                return (
                  <tr key={d.date}>
                    <td>{formatDateID(d.date)}</td>
                    <td>{day}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums', fontWeight:500}}>{rupiah(d.total)}</td>
                    <td style={{textAlign:'right', fontVariantNumeric:'tabular-nums'}}>{pct.toFixed(0)}%</td>
                    <td><Pill tone={tone}>{status}</Pill></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { Laporan });
