// Dashboard page + KPI/sparkline/cashflow/composition primitives.
const { useMemo: useMemo$dash } = React;

function KpiCard({ label, value, delta = 0, deltaLabel, series, highlight }) {
  const up = delta >= 0;
  return (
    <div className="stat" style={highlight ? {background:'hsl(var(--accent-h) var(--accent-s) 96%)', borderColor:'hsl(var(--accent-h) var(--accent-s) 80%)'} : {}}>
      <div className="stat-label">{label}</div>
      <div className="stat-value">{value}</div>
      <div className="row between mt-2" style={{alignItems:'center'}}>
        <div style={{fontSize:11.5}}>
          <span style={{color: up ? 'hsl(var(--success))' : 'hsl(var(--destructive))', fontWeight:500}}>
            {up ? '↑' : '↓'} {rupiah(Math.abs(delta), { compact: true })}
          </span>
          <span style={{color:'hsl(var(--muted-foreground))'}}> · {deltaLabel}</span>
        </div>
        {series && <Sparkline series={series} />}
      </div>
    </div>
  );
}

function Sparkline({ series }) {
  if (!series || series.length === 0) return null;
  const min = Math.min(...series, 0), max = Math.max(...series, 1);
  const range = max - min || 1;
  const w = 68, h = 18;
  const pts = series.map((v, i) => `${(i / (series.length - 1)) * w},${h - ((v - min) / range) * (h - 2) - 1}`).join(' ');
  const accent = `hsl(var(--accent-h) var(--accent-s) var(--accent-l))`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width={w} height={h} preserveAspectRatio="none">
      <polyline points={pts} fill="none" stroke={accent} strokeWidth="1.4" />
      <circle cx={w} cy={h - ((series.at(-1) - min) / range) * (h - 2) - 1} r="1.5" fill={accent} />
    </svg>
  );
}

function CashflowChart({ data }) {
  const max = Math.max(...data.map(d => Math.max(d.inflow, d.outflow)), 1);
  return (
    <div style={{height:200, display:'flex', alignItems:'flex-end', gap:3, marginTop:8, paddingRight:8}}>
      {data.map(d => {
        const inH = (d.inflow / max) * 170;
        const outH = (d.outflow / max) * 170;
        return (
          <div key={d.date} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:2, minWidth:0}}>
            <div style={{flex:1, display:'flex', flexDirection:'column', justifyContent:'flex-end', width:'100%', gap:2}}>
              {d.inflow > 0 && <div style={{width:'100%', background:'hsl(var(--accent-h) var(--accent-s) var(--accent-l))', borderRadius:2, height: inH + 'px'}} title={`Masuk: ${rupiah(d.inflow,{sym:true})}`} />}
              {d.outflow > 0 && <div style={{width:'100%', background:'hsl(220 18% 22%)', borderRadius:2, height: outH + 'px', opacity:0.9}} title={`Keluar: ${rupiah(d.outflow,{sym:true})}`} />}
            </div>
            <div style={{fontSize:9, color:'hsl(var(--muted-foreground))', fontVariantNumeric:'tabular-nums'}}>{parseInt(d.date.slice(8))}</div>
          </div>
        );
      })}
    </div>
  );
}

