/**
 * @fileOverview GeneralModal.js
 * @description General modal window, this modal window is used to show a message and ask for confirmation. In order to use it, you must include GeneralModal.ascx in the page.
 * @constructor
 */
const GeneralModal = function () {
    let generalModal;
    let dangerModal;

    function isElementVisible(elementId) {
        const element = document.getElementById(elementId);
        const style = window.getComputedStyle(element);
        if (style.display === 'none') return false;
        if (style.visibility !== 'visible') return false;
        return element.offsetWidth > 0 || element.offsetHeight > 0;
    }

    function initializeModal(modalId, modalReference) {
        const htmlElement = document.getElementById(modalId);
        return modalReference || new bootstrap.Modal(htmlElement, {
            keyboard: false,
            backdrop: 'static'
        });
    }

    function setupModal(
        modalId,
        title,
        message,
        cancelButtonText,
        okButtonText,
        action,
        showCancelButton = false,
        onShownAction = null,
        onHiddenAction = null,
        showModal = true
    ) {
        const htmlElement = document.getElementById(modalId);

        const modal = modalId === 'generalModal'
            ? (generalModal = initializeModal(modalId, generalModal))
            : (dangerModal = initializeModal(modalId, dangerModal));

        htmlElement.addEventListener('shown.bs.modal', function () {
            document.activeElement?.blur();
            
            onShownAction?.call();
            
            // Create a h5 and replace the title
            const titleElement = document.createElement('h5');
            titleElement.innerHTML = title;
            titleElement.classList.add('modal-title')
            
            const currentTitle = document.querySelector(`#${modalId} .modal-title`);
            
            if (currentTitle) {
                currentTitle.parentNode.replaceChild(titleElement, currentTitle);
            }           
            
            document.querySelector(`#${modalId} .modal-body`).innerHTML = message;
            document.querySelector(`#${modalId} [data-purpose="CancelBtn"]`).innerHTML = cancelButtonText;
            document.querySelector(`#${modalId} [data-purpose="CancelBtn"]`).style.display = showCancelButton ? 'block' : 'none';
            document.querySelector(`#${modalId} [data-purpose="OkBtn"]`).innerHTML = okButtonText;
            document.querySelector(`#${modalId} [data-purpose="OkBtn"]`).style.display = 'block';

            replaceAndAttachEventListener(`#${modalId} [data-purpose="OkBtn"]`, 'click', function () {
                modal?.hide();
                action?.call();
            });
        }, {once: false});

        if (showModal) modal.show();
        
        if (onHiddenAction) {
            htmlElement.addEventListener('hidden.bs.modal', onHiddenAction, {once: false});
        }
        
        return modal;
    }

    function replaceAndAttachEventListener(selector, event, handler) {
        const originalElement = document.querySelector(selector);
        if (!originalElement) return;

        const clonedElement = originalElement.cloneNode(true);
        originalElement.parentNode.replaceChild(clonedElement, originalElement);
        clonedElement.addEventListener(event, handler, {once: true});
    }

    function createConfirmWindow(title, message, cancelButtonText, okButtonText, action) {
        setupModal('generalModal', title, message, cancelButtonText, okButtonText, action, true);
    }
    
    function createAutoLogoutWindow(title, message, cancelButtonText, okButtonText, action, onShownAction, onHiddenAction) {
        return setupModal('autoLogoutModal',
            title,
            message,
            cancelButtonText,
            okButtonText,
            action,
            true,
            onShownAction,
            onHiddenAction,
            false
        );
    }

    function createErrorWindow(title, message, callback, showCancelButton = false) {
        setupModal(
            'dangerModal',
            title || 'Error',
            message || 'An error has occurred',
            'Close',
            'OK',
            callback,
            showCancelButton
        );
    }

    return {
        createConfirmWindow: createConfirmWindow,
        createErrorWindow: createErrorWindow,
        createAutoLogoutWindow: createAutoLogoutWindow,
        isErrorWindowOpened: () => isElementVisible('dangerModal'),
        isConfirmWindowOpened: () => isElementVisible('generalModal')
    };
};
