/**
 * RSL Inlay Alert Generator
 *
 * Dynamic alert/notification system with customizable styling, animations, and
 * auto-close functionality. Generates accessible, dismissible alerts with ARIA
 * attributes, progress bars, and callback hooks. Integrates with RSL color
 * adjustment utilities for automatic text contrast.
 *
 * @fileoverview Customizable alert generation system with accessibility support
 * @version 1.0.0
 * @license MIT
 *
 * Key Features:
 * - Predefined alert types (success, warning, error, info, default)
 * - Auto-closing alerts with countdown progress bar
 * - Custom color overrides for all elements
 * - CSS animation support
 * - onShow and onClose callback hooks
 * - Automatic text contrast adjustment
 * - Optional message wrapping with background
 * - Drop shadow options
 * - Full ARIA accessibility
 *
 * Usage:
 * // Basic success alert
 * generateAlert({
 *   type: 'success',
 *   message: 'Operation completed!',
 *   details: 'Your changes have been saved.',
 *   location: '#alertContainer'
 * });
 *
 * // Auto-closing alert with progress bar
 * generateAlert({
 *   type: 'warning',
 *   message: 'Session expiring',
 *   details: 'You will be logged out in 30 seconds.',
 *   location: '#notifications',
 *   timeout: 30000
 * });
 *
 * // Fully customized alert
 * generateAlert({
 *   type: 'error',
 *   message: 'Custom Alert',
 *   details: 'With custom colors and callbacks',
 *   location: '#container',
 *   overrideBackgroundColor: '#ff5733',
 *   overrideTextColor: '#ffffff',
 *   overrideIcon: 'fa-exclamation-circle',
 *   animation: 'fadeIn',
 *   timeout: 5000,
 *   onShow: () => console.log('Alert shown'),
 *   onClose: () => console.log('Alert closed')
 * });
 *
 * Public API:
 * - generateAlert(options) - Create and display an alert
 * - runMeWhen(message) - Example callback function
 */

