let initialized = false;

export function initModalSystem() {
    if (!initialized) {
        document.addEventListener('click', handleDocumentClick);
        document.addEventListener('keydown', handleKeydown);
        initialized = true;
    }
}

function handleDocumentClick(event: MouseEvent) {
    if (!(event.target instanceof HTMLElement)) {
        return;
    }

    const target = event.target as HTMLElement;

    const modalToOpen = getModalToOpen(target);
    if (modalToOpen) {
        openModal(modalToOpen);
        return;
    }

    const modalToClose = getModalToClose(target);
    if (modalToClose) {
        closeModal(modalToClose);
    }
}

function getModalToOpen(target: HTMLElement): HTMLElement | null {
    const trigger = target.closest('[data-modal-open]') as HTMLElement | null;
    if (!trigger) return null;

    const id = trigger.dataset.modalOpen;
    if (!id) return null;

    return document.getElementById(id);
}

function openModal(modal: HTMLElement) {
    modal.classList.remove('hidden');
    modal.classList.add('flex');
    document.body.classList.add('overflow-hidden');
}

function getModalToClose(target: HTMLElement): HTMLElement | null {
    // Close button
    const closeTrigger = target.closest('[data-modal-close]');
    if (closeTrigger) {
        return closeTrigger.closest('.modal') as HTMLElement | null;
    }

    // Backdrop click
    const backdrop = target.closest('.modal');
    if (
        backdrop &&
        backdrop.classList.contains('flex') &&
        target === backdrop // ensures we only close when clicking backdrop itself
    ) {
        return backdrop as HTMLElement;
    }

    return null;
}

function closeModal(modal: HTMLElement) {
    modal.classList.add('hidden');
    modal.classList.remove('flex');
    document.body.classList.remove('overflow-hidden');
}

function handleKeydown(event: KeyboardEvent) {
    if (event.key !== 'Escape') return;

    const modal = getOpenModal();
    if (modal) {
        closeModal(modal);
    }
}

function getOpenModal(): HTMLElement | null {
    const openModals = document.querySelectorAll('.modal.flex');
    return openModals.length
        ? (openModals[openModals.length - 1] as HTMLElement)
        : null;
}