document.addEventListener('click', function (e) {
  const btn = e.target.closest('.ap-item-btn');
  const dlg = document.getElementById('apModal');

  // close
  if (e.target.closest('[data-ap-close]')) {
    if (dlg && dlg.open) dlg.close();
    return;
  }

  if (!btn || !dlg) return;

  const title = btn.getAttribute('data-ap-title') || 'Agenda Pimpinan';
  const date  = btn.getAttribute('data-ap-date') || '-';
  const loc   = btn.getAttribute('data-ap-location') || '-';
  const type  = btn.getAttribute('data-ap-type') || '-';

  document.getElementById('apModalTitle').textContent = title;
  document.getElementById('apModalDate').textContent = date;
  document.getElementById('apModalLocation').textContent = loc;
  document.getElementById('apModalType').textContent = type;

  if (typeof dlg.showModal === 'function') {
    dlg.showModal();
  } else {
    // fallback (browser lama): buka sebagai blok biasa
    dlg.setAttribute('open', 'open');
  }
});

// klik backdrop close (untuk <dialog>)
document.addEventListener('click', function (e) {
  const dlg = document.getElementById('apModal');
  if (!dlg || !dlg.open) return;

  // Jika yang diklik adalah tombol buka/edit, jangan jalankan logika tutup ini
  if (e.target.closest('.ap-item-btn')) return;

  const rect = dlg.getBoundingClientRect();
  const inDialog =
    rect.top <= e.clientY && e.clientY <= rect.bottom &&
    rect.left <= e.clientX && e.clientX <= rect.right;

  if (!inDialog) dlg.close();
});
