// 모달 — 단일 인스턴스
const backdrop = () => document.getElementById('modal-backdrop');
const content = () => document.getElementById('modal-content');

let onCloseCb = null;

export function initModal() {
  const bd = backdrop();
  if (!bd) return;
  bd.addEventListener('click', (e) => {
    if (e.target === bd) closeModal();
  });
  document.addEventListener('click', (e) => {
    if (e.target.matches('[data-modal-close]') || e.target.closest('[data-modal-close]')) {
      closeModal();
    }
  });
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') closeModal();
  });
}

export function openModal(html, opts = {}) {
  const bd = backdrop();
  content().innerHTML = html;
  bd.classList.toggle('is-urgent', !!opts.urgent);
  bd.classList.add('is-open');
  onCloseCb = opts.onClose || null;
}

export function closeModal() {
  const bd = backdrop();
  bd.classList.remove('is-open', 'is-urgent');
  if (onCloseCb) { try { onCloseCb(); } catch(_){} onCloseCb = null; }
}

export function escapeHtml(str) {
  return String(str ?? '').replace(/[&<>"']/g, m => ({
    '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
  }[m]));
}
