<script>
const gxDialogOverlay = document.getElementById("gx-dialog-overlay");
const gxDialog = document.getElementById("gx-dialog");
const gxDialogTitle = gxDialog.querySelector(".gx-dialog-title");
const gxDialogBody = gxDialog.querySelector(".gx-dialog-body");
const gxDialogConfirm = document.getElementById("gx-dialog-confirm");

let gxDialogCallback = null;

/* ---- OPEN ---- */
function openDialog(title, body, onConfirm = null) {
    gxDialogTitle.textContent = title;
    gxDialogBody.innerHTML = body;
    gxDialogCallback = onConfirm;

    gxDialog.classList.add("show");
    gxDialogOverlay.classList.add("show");

    // Move focus to dialog for a11y
    setTimeout(() => gxDialog.focus(), 10);
}

/* ---- CLOSE ---- */
function closeDialog() {
    gxDialog.classList.remove("show");
    gxDialogOverlay.classList.remove("show");
    gxDialogCallback = null;
}

/* ---- Confirm ---- */
gxDialogConfirm.addEventListener("click", () => {
    if (gxDialogCallback) gxDialogCallback();
    closeDialog();
});

/* ---- Buttons with data-dialog-close ---- */
document.querySelectorAll("[data-dialog-close]").forEach(btn =>
    btn.addEventListener("click", closeDialog)
);

/* ---- Click outside ---- */
gxDialogOverlay.addEventListener("click", closeDialog);

/* ---- ESC ---- */
document.addEventListener("keydown", e => {
    if (e.key === "Escape") closeDialog();
});
</script>
