<?php $umur = $warga['tanggal_lahir'] ? hitungUmur($warga['tanggal_lahir']) : 0; ?>
<?php ob_start(); ?>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const lat = <?= (float)$warga['lat'] ?>;
  const lng = <?= (float)$warga['lng'] ?>;
  if (lat && lng) {
    const map = L.map('warga-detail-map').setView([lat,lng],16);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19}).addTo(map);
    const color = '<?= warnaMiskin($warga['status_kemiskinan']) ?>';
    L.circleMarker([lat,lng],{radius:12,fillColor:color,color:'#fff',weight:3,fillOpacity:0.9})
     .bindPopup('<strong><?= addslashes($warga['nama']) ?></strong>').addTo(map).openPopup();
    <?php if($warga['ri_lat'] && $warga['ri_lng']): ?>
    GISMap.map = map;
    GISMap.createRIMarker({lat:<?= (float)$warga['ri_lat'] ?>,lng:<?= (float)$warga['ri_lng'] ?>})
      .bindPopup('<?= addslashes($warga['rumah_ibadah_nama']??'Rumah Ibadah') ?>').addTo(map);
    <?php endif; ?>
  }
});
</script>
<?php $extraJs = ob_get_clean(); ?>

<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
  <a href="<?= APP_URL ?>/verifikator/warga" class="btn btn-ghost btn-sm">← Kembali</a>
  <h2 style="font-size:1.1rem;font-weight:700"><?= e($warga['nama']) ?></h2>
  <?php $sc=['Miskin Ekstrem'=>'badge-red','Miskin'=>'badge-orange','Rentan Miskin'=>'badge-yellow']; ?>
  <span class="badge <?= $sc[$warga['status_kemiskinan']]??'badge-gray' ?>"><?= e($warga['status_kemiskinan']) ?></span>
  <?php if($warga['is_blind_spot']): ?><span class="badge badge-purple">⚠ Blind Spot</span><?php endif; ?>
  <div style="margin-left:auto;display:flex;gap:8px">
    <button class="btn btn-primary btn-sm" onclick="App.showModal('modal-edit')">✏️ Edit Data</button>
  </div>
</div>

