<?php ob_start(); ?>
<script>
document.addEventListener('DOMContentLoaded', async () => {
  // Peta eksekutif dengan heatmap
  const map = GISMap.init('wk-map', <?= MAP_DEFAULT_LAT ?>, <?= MAP_DEFAULT_LNG ?>, 12);

  const [heatData, petaData] = await Promise.all([
    App.fetchJSON('<?= APP_URL ?>/dinsos/api/heatmap'),
    App.fetchJSON('<?= APP_URL ?>/walikota/api/peta')
  ]);

  if(petaData) {
    GISMap.addRILayer(petaData.rumah_ibadah||[]);
  }
  if(heatData) GISMap.addHeatmap(heatData);
  // Auto zoom ke seluruh Kota Pontianak
  GISMap.autoFitBounds();

  // Chart per kecamatan (horizontal bar)
  const kec = <?= json_encode(array_column($perKecamatan,'nama')) ?>;
  const totals = <?= json_encode(array_column($perKecamatan,'total')) ?>;
  const ekstrems = <?= json_encode(array_column($perKecamatan,'ekstrem')) ?>;
  new Chart(document.getElementById('chart-kec'), {
    type: 'bar',
    data: {
      labels: kec,
      datasets: [
        {label:'Total', data:totals, backgroundColor:'#1a3a5ccc', borderRadius:4},
        {label:'Ekstrem', data:ekstrems, backgroundColor:'#dc2626cc', borderRadius:4}
      ]
    },
    options:{responsive:true,maintainAspectRatio:false,
      indexAxis:'y',
      scales:{x:{beginAtZero:true,grid:{color:'#f1f5f9'}},y:{grid:{display:false}}}}
  });

  // Chart tren bulanan
  const bulan = <?= json_encode(array_column($trenBulanan,'bulan')) ?>;
  const bantuanData = <?= json_encode(array_column($trenBulanan,'jumlah')) ?>;
  Charts.line('chart-tren-wk', bulan, [{label:'Bantuan Tersalurkan', data:bantuanData}]);

  // Donut komposisi kemiskinan
  Charts.donut('chart-komposisi',
    ['Miskin Ekstrem','Miskin','Rentan Miskin'],
    [<?= ($stats['ekstrem']??0).','.(($stats['miskin']??0)).','.(($stats['rentan']??0)) ?>],
    ['#dc2626','#ea580c','#ca8a04']
  );
});
</script>
<?php $extraJs = ob_get_clean(); ?>

<!-- Executive Header Banner -->
<div style="background:linear-gradient(135deg,#1a0533 0%,#2d1b69 50%,#4c1d95 100%);color:#fff;border-radius:var(--radius-lg);padding:28px 32px;margin-bottom:24px;display:flex;align-items:center;gap:24px">
  <div style="font-size:4rem">🏛</div>
  <div>
    <div style="font-size:0.75rem;text-transform:uppercase;letter-spacing:0.12em;color:rgba(255,255,255,0.55);margin-bottom:6px">Dashboard Eksekutif</div>
    <div style="font-size:1.5rem;font-weight:900;letter-spacing:-0.01em">Penanganan Kemiskinan Kota Pontianak</div>
    <div style="font-size:0.85rem;color:rgba(255,255,255,0.65);margin-top:6px">Data real-time sistem SINERGI · <?= date('d F Y') ?></div>
  </div>
  <div style="margin-left:auto;text-align:right">
    <div style="font-size:0.72rem;color:rgba(255,255,255,0.45);text-transform:uppercase;letter-spacing:0.08em">Status Sistem</div>
    <div style="font-size:1rem;font-weight:700;color:#4ade80;margin-top:4px">● Aktif & Online</div>
  </div>
</div>

<!-- KPI Cards Row 1 -->
<div class="stats-grid" style="grid-template-columns:repeat(5,1fr)">
  <div class="stat-card" style="border-top:3px solid #dc2626">
    <div class="stat-card-icon red">👥</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['total_warga']??0) ?></div>
      <div class="stat-card-label">Total Warga Miskin</div>
    </div>
  </div>
  <div class="stat-card" style="border-top:3px solid #dc2626">
    <div class="stat-card-icon red">💀</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['ekstrem']??0) ?></div>
      <div class="stat-card-label">Miskin Ekstrem</div>
      <div class="stat-card-sub"><?= $stats['total_warga']>0?round($stats['ekstrem']/$stats['total_warga']*100,1):0 ?>% dari total</div>
    </div>
  </div>
  <div class="stat-card" style="border-top:3px solid #7c3aed">
    <div class="stat-card-icon purple">⚠️</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['blind_spot']??0) ?></div>
      <div class="stat-card-label">Warga Blind Spot</div>
      <div class="stat-card-sub">Belum terjangkau</div>
    </div>
  </div>
  <div class="stat-card" style="border-top:3px solid #16a34a">
    <div class="stat-card-icon green">⛪</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['total_ri']??0) ?></div>
      <div class="stat-card-label">Rumah Ibadah Aktif</div>
    </div>
  </div>
  <div class="stat-card" style="border-top:3px solid #0284c7">
    <div class="stat-card-icon teal">📦</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['bantuan_tahun_ini']??0) ?></div>
      <div class="stat-card-label">Bantuan Tahun Ini</div>
      <div class="stat-card-sub">Total: <?= number_format($stats['total_bantuan']??0) ?></div>
    </div>
  </div>
</div>

