// Global notification function using Bootstrap toasts
// Escape HTML to prevent XSS in dynamic content
function escapeHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

window.showNotification = function(type, message) {

    // Define notification types
    var types = {
        'success': { bgClass: 'bg-success', iconClass: 'ri-check-line' },
        'error': { bgClass: 'bg-danger', iconClass: 'ri-close-line' },
        'warning': { bgClass: 'bg-warning', iconClass: 'ri-alert-line' },
        'info': { bgClass: 'bg-info', iconClass: 'ri-information-line' }
    };

    // Default to error if type not recognized
    var notificationType = types[type] || types['error'];
    var bgClass = notificationType.bgClass;
    var iconClass = notificationType.iconClass;

    var toastHtml = '<div class="toast align-items-center text-white ' + bgClass + ' border-0" role="alert" aria-live="assertive" aria-atomic="true">' +
        '<div class="d-flex">' +
        '<div class="toast-body">' +
        '<i class="' + iconClass + ' me-2"></i>' + escapeHtml(message) +
        '</div>' +
        '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>' +
        '</div>' +
        '</div>';
    
    // Create toast container if it doesn't exist
    var toastContainer = document.getElementById('toast-container-global');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container-global';
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    // Add toast to container
    var toastElement = document.createElement('div');
    toastElement.innerHTML = toastHtml;
    toastContainer.appendChild(toastElement);
    
    // Initialize and show toast
    var toast = new bootstrap.Toast(toastElement.firstChild, {
        autohide: true,
        delay: 3000
    });
    toast.show();
    
    // Remove element after it's hidden
    toastElement.firstChild.addEventListener('hidden.bs.toast', function() {
        toastElement.remove();
    });
};