<div style="display:grid;grid-template-columns:1fr 340px;gap:20px">
  <!-- KIRI -->
  <div style="display:flex;flex-direction:column;gap:16px">

    <!-- Skor Prioritas Card -->
    <div class="card" style="border-left:4px solid <?= ['Tinggi'=>'#dc2626','Sedang'=>'#d97706','Rendah'=>'#16a34a'][$warga['level_prioritas']]??'#6b7280' ?>">
      <div class="card-body">
        <div style="display:flex;align-items:center;gap:20px">
          <div style="text-align:center;min-width:90px">
            <div style="font-size:2.5rem;font-weight:900;color:<?= ['Tinggi'=>'#dc2626','Sedang'=>'#d97706','Rendah'=>'#16a34a'][$warga['level_prioritas']]??'#6b7280' ?>"><?= $warga['skor_prioritas'] ?></div>
            <div class="text-xs text-muted">Skor / 100</div>
          </div>
          <div style="flex:1">
            <div class="priority-bar" style="height:10px;margin-bottom:8px">
              <div class="priority-bar-fill <?= strtolower($warga['level_prioritas'])==='tinggi'?'high':(strtolower($warga['level_prioritas'])==='sedang'?'medium':'low') ?>"
                   style="width:<?= min(100,$warga['skor_prioritas']) ?>%"></div>
            </div>
            <div style="font-size:1rem;font-weight:700">Prioritas <?= e($warga['level_prioritas']) ?></div>
            <div class="text-sm text-muted">Diperbarui otomatis berdasarkan data sosial ekonomi</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Data Pribadi -->
    <div class="card">
      <div class="card-header"><span class="card-icon">👤</span><h3>Data Pribadi</h3></div>
      <div class="card-body">
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px">
          <?php $items = [
            ['NIK', $warga['nik']??'—'],
            ['Tempat Lahir', $warga['tempat_lahir']??'—'],
            ['Tanggal Lahir', $warga['tanggal_lahir'] ? formatTanggal($warga['tanggal_lahir'])." ($umur thn)" : '—'],
            ['Jenis Kelamin', $warga['jenis_kelamin']==='L'?'Laki-laki':'Perempuan'],
            ['Agama', $warga['agama']??'—'],
            ['No HP', $warga['no_hp']??'—'],
          ]; foreach($items as [$l,$v]): ?>
          <div>
            <div class="text-xs text-muted"><?= $l ?></div>
            <div style="font-weight:500;font-size:0.875rem;margin-top:2px"><?= e($v) ?></div>
          </div>
          <?php endforeach; ?>
        </div>
        <hr class="divider">
        <div>
          <div class="text-xs text-muted">Alamat</div>
          <div style="font-weight:500;margin-top:2px"><?= e($warga['alamat']) ?></div>
          <div class="text-xs text-muted" style="margin-top:2px"><?= e($warga['kelurahan']) ?>, <?= e($warga['kecamatan']) ?></div>
        </div>
        <?php if($warga['foto']): ?>
        <hr class="divider">
        <img src="<?= uploadUrl($warga['foto']) ?>" style="width:100px;height:100px;object-fit:cover;border-radius:8px;border:1px solid var(--clr-border)">
        <?php endif; ?>
      </div>
    </div>

    <!-- Sosial Ekonomi -->
    <div class="card">
      <div class="card-header"><span class="card-icon">💼</span><h3>Data Sosial Ekonomi</h3></div>
      <div class="card-body">
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px">
          <?php $items2 = [
            ['Pendidikan', $warga['pendidikan_terakhir']??'—'],
            ['Pekerjaan', $warga['pekerjaan']??'—'],
            ['Penghasilan', formatRupiah($warga['penghasilan_bulanan']??0).'/bln'],
            ['Tanggungan', ($warga['jumlah_tanggungan']??0).' orang'],
            ['Kondisi Rumah', $warga['kondisi_rumah']??'—'],
            ['Riwayat Penyakit', $warga['riwayat_penyakit']??'—'],
          ]; foreach($items2 as [$l,$v]): ?>
          <div>
            <div class="text-xs text-muted"><?= $l ?></div>
            <div style="font-weight:500;font-size:0.875rem;margin-top:2px"><?= e($v) ?></div>
          </div>
          <?php endforeach; ?>
        </div>
        <hr class="divider">
        <div style="display:flex;gap:12px;flex-wrap:wrap">
          <?php if($warga['is_lansia']): ?>
          <span class="badge badge-orange" style="font-size:0.8rem;padding:4px 10px">👴 Lansia</span>
          <?php endif; ?>
          <?php if($warga['is_disabilitas']): ?>
          <span class="badge badge-blue" style="font-size:0.8rem;padding:4px 10px">♿ Disabilitas: <?= e($warga['disabilitas_jenis']??'') ?></span>
          <?php endif; ?>
          <?php if($warga['is_blind_spot']): ?>
          <span class="badge badge-purple" style="font-size:0.8rem;padding:4px 10px">⚠ Blind Spot</span>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <!-- Histori Bantuan -->
    <div class="card">
      <div class="card-header"><span class="card-icon">📦</span><h3>Histori Bantuan (<?= count($bantuan) ?>)</h3></div>
      <div class="card-body no-pad">
        <?php if($bantuan): ?>
        <div class="table-wrap">
          <table>
            <thead><tr><th>Tanggal</th><th>Kategori</th><th>Jumlah</th><th>Rumah Ibadah</th></tr></thead>
            <tbody>
              <?php foreach($bantuan as $b): ?>
              <tr>
                <td class="text-sm"><?= formatTanggal($b['tanggal_penyaluran']) ?></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"><?= e($b['rumah_ibadah']) ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php else: ?>
        <div class="empty-state" style="padding:24px"><div class="empty-state-icon">📭</div><p>Belum ada bantuan</p></div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- KANAN: Peta + RI Info -->
  <div style="display:flex;flex-direction:column;gap:16px">
    <div class="card">
      <div class="card-header"><span class="card-icon">📍</span><h3>Lokasi</h3></div>
      <div class="card-body no-pad">
        <div id="warga-detail-map" style="height:260px"></div>
      </div>
      <div class="card-body">
        <div class="text-xs text-muted">Koordinat</div>
        <div style="font-family:monospace;font-size:0.8rem"><?= $warga['lat'] ?>, <?= $warga['lng'] ?></div>
      </div>
    </div>

    <?php if($warga['rumah_ibadah_nama']): ?>
    <div class="card" style="border:1px solid #bbf7d0">
      <div class="card-header" style="background:#f0fdf4">
        <span class="card-icon">⛪</span><h3>Rumah Ibadah Penanggung Jawab</h3>
      </div>
      <div class="card-body">
        <div style="font-weight:700;font-size:1rem;color:var(--clr-success)"><?= e($warga['rumah_ibadah_nama']) ?></div>
        <div class="text-sm text-muted" style="margin-top:4px">Ditetapkan otomatis berdasarkan Haversine Formula</div>
      </div>
    </div>
    <?php endif; ?>

    <div class="card">
      <div class="card-header"><span class="card-icon">ℹ️</span><h3>Info Verifikasi</h3></div>
      <div class="card-body">
        <div class="text-xs text-muted">Tanggal Verifikasi</div>
        <div class="text-sm"><?= $warga['tanggal_verifikasi'] ? formatTanggal($warga['tanggal_verifikasi']) : '—' ?></div>
      </div>
    </div>
  </div>
