/**
 * RSL Toast Notification System
 *
 * Lightweight, flexible toast notification system for displaying temporary messages.
 * Supports both static HTML toasts and dynamically generated toasts via JavaScript API.
 * Features positioning control, auto-dismiss, and customizable styling.
 *
 * @fileoverview Toast notification system with auto-dismiss and positioning
 * @version 1.0.0
 * @license MIT
 *
 * Key Features:
 * - Fixed and absolute positioning modes
 * - Six position variants (top/bottom x left/center/right)
 * - Auto-dismiss with configurable timeout
 * - Manual close button support
 * - Smooth fade animations
 * - Customizable header colors
 * - Data attribute trigger integration
 * - Auto-initialization for static HTML
 *
 * Position Options:
 * - top-left, top-center, top-right
 * - bottom-left, bottom-center, bottom-right
 *
 * Positioning Types:
 * - fixed: Positioned relative to viewport (stays in place during scroll)
 * - absolute: Positioned relative to parent container
 *
 * Usage:
 * // Static HTML:
 * <div class="rsl-toast rsl-fixed rsl-top-right" data-timeout="3000">
 *   <div class="rsl-toast-header">
 *     Notification
 *     <button class="rsl-toast-close">&times;</button>
 *   </div>
 *   <div class="rsl-toast-body">Message content here</div>
 * </div>
 *
 * // Dynamic JavaScript:
 * showToast({
 *   header: 'Success',
 *   body: 'Your changes have been saved!',
 *   position: 'top-right',
 *   timeout: 3000,
 *   bgColor: '#28a745'
 * });
 *
 * // Trigger via button:
 * <button data-toast-trigger
 *         data-toast-header="Alert"
 *         data-toast-body="This is a toast"
 *         data-toast-position="top-right"
 *         data-toast-timeout="5000"
 *         data-toast-bg="#007bff">
 *   Show Toast
 * </button>
 *
 * Public API:
 * - showToast(options) - Create and display a toast notification
 * - initToast(element) - Initialize behavior for a toast element
 */