function CompositionBar({ data }) {
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  return (
    <div className="col gap-3">
      <div style={{fontSize:22, fontWeight:600, letterSpacing:'-0.02em', fontVariantNumeric:'tabular-nums'}}>{rupiah(total, { sym: true })}</div>
      <div className="composition-bar">
        {data.map((d, i) => (
          <div key={i} className="composition-bar-segment" style={{width: (d.value/total*100)+'%', background: d.color}} title={`${d.label}: ${rupiah(d.value,{sym:true})}`} />
        ))}
      </div>
      <div className="col" style={{gap:6}}>
        {data.map((d, i) => (
          <div key={i} className="row" style={{fontSize:12, gap:8}}>
            <span style={{width:8, height:8, borderRadius:2, background:d.color, display:'inline-block'}} />
            <span className="muted" style={{flex:1}}>{d.label}</span>
            <span className="tnum muted" style={{fontSize:11}}>{((d.value/total)*100).toFixed(1)}%</span>
            <span className="tnum" style={{fontWeight:500, width:80, textAlign:'right'}}>{rupiah(d.value, { compact: true })}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Dashboard({ period, role }) {
  const cashTotal = accountClosing('1-1010', period) + accountClosing('1-1020', period) + accountClosing('1-1030', period);
  const revenue = ['4-1010','4-1020','4-1030','4-2010','4-2020'].reduce((s, c) => s + accountMovement(c, period).credit, 0);
  const expense = ['5-1010','5-1020','5-1030','5-1040','5-1050','5-1060','5-2010','5-3010'].reduce((s, c) => s + accountMovement(c, period).debit, 0);
  const surplus = revenue - expense;
  const piutangSPP = accountClosing('1-1110', period);

  const cashLastMonth = (OPENING_BALANCES['1-1010']||0) + (OPENING_BALANCES['1-1020']||0) + (OPENING_BALANCES['1-1030']||0);
  const deltaCash = cashTotal - cashLastMonth;

  const dayBuckets = useMemo$dash(() => {
    const days = new Set();
    JOURNALS.forEach(j => j.date.startsWith(period) && days.add(j.date.slice(8)));
    return [...days].sort().map(d => {
      const date = period + '-' + d;
      const cashAccs = ['1-1010','1-1020','1-1030'];
      const inflow  = JOURNALS.filter(j => j.date === date).flatMap(j => j.lines).filter(l => cashAccs.includes(l.code)).reduce((s, l) => s + l.debit, 0);
      const outflow = JOURNALS.filter(j => j.date === date).flatMap(j => j.lines).filter(l => cashAccs.includes(l.code)).reduce((s, l) => s + l.credit, 0);
      return { date, inflow, outflow, net: inflow - outflow };
    });
  }, [period]);

  const accentBase = 'hsl(var(--accent-h) var(--accent-s) var(--accent-l))';
  const revComposition = [
    { label: 'SPP',          value: accountMovement('4-1010', period).credit, color: accentBase },
    { label: 'Uang Pangkal', value: accountMovement('4-1020', period).credit, color: 'hsl(var(--accent-h) 60% 60%)' },
    { label: 'Kegiatan',     value: accountMovement('4-1030', period).credit, color: 'hsl(var(--accent-h) 40% 70%)' },
    { label: 'Donasi',       value: accountMovement('4-2010', period).credit, color: 'hsl(var(--accent-h) 30% 78%)' },
    { label: 'Bunga Bank',   value: accountMovement('4-2020', period).credit, color: 'hsl(var(--accent-h) 18% 86%)' },
  ];
  const expComposition = [
    { label: 'Gaji',         value: accountMovement('5-1010', period).debit + accountMovement('5-1020', period).debit, color: 'hsl(220 18% 22%)' },
    { label: 'Utilitas',     value: accountMovement('5-1030', period).debit, color: 'hsl(220 12% 36%)' },
    { label: 'Bahan & Buku', value: accountMovement('5-1040', period).debit, color: 'hsl(220 10% 50%)' },
    { label: 'Pemeliharaan', value: accountMovement('5-1050', period).debit, color: 'hsl(220 8% 64%)' },
    { label: 'Kegiatan',     value: accountMovement('5-1060', period).debit, color: 'hsl(220 6% 76%)' },
    { label: 'Penyusutan',   value: accountMovement('5-2010', period).debit, color: 'hsl(220 5% 86%)' },
  ];

  const recentJournals = [...JOURNALS].sort((a,b) => b.date.localeCompare(a.date)).slice(0, 6);
  const pending = JOURNALS.filter(j => j.status === 'pending');

  return (
    <div className="col gap-6">
      {/* KPI row */}
      <div className="stat-grid">
        <KpiCard label="Kas & Setara Kas" value={rupiah(cashTotal, { sym: true })} delta={deltaCash} deltaLabel="vs bulan lalu" series={dayBuckets.map(d => d.net)} />
        <KpiCard label={`Pendapatan ${periodLabel(period).split(' ')[0]}`} value={rupiah(revenue, { sym: true })} delta={revenue * 0.084} deltaLabel="vs bulan lalu" />
        <KpiCard label="Beban Operasional" value={rupiah(expense, { sym: true })} delta={-expense * 0.022} deltaLabel="vs bulan lalu" />
        <KpiCard label="Surplus Bulan Berjalan" value={rupiah(surplus, { sym: true })} delta={surplus * 0.18} deltaLabel="vs bulan lalu" highlight />
      </div>

      {/* Cashflow + Pending */}
      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:14}}>
        <Card>
          <div className="card-header">
            <div>
              <div className="card-title">Arus Kas Harian</div>
              <div className="card-desc">Pergerakan kas bulan {periodLabel(period)}</div>
            </div>
            <div className="row gap-3" style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>
              <span className="row gap-2"><span style={{width:8, height:8, borderRadius:999, background:accentBase}} />Masuk</span>
              <span className="row gap-2"><span style={{width:8, height:8, borderRadius:999, background:'hsl(220 18% 22%)'}} />Keluar</span>
            </div>
          </div>
          <div className="card-body">
            <CashflowChart data={dayBuckets} />
          </div>
        </Card>

        <Card>
          <div className="card-header">
            <div>
              <div className="card-title">Menunggu Persetujuan</div>
              <div className="card-desc">{pending.length} entri jurnal pending</div>
            </div>
          </div>
          <div className="card-body col gap-3">
            {pending.length === 0 && <div className="empty">Tidak ada entri menunggu.</div>}
            {pending.slice(0, 4).map(j => (
              <div key={j.id} style={{padding:'10px 12px', borderRadius:6, background:'hsl(220 22% 98%)', border:'1px solid hsl(var(--border))'}}>
                <div className="row between" style={{alignItems:'flex-start'}}>
                  <div style={{fontSize:12.5, fontWeight:500, lineHeight:1.35, paddingRight:8}}>{j.desc}</div>
                  <Pill tone="warn" dot>Pending</Pill>
                </div>
                <div className="row gap-3 mt-2" style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>
                  <span className="mono">{j.id}</span>
                  <span>·</span>
                  <span>{formatDateID(j.date)}</span>
                  <span className="tnum" style={{marginLeft:'auto', fontWeight:500, color:'hsl(var(--foreground))'}}>{rupiah(j.lines[0].debit, { compact: true })}</span>
                </div>
              </div>
            ))}
            {ROLES[role].can.approve && pending.length > 0 && (
              <div className="row gap-2 mt-2" style={{paddingTop:12, borderTop:'1px solid hsl(var(--border))'}}>
                <Btn tone="primary" size="sm" icon="check">Setujui semua</Btn>
                <Btn tone="ghost" size="sm">Tinjau</Btn>
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* Composition + piutang */}
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14}}>
        <Card>
          <div className="card-header"><div><div className="card-title">Komposisi Pendapatan</div><div className="card-desc">{periodLabel(period)}</div></div></div>
          <div className="card-body"><CompositionBar data={revComposition.filter(d => d.value > 0)} /></div>
        </Card>
        <Card>
          <div className="card-header"><div><div className="card-title">Komposisi Beban</div><div className="card-desc">{periodLabel(period)}</div></div></div>
          <div className="card-body"><CompositionBar data={expComposition.filter(d => d.value > 0)} /></div>
        </Card>
        <Card>
          <div className="card-header"><div><div className="card-title">Piutang SPP</div><div className="card-desc">16 siswa belum lunas April</div></div></div>
          <div className="card-body col gap-3">
            <div style={{display:'flex', alignItems:'baseline', gap:8}}>
              <span style={{fontSize:24, fontWeight:600, letterSpacing:'-0.02em', fontVariantNumeric:'tabular-nums'}}>{rupiah(piutangSPP, { sym: true })}</span>
              <span style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>total saldo</span>
            </div>
            <div className="col" style={{gap:6}}>
              {[
                { age: '0–30 hari',   count: 16, amt: 12_480_000, pct: 17, tone: 'progress-bar' },
                { age: '31–60 hari',  count: 5,  amt: 3_900_000,  pct: 5,  tone: 'progress-bar warning' },
                { age: '> 60 hari',   count: 1,  amt: 780_000,    pct: 1,  tone: 'progress-bar destructive' },
              ].map((row, i) => (
                <div key={i} className="row" style={{fontSize:12, gap:10}}>
                  <span className="muted" style={{width:90}}>{row.age}</span>
                  <div className="progress" style={{flex:1}}>
                    <div className={row.tone} style={{width: row.pct + '%'}} />
                  </div>
                  <span className="tnum muted" style={{width:60, textAlign:'right'}}>{row.count} siswa</span>
                  <span className="tnum" style={{width:90, textAlign:'right', fontWeight:500}}>{rupiah(row.amt, { compact: true })}</span>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>

      {/* Recent journals */}
      <Card>
        <div className="card-header">
          <div><div className="card-title">Transaksi Terkini</div><div className="card-desc">6 entri jurnal terbaru</div></div>
        </div>
        <div className="card-body flush">
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th style={{width:120}}>Tanggal</th>
                  <th style={{width:130}}>No. Jurnal</th>
                  <th>Keterangan</th>
                  <th className="num" style={{width:160}}>Nilai</th>
                  <th style={{width:110}}>Status</th>
                </tr>
              </thead>
              <tbody>
                {recentJournals.map(j => (
                  <tr key={j.id}>
                    <td className="muted tnum">{formatDateID(j.date)}</td>
                    <td className="code">{j.id}</td>
                    <td>{j.desc}</td>
                    <td className="num" style={{fontWeight:500}}>{rupiah(j.lines[0].debit, { sym: true })}</td>
                    <td>{j.status === 'posted' ? <Pill tone="ok" dot>Posted</Pill> : <Pill tone="warn" dot>Pending</Pill>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { KpiCard, Sparkline, CashflowChart, CompositionBar, Dashboard });
