<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px">
  <div>
    <h2 style="font-size:1.2rem;font-weight:700">🗺 Monitoring Kemiskinan</h2>
    <p class="text-muted text-sm"><?= count($data) ?> warga terfilter · Klik marker pada peta untuk detail</p>
  </div>
</div>

<!-- Filter Bar -->
<form method="GET" action="<?= APP_URL ?>/dinsos/kemiskinan">
  <div class="filters-bar" style="margin-bottom:16px">
    <select name="kecamatan" class="form-control" onchange="this.form.submit()">
      <option value="">— Semua Kecamatan —</option>
      <?php foreach($kecamatan as $k): ?>
      <option value="<?= $k['id'] ?>" <?= $filter_kec==$k['id']?'selected':'' ?>><?= e($k['nama']) ?></option>
      <?php endforeach; ?>
    </select>
    <?php if(!empty($kelurahan)): ?>
    <select name="kelurahan" class="form-control" onchange="this.form.submit()">
      <option value="">— Semua Kelurahan —</option>
      <?php foreach($kelurahan as $k): ?>
      <option value="<?= $k['id'] ?>" <?= $filter_kel==$k['id']?'selected':'' ?>><?= e($k['nama']) ?></option>
      <?php endforeach; ?>
    </select>
    <?php endif; ?>
    <select name="status" class="form-control" onchange="this.form.submit()">
      <option value="">— Semua Status —</option>
      <?php foreach(['Miskin Ekstrem','Miskin','Rentan Miskin'] as $s): ?>
      <option value="<?= $s ?>" <?= $filter_status===$s?'selected':'' ?>><?= $s ?></option>
      <?php endforeach; ?>
    </select>
    <select name="prioritas" class="form-control" onchange="this.form.submit()">
      <option value="">— Semua Prioritas —</option>
      <?php foreach(['Tinggi','Sedang','Rendah'] as $p): ?>
      <option value="<?= $p ?>" <?= $filter_prioritas===$p?'selected':'' ?>><?= $p ?></option>
      <?php endforeach; ?>
    </select>
    <?php if($filter_kec||$filter_kel||$filter_status||$filter_prioritas): ?>
    <a href="<?= APP_URL ?>/dinsos/kemiskinan" class="btn btn-ghost btn-sm">✕ Reset</a>
    <?php endif; ?>
  </div>
</form>

<!-- Grid: Peta + Daftar -->
<div style="display:grid;grid-template-columns:1fr 360px;gap:16px">
  <!-- PETA -->
  <div class="card">
    <div class="card-body no-pad" style="position:relative">
      <div id="kemiskinan-map" style="height:600px"></div>
      <div class="map-legend">
        <h4>Legenda</h4>
        <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 class="map-legend-item"><div class="map-legend-dot legend-dot-ri"></div> Rumah Ibadah</div>
        <div class="map-legend-item"><div class="map-legend-dot legend-dot-blind"></div> Blind Spot</div>
      </div>
    </div>
  </div>

  <!-- DAFTAR WARGA -->
  <div class="card">
    <div class="card-header">
      <span class="card-icon">👥</span>
      <h3>Daftar Warga (<?= count($data) ?>)</h3>
    </div>
    <div style="overflow-y:auto;max-height:560px">
      <?php foreach($data as $w): ?>
      <div class="sidebar-panel-item" id="warga-item-<?= $w['id'] ?>"
           onclick="highlightWarga(<?= $w['id'] ?>,<?= (float)$w['lat'] ?>,<?= (float)$w['lng'] ?>)">
        <div style="display:flex;justify-content:space-between;align-items:center">
          <h4><?= e($w['nama']) ?></h4>
          <div style="display:flex;gap:4px;align-items:center">
            <?php if($w['is_blind_spot']): ?><span class="badge badge-purple" style="font-size:0.62rem">Blind</span><?php endif; ?>
            <?php $pc=['Tinggi'=>'badge-red','Sedang'=>'badge-yellow','Rendah'=>'badge-green']; ?>
            <span class="badge <?= $pc[$w['level_prioritas']]??'badge-gray' ?>" style="font-size:0.62rem"><?= $w['level_prioritas'] ?></span>
          </div>
        </div>
        <p><?= e($w['kecamatan']) ?> › <?= e($w['kelurahan']) ?></p>
        <div style="font-size:0.72rem;color:var(--clr-text-muted);margin-top:2px">
          <?= e($w['status_kemiskinan']) ?> · <?= formatRupiah($w['penghasilan_bulanan']??0) ?>/bln
        </div>
      </div>
      <?php endforeach; ?>
      <?php if(empty($data)): ?>
      <div class="empty-state"><div class="empty-state-icon">👥</div><h3>Tidak ada data</h3></div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
let wargaMarkers = {};

function highlightWarga(id, lat, lng) {
  document.querySelectorAll('.sidebar-panel-item').forEach(el => el.classList.remove('active'));
  document.getElementById('warga-item-'+id)?.classList.add('active');
  if (wargaMarkers[id]) {
    wargaMarkers[id].openPopup();
    GISMap.map.setView([lat,lng],16);
  }
}

document.addEventListener('DOMContentLoaded', async () => {
  const map = GISMap.init('kemiskinan-map', <?= MAP_DEFAULT_LAT ?>, <?= MAP_DEFAULT_LNG ?>, 12);

  const riData = await App.fetchJSON('<?= APP_URL ?>/api/rumah-ibadah');
  if(riData) GISMap.addRILayer(riData);
  // Zoom ke Pontianak terlebih dahulu
  GISMap.autoFitBounds();

  const wData = <?= json_encode(array_map(fn($w) => [
    'id'=>$w['id'],'nama'=>$w['nama'],'lat'=>(float)$w['lat'],'lng'=>(float)$w['lng'],
    'status_kemiskinan'=>$w['status_kemiskinan'],'level_prioritas'=>$w['level_prioritas'],
    'is_blind_spot'=>$w['is_blind_spot'],'kelurahan'=>$w['kelurahan']??'',
    'kecamatan'=>$w['kecamatan']??'','penghasilan_bulanan'=>$w['penghasilan_bulanan']??0
  ], array_filter($data, fn($w)=>$w['lat']&&$w['lng']))) ?>;

  const colors = {'Miskin Ekstrem':'#dc2626','Miskin':'#ea580c','Rentan Miskin':'#ca8a04'};

  wData.forEach(w => {
    const color = w.is_blind_spot ? '#7c3aed' : (colors[w.status_kemiskinan]||'#6b7280');
    const m = L.circleMarker([w.lat,w.lng],{radius:9,fillColor:color,color:'#fff',weight:2,fillOpacity:0.9})
      .bindPopup(`<div style="min-width:180px"><strong>${w.nama}</strong><br>
        <span style="font-size:12px;color:#6b7280">${w.kecamatan} › ${w.kelurahan}</span><br>
        <span style="color:${color};font-weight:700;font-size:11px">${w.status_kemiskinan}</span>
        ${w.is_blind_spot?'<br><span style="color:#7c3aed;font-weight:700;font-size:11px">⚠ Blind Spot</span>':''}
        </div>`)
      .addTo(map);
    wargaMarkers[w.id] = m;
    m.on('click', () => {
      document.querySelectorAll('.sidebar-panel-item').forEach(el=>el.classList.remove('active'));
      document.getElementById('warga-item-'+w.id)?.classList.add('active');
      document.getElementById('warga-item-'+w.id)?.scrollIntoView({behavior:'smooth',block:'nearest'});
    });
  });
});
</script>
