import { Alpine } from "./alpine";

let escapeHandler: ((e: KeyboardEvent) => void) | null = null;

function closeProfileModal(): void {
  const modal = document.getElementById("profile-modal");
  if (modal) {
    modal.remove();
  }
  // Remove escape key listener when modal closes
  if (escapeHandler) {
    document.removeEventListener("keydown", escapeHandler);
    escapeHandler = null;
  }
}

function setupProfileModal(): void {
  // Set up escape key listener to close modal
  escapeHandler = (e: KeyboardEvent) => {
    if (e.key === "Escape") {
      closeProfileModal();
    }
  };
  document.addEventListener("keydown", escapeHandler);
}

export { closeProfileModal, setupProfileModal };

Alpine.data("profileModal", () => ({
  closeProfileModal,
  setupProfileModal,
}));
