<?php ob_start(); ?>
<script>
document.addEventListener('DOMContentLoaded', async () => {
  const ri = <?= json_encode(['lat'=>(float)$ri['lat'],'lng'=>(float)$ri['lng'],'nama'=>$ri['nama'],'radius_meter'=>(int)$ri['radius_meter']]) ?>;

  // Fokus ke lokasi rumah ibadah
  const map = GISMap.init('ri-dashboard-map', ri.lat, ri.lng, 15);

  // Marker rumah ibadah
  L.circle([ri.lat, ri.lng], {
    radius: ri.radius_meter, fillColor:'#16a34a', fillOpacity:0.08,
    color:'#16a34a', weight:2, dashArray:'6,4'
  }).addTo(map).bindPopup('<strong>Radius Pelayanan: '+ri.radius_meter+'m</strong>');

  GISMap.createRIMarker(ri).bindPopup('<strong>'+ri.nama+'</strong>').addTo(map).openPopup();

  // Warga binaan
  const wargaData = await App.fetchJSON('<?= APP_URL ?>/rumah-ibadah/api/peta');
  if (wargaData?.warga && wargaData.warga.length > 0) {
    GISMap.addWargaLayer(wargaData.warga, w => {
      window.location.href = '<?= APP_URL ?>/rumah-ibadah/warga/' + w.id;
    });
    // Zoom ke area RI + warga binaan (sudah fokus ke RI dari init)
    // Tambahkan koordinat RI ke bounds agar tetap kelihatan
    GISMap._allMarkerBounds.push([ri.lat, ri.lng]);
    GISMap.autoFitBounds();
  }
  // Jika tidak ada warga, tetap fokus ke lokasi RI (sudah di-setView dari init)

  // Chart prioritas
  const pData = <?= json_encode([
    ($stats['prioritas_tinggi']??0),
    ($stats['prioritas_sedang']??0),
    (($stats['total_warga']??0)-($stats['prioritas_tinggi']??0)-($stats['prioritas_sedang']??0))
  ]) ?>;
  Charts.donut('chart-prioritas',
    ['Prioritas Tinggi','Prioritas Sedang','Prioritas Rendah'],
    pData, ['#dc2626','#d97706','#16a34a']
  );
});
</script>
<?php $extraJs = ob_get_clean(); ?>

<!-- Header RI Info -->
<div style="background:var(--clr-primary);color:#fff;border-radius:var(--radius-md);padding:20px 24px;margin-bottom:20px;display:flex;align-items:center;gap:20px">
  <div style="font-size:3rem">⛪</div>
  <div>
    <div style="font-size:1.2rem;font-weight:800"><?= e($ri['nama']) ?></div>
    <div style="font-size:0.85rem;color:rgba(255,255,255,0.7)"><?= e($ri['jenis']??'') ?> · <?= e($ri['kelurahan']??'') ?>, <?= e($ri['kecamatan']??'') ?></div>
    <div style="font-size:0.8rem;color:rgba(255,255,255,0.6);margin-top:4px">📍 <?= e($ri['alamat']??'') ?> &nbsp;|&nbsp; Radius: <?= number_format($ri['radius_meter']??500) ?>m</div>
  </div>
</div>

<!-- Stats -->
<div class="stats-grid">
  <div class="stat-card">
    <div class="stat-card-icon blue">👥</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 Binaan</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon red">🔥</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['prioritas_tinggi']??0) ?></div>
      <div class="stat-card-label">Prioritas Tinggi</div>
      <div class="stat-card-sub"><a href="<?= APP_URL ?>/rumah-ibadah/prioritas" style="color:var(--clr-primary-l)">Lihat →</a></div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon orange">⚠</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>
  </div>
  <div class="stat-card">
    <div class="stat-card-icon green">📦</div>
    <div class="stat-card-body">
      <div class="stat-card-value"><?= number_format($stats['total_bantuan']??0) ?></div>
      <div class="stat-card-label">Total Bantuan Disalurkan</div>
      <div class="stat-card-sub"><?= number_format($stats['bantuan_bulan_ini']??0) ?> bulan ini</div>
    </div>
  </div>
</div>