<!-- Grid: Peta Besar + Sidebar Charts -->
<div style="display:grid;grid-template-columns:1fr 380px;gap:20px;margin-bottom:20px">
  <!-- PETA UTAMA HEATMAP -->
  <div class="card">
    <div class="card-header" style="background:linear-gradient(to right,#1a0533,#2d1b69);color:#fff;border-radius:0">
      <span class="card-icon">🌡</span>
      <h3 style="color:#fff">Heatmap Kemiskinan Kota Pontianak</h3>
    </div>
    <div class="card-body no-pad" style="position:relative">
      <div id="wk-map" style="height:440px"></div>
      <div class="map-legend">
        <h4>Intensitas</h4>
        <div style="height:10px;border-radius:5px;background:linear-gradient(to right,#fef9c3,#fb923c,#ef4444,#7f1d1d);margin:4px 0 6px"></div>
        <div style="display:flex;justify-content:space-between;font-size:0.6rem;color:var(--clr-text-muted)"><span>Rendah</span><span>Tinggi</span></div>
        <div class="map-legend-item" style="margin-top:8px"><div class="map-legend-dot legend-dot-ri"></div> Rumah Ibadah</div>
      </div>
    </div>
  </div>

  <!-- SIDEBAR CHARTS -->
  <div style="display:flex;flex-direction:column;gap:16px">
    <!-- Komposisi -->
    <div class="card">
      <div class="card-header"><span class="card-icon">🥧</span><h3>Komposisi Kemiskinan</h3></div>
      <div class="card-body"><div class="chart-wrap" style="height:160px"><canvas id="chart-komposisi"></canvas></div></div>
    </div>

    <!-- Peringkat Kecamatan -->
    <div class="card" style="flex:1">
      <div class="card-header"><span class="card-icon">🏆</span><h3>Ranking Kecamatan</h3></div>
      <div class="card-body no-pad">
        <?php foreach($perKecamatan as $i=>$k): ?>
        <div style="padding:10px 16px;border-bottom:1px solid #f1f5f9">
          <div style="display:flex;align-items:center;gap:10px">
            <div style="width:22px;height:22px;border-radius:50%;background:<?= $i===0?'#dc2626':($i===1?'#d97706':($i===2?'#65a30d':'#94a3b8')) ?>;color:#fff;display:flex;align-items:center;justify-content:center;font-size:0.72rem;font-weight:800;flex-shrink:0"><?= $i+1 ?></div>
            <div style="flex:1;min-width:0">
              <div style="font-size:0.82rem;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= e($k['nama']) ?></div>
              <div style="height:4px;background:#f1f5f9;border-radius:2px;margin-top:3px;overflow:hidden">
                <?php $mx=max(array_column($perKecamatan,'total')?:[1]); ?>
                <div style="height:100%;background:<?= $i===0?'#dc2626':($i===1?'#d97706':'#1a3a5c') ?>;width:<?= $mx>0?round($k['total']/$mx*100):0 ?>%;border-radius:2px"></div>
              </div>
            </div>
            <strong style="font-size:0.9rem;color:var(--clr-text)"><?= number_format($k['total']) ?></strong>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</div>

<!-- Bottom Charts Row -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
  <div class="card">
    <div class="card-header"><span class="card-icon">📊</span><h3>Perbandingan Kemiskinan per Kecamatan</h3></div>
    <div class="card-body"><div class="chart-wrap" style="height:260px"><canvas id="chart-kec"></canvas></div></div>
  </div>
  <div class="card">
    <div class="card-header"><span class="card-icon">📈</span><h3>Tren Bantuan Tersalurkan (12 Bulan)</h3></div>
    <div class="card-body"><div class="chart-wrap" style="height:260px"><canvas id="chart-tren-wk"></canvas></div></div>
  </div>
</div>

<!-- Rumah Ibadah Paling Aktif -->
<div class="card">
  <div class="card-header"><span class="card-icon">🏆</span><h3>5 Rumah Ibadah Paling Aktif</h3></div>
  <div class="card-body no-pad">
    <div class="table-wrap">
      <table>
        <thead><tr><th>Peringkat</th><th>Nama</th><th>Jenis</th><th>Kecamatan</th><th>Warga Binaan</th><th>Bantuan Disalurkan</th></tr></thead>
        <tbody>
          <?php foreach($topRi as $i=>$r): ?>
          <tr>
            <td>
              <div style="width:28px;height:28px;border-radius:50%;background:<?= $i===0?'#f59e0b':($i===1?'#94a3b8':($i===2?'#c2410c':'#e2e8f0')) ?>;color:<?= $i<3?'#fff':'var(--clr-text)' ?>;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:0.85rem"><?= $i+1 ?></div>
            </td>
            <td style="font-weight:600"><?= e($r['nama']) ?></td>
            <td><span class="badge badge-green"><?= e($r['jenis']) ?></span></td>
            <td class="text-sm"><?= e($r['kecamatan']) ?></td>
            <td class="text-sm"><strong><?= number_format($r['jml_warga']) ?></strong> warga</td>
            <td>
              <div style="display:flex;align-items:center;gap:8px">
                <strong style="color:var(--clr-success)"><?= number_format($r['jml_bantuan']) ?></strong>
                <div style="flex:1;max-width:80px">
                  <div class="priority-bar">
                    <?php $mx2=max(array_column($topRi,'jml_bantuan')?:[1]); ?>
                    <div class="priority-bar-fill low" style="width:<?= $mx2>0?round($r['jml_bantuan']/$mx2*100):0 ?>%"></div>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