$(document).ready(function () {
    var modal_id = 'myModal';
    
    // Prevent Enter key from submitting forms in modals (except in textareas)
    $(document).on('keypress', '.modal form input:not([type="submit"]):not([type="button"]), .modal form select', function(e) {
        if (e.which === 13) { // Enter key
            e.preventDefault();
            
            // Find the next input field and focus on it
            var inputs = $(this).closest('form').find(':input:visible:not([type="submit"]):not([type="button"]):not([readonly]):not([disabled])');
            var currentIndex = inputs.index(this);
            
            if (currentIndex < inputs.length - 1) {
                // Focus on next input
                inputs.eq(currentIndex + 1).focus();
            }
            
            return false;
        }
    });
    
    // Also prevent Enter in Select2 search boxes within modals
    $(document).on('keypress', '.modal .select2-search__field', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    });
    
    function initializeModalButton() {
        $(document).on('click', '.modal-btn', function (e) {
            e.preventDefault();
            var dot = '<div class="spinner-border text-info" role="status"><span class="sr-only">'+translations.loadingText+'</span></div>';
            var loader = '<div class="text-center">' + dot + '</div>';
            var url = $(this).data('modal-url');
            var title = $(this).data('modal-title');
            var size = $(this).data('modal-size') || 'modal-lg';
            
            // Store the active security group tab if on firewall management page
            var activeSecurityTab = $('.security-group-tab.active');
            if (activeSecurityTab.length > 0) {
                var securityGroupId = activeSecurityTab.attr('data-security-group-id');
                if (securityGroupId) {
                    sessionStorage.setItem('activeSecurityGroupId', securityGroupId);
                }
            }

            // Set initial loading state
            $('#' + modal_id).find('.modal-title').html(translations.loadingText);
            $('#' + modal_id).find('.modal-body').html(loader);
            
            // Remove any existing size classes and add the new one
            var $modalDialog = $("#" + modal_id).find('.modal-dialog');
            $modalDialog.removeClass('modal-sm modal-lg modal-xl modal-fullscreen');
            $modalDialog.addClass(size);

            // Load content via AJAX with handling for redirect response
            $.ajax({
                type: 'GET',
                url: url,
                success: function (data) {
                    // Check if the response is a redirect
                    if (data.redirect) {
                        window.location.href = data.redirect;
                    } else {
                        // Populate modal with response data if not a redirect
                        $('#' + modal_id).find('.modal-body').html(data);
                        $('#' + modal_id).find('.modal-title').html(title);
                    }
                },
                error: function () {
                    $('#' + modal_id).find('.modal-body').html('<p>'+translations.errorLoadingContent+'</p>');
                    $('#' + modal_id).find('.modal-title').html('Error');
                }
            });

            // Show the modal
            $('#' + modal_id).modal('show');
        });
    }

    initializeModalButton();

    var hash = window.location.hash.substring(1);

    // Target the <a> element with data-modal-url matching the hash value
    // Validate hash to prevent selector injection (only allow safe URL characters)
    if (hash && /^[a-zA-Z0-9\/_\-\.%=&\?]+$/.test(hash)) {
        var targetElement = $('a[data-modal-url="' + hash + '"]');

        // Trigger the click event if the target element exists
        if (targetElement.length) {
            targetElement.trigger('click');
        }
    }

    // Handle modal close event
    $('#' + modal_id).on('hidden.bs.modal', function () {
        var currentURL = window.location.href;
        var parts = currentURL.split('#');

        if (parts.length > 1) {
            var orig_url = parts[0];
            window.history.replaceState(null, null, orig_url);
        }
        
        // Reset modal to original state
        var modalContent = '<div class="modal-header">' +
            '<h5 class="modal-title">' + translations.loadingText + '</h5>' +
            '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>' +
            '</div>' +
            '<div class="modal-body">' + translations.loadingText + '</div>';
        $('#' + modal_id).find('.modal-content').html(modalContent);
        
        // Remove any extra classes that might have been added
        $('#' + modal_id).find('.modal-dialog').removeClass('modal-xl modal-lg modal-sm  modal-fullscreen');
        
        $('#' + modal_id).modal('hide');
    });

    // Override Yii confirm function with SweetAlert
    yii.confirm = function (message, okCallback, cancelCallback) {
        Swal.fire({
            title: translations.areYouSureText,
            text: message,
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: translations.yesText,
            cancelButtonText: translations.cancelText
        }).then((result) => {
            if (result.isConfirmed) {
                okCallback();
            }
        });
    };

    // =========================================================================
    // Global Submit Guard — prevents double form submissions & duplicate AJAX
    // requests caused by rapid button clicks (fixes SQL Error 1205 lock waits)
    // =========================================================================
    var SubmitGuard = {
        TIMEOUT_MS: 10000,

        // Returns true to allow submission, false to block it
        guard: function ($btn) {
            if (!$btn.length || $btn.closest('[data-no-submit-guard]').length || $btn.is('[data-no-submit-guard]')) {
                return false;
            }
            if ($btn.data('submit-guarded')) {
                return true; // already guarded — caller should block
            }

            $btn.data('submit-guarded', true);
            $btn.addClass('disabled');
            $btn.css('pointer-events', 'none');

            if ($btn.text().trim().length > 0) {
                $btn.prepend('<span class="spinner-border spinner-border-sm me-1 submit-guard-spinner" role="status" aria-hidden="true"></span>');
            }

            var timeoutId = setTimeout(function () {
                SubmitGuard.release($btn);
            }, SubmitGuard.TIMEOUT_MS);
            $btn.data('submit-guard-timeout', timeoutId);

            return false; // first guard — caller should allow
        },

        release: function ($btn) {
            if (!$btn.length || !$btn.data('submit-guarded')) {
                return;
            }

            clearTimeout($btn.data('submit-guard-timeout'));
            $btn.find('.submit-guard-spinner').remove();
            $btn.prop('disabled', false);
            $btn.removeClass('disabled');
            $btn.css('pointer-events', '');
            $btn.removeData('submit-guarded submit-guard-timeout');
        },

        releaseAll: function ($container) {
            // release() no-ops on non-guarded buttons, so scanning all is safe
            $container.find('button, input[type="submit"], a.btn').each(function () {
                SubmitGuard.release($(this));
            });
        }
    };

    // Guard on submit button click
    // First click: guard() returns false → allow click through (form validates & submits)
    // Second click: guard() returns true → block click entirely
    // Uses CSS 'pointer-events: none' + 'disabled' class instead of prop('disabled')
    // so the button LOOKS disabled but doesn't break form serialization
    $(document).on('click', 'button[type="submit"], input[type="submit"]', function (e) {
        var blocked = SubmitGuard.guard($(this));
        if (blocked) {
            e.preventDefault();
            e.stopImmediatePropagation();
            return false;
        }
    });

    // Release on Pjax completion or error
    $(document).on('pjax:complete pjax:error', function (e) {
        SubmitGuard.releaseAll($(e.target));
    });

    // Release all guarded buttons inside modals when modal closes
    $('#' + modal_id).on('hidden.bs.modal', function () {
        SubmitGuard.releaseAll($(this));
    });
});