<!-- Dashboard Grid: Peta + Sidebar -->
<div class="dashboard-grid" style="margin-bottom:20px">
  <!-- PETA: fokus ke rumah ibadah + radius + warga -->
  <div class="card">
    <div class="card-header">
      <span class="card-icon">🗺</span>
      <h3>Peta Wilayah Pelayanan & Warga Binaan</h3>
      <div class="card-actions">
        <a href="<?= APP_URL ?>/rumah-ibadah/bantuan/tambah" class="btn btn-accent btn-sm">➕ Catat Bantuan</a>
      </div>
    </div>
    <div class="card-body no-pad" style="position:relative">
      <div id="ri-dashboard-map" style="height:460px"></div>
      <div class="map-legend">
        <h4>Legenda</h4>
        <div class="map-legend-item"><div class="map-legend-dot legend-dot-ri"></div> Rumah Ibadah Anda</div>
        <div class="map-legend-item"><div class="map-legend-dot legend-dot-ekstrem"></div> Miskin Ekstrem</div>
        <div class="map-legend-item"><div class="map-legend-dot legend-dot-miskin"></div> Miskin</div>
        <div class="map-legend-item"><div class="map-legend-dot legend-dot-rentan"></div> Rentan Miskin</div>
      </div>
    </div>
  </div>

  <!-- SIDEBAR -->
  <div style="display:flex;flex-direction:column;gap:16px">
    <!-- Chart Prioritas -->
    <div class="card">
      <div class="card-header"><span class="card-icon">📊</span><h3>Distribusi Prioritas</h3></div>
      <div class="card-body"><div class="chart-wrap" style="height:180px"><canvas id="chart-prioritas"></canvas></div></div>
    </div>

    <!-- Warga Prioritas Tinggi -->
    <div class="card" style="flex:1">
      <div class="card-header">
        <span class="card-icon">🔥</span><h3>Warga Prioritas Tinggi</h3>
        <div class="card-actions"><a href="<?= APP_URL ?>/rumah-ibadah/prioritas" class="btn btn-ghost btn-sm">Semua</a></div>
      </div>
      <div class="card-body no-pad" style="max-height:280px;overflow-y:auto">
        <?php
        $topWarga = array_filter($wargaList, fn($w) => $w['level_prioritas']==='Tinggi');
        foreach(array_slice($topWarga,0,8) as $w):
        ?>
        <a href="<?= APP_URL ?>/rumah-ibadah/warga/<?= $w['id'] ?>" style="display:block;text-decoration:none;color:inherit">
          <div class="sidebar-panel-item">
            <div style="display:flex;justify-content:space-between;align-items:center">
              <h4 style="font-size:0.82rem"><?= e($w['nama']) ?></h4>
              <span style="font-size:0.78rem;font-weight:700;color:var(--clr-danger)"><?= $w['skor_prioritas'] ?>/100</span>
            </div>
            <p><?= e($w['status_kemiskinan']) ?> · Tgn: <?= $w['jumlah_tanggungan'] ?></p>
          </div>
        </a>
        <?php endforeach; ?>
        <?php if(empty($topWarga)): ?>
        <div class="empty-state" style="padding:20px"><p>Tidak ada warga prioritas tinggi</p></div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- Bantuan Terakhir -->
<div class="card">
  <div class="card-header">
    <span class="card-icon">📦</span><h3>Bantuan Terakhir Disalurkan</h3>
    <div class="card-actions"><a href="<?= APP_URL ?>/rumah-ibadah/bantuan" class="btn btn-ghost btn-sm">Histori Lengkap</a></div>
  </div>
  <div class="card-body no-pad">
    <div class="table-wrap">
      <table>
        <thead><tr><th>Kode</th><th>Warga</th><th>Kategori</th><th>Jumlah</th><th>Tanggal</th></tr></thead>
        <tbody>
          <?php foreach($bantuanTerakhir as $b): ?>
          <tr>
            <td><code style="font-size:0.72rem;background:#f1f5f9;padding:1px 5px;border-radius:3px"><?= e($b['kode_bantuan']) ?></code></td>
            <td style="font-weight:600;font-size:0.875rem"><?= e($b['warga']) ?></td>
            <td><span class="badge badge-green"><?= e($b['kategori']) ?></span></td>
            <td class="text-sm"><?= $b['jumlah'] ? ($b['satuan']==='rupiah'?formatRupiah($b['jumlah']):(number_format($b['jumlah']).' '.$b['satuan'])) : '—' ?></td>
            <td class="text-sm text-muted"><?= formatTanggal($b['tanggal_penyaluran']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php if(empty($bantuanTerakhir)): ?>
    <div class="empty-state" style="padding:24px"><div class="empty-state-icon">📭</div><p>Belum ada bantuan disalurkan</p></div>
    <?php endif; ?>
  </div>
</div>
