/**
 * RSL Alert System
 *
 * ADA-compliant alert, confirm, and prompt dialogs with focus trapping,
 * scroll locking, and keyboard navigation support.
 *
 * @fileoverview Modal alert system with accessibility features
 * @version 2.0.0
 * @license MIT
 *
 * Key Features:
 * - Three dialog types: alert, confirm, prompt
 * - Full keyboard navigation and focus trapping
 * - Scroll locking when dialogs are open
 * - ARIA attributes for screen readers
 * - Email validation for prompt dialogs
 * - Data attribute triggers for declarative usage
 * - Promise-based API for async/await support
 * - Customizable animations and positioning
 *
 * Usage:
 * // Simple alert
 * rslAlert('Hello World!');
 *
 * // Confirm dialog
 * const confirmed = await rslConfirm('Are you sure?');
 *
 * // Prompt with validation
 * const email = await rslPrompt({
 *   title: 'Email',
 *   message: 'Enter your email:',
 *   inputType: 'email',
 *   required: true
 * });
 *
 * // Data attribute usage
 * <button data-rsl-alert="Hello!" data-rsl-alert-type="success">Show Alert</button>
 *
 * Public API:
 * - window.rslAlert(options) - Show alert dialog
 * - window.rslConfirm(options) - Show confirmation dialog
 * - window.rslPrompt(options) - Show input prompt dialog
 */