(function() {
    'use strict';

    /**
     * Alert type definitions with default colors and icons
     * @const
     * @private
     */
    const alertTypes = {
        success: {
            color: '#28a745',
            icon: 'fa-check-circle'
        },
        warning: {
            color: '#ffc107',
            icon: 'fa-exclamation-triangle'
        },
        error: {
            color: '#dc3545',
            icon: 'fa-times-circle'
        },
        info: {
            color: '#17a2b8',
            icon: 'fa-info-circle'
        },
        default: {
            color: '#6c757d',
            icon: 'fa-bell'
        }
    };

    /**
     * Example callback function for alert events
     *
     * Simple demonstration function that can be used with onShow/onClose
     * callbacks. Replace with your own logic as needed.
     *
     * @param {string} test - Message to display
     *
     * @example
     * generateAlert({
     *   type: 'info',
     *   message: 'Test',
     *   location: '#alerts',
     *   onShow: () => runMeWhen('Alert displayed!')
     * });
     */
    window.runMeWhen = function(test) {
        alert(test);
    };

    /**
     * Generate and display a customizable alert notification
     *
     * Creates a rich alert element with icon, message, details, and close button.
     * Supports auto-closing with progress bar, custom colors, animations, and
     * callback hooks. Automatically adjusts text color for accessibility.
     *
     * @param {Object} options - Alert configuration options
     * @param {string} options.type - Alert type: 'success', 'warning', 'error', 'info', or 'default'
     * @param {string} [options.message] - Alert heading/title
     * @param {string} [options.details] - Alert body/description text
     * @param {string} options.location - CSS selector for container (must start with # or .)
     * @param {string} [options.dropShadow] - CSS class for drop shadow effect
     * @param {string} [options.wrapMessage] - 'true' to wrap details in styled background
     * @param {string} [options.overrideBackgroundColor] - Custom background color (HEX or RGB)
     * @param {string} [options.overrideTextColor] - Custom text color (HEX or RGB)
     * @param {string} [options.overrideTitleColor] - Custom title/heading color
     * @param {string} [options.overrideIconColor] - Custom icon color
     * @param {string} [options.overrideCloseColor] - Custom close button color
     * @param {number} [options.timeout] - Auto-close delay in milliseconds
     * @param {string} [options.overrideIcon] - FontAwesome icon class (e.g., 'fa-bell')
     * @param {string} [options.animation] - CSS animation class
     * @param {Function} [options.onShow] - Callback fired when alert is shown
     * @param {Function} [options.onClose] - Callback fired when alert is closed
     *
     * @example
     * // Auto-closing success alert
     * generateAlert({
     *   type: 'success',
     *   message: 'Saved!',
     *   details: 'Your profile has been updated.',
     *   location: '#notifications',
     *   timeout: 3000
     * });
     *
     * @example
     * // Custom styled alert with callbacks
     * generateAlert({
     *   type: 'warning',
     *   message: 'Important Notice',
     *   details: 'System maintenance scheduled.',
     *   location: '#banner',
     *   overrideBackgroundColor: '#ff9800',
     *   overrideTextColor: '#000',
     *   animation: 'slideInDown',
     *   onShow: () => console.log('Alert displayed'),
     *   onClose: () => console.log('Alert dismissed')
     * });
     */
    window.generateAlert = function(obj) {
        const {
            type,
            message,
            details,
            location,
            dropShadow,
            wrapMessage,
            overrideBackgroundColor,
            overrideTextColor,
            overrideTitleColor,
            overrideIconColor,
            overrideCloseColor,
            timeout,
            overrideIcon,
            animation,
            onShow,
            onClose,
        } = obj;

        // Find alert container
        let alertContainer;
        if (location.startsWith('#')) {
            alertContainer = document.getElementById(location.slice(1));
        } else if (location.startsWith('.')) {
            alertContainer = document.querySelector(location);
        } else {
            console.error('Location must start with a # (for an ID) or a . (for a class)');
            return;
        }

        if (!alertContainer) {
            console.error('Alert container not found:', location);
            return;
        }

        // Determine alert styling
        const alertType = alertTypes[type] || alertTypes.default;
        const backgroundColor = overrideBackgroundColor || alertType.color;

        let textColor;
        try {
            // Auto-calculate text color for contrast if not overridden
            if (typeof isLight === 'function' && typeof adjustColor === 'function') {
                textColor = overrideTextColor || (isLight(backgroundColor)
                    ? adjustColor(backgroundColor, 70)
                    : adjustColor(backgroundColor, -70));
            } else {
                textColor = overrideTextColor || '#000000';
            }
        } catch (error) {
            console.warn("Invalid background color, defaulting text color to black.");
            textColor = "#000000";
        }

        const iconType = overrideIcon || alertType.icon;

        // Create alert element
        const alertElement = document.createElement('div');
        alertElement.setAttribute("role", "alert");
        alertElement.setAttribute("aria-label", `${type}: ${message} ${details}`);
        alertElement.className = `inlay-alert dynamic ${dropShadow || ''} ${animation || ''}`;

        alertElement.style.backgroundColor = backgroundColor;
        alertElement.style.color = textColor;

        // Build alert HTML
        const alertMessage = message
            ? `<h4 style="color: ${overrideTitleColor || textColor};">${message}</h4>`
            : '';

        const icon = typeof overrideIconColor !== 'undefined'
            ? `<i class="fas ${iconType}" aria-hidden="true" style="color: ${overrideIconColor || textColor};"></i>`
            : `<i class="fas ${iconType}" aria-hidden="true"></i>`;

        const closeIcon = typeof overrideCloseColor !== 'undefined'
            ? `<button class="close" aria-label="Close" style="color: ${overrideCloseColor || textColor};"><i class="fas fa-times closer" aria-hidden="true"></i></button>`
            : `<button class="close" aria-label="Close"><i class="fas fa-times closer" aria-hidden="true"></i></button>`;

        const alertDetails = details
            ? wrapMessage === 'true'
                ? `<div class="message-wrapper"><p><div class="alert-message-around">${details}</div></p></div>`
                : `<div class="message-wrapper"><p>${details}</p></div>`
            : '';

        alertElement.innerHTML = `
            <div class="alert-content">
                ${icon}
                <div class="alert-message">
                ${alertMessage}
                ${alertDetails}
                </div>
                ${closeIcon}
            </div>
        `;

        // Add close button handler
        alertElement.querySelector('.close').addEventListener('click', () => {
            alertElement.style.opacity = '0';
            setTimeout(() => {
                alertContainer.removeChild(alertElement);
                if (onClose) onClose();
            }, 500);
        });

        // Add to container
        alertContainer.appendChild(alertElement);

        // Fire onShow callback
        if (onShow) onShow();

        // Setup auto-close with progress bar
        if (timeout) {
            // Create progress bar
            const progressBar = document.createElement('div');
            progressBar.className = 'progress-bar';
            progressBar.style.animationDuration = `${timeout}ms`;

            // Append progress bar to alert
            alertElement.appendChild(progressBar);

            // Auto-close after timeout
            setTimeout(() => {
                alertElement.style.opacity = '0';
                setTimeout(() => {
                    alertContainer.removeChild(alertElement);
                    if (onClose) onClose();
                }, 500); // Matches CSS transition duration
            }, timeout);
        }

        // Apply text color adjustments if not overridden
        if (!overrideTextColor && typeof adjustTextColor === 'function') {
            adjustTextColor(alertElement);
        }

        // Adjust message wrapper colors if function available
        if (typeof adjustAlertMessageStaticColors === 'function') {
            adjustAlertMessageStaticColors();
        }
    };

    /**
     * Example usage demonstrations
     * Uncomment to test different alert configurations
     */

    /*
    // Auto-closing alert with progress bar
    generateAlert({
        type: 'success',
        message: 'Auto-closing Alert!',
        details: 'This alert will close after 3 seconds.',
        location: '#alertContainer',
        timeout: 3000
    });

    // Alert with custom onShow and onClose functions
    generateAlert({
        type: 'warning',
        message: 'Alert with custom functions!',
        details: 'This alert runs functions when shown and closed.',
        location: '#alertContainer',
        onShow: () => runMeWhen("Alert is shown"),
        onClose: () => runMeWhen("Alert is closed")
    });

    // Alert with a custom icon and animation
    generateAlert({
        type: 'info',
        message: 'Animated Alert!',
        details: 'This alert slides in from the right and has a custom icon.',
        location: '#alertContainer',
        overrideIcon: 'fa-exclamation-triangle',
        animation: 'slide-in-right'
    });

    // Alert with all options
    generateAlert({
        type: 'error',
        message: 'This is an alert with all options!',
        details: 'It has custom colors, a custom icon, animations, and it auto-closes after 5 seconds.',
        location: '#alertContainer',
        dropShadow: 'alert-dropshadow-a',
        wrapMessage: 'true',
        overrideBackgroundColor: 'red',
        overrideTextColor: '#FFFF00',
        overrideTitleColor: '#FFFFFF',
        overrideIconColor: '#FFA500',
        overrideCloseColor: '#FFC0CB',
        timeout: 5000,
        overrideIcon: 'fa-exclamation-triangle',
        animation: 'slide-in-right',
        onShow: () => runMeWhen("Alert is shown"),
        onClose: () => runMeWhen("Alert is closed")
    });
    */

})();