(function() {
    'use strict';

    /**
     * Default configuration for toast notifications
     * @const
     * @type {Object}
     */
    const DEFAULT_OPTIONS = {
        header: 'Notification',
        body: 'This is a toast notification',
        position: 'top-right',
        timeout: 3000,
        type: 'fixed',
        bgColor: '#007bff',
        parent: null
    };

    /**
     * Initialize behavior for a toast element
     *
     * Sets up close button handler and auto-dismiss timer for both
     * static HTML toasts and dynamically created ones. Handles fade
     * out animation and DOM removal.
     *
     * @param {HTMLElement} toast - The toast element to initialize
     *
     * @example
     * const toast = document.querySelector('.rsl-toast');
     * initToast(toast);
     */
    function initToast(toast) {
        const timeout = parseInt(toast.dataset.timeout) || DEFAULT_OPTIONS.timeout;
        const closeBtn = toast.querySelector('.rsl-toast-close');

        // Setup close button
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                closeToast(toast);
            });
        }

        // Setup auto-dismiss
        setTimeout(function() {
            closeToast(toast);
        }, timeout);
    }

    /**
     * Close a toast notification
     *
     * Fades out the toast and removes it from the DOM after animation completes.
     *
     * @param {HTMLElement} toast - The toast element to close
     */
    function closeToast(toast) {
        toast.style.opacity = 0;
        setTimeout(function() {
            toast.remove();
        }, 250);
    }

    /**
     * Create and show a toast notification programmatically
     *
     * Dynamically generates a toast element with specified options,
     * adds it to the DOM, and initializes its behavior. Supports
     * both fixed viewport positioning and absolute positioning
     * within a parent container.
     *
     * @param {Object} options - Toast configuration
     * @param {string} [options.header='Notification'] - Toast header text
     * @param {string} [options.body='This is a toast notification'] - Toast body content
     * @param {string} [options.position='top-right'] - Toast position: 'top-left', 'top-center', 'top-right', 'bottom-left', 'bottom-center', 'bottom-right'
     * @param {number} [options.timeout=3000] - Auto-dismiss timeout in milliseconds
     * @param {string} [options.type='fixed'] - Positioning type: 'fixed' or 'absolute'
     * @param {string} [options.bgColor='#007bff'] - Header background color (hex, rgb, etc.)
     * @param {HTMLElement} [options.parent=null] - Parent element for absolute positioning
     *
     * @example
     * // Simple success toast
     * showToast({
     *   header: 'Success!',
     *   body: 'Changes saved successfully',
     *   position: 'top-right',
     *   bgColor: '#28a745'
     * });
     *
     * @example
     * // Long duration warning
     * showToast({
     *   header: 'Warning',
     *   body: 'Your session will expire in 5 minutes',
     *   position: 'top-center',
     *   timeout: 10000,
     *   bgColor: '#ffc107'
     * });
     *
     * @example
     * // Absolute positioned within container
     * const container = document.querySelector('#notifications');
     * showToast({
     *   header: 'New Message',
     *   body: 'You have a new message from John',
     *   type: 'absolute',
     *   parent: container,
     *   position: 'bottom-right'
     * });
     */
    function showToast(options) {
        const settings = Object.assign({}, DEFAULT_OPTIONS, options);

        // Create toast element
        const toast = document.createElement('div');
        toast.className = `rsl-toast rsl-${settings.type} rsl-${settings.position}`;
        toast.dataset.timeout = settings.timeout;
        toast.style.opacity = 0;

        // Create header
        const header = document.createElement('div');
        header.className = 'rsl-toast-header';
        header.style.backgroundColor = settings.bgColor;
        header.innerHTML = settings.header + '<button type="button" class="rsl-toast-close" aria-label="Close">&times;</button>';

        // Create body
        const body = document.createElement('div');
        body.className = 'rsl-toast-body';
        body.innerHTML = settings.body;

        // Assemble toast
        toast.appendChild(header);
        toast.appendChild(body);

        // Append to parent or body
        if (settings.parent) {
            settings.parent.appendChild(toast);
        } else {
            document.body.appendChild(toast);
        }

        // Fade in
        setTimeout(function() {
            toast.style.transition = 'opacity 0.25s';
            toast.style.opacity = 1;
        }, 10);

        // Initialize toast behavior
        initToast(toast);
    }

    /**
     * Handle button-triggered toasts
     *
     * Event delegation for elements with data-toast-trigger attribute.
     * Reads configuration from data attributes and creates toast.
     *
     * @param {Event} e - Click event
     */
    function handleTriggerClick(e) {
        if (e.target.matches('[data-toast-trigger]')) {
            const btn = e.target;
            const options = {
                header: btn.dataset.toastHeader || DEFAULT_OPTIONS.header,
                body: btn.dataset.toastBody || DEFAULT_OPTIONS.body,
                position: btn.dataset.toastPosition || DEFAULT_OPTIONS.position,
                timeout: parseInt(btn.dataset.toastTimeout) || DEFAULT_OPTIONS.timeout,
                bgColor: btn.dataset.toastBg || DEFAULT_OPTIONS.bgColor
            };
            showToast(options);
        }
    }

    /**
     * Auto-initialize on page load (for backward compatibility)
     */
    document.addEventListener('DOMContentLoaded', function() {
        RSL.Toast.init();
    });

    /**
     * Event delegation for toast trigger buttons
     */
    document.addEventListener('click', handleTriggerClick);

    /**
     * Expose public API
     */
    window.RSL = window.RSL || {};
    window.RSL.Toast = {
        /**
         * Track initialized toast elements to prevent double-initialization
         */
        instances: new Set(),

        /**
         * Initialize all toast elements on the page
         * Scans for .rsl-toast elements and initializes them
         * Used by JSON Layout API for auto-initialization
         */
        init: function() {
            var toasts = document.querySelectorAll('.rsl-toast');
            toasts.forEach(function(toast) {
                if (!RSL.Toast.instances.has(toast)) {
                    RSL.Toast.create(toast);
                }
            });
        },

        /**
         * Initialize a specific toast element
         * @param {HTMLElement} toast - The toast element to initialize
         */
        create: function(toast) {
            if (RSL.Toast.instances.has(toast)) {
                return; // Already initialized
            }

            initToast(toast);
            RSL.Toast.instances.add(toast);
        },

        /**
         * Programmatically show a toast notification
         * @param {Object} options - Toast configuration
         */
        show: showToast
    };

})();