(function() {
    'use strict';

    // ==========================================
    // CONFIGURATION & STATE
    // ==========================================

    /**
     * Selector for all focusable elements
     * @const {string}
     */
    const FOCUSABLE_SELECTOR =
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

    /**
     * Currently active alert element
     * @type {HTMLElement|null}
     */
    let activeAlert = null;

    /**
     * Array of focusable elements in active alert
     * @type {Array<HTMLElement>}
     */
    let activeFocusables = [];

    /**
     * Stored scroll position for restoration
     * @type {number}
     */
    let scrollPosition = 0;

    // ==========================================
    // SCROLL LOCKING
    // ==========================================

    /**
     * Lock page scrolling
     *
     * Prevents background scrolling while alert is open by saving current
     * scroll position and fixing the body element.
     */
    function lockScroll() {
        scrollPosition =
            window.pageYOffset || document.documentElement.scrollTop;
        document.body.classList.add('scroll-lock');
        document.body.style.top = `-${scrollPosition}px`;
    }

    /**
     * Unlock page scrolling
     *
     * Restores background scrolling and returns to previous scroll position.
     */
    function unlockScroll() {
        document.body.classList.remove('scroll-lock');
        document.body.style.top = '';
        window.scrollTo(0, scrollPosition);
    }

    // ==========================================
    // FOCUS TRAP
    // ==========================================

    /**
     * Handle keyboard events for focus trap
     *
     * Traps Tab/Shift+Tab navigation within the active alert and
     * handles Escape key to close the alert.
     *
     * @param {KeyboardEvent} event - Keyboard event
     */
    function handleFocusTrapKeydown(event) {
        if (!activeAlert) return;

        // Escape closes the alert
        if (event.key === 'Escape') {
            const cancelBtn = activeAlert.querySelector(
                '.alert-cancel, .alert-close, .alert-ok'
            );
            if (cancelBtn) {
                cancelBtn.click();
            }
            return;
        }

        if (event.key !== 'Tab') return;

        const focusables =
            activeFocusables && activeFocusables.length
                ? activeFocusables
                : Array.from(
                      activeAlert.querySelectorAll(FOCUSABLE_SELECTOR)
                  );

        if (!focusables.length) return;

        const first = focusables[0];
        const last = focusables[focusables.length - 1];

        // If focus somehow left the alert, pull it back in
        if (!activeAlert.contains(document.activeElement)) {
            first.focus();
            event.preventDefault();
            return;
        }

        if (event.shiftKey) {
            // SHIFT + TAB: loop from first -> last
            if (document.activeElement === first) {
                last.focus();
                event.preventDefault();
            }
        } else {
            // TAB: loop from last -> first
            if (document.activeElement === last) {
                first.focus();
                event.preventDefault();
            }
        }
    }

    /**
     * Activate focus trap for alert dialog
     *
     * Restricts keyboard focus to elements within the alert and
     * sets initial focus to specified element.
     *
     * @param {HTMLElement} alert - Alert element to trap focus within
     * @param {HTMLElement} [initialFocusElement] - Element to focus initially
     */
    function activateFocusTrap(alert, initialFocusElement) {
        activeAlert = alert;
        activeFocusables = Array.from(
            alert.querySelectorAll(FOCUSABLE_SELECTOR)
        );

        // Focus the specified element or first focusable
        const targetFocus = initialFocusElement || activeFocusables[0];
        if (targetFocus) {
            // Small delay to ensure alert is visible
            setTimeout(() => targetFocus.focus(), 50);
        }

        // Add focus trap event listener
        document.addEventListener('keydown', handleFocusTrapKeydown);
    }

    /**
     * Deactivate focus trap
     *
     * Removes keyboard event listener and clears active alert state.
     */
    function deactivateFocusTrap() {
        document.removeEventListener('keydown', handleFocusTrapKeydown);
        activeAlert = null;
        activeFocusables = [];
    }

    // ==========================================
    // OVERLAY MANAGEMENT
    // ==========================================

    /**
     * Create or get the alert overlay element
     *
     * Creates a semi-transparent overlay that appears behind alerts.
     * Reuses existing overlay if already created.
     *
     * @returns {HTMLElement} Overlay element
     */
    function createOverlay() {
        let overlay = document.querySelector('.rsl-alert-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.className = 'rsl-alert-overlay';
            overlay.setAttribute('aria-hidden', 'true');
            overlay.style.cssText =
                'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 999; display: none;';
            document.body.appendChild(overlay);
        }
        return overlay;
    }

    /**
     * Show the overlay
     *
     * Displays the semi-transparent background overlay.
     */
    function showOverlay() {
        const overlay = createOverlay();
        overlay.style.display = 'block';
        overlay.setAttribute('aria-hidden', 'false');
    }

    /**
     * Hide the overlay
     *
     * Hides the background overlay.
     */
    function hideOverlay() {
        const overlay = document.querySelector('.rsl-alert-overlay');
        if (overlay) {
            overlay.style.display = 'none';
            overlay.setAttribute('aria-hidden', 'true');
        }
    }

    // ==========================================
    // FORM VALIDATION INTEGRATION
    // ==========================================

    /**
     * Validate alert input field
     *
     * Validates input based on required attribute and input type.
     * Shows inline error messages for validation failures.
     *
     * @param {HTMLInputElement} input - Input element to validate
     * @returns {boolean} True if validation passes, false otherwise
     */
    function validateAlertInput(input) {
        if (!input) return true;

        const isRequired =
            input.classList.contains('input-required') ||
            input.hasAttribute('required');
        const value = input.value.trim();

        // Check if required and empty
        if (isRequired && !value) {
            input.classList.add('input-error');
            input.setAttribute('aria-invalid', 'true');

            // Add or update error message
            let errorMsg = input.nextElementSibling;
            if (
                !errorMsg ||
                !errorMsg.classList.contains('alert-input-error')
            ) {
                errorMsg = document.createElement('div');
                errorMsg.className = 'alert-input-error';
                errorMsg.setAttribute('role', 'alert');
                errorMsg.style.cssText =
                    'color: #dc3545; font-size: 12px; margin-top: 4px;';
                input.parentNode.insertBefore(errorMsg, input.nextSibling);
            }
            errorMsg.textContent = 'This field is required';
            return false;
        }

        // Email validation if type is email (validate format even if not required, but only if value exists)
        if (input.type === 'email' && value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(value)) {
                input.classList.add('input-error');
                input.setAttribute('aria-invalid', 'true');

                let errorMsg = input.nextElementSibling;
                if (
                    !errorMsg ||
                    !errorMsg.classList.contains('alert-input-error')
                ) {
                    errorMsg = document.createElement('div');
                    errorMsg.className = 'alert-input-error';
                    errorMsg.setAttribute('role', 'alert');
                    errorMsg.style.cssText =
                        'color: #dc3545; font-size: 12px; margin-top: 4px;';
                    input.parentNode.insertBefore(errorMsg, input.nextSibling);
                }
                errorMsg.textContent = 'Please enter a valid email address';
                return false;
            }
        }

        // Clear errors if validation passes
        input.classList.remove('input-error');
        input.setAttribute('aria-invalid', 'false');
        const errorMsg = input.nextElementSibling;
        if (errorMsg && errorMsg.classList.contains('alert-input-error')) {
            errorMsg.remove();
        }

        return true;
    }

    /**
     * Clear validation errors from input
     *
     * Removes error styling and error messages from input field.
     *
     * @param {HTMLInputElement} input - Input element to clear errors from
     */
    function clearValidationErrors(input) {
        if (!input) return;
        input.classList.remove('input-error');
        input.removeAttribute('aria-invalid');
        const errorMsg = input.nextElementSibling;
        if (errorMsg && errorMsg.classList.contains('alert-input-error')) {
            errorMsg.remove();
        }
    }

    // ==========================================
    // ALERT CREATION & CLEANUP
    // ==========================================

    /**
     * Create alert DOM element
     *
     * Builds the HTML structure for alert, confirm, or prompt dialog
     * with proper ARIA attributes and content based on options.
     *
     * @param {Object} options - Alert options
     * @param {string} alertType - Type of alert: 'alert', 'confirm', or 'prompt'
     * @returns {HTMLElement} Created alert element
     */
    function createAlertElement(options, alertType) {
        const alert = document.createElement('div');
        alert.className =
            'alert ' +
            options.animation +
            ' rsl-alert-' +
            options.position +
            ' rsl-alert-' +
            options.type;

        // Add ARIA attributes for accessibility
        const timeStamp = Date.now();
        const titleId = 'alert-title-' + timeStamp;
        const descId = 'alert-desc-' + timeStamp;

        alert.setAttribute(
            'role',
            alertType === 'alert' ? 'alertdialog' : 'dialog'
        );
        alert.setAttribute('aria-modal', 'true');
        alert.setAttribute('aria-labelledby', titleId);
        alert.setAttribute('aria-describedby', descId);

        let html =
            '<h3 class="alert-title" id="' +
            titleId +
            '">' +
            options.title +
            '</h3>' +
            '<p class="alert-text" id="' +
            descId +
            '">' +
            options.message +
            '</p>';

        if (alertType === 'prompt') {
            const inputId = 'alert-input-' + timeStamp;
            html +=
                '<input type="' +
                options.inputType +
                '" ' +
                'id="' +
                inputId +
                '" ' +
                'class="alert-input ' +
                (options.required ? 'input-required' : '') +
                '" ' +
                'placeholder="' +
                options.placeholder +
                '" ' +
                'value="' +
                options.defaultValue +
                '" ' +
                'aria-label="' +
                options.message +
                '" ' +
                (options.required ? 'required aria-required="true"' : '') +
                '>';
        }

        if (alertType === 'alert') {
            html +=
                '<button class="alert-btn alert-ok" aria-label="Close alert">' +
                options.okText +
                '</button>';
        } else {
            html +=
                '<div class="alert-buttons">' +
                '<button class="alert-btn alert-cancel" aria-label="Cancel">' +
                options.cancelText +
                '</button>' +
                '<button class="alert-btn alert-confirm" aria-label="Confirm">' +
                options.confirmText +
                '</button>' +
                '</div>';
        }

        alert.innerHTML = html;
        return alert;
    }

    /**
     * Clean up and close alert
     *
     * Handles cleanup when alert is closed: removes focus trap,
     * unlocks scroll, hides overlay, removes alert element, and
     * restores focus to the element that opened the alert.
     *
     * @param {HTMLElement} alert - Alert element to clean up
     * @param {Function} resolveCallback - Promise resolve function
     * @param {*} value - Value to resolve promise with
     */
    function cleanupAlert(alert, resolveCallback, value) {
        // Element that opened this alert
        const opener = alert._rslOpener || null;

        // Deactivate focus trap and unlock scroll
        deactivateFocusTrap();
        unlockScroll();
        hideOverlay();

        // Remove alert with fade out
        alert.style.opacity = '0';
        alert.style.transition = 'opacity 0.25s';

        setTimeout(function() {
            if (alert.parentNode) {
                alert.remove();
            }

            // Restore focus back to opener if it still exists
            if (opener && typeof opener.focus === 'function' && document.contains(opener)) {
                opener.focus();
            }

            resolveCallback(value);
        }, 250);
    }

    // ==========================================
    // RSL ALERT - Simple Alert Dialog
    // ==========================================

    /**
     * Show simple alert dialog
     *
     * Displays a basic alert with a message and OK button.
     * Returns a promise that resolves when user clicks OK or closes the alert.
     *
     * @param {string|Object} options - Alert message or options object
     * @param {string} [options.title='Alert'] - Alert title
     * @param {string} [options.message] - Alert message
     * @param {string} [options.okText='OK'] - OK button text
     * @param {string} [options.animation='zoom-in'] - Animation: 'zoom-in', 'fade-in', 'slide-down', 'slide-up'
     * @param {string} [options.position='center'] - Position: 'top', 'center', 'bottom'
     * @param {string} [options.type='info'] - Type: 'info', 'success', 'warning', 'error'
     * @returns {Promise<boolean>} Promise that resolves to true when closed
     *
     * @example
     * // Simple usage
     * await rslAlert('Hello World!');
     *
     * @example
     * // With options
     * await rslAlert({
     *   title: 'Success',
     *   message: 'Operation completed!',
     *   type: 'success',
     *   animation: 'slide-down'
     * });
     */
    function rslAlert(options) {
        if (typeof options === 'string') {
            options = { message: options };
        }

        const defaults = {
            title: 'Alert',
            message: 'This is an alert message',
            okText: 'OK',
            animation: 'zoom-in',
            position: 'center',
            type: 'info'
        };

        const settings = Object.assign({}, defaults, options);

        return new Promise(function(resolve) {
            // Capture the element that opened the alert
            const opener = document.activeElement;

            // Lock scroll and show overlay
            lockScroll();
            showOverlay();

            // Create alert element
            const alert = createAlertElement(settings, 'alert');
            alert._rslOpener = opener;
            document.body.appendChild(alert);

            // Show alert
            setTimeout(function() {
                alert.style.display = 'block';
                alert.style.opacity = '1';

                // Activate focus trap (focus OK button)
                const okBtn = alert.querySelector('.alert-ok');
                activateFocusTrap(alert, okBtn);
            }, 10);

            // OK button handler
            const okBtn = alert.querySelector('.alert-ok');
            okBtn.addEventListener('click', function() {
                cleanupAlert(alert, resolve, true);
            });

            // Overlay click handler (close on overlay click)
            const overlay = document.querySelector('.rsl-alert-overlay');
            function overlayHandler() {
                overlay.removeEventListener('click', overlayHandler);
                cleanupAlert(alert, resolve, true);
            }
            overlay.addEventListener('click', overlayHandler);
        });
    }

    // ==========================================
    // RSL CONFIRM - Confirmation Dialog
    // ==========================================

    /**
     * Show confirmation dialog
     *
     * Displays a confirmation dialog with Yes/No buttons.
     * Returns a promise that resolves to true if confirmed, false if cancelled.
     *
     * @param {string|Object} options - Confirmation message or options object
     * @param {string} [options.title='Confirm'] - Dialog title
     * @param {string} [options.message] - Confirmation message
     * @param {string} [options.confirmText='Yes'] - Confirm button text
     * @param {string} [options.cancelText='No'] - Cancel button text
     * @param {string} [options.animation='zoom-in'] - Animation style
     * @param {string} [options.position='center'] - Dialog position
     * @param {string} [options.type='warning'] - Dialog type
     * @returns {Promise<boolean>} Promise that resolves to true/false
     *
     * @example
     * const confirmed = await rslConfirm('Are you sure?');
     * if (confirmed) {
     *   // User clicked Yes
     * }
     *
     * @example
     * const result = await rslConfirm({
     *   title: 'Delete Item',
     *   message: 'This cannot be undone!',
     *   confirmText: 'Delete',
     *   cancelText: 'Cancel',
     *   type: 'error'
     * });
     */
    function rslConfirm(options) {
        if (typeof options === 'string') {
            options = { message: options };
        }

        const defaults = {
            title: 'Confirm',
            message: 'Are you sure?',
            confirmText: 'Yes',
            cancelText: 'No',
            animation: 'zoom-in',
            position: 'center',
            type: 'warning'
        };

        const settings = Object.assign({}, defaults, options);

        return new Promise(function(resolve) {
            // Capture the element that opened the confirm
            const opener = document.activeElement;

            // Lock scroll and show overlay
            lockScroll();
            showOverlay();

            // Create alert element
            const alert = createAlertElement(settings, 'confirm');
            alert._rslOpener = opener;
            document.body.appendChild(alert);

            // Show alert
            setTimeout(function() {
                alert.style.display = 'block';
                alert.style.opacity = '1';

                // Activate focus trap (focus cancel button for safety)
                const cancelBtn = alert.querySelector('.alert-cancel');
                activateFocusTrap(alert, cancelBtn);
            }, 10);

            // Button handlers
            const confirmBtn = alert.querySelector('.alert-confirm');
            const cancelBtn = alert.querySelector('.alert-cancel');

            confirmBtn.addEventListener('click', function() {
                cleanupAlert(alert, resolve, true);
            });

            cancelBtn.addEventListener('click', function() {
                cleanupAlert(alert, resolve, false);
            });

            // Overlay click handler (counts as cancel)
            const overlay = document.querySelector('.rsl-alert-overlay');
            function overlayHandler() {
                overlay.removeEventListener('click', overlayHandler);
                cleanupAlert(alert, resolve, false);
            }
            overlay.addEventListener('click', overlayHandler);
        });
    }

    // ==========================================
    // RSL PROMPT - Input Dialog with Validation
    // ==========================================

    /**
     * Show input prompt dialog
     *
     * Displays an input dialog that collects user input with validation support.
     * Returns a promise that resolves to the input value or null if cancelled.
     *
     * @param {string|Object} options - Prompt message or options object
     * @param {string} [options.title='Input Required'] - Dialog title
     * @param {string} [options.message] - Prompt message
     * @param {string} [options.placeholder=''] - Input placeholder
     * @param {string} [options.defaultValue=''] - Default input value
     * @param {string} [options.confirmText='Submit'] - Submit button text
     * @param {string} [options.cancelText='Cancel'] - Cancel button text
     * @param {string} [options.animation='zoom-in'] - Animation style
     * @param {string} [options.position='center'] - Dialog position
     * @param {string} [options.type='info'] - Dialog type
     * @param {string} [options.inputType='text'] - Input type: 'text', 'email', 'number', etc.
     * @param {boolean} [options.required=false] - Whether input is required
     * @returns {Promise<string|null>} Promise that resolves to input value or null
     *
     * @example
     * const name = await rslPrompt('Enter your name:');
     * if (name) {
     *   console.log('Hello, ' + name);
     * }
     *
     * @example
     * const email = await rslPrompt({
     *   title: 'Email Address',
     *   message: 'Please enter your email:',
     *   placeholder: 'user@example.com',
     *   inputType: 'email',
     *   required: true
     * });
     */
    function rslPrompt(options) {
        if (typeof options === 'string') {
            options = { message: options };
        }

        const defaults = {
            title: 'Input Required',
            message: 'Please enter a value:',
            placeholder: '',
            defaultValue: '',
            confirmText: 'Submit',
            cancelText: 'Cancel',
            animation: 'zoom-in',
            position: 'center',
            type: 'info',
            inputType: 'text',
            required: false
        };

        const settings = Object.assign({}, defaults, options);

        return new Promise(function(resolve) {
            // Capture the element that opened the prompt
            const opener = document.activeElement;

            // Lock scroll and show overlay
            lockScroll();
            showOverlay();

            // Create alert element
            const alert = createAlertElement(settings, 'prompt');
            alert._rslOpener = opener;
            document.body.appendChild(alert);

            // Show alert
            setTimeout(function() {
                alert.style.display = 'block';
                alert.style.opacity = '1';

                // Activate focus trap (focus input field)
                const input = alert.querySelector('.alert-input');
                activateFocusTrap(alert, input);

                // Select text if there's a default value
                if (input && settings.defaultValue) {
                    input.select();
                }
            }, 10);

            // Get elements
            const confirmBtn = alert.querySelector('.alert-confirm');
            const cancelBtn = alert.querySelector('.alert-cancel');
            const input = alert.querySelector('.alert-input');

            // Submit function with validation
            function handleSubmit() {
                // Always validate if there's a value or if field is required
                const hasValue = input.value.trim() !== '';
                const isRequired = settings.required || input.classList.contains('input-required');

                if ((isRequired || hasValue) && !validateAlertInput(input)) {
                    input.focus();
                    return; // Don't close if validation fails
                }

                const value = input.value;
                cleanupAlert(alert, resolve, value);
            }

            // Enter key handler
            if (input) {
                input.addEventListener('keyup', function(e) {
                    // Clear validation errors on input
                    clearValidationErrors(input);

                    if (e.key === 'Enter') {
                        handleSubmit();
                    }
                });
            }

            // Button handlers
            confirmBtn.addEventListener('click', handleSubmit);

            cancelBtn.addEventListener('click', function() {
                cleanupAlert(alert, resolve, null);
            });

            // Overlay click handler (counts as cancel)
            const overlay = document.querySelector('.rsl-alert-overlay');
            function overlayHandler() {
                overlay.removeEventListener('click', overlayHandler);
                cleanupAlert(alert, resolve, null);
            }
            overlay.addEventListener('click', overlayHandler);
        });
    }

    // ==========================================
    // STATIC ALERT INITIALIZATION
    // ==========================================

    /**
     * Initialize static alert triggers on DOM ready
     *
     * Sets up click handlers for elements with .alert-trigger class
     * for backward compatibility with legacy static alerts.
     */
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize existing static alerts (legacy support)
        document.querySelectorAll('.alert-trigger').forEach(function(trigger) {
            trigger.addEventListener('click', function() {
                const targetSelector = trigger.getAttribute(
                    'data-alert-target'
                );
                const alertElement = document.querySelector(targetSelector);

                if (alertElement) {
                    // Lock scroll and show as dialog
                    lockScroll();
                    alertElement.style.display = 'block';
                    alertElement.setAttribute('role', 'alertdialog');
                    alertElement.setAttribute('aria-modal', 'true');

                    // Remember opener for this static alert
                    alertElement._rslOpener = trigger;

                    // Activate focus trap
                    const firstFocusable = alertElement.querySelector(
                        FOCUSABLE_SELECTOR
                    );
                    activateFocusTrap(alertElement, firstFocusable);

                    // Handle close button
                    const closeBtn = alertElement.querySelector(
                        '.alert-btn, .alert-close'
                    );
                    if (closeBtn) {
                        closeBtn.addEventListener('click', function() {
                            alertElement.style.display = 'none';
                            deactivateFocusTrap();
                            unlockScroll();

                            const opener = alertElement._rslOpener;
                            if (
                                opener &&
                                typeof opener.focus === 'function' &&
                                document.contains(opener)
                            ) {
                                opener.focus();
                            }
                        });
                    }
                }
            });
        });
    });

    // ==========================================
    // DATA ATTRIBUTE TRIGGERS
    // ==========================================

    /**
     * Global click handler for data attribute triggers
     *
     * Allows declarative alert usage via data attributes:
     * - [data-rsl-alert] - Trigger alert
     * - [data-rsl-confirm] - Trigger confirm dialog
     * - [data-rsl-prompt] - Trigger prompt dialog
     *
     * @example
     * <button data-rsl-alert="Success!" data-rsl-alert-type="success">
     *   Show Alert
     * </button>
     */
    document.addEventListener('click', function(e) {
        const target = e.target;

        // Alert trigger
        if (target.matches('[data-rsl-alert]')) {
            e.preventDefault();
            rslAlert({
                title: target.dataset.rslAlertTitle || 'Alert',
                message: target.dataset.rslAlert,
                type: target.dataset.rslAlertType || 'info',
                animation: target.dataset.rslAlertAnimation || 'zoom-in'
            });
        }

        // Confirm trigger
        if (target.matches('[data-rsl-confirm]')) {
            e.preventDefault();
            rslConfirm({
                title: target.dataset.rslConfirmTitle || 'Confirm',
                message: target.dataset.rslConfirm,
                type: target.dataset.rslConfirmType || 'warning',
                animation: target.dataset.rslConfirmAnimation || 'zoom-in'
            }).then(function(result) {
                if (result && target.dataset.rslConfirmCallback) {
                    window[target.dataset.rslConfirmCallback]();
                }
            });
        }

        // Prompt trigger
        if (target.matches('[data-rsl-prompt]')) {
            e.preventDefault();
            rslPrompt({
                title: target.dataset.rslPromptTitle || 'Input Required',
                message: target.dataset.rslPrompt,
                placeholder: target.dataset.rslPromptPlaceholder || '',
                type: target.dataset.rslPromptType || 'info',
                animation: target.dataset.rslPromptAnimation || 'zoom-in',
                required: target.dataset.rslPromptRequired === 'true'
            }).then(function(result) {
                if (result !== null && target.dataset.rslPromptCallback) {
                    window[target.dataset.rslPromptCallback](result);
                }
            });
        }
    });

    // ==========================================
    // EXPOSE PUBLIC API
    // ==========================================

    // Backward compatibility - global functions
    window.rslAlert = rslAlert;
    window.rslConfirm = rslConfirm;
    window.rslPrompt = rslPrompt;

    // Modern RSL namespace for JSON API compatibility
    window.RSL = window.RSL || {};
    window.RSL.Alerts = {
        /**
         * Initialize alerts system (already handled by global click listener)
         * This method exists for JSON API compatibility but doesn't need to do anything
         * since the component uses event delegation on document
         */
        init: function() {
            // Event delegation is already set up on document.addEventListener('click')
            // No per-element initialization needed for alerts
            // This init() exists purely for JSON API compatibility
        },

        /**
         * Show alert dialog
         * @param {Object|string} options - Alert options or message string
         */
        alert: rslAlert,

        /**
         * Show confirmation dialog
         * @param {Object|string} options - Confirm options or message string
         */
        confirm: rslConfirm,

        /**
         * Show prompt dialog
         * @param {Object|string} options - Prompt options or message string
         */
        prompt: rslPrompt
    };
})();
