/**
 * RSL Thumbnail Component
 *
 * Accessible-first thumbnail/image gallery component with auto-generated ARIA labels,
 * ALT tags, modal support, and comprehensive keyboard navigation.
 *
 * Features:
 * - Auto-generates ARIA labels from caption/header/link text
 * - Auto-generates ALT tags intelligently (caption → link → empty)
 * - Customizable overlay colors and opacity via data attributes
 * - One or two button configurations
 * - Modal support for enlarged image viewing
 * - Full keyboard navigation (Tab, Enter, Escape)
 * - Programmatic API for dynamic control
 * - Integration with RSL grid system
 * - Dark mode support
 *
 * @fileoverview RSL Thumbnail Component with automatic accessibility
 * @version 1.0.0
 * @license MIT
 *
 * Usage:
 * <!-- Minimal setup - JavaScript handles accessibility -->
 * <div class="rsl-thumbnail"
 *      data-thumbnail-image="path/to/image.jpg"
 *      data-thumbnail-header="Image Title"
 *      data-thumbnail-description="Image description">
 * </div>
 *
 * <!-- With link -->
 * <div class="rsl-thumbnail"
 *      data-thumbnail-image="image.jpg"
 *      data-thumbnail-header="Title"
 *      data-thumbnail-link="/destination"
 *      data-thumbnail-link-text="View More">
 * </div>
 *
 * <!-- With modal -->
 * <div class="rsl-thumbnail"
 *      data-thumbnail-image="image.jpg"
 *      data-thumbnail-modal="true"
 *      data-thumbnail-header="Title">
 * </div>
 *
 * <!-- With overlay button(s) -->
 * <div class="rsl-thumbnail"
 *      data-thumbnail-image="image.jpg"
 *      data-thumbnail-button1-text="View"
 *      data-thumbnail-button1-action="viewDetails"
 *      data-thumbnail-button2-text="Download"
 *      data-thumbnail-button2-link="/download">
 * </div>
 *
 * Public API:
 * - RSL.Thumbnail.init() - Initialize all thumbnails
 * - RSL.Thumbnail.create(element) - Create single thumbnail instance
 * - RSL.Thumbnail.openModal(element) - Open modal for thumbnail
 * - RSL.Thumbnail.closeModal(modalId) - Close specific modal
 * - RSL.Thumbnail.destroy(element) - Remove thumbnail instance
 */