</div>

<!-- MODAL EDIT (sederhana) -->
<div class="modal-overlay" id="modal-edit">
  <div class="modal" style="max-width:680px">
    <div class="modal-header">
      <h3>✏️ Edit Data Warga</h3>
      <button class="modal-close" onclick="App.hideModal('modal-edit')">✕</button>
    </div>
    <form method="POST" action="<?= APP_URL ?>/verifikator/warga/<?= $warga['id'] ?>/update" enctype="multipart/form-data">
      <?= csrfField() ?>
      <div class="modal-body">
        <div class="form-row cols-2">
          <div class="form-group"><label class="form-label">Nama <span class="required">*</span></label>
            <input type="text" name="nama" class="form-control" value="<?= e($warga['nama']) ?>" required></div>
          <div class="form-group"><label class="form-label">NIK</label>
            <input type="text" name="nik" class="form-control" value="<?= e($warga['nik']??'') ?>" maxlength="16"></div>
        </div>
        <div class="form-row cols-2">
          <div class="form-group"><label class="form-label">Tempat Lahir</label>
            <input type="text" name="tempat_lahir" class="form-control" value="<?= e($warga['tempat_lahir']??'') ?>"></div>
          <div class="form-group"><label class="form-label">Tgl Lahir</label>
            <input type="date" name="tanggal_lahir" class="form-control" value="<?= $warga['tanggal_lahir']??'' ?>"></div>
        </div>
        <div class="form-row cols-3">
          <div class="form-group"><label class="form-label">JK</label>
            <select name="jenis_kelamin" class="form-control">
              <option value="L" <?= $warga['jenis_kelamin']==='L'?'selected':'' ?>>Laki-laki</option>
              <option value="P" <?= $warga['jenis_kelamin']==='P'?'selected':'' ?>>Perempuan</option>
            </select></div>
          <div class="form-group"><label class="form-label">Agama</label>
            <select name="agama" class="form-control">
              <?php foreach(['Islam','Kristen','Katolik','Hindu','Buddha','Konghucu','Lainnya'] as $ag): ?>
              <option value="<?= $ag ?>" <?= ($warga['agama']??'')===$ag?'selected':'' ?>><?= $ag ?></option>
              <?php endforeach; ?>
            </select></div>
          <div class="form-group"><label class="form-label">No HP</label>
            <input type="text" name="no_hp" class="form-control" value="<?= e($warga['no_hp']??'') ?>"></div>
        </div>
        <div class="form-group"><label class="form-label">Alamat</label>
          <input type="text" name="alamat" class="form-control" value="<?= e($warga['alamat']) ?>"></div>
        <div class="form-row cols-2">
          <div class="form-group"><label class="form-label">Penghasilan/Bln</label>
            <input type="number" name="penghasilan_bulanan" class="form-control" value="<?= $warga['penghasilan_bulanan']??0 ?>"></div>
          <div class="form-group"><label class="form-label">Tanggungan</label>
            <input type="number" name="jumlah_tanggungan" class="form-control" value="<?= $warga['jumlah_tanggungan']??0 ?>"></div>
        </div>
        <div class="form-row cols-2">
          <div class="form-group"><label class="form-label">Pendidikan</label>
            <select name="pendidikan_terakhir" class="form-control">
              <?php foreach(['Tidak Sekolah','SD','SMP','SMA','D3','S1','S2','S3'] as $p): ?>
              <option value="<?= $p ?>" <?= $warga['pendidikan_terakhir']===$p?'selected':'' ?>><?= $p ?></option>
              <?php endforeach; ?>
            </select></div>
          <div class="form-group"><label class="form-label">Pekerjaan</label>
            <input type="text" name="pekerjaan" class="form-control" value="<?= e($warga['pekerjaan']??'') ?>" placeholder="Buruh, Petani, dll"></div>
        </div>
        <div class="form-row cols-2">
          <div class="form-group"><label class="form-label">Kondisi Rumah</label>
            <select name="kondisi_rumah" class="form-control">
              <?php foreach(['Sangat Tidak Layak','Tidak Layak','Cukup Layak','Layak'] as $k): ?>
              <option value="<?= $k ?>" <?= $warga['kondisi_rumah']===$k?'selected':'' ?>><?= $k ?></option>
              <?php endforeach; ?>
            </select></div>
        </div>
        <div class="form-group"><label class="form-label">Riwayat Penyakit</label>
          <input type="text" name="riwayat_penyakit" class="form-control" value="<?= e($warga['riwayat_penyakit']??'') ?>"></div>
        <div style="display:flex;gap:20px">
          <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
            <input type="checkbox" name="is_lansia" value="1" <?= $warga['is_lansia']?'checked':'' ?>> Lansia</label>
          <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
            <input type="checkbox" name="is_disabilitas" id="edit-is-dis" value="1" <?= $warga['is_disabilitas']?'checked':'' ?>
              onchange="document.getElementById('edit-jenis-dis').style.display=this.checked?'block':'none'"> Disabilitas</label>
        </div>
        <div id="edit-jenis-dis" style="margin-top:10px;<?= $warga['is_disabilitas']?'':'display:none' ?>">
          <div class="form-group"><label class="form-label">Jenis Disabilitas</label>
            <input type="text" name="disabilitas_jenis" class="form-control" value="<?= e($warga['disabilitas_jenis']??'') ?>" placeholder="Tuna netra, tuna daksa, dll"></div>
        </div>
        <div class="form-row cols-2" style="margin-top:12px">
          <div class="form-group"><label class="form-label">Latitude</label>
            <input type="number" name="lat" class="form-control" value="<?= $warga['lat'] ?>" step="0.0000001"></div>
          <div class="form-group"><label class="form-label">Longitude</label>
            <input type="number" name="lng" class="form-control" value="<?= $warga['lng'] ?>" step="0.0000001"></div>
        </div>
        <div class="form-group"><label class="form-label">Foto Baru</label>
          <input type="file" name="foto" class="form-control" accept="image/*"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="App.hideModal('modal-edit')">Batal</button>
        <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
      </div>
    </form>
  </div>
</div>