(function() {
    'use strict';

    window.RSL = window.RSL || {};

    /**
     * Thumbnail Component
     */
    window.RSL.Thumbnail = {
        instances: new Map(),
        modalCounter: 0,

        // Preset color names that map to CSS classes
        presetColors: ['primary', 'secondary', 'success', 'danger', 'info', 'warning', 'dark', 'light'],

        /**
         * Check if a color value is a custom color (not a preset)
         * Custom colors include: hex (#fff, #ffffff), rgb(), rgba(), hsl(), hsla(), or named CSS colors
         *
         * @param {String} color - The color value to check
         * @returns {Boolean} True if custom color
         */
        isCustomColor: function(color) {
            if (!color) return false;
            // Check if it's NOT one of our preset names
            return !this.presetColors.includes(color.toLowerCase());
        },

        /**
         * Initialize all thumbnails on the page
         */
        init: function() {
            var thumbnails = document.querySelectorAll('[data-thumbnail-image]');
            thumbnails.forEach(function(element) {
                if (!RSL.Thumbnail.instances.has(element)) {
                    RSL.Thumbnail.create(element);
                }
            });
        },

        /**
         * Create a thumbnail instance from an element
         *
         * @param {HTMLElement} element - The thumbnail container element
         * @returns {Object} The thumbnail instance
         */
        create: function(element) {
            // Prevent double-initialization
            if (RSL.Thumbnail.instances.has(element)) {
                return RSL.Thumbnail.instances.get(element);
            }

            // Extract configuration from data attributes
            var config = RSL.Thumbnail.getConfig(element);

            // Create instance object
            var instance = {
                element: element,
                config: config,
                modalId: null
            };

            // Build the thumbnail UI
            RSL.Thumbnail.build(instance);

            // Apply accessibility enhancements
            RSL.Thumbnail.applyAccessibility(instance);

            // Attach event listeners
            RSL.Thumbnail.attachEvents(instance);

            // Store instance
            RSL.Thumbnail.instances.set(element, instance);

            return instance;
        },

        /**
         * Extract configuration from data attributes
         *
         * @param {HTMLElement} element - The thumbnail container
         * @returns {Object} Configuration object
         * @private
         */
        getConfig: function(element) {
            return {
                // Image
                image: element.getAttribute('data-thumbnail-image') || '',
                imageAlt: element.getAttribute('data-thumbnail-image-alt') || '', // Manual override
                aspect: element.getAttribute('data-thumbnail-aspect') || '3:2',

                // Content
                header: element.getAttribute('data-thumbnail-header') || '',
                description: element.getAttribute('data-thumbnail-description') || '',

                // Link
                link: element.getAttribute('data-thumbnail-link') || '',
                linkText: element.getAttribute('data-thumbnail-link-text') || 'Learn More',
                linkTarget: element.getAttribute('data-thumbnail-link-target') || '_self',

                // Overlay
                overlayColor: element.getAttribute('data-overlay-color') || 'dark',
                overlayOpacity: element.getAttribute('data-overlay-opacity') || 'medium',
                showOverlayButtons: element.getAttribute('data-thumbnail-show-buttons') !== 'false',

                // Custom colors (hex, rgba, or CSS color values)
                buttonColor: element.getAttribute('data-button-color') || '',
                buttonBgColor: element.getAttribute('data-button-bg-color') || '',
                buttonHoverColor: element.getAttribute('data-button-hover-color') || '',
                buttonHoverBgColor: element.getAttribute('data-button-hover-bg-color') || '',
                buttonIconColor: element.getAttribute('data-button-icon-color') || '',
                buttonIconHoverColor: element.getAttribute('data-button-icon-hover-color') || '',

                // Buttons
                button1Text: element.getAttribute('data-thumbnail-button1-text') || '',
                button1Action: element.getAttribute('data-thumbnail-button1-action') || '',
                button1Link: element.getAttribute('data-thumbnail-button1-link') || '',
                button1Icon: element.getAttribute('data-thumbnail-button1-icon') || '',
                button1Target: element.getAttribute('data-thumbnail-button1-target') || '_self',

                button2Text: element.getAttribute('data-thumbnail-button2-text') || '',
                button2Action: element.getAttribute('data-thumbnail-button2-action') || '',
                button2Link: element.getAttribute('data-thumbnail-button2-link') || '',
                button2Icon: element.getAttribute('data-thumbnail-button2-icon') || '',
                button2Target: element.getAttribute('data-thumbnail-button2-target') || '_self',

                // Modal
                enableModal: element.getAttribute('data-thumbnail-modal') === 'true',
                modalHeader: element.getAttribute('data-thumbnail-modal-header') || '',
                modalDescription: element.getAttribute('data-thumbnail-modal-description') || '',

                // Behavior
                lazyLoad: element.getAttribute('data-thumbnail-lazy') === 'true',
                disabled: element.getAttribute('data-thumbnail-disabled') === 'true'
            };
        },

        /**
         * Build the thumbnail HTML structure
         *
         * @param {Object} instance - The thumbnail instance
         * @private
         */
        build: function(instance) {
            var config = instance.config;
            var element = instance.element;

            // Add class if not present
            if (!element.classList.contains('rsl-thumbnail')) {
                element.classList.add('rsl-thumbnail');
            }

            // Set data attributes for CSS
            if (config.aspect) {
                element.setAttribute('data-thumbnail-aspect', config.aspect);
            }

            // Handle overlay color - preset vs custom
            if (config.overlayColor) {
                if (RSL.Thumbnail.isCustomColor(config.overlayColor)) {
                    // Custom color - use CSS variable
                    element.style.setProperty('--rsl-thumbnail-overlay-color', config.overlayColor);
                    element.setAttribute('data-overlay-color', 'custom');
                } else {
                    // Preset color - use data attribute for CSS class
                    element.setAttribute('data-overlay-color', config.overlayColor);
                }
            }

            if (config.overlayOpacity) {
                element.setAttribute('data-overlay-opacity', config.overlayOpacity);
            }
            if (config.disabled) {
                element.setAttribute('aria-disabled', 'true');
            }

            // Apply custom button colors via CSS variables
            if (config.buttonColor) {
                element.style.setProperty('--rsl-thumbnail-btn-color', config.buttonColor);
            }
            if (config.buttonBgColor) {
                element.style.setProperty('--rsl-thumbnail-btn-bg', config.buttonBgColor);
            }
            if (config.buttonHoverColor) {
                element.style.setProperty('--rsl-thumbnail-btn-hover-color', config.buttonHoverColor);
            }
            if (config.buttonHoverBgColor) {
                element.style.setProperty('--rsl-thumbnail-btn-hover-bg', config.buttonHoverBgColor);
            }
            if (config.buttonIconColor) {
                element.style.setProperty('--rsl-thumbnail-btn-icon-color', config.buttonIconColor);
            }
            if (config.buttonIconHoverColor) {
                element.style.setProperty('--rsl-thumbnail-btn-icon-hover-color', config.buttonIconHoverColor);
            }

            // Build HTML structure
            var html = '';

            // Image container with overlay
            html += '<div class="rsl-thumbnail-image-container">';

            // Image
            var imgTag = '<img src="' + config.image + '" ';
            imgTag += 'alt="" '; // ALT will be set by applyAccessibility()
            if (config.lazyLoad) {
                imgTag += 'loading="lazy" ';
            }
            imgTag += '/>';
            html += imgTag;

            // Overlay (if buttons are enabled)
            if (config.showOverlayButtons && (config.button1Text || config.button2Text || config.enableModal)) {
                html += '<div class="rsl-thumbnail-overlay">';
                html += '<div class="rsl-thumbnail-buttons">';

                // Button 1
                if (config.button1Text) {
                    html += RSL.Thumbnail.buildButton(config, 1);
                }

                // Button 2
                if (config.button2Text) {
                    html += RSL.Thumbnail.buildButton(config, 2);
                }

                // Modal button (if no buttons specified)
                if (config.enableModal && !config.button1Text && !config.button2Text) {
                    html += '<button class="rsl-thumbnail-button rsl-thumbnail-modal-trigger" type="button">';
                    html += '<i class="fas fa-expand"></i> View Larger';
                    html += '</button>';
                }

                html += '</div>'; // .rsl-thumbnail-buttons
                html += '</div>'; // .rsl-thumbnail-overlay
            }

            html += '</div>'; // .rsl-thumbnail-image-container

            // Content area (caption)
            if (config.header || config.description || config.link) {
                html += '<div class="rsl-thumbnail-content">';

                if (config.header) {
                    html += '<h3 class="rsl-thumbnail-header">' + config.header + '</h3>';
                }

                if (config.description) {
                    html += '<p class="rsl-thumbnail-description">' + config.description + '</p>';
                }

                if (config.link) {
                    html += '<a href="' + config.link + '" ';
                    html += 'class="rsl-thumbnail-link" ';
                    html += 'target="' + config.linkTarget + '">';
                    html += config.linkText;
                    html += ' <i class="fas fa-arrow-right"></i>';
                    html += '</a>';
                }

                html += '</div>'; // .rsl-thumbnail-content
            }

            // Set HTML
            element.innerHTML = html;

            // Create modal if enabled
            if (config.enableModal) {
                instance.modalId = RSL.Thumbnail.createModal(instance);
            }
        },

        /**
         * Build a button element
         *
         * @param {Object} config - The thumbnail configuration
         * @param {Number} buttonNum - Button number (1 or 2)
         * @returns {String} Button HTML
         * @private
         */
        buildButton: function(config, buttonNum) {
            var text = config['button' + buttonNum + 'Text'];
            var action = config['button' + buttonNum + 'Action'];
            var link = config['button' + buttonNum + 'Link'];
            var icon = config['button' + buttonNum + 'Icon'];
            var target = config['button' + buttonNum + 'Target'];

            var html = '';

            if (link) {
                // Button as link
                html += '<a href="' + link + '" ';
                html += 'class="rsl-thumbnail-button" ';
                html += 'target="' + target + '" ';
                html += 'data-button-num="' + buttonNum + '">';
            } else {
                // Button as button
                html += '<button type="button" ';
                html += 'class="rsl-thumbnail-button" ';
                html += 'data-button-num="' + buttonNum + '" ';
                if (action) {
                    html += 'data-action="' + action + '" ';
                }
                html += '>';
            }

            if (icon) {
                html += '<i class="' + icon + '"></i> ';
            }
            html += text;

            html += link ? '</a>' : '</button>';

            return html;
        },

        /**
         * Create modal for thumbnail
         *
         * @param {Object} instance - The thumbnail instance
         * @returns {String} Modal ID
         * @private
         */
        createModal: function(instance) {
            var config = instance.config;
            RSL.Thumbnail.modalCounter++;
            var modalId = 'rsl-thumbnail-modal-' + RSL.Thumbnail.modalCounter;

            var modalHeader = config.modalHeader || config.header || 'Image';
            var modalDescription = config.modalDescription || config.description || '';

            // Create modal HTML
            var modalHTML = '<div class="modal-container rsl-thumbnail-modal default-modal-size" ';
            modalHTML += 'id="' + modalId + '" ';
            modalHTML += 'role="dialog" ';
            modalHTML += 'aria-labelledby="' + modalId + '-title" ';
            modalHTML += 'aria-modal="true">';
            modalHTML += '<div class="modal">';

            // Header
            modalHTML += '<div class="modal-header">';
            modalHTML += '<h2 id="' + modalId + '-title">' + modalHeader + '</h2>';
            modalHTML += '<button class="close-modal" aria-label="Close Modal" data-animation-out="fadeOut">&times;</button>';
            modalHTML += '</div>';

            // Body
            modalHTML += '<div class="modal-body">';
            modalHTML += '<img src="' + config.image + '" ';
            modalHTML += 'alt="' + modalHeader + '" ';
            modalHTML += 'class="rsl-thumbnail-modal-image" />';
            modalHTML += '</div>';

            // Footer
            modalHTML += '<div class="modal-footer modal-buttons-right">';
            if (modalDescription) {
                modalHTML += '<div class="rsl-thumbnail-modal-caption">';
                modalHTML += '<p>' + modalDescription + '</p>';
                modalHTML += '</div>';
            }
            modalHTML += '<button class="btn close-modal" data-animation-out="fadeOut">Close</button>';
            modalHTML += '</div>';

            modalHTML += '</div>'; // .modal
            modalHTML += '</div>'; // .modal-container

            // Append to body
            var temp = document.createElement('div');
            temp.innerHTML = modalHTML;
            document.body.appendChild(temp.firstElementChild);

            // Initialize modal if RSL.Modal is available
            if (window.RSL && window.RSL.Modal && typeof window.RSL.Modal.init === 'function') {
                setTimeout(function() {
                    RSL.Modal.init();
                }, 100);
            }

            return modalId;
        },

        /**
         * Apply automatic accessibility enhancements
         *
         * @param {Object} instance - The thumbnail instance
         * @private
         */
        applyAccessibility: function(instance) {
            var config = instance.config;
            var element = instance.element;

            // Generate ALT tag for image
            var altText = RSL.Thumbnail.generateAltText(config);
            var img = element.querySelector('img');
            if (img && altText) {
                img.setAttribute('alt', altText);
            }

            // Generate ARIA label for thumbnail container
            var ariaLabel = RSL.Thumbnail.generateAriaLabel(config);
            if (ariaLabel) {
                element.setAttribute('aria-label', ariaLabel);
            }

            // Make thumbnail keyboard accessible if it has interaction
            if (config.link || config.enableModal || config.button1Text || config.button2Text) {
                element.setAttribute('tabindex', '0');
                element.setAttribute('role', 'button');

                // If direct link, announce it
                if (config.link && !config.button1Text && !config.button2Text) {
                    element.setAttribute('role', 'link');
                }
            }

            // Add screen reader helper text
            if (config.link) {
                var srText = document.createElement('span');
                srText.className = 'sr-only';
                srText.textContent = 'Press Enter to navigate to ' + config.link;
                element.appendChild(srText);
            }
        },

        /**
         * Generate intelligent ALT text for image
         *
         * Priority: Manual ALT → Header + Description → Header → Description → Link destination → Empty
         *
         * @param {Object} config - The thumbnail configuration
         * @returns {String} ALT text
         * @private
         */
        generateAltText: function(config) {
            // 1. Manual override
            if (config.imageAlt) {
                return config.imageAlt;
            }

            // 2. Header + Description
            if (config.header && config.description) {
                return config.header + ' - ' + config.description;
            }

            // 3. Header only
            if (config.header) {
                return config.header;
            }

            // 4. Description only
            if (config.description) {
                return config.description;
            }

            // 5. Link destination (announce where it goes)
            if (config.link) {
                return 'Thumbnail linking to ' + config.link;
            }

            // 6. Empty (decorative image)
            return '';
        },

        /**
         * Generate comprehensive ARIA label for thumbnail
         *
         * @param {Object} config - The thumbnail configuration
         * @returns {String} ARIA label
         * @private
         */
        generateAriaLabel: function(config) {
            var parts = [];

            // Add header
            if (config.header) {
                parts.push(config.header);
            }

            // Add description
            if (config.description) {
                parts.push(config.description);
            }

            // Announce buttons
            var buttonCount = 0;
            if (config.button1Text) buttonCount++;
            if (config.button2Text) buttonCount++;

            if (buttonCount > 0) {
                parts.push('Contains ' + buttonCount + ' button' + (buttonCount > 1 ? 's' : ''));
                if (config.button1Text) {
                    parts.push('Button 1: ' + config.button1Text);
                }
                if (config.button2Text) {
                    parts.push('Button 2: ' + config.button2Text);
                }
            }

            // Announce link
            if (config.link) {
                parts.push('Link: ' + config.linkText + ' - goes to ' + config.link);
            }

            // Announce modal
            if (config.enableModal) {
                parts.push('Press Enter or click to view larger image');
            }

            // Join parts
            return parts.join('. ');
        },

        /**
         * Attach event listeners to thumbnail
         *
         * @param {Object} instance - The thumbnail instance
         * @private
         */
        attachEvents: function(instance) {
            var config = instance.config;
            var element = instance.element;

            // Keyboard navigation for main thumbnail
            if (config.link || config.enableModal) {
                element.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();

                        if (config.enableModal) {
                            RSL.Thumbnail.openModal(element);
                        } else if (config.link) {
                            window.location.href = config.link;
                        }
                    }
                });

                // Click for modal
                if (config.enableModal && !config.showOverlayButtons) {
                    element.addEventListener('click', function(e) {
                        // Don't trigger if clicking a button
                        if (!e.target.closest('.rsl-thumbnail-button')) {
                            RSL.Thumbnail.openModal(element);
                        }
                    });
                }
            }

            // Button actions
            var buttons = element.querySelectorAll('.rsl-thumbnail-button');
            buttons.forEach(function(button) {
                var action = button.getAttribute('data-action');

                if (button.classList.contains('rsl-thumbnail-modal-trigger')) {
                    button.addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        RSL.Thumbnail.openModal(element);
                    });
                } else if (action) {
                    button.addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();

                        // Call global function if it exists
                        if (typeof window[action] === 'function') {
                            window[action](element, instance);
                        } else {
                            console.warn('RSL.Thumbnail: Action function not found:', action);
                        }
                    });
                }
            });
        },

        /**
         * Open modal for a thumbnail
         *
         * @param {HTMLElement} element - The thumbnail element
         */
        openModal: function(element) {
            var instance = RSL.Thumbnail.instances.get(element);
            if (!instance || !instance.modalId) {
                console.warn('RSL.Thumbnail: No modal found for thumbnail');
                return;
            }

            var modalContainer = document.getElementById(instance.modalId);
            if (!modalContainer) {
                console.warn('RSL.Thumbnail: Modal container not found');
                return;
            }

            var modal = modalContainer.querySelector('.modal');
            var closeButtons = modalContainer.querySelectorAll('.close-modal');

            // Use RSL.Modal if available
            if (window.RSL && window.RSL.Modal && typeof window.RSL.Modal.showModal === 'function') {
                // Remove old event listeners by cloning close buttons
                closeButtons.forEach(function(btn) {
                    var newBtn = btn.cloneNode(true);
                    btn.parentNode.replaceChild(newBtn, btn);
                });

                // Re-query close buttons after cloning
                closeButtons = modalContainer.querySelectorAll('.close-modal');

                // Attach new close listeners with thumbnail element as trigger
                closeButtons.forEach(function(closeButton) {
                    closeButton.addEventListener('click', function() {
                        var animationOut = this.getAttribute('data-animation-out') || 'fadeOut';
                        if (window.closeModal) {
                            window.closeModal(modalContainer, modal, animationOut, element);
                        }
                    });
                });

                // Handle backdrop click with focus restoration
                modalContainer.addEventListener('click', function(event) {
                    if (event.target === modalContainer) {
                        var animationOut = closeButtons[0] ? closeButtons[0].getAttribute('data-animation-out') || 'fadeOut' : 'fadeOut';
                        if (window.closeModal) {
                            window.closeModal(modalContainer, modal, animationOut, element);
                        }
                    }
                });

                // Open the modal using RSL.Modal
                RSL.Modal.showModal({
                    target: '#' + instance.modalId,
                    trigger: element
                });
            } else {
                // Fallback: show modal manually
                if (modalContainer) {
                    modalContainer.style.display = 'flex';
                    modalContainer.setAttribute('aria-hidden', 'false');

                    // Focus first focusable element
                    var focusable = modalContainer.querySelector('button, a, input');
                    if (focusable) {
                        focusable.focus();
                    }

                    // Attach close listeners with focus restoration
                    closeButtons.forEach(function(closeButton) {
                        closeButton.addEventListener('click', function() {
                            modalContainer.style.display = 'none';
                            modalContainer.setAttribute('aria-hidden', 'true');
                            element.focus(); // Restore focus to thumbnail
                        });
                    });
                }
            }
        },

        /**
         * Close a specific modal
         *
         * @param {String} modalId - The modal ID
         */
        closeModal: function(modalId) {
            if (window.RSL && window.RSL.Modal && typeof window.RSL.Modal.closeModal === 'function') {
                var modal = document.getElementById(modalId);
                if (modal) {
                    RSL.Modal.closeModal({ target: modal });
                }
            } else {
                // Fallback: hide modal manually
                var modal = document.getElementById(modalId);
                if (modal) {
                    modal.style.display = 'none';
                    modal.setAttribute('aria-hidden', 'true');
                }
            }
        },

        /**
         * Destroy a thumbnail instance
         *
         * @param {HTMLElement} element - The thumbnail element
         */
        destroy: function(element) {
            var instance = RSL.Thumbnail.instances.get(element);
            if (!instance) return;

            // Remove modal if it exists
            if (instance.modalId) {
                var modal = document.getElementById(instance.modalId);
                if (modal && modal.parentNode) {
                    modal.parentNode.removeChild(modal);
                }
            }

            // Remove instance
            RSL.Thumbnail.instances.delete(element);
        },

        /**
         * Get thumbnail instance
         *
         * @param {HTMLElement} element - The thumbnail element
         * @returns {Object|null} The instance or null
         */
        getInstance: function(element) {
            return RSL.Thumbnail.instances.get(element) || null;
        }
    };

    // Auto-initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        RSL.Thumbnail.init();
    });

})();
