/**
 * RSL Testimonial/Quote Component
 * Version: 1.0.0
 *
 * A premium, accessible testimonial component supporting:
 * - Multiple variants (card, minimal, featured, bubble)
 * - Star rating integration via RSL.StarRating
 * - FilterBus integration for filtering by category/rating
 * - Slideshow/carousel mode with full keyboard navigation
 * - Avatar fallback with initials
 * - Animate on scroll
 *
 * WCAG 2.1 AA Compliant:
 * - Semantic HTML (blockquote, cite, figure)
 * - Full keyboard navigation in slideshow mode
 * - Screen reader announcements via aria-live
 * - Visible focus indicators
 * - Respects prefers-reduced-motion
 *
 * @namespace RSL.Testimonial
 */

(function() {
    'use strict';

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

    // Track initialized instances
    const instances = new Map();

    // SVG Icons
    const ICONS = {
        chevronLeft: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"></polyline></svg>',
        chevronRight: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"></polyline></svg>',
        verified: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>'
    };

    /**
     * Default configuration
     */
    const DEFAULTS = {
        variant: 'card',           // card, minimal, featured, bubble
        size: 'md',                // sm, md, lg
        animate: false,            // Enable animate on scroll
        slideshow: false,          // Enable slideshow mode
        autoplay: false,           // Autoplay slideshow
        autoplayInterval: 5000,    // Autoplay interval in ms
        pauseOnHover: true,        // Pause autoplay on hover
        showNavigation: true,      // Show prev/next buttons
        showDots: true,            // Show pagination dots
        accentColor: null,         // purple, green, orange, red, teal, or custom hex
        filterCategory: null,      // FilterBus category field
        filterRating: null         // FilterBus rating field
    };

    /**
     * Get configuration from data attributes
     * @param {HTMLElement} element - The testimonial element
     * @returns {Object} Configuration object
     */
    function getConfig(element) {
        return {
            variant: element.dataset.testimonialVariant || DEFAULTS.variant,
            size: element.dataset.testimonialSize || DEFAULTS.size,
            animate: element.dataset.testimonialAnimate === 'true',
            slideshow: element.dataset.testimonialSlideshow === 'true',
            autoplay: element.dataset.testimonialAutoplay === 'true',
            autoplayInterval: parseInt(element.dataset.testimonialInterval, 10) || DEFAULTS.autoplayInterval,
            pauseOnHover: element.dataset.testimonialPauseOnHover !== 'false',
            showNavigation: element.dataset.testimonialNav !== 'false',
            showDots: element.dataset.testimonialDots !== 'false',
            accentColor: element.dataset.testimonialAccent || DEFAULTS.accentColor,
            filterCategory: element.dataset.filterbusCategory || DEFAULTS.filterCategory,
            filterRating: element.dataset.filterbusRating || DEFAULTS.filterRating,
            // Individual testimonial data
            avatar: element.dataset.testimonialAvatar || null,
            avatarAlt: element.dataset.testimonialAvatarAlt || null,
            name: element.dataset.testimonialName || null,
            title: element.dataset.testimonialTitle || null,
            company: element.dataset.testimonialCompany || null,
            logo: element.dataset.testimonialLogo || null,
            logoAlt: element.dataset.testimonialLogoAlt || null,
            rating: parseFloat(element.dataset.testimonialRating) || null,
            category: element.dataset.testimonialCategory || null,
            date: element.dataset.testimonialDate || null,
            verified: element.dataset.testimonialVerified === 'true'
        };
    }

    /**
     * Generate initials from a name
     * @param {string} name - Full name
     * @returns {string} Initials (up to 2 characters)
     */
    function getInitials(name) {
        if (!name) return '?';
        const parts = name.trim().split(/\s+/);
        if (parts.length === 1) {
            return parts[0].charAt(0).toUpperCase();
        }
        return (parts[0].charAt(0) + parts[parts.length - 1].charAt(0)).toUpperCase();
    }

    /**
     * Generate a deterministic color from a string
     * @param {string} str - Input string
     * @returns {string} HSL color
     */
    function stringToColor(str) {
        if (!str) return 'hsl(230, 70%, 55%)';
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            hash = str.charCodeAt(i) + ((hash << 5) - hash);
        }
        const hue = hash % 360;
        return 'hsl(' + Math.abs(hue) + ', 65%, 50%)';
    }

    /**
     * Format date for display
     * @param {string} dateStr - Date string
     * @returns {string} Formatted date
     */
    function formatDate(dateStr) {
        if (!dateStr) return '';
        try {
            const date = new Date(dateStr);
            return date.toLocaleDateString(undefined, {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        } catch (e) {
            return dateStr;
        }
    }

    /**
     * Create a single testimonial element
     * @param {HTMLElement} element - The container element
     * @param {Object} config - Configuration object
     */
    function buildTestimonial(element, config) {
        // Don't rebuild if already built (for slideshows with multiple items)
        if (element.dataset.testimonialBuilt === 'true') return;

        // Get existing content (blockquote)
        let quoteElement = element.querySelector('blockquote');
        let quoteText = '';

        if (quoteElement) {
            quoteText = quoteElement.innerHTML;
        }

        // Get existing cite if present
        let citeElement = element.querySelector('cite');
        let citeName = config.name;
        if (citeElement && !citeName) {
            citeName = citeElement.textContent;
        }

        // Clear and rebuild
        element.innerHTML = '';

        // Apply variant class
        element.classList.add('rsl-testimonial-' + config.variant);

        // Apply size class
        if (config.size && config.size !== 'md') {
            element.classList.add('rsl-testimonial-' + config.size);
        }

        // Apply accent color
        if (config.accentColor) {
            if (['purple', 'green', 'orange', 'red', 'teal'].includes(config.accentColor)) {
                element.classList.add('rsl-testimonial-accent-' + config.accentColor);
            } else {
                // Custom hex color
                element.style.setProperty('--rsl-testimonial-accent', config.accentColor);
                element.style.setProperty('--rsl-testimonial-avatar-bg', config.accentColor);
            }
        }

        // Apply animate class
        if (config.animate) {
            element.classList.add('rsl-testimonial-animate');
        }

        // Add category tag if present
        if (config.category) {
            const categoryTag = document.createElement('span');
            categoryTag.className = 'rsl-testimonial-category';
            categoryTag.textContent = config.category;
            element.appendChild(categoryTag);

            // Set data attribute for filtering
            element.dataset.category = config.category.toLowerCase();
        }

        // Create figure for semantic structure
        const figure = document.createElement('figure');
        figure.className = 'rsl-testimonial-figure';

        // Create blockquote
        const blockquote = document.createElement('blockquote');
        blockquote.className = 'rsl-testimonial-quote';
        blockquote.innerHTML = quoteText;

        // Generate unique IDs for ARIA
        const quoteId = 'testimonial-quote-' + generateId();
        const authorId = 'testimonial-author-' + generateId();
        blockquote.id = quoteId;
        blockquote.setAttribute('aria-labelledby', authorId);

        figure.appendChild(blockquote);

        // Add star rating if present
        if (config.rating !== null && config.rating > 0) {
            const ratingContainer = document.createElement('div');
            ratingContainer.className = 'rsl-testimonial-rating';
            ratingContainer.setAttribute('aria-label', config.rating + ' out of 5 stars');

            // Use RSL.StarRating if available, otherwise create simple stars
            if (window.RSL && window.RSL.StarRating && window.RSL.StarRating.create) {
                const ratingEl = document.createElement('div');
                ratingEl.setAttribute('data-rsl-star-rating', '');
                ratingEl.setAttribute('data-star-value', config.rating);
                ratingEl.setAttribute('data-star-readonly', 'true');
                ratingEl.setAttribute('data-star-show-value', 'true');
                ratingEl.setAttribute('data-star-size', 'small');
                ratingContainer.appendChild(ratingEl);

                // Initialize after appending
                setTimeout(function() {
                    window.RSL.StarRating.create(ratingEl);
                }, 0);
            } else {
                // Fallback to simple star display
                ratingContainer.innerHTML = createSimpleStars(config.rating);
            }

            // Set data attribute for filtering
            element.dataset.rating = Math.floor(config.rating);

            figure.appendChild(ratingContainer);
        }

        // Create figcaption for attribution
        const figcaption = document.createElement('figcaption');
        figcaption.className = 'rsl-testimonial-attribution';
        figcaption.id = authorId;

        // Avatar
        if (config.avatar || citeName) {
            const avatarContainer = document.createElement('div');
            avatarContainer.className = 'rsl-testimonial-avatar';

            if (config.avatar) {
                const avatarImg = document.createElement('img');
                avatarImg.src = config.avatar;
                avatarImg.alt = config.avatarAlt || (citeName ? 'Photo of ' + citeName : 'Testimonial author');
                avatarImg.loading = 'lazy';

                // Handle image load error - show initials fallback
                avatarImg.onerror = function() {
                    avatarImg.style.display = 'none';
                    const fallback = document.createElement('span');
                    fallback.className = 'rsl-testimonial-avatar-fallback';
                    fallback.textContent = getInitials(citeName);
                    // Only set deterministic color if no accent color is specified
                    if (!config.accentColor) {
                        avatarContainer.style.backgroundColor = stringToColor(citeName);
                    }
                    avatarContainer.appendChild(fallback);
                };

                avatarContainer.appendChild(avatarImg);
            } else {
                // Show initials fallback
                const fallback = document.createElement('span');
                fallback.className = 'rsl-testimonial-avatar-fallback';
                fallback.textContent = getInitials(citeName);
                // Only set deterministic color if no accent color is specified
                if (!config.accentColor) {
                    avatarContainer.style.backgroundColor = stringToColor(citeName);
                }
                avatarContainer.appendChild(fallback);
            }

            figcaption.appendChild(avatarContainer);
        }

        // Author info container
        const authorInfo = document.createElement('div');
        authorInfo.className = 'rsl-testimonial-author';

        // Name with cite element
        if (citeName) {
            const nameEl = document.createElement('cite');
            nameEl.className = 'rsl-testimonial-name';
            nameEl.textContent = citeName;

            // Add verified badge if applicable
            if (config.verified) {
                const verifiedBadge = document.createElement('span');
                verifiedBadge.className = 'rsl-testimonial-verified';
                verifiedBadge.innerHTML = ICONS.verified + ' Verified';
                verifiedBadge.setAttribute('title', 'Verified customer');
                nameEl.appendChild(verifiedBadge);
            }

            authorInfo.appendChild(nameEl);
        }

        // Title
        if (config.title) {
            const titleEl = document.createElement('p');
            titleEl.className = 'rsl-testimonial-title';
            titleEl.textContent = config.title;
            authorInfo.appendChild(titleEl);
        }

        // Company
        if (config.company) {
            const companyEl = document.createElement('p');
            companyEl.className = 'rsl-testimonial-company';
            companyEl.textContent = config.company;
            authorInfo.appendChild(companyEl);
        }

        // Date
        if (config.date) {
            const dateEl = document.createElement('time');
            dateEl.className = 'rsl-testimonial-date';
            dateEl.dateTime = config.date;
            dateEl.textContent = formatDate(config.date);
            authorInfo.appendChild(dateEl);
        }

        figcaption.appendChild(authorInfo);

        // Company logo
        if (config.logo) {
            const logoImg = document.createElement('img');
            logoImg.className = 'rsl-testimonial-logo';
            logoImg.src = config.logo;
            logoImg.alt = config.logoAlt || (config.company ? config.company + ' logo' : 'Company logo');
            logoImg.loading = 'lazy';
            figcaption.appendChild(logoImg);
        }

        figure.appendChild(figcaption);
        element.appendChild(figure);

        // Mark as built
        element.dataset.testimonialBuilt = 'true';
    }

    /**
     * Create simple star display (fallback when StarRating not available)
     * @param {number} rating - Rating value
     * @returns {string} HTML string
     */
    function createSimpleStars(rating) {
        let html = '<span class="rsl-testimonial-stars" aria-hidden="true">';
        const fullStars = Math.floor(rating);
        const hasHalf = rating % 1 >= 0.5;

        for (let i = 0; i < 5; i++) {
            if (i < fullStars) {
                html += '<span style="color: #ffc107;">&#9733;</span>';
            } else if (i === fullStars && hasHalf) {
                html += '<span style="color: #ffc107;">&#9733;</span>'; // Could use half star
            } else {
                html += '<span style="color: #e0e0e0;">&#9733;</span>';
            }
        }
        html += '</span>';
        return html;
    }

    /**
     * Initialize slideshow functionality
     * @param {HTMLElement} container - Slideshow container
     * @param {Object} config - Configuration
     */
    function initSlideshow(container, config) {
        // Look for explicit slide wrappers first, then fall back to direct testimonial children
        var slides = container.querySelectorAll(':scope > .rsl-testimonial-slide');
        var needsWrap = false;

        if (slides.length === 0) {
            // No slide wrappers - look for direct testimonial children
            slides = container.querySelectorAll(':scope > .rsl-testimonial');
            needsWrap = true;
        }

        if (slides.length <= 1) return;

        // If testimonials aren't wrapped in slide divs, wrap them now
        if (needsWrap) {
            Array.prototype.forEach.call(slides, function(testimonial) {
                var wrapper = document.createElement('div');
                wrapper.className = 'rsl-testimonial-slide';
                testimonial.parentNode.insertBefore(wrapper, testimonial);
                wrapper.appendChild(testimonial);
            });
            // Re-query for the new slide wrappers
            slides = container.querySelectorAll(':scope > .rsl-testimonial-slide');
        }

        let currentIndex = 0;
        let autoplayTimer = null;
        let isPaused = false;

        // Create slides wrapper
        var slidesWrapper = document.createElement('div');
        slidesWrapper.className = 'rsl-testimonial-slides';
        slidesWrapper.setAttribute('role', 'region');
        slidesWrapper.setAttribute('aria-label', 'Testimonials slideshow');

        // Move slides into wrapper
        var slidesArray = Array.prototype.slice.call(slides);
        slidesArray.forEach(function(slide, index) {
            slide.setAttribute('role', 'group');
            slide.setAttribute('aria-roledescription', 'slide');
            slide.setAttribute('aria-label', 'Slide ' + (index + 1) + ' of ' + slidesArray.length);
            slidesWrapper.appendChild(slide);
        });

        container.insertBefore(slidesWrapper, container.firstChild);

        // Create live region for announcements
        const liveRegion = document.createElement('div');
        liveRegion.className = 'rsl-testimonial-live';
        liveRegion.setAttribute('aria-live', 'polite');
        liveRegion.setAttribute('aria-atomic', 'true');
        container.appendChild(liveRegion);

        // Create navigation buttons
        if (config.showNavigation) {
            const prevBtn = document.createElement('button');
            prevBtn.className = 'rsl-testimonial-nav rsl-testimonial-nav-prev';
            prevBtn.innerHTML = ICONS.chevronLeft;
            prevBtn.setAttribute('aria-label', 'Previous testimonial');
            prevBtn.type = 'button';

            const nextBtn = document.createElement('button');
            nextBtn.className = 'rsl-testimonial-nav rsl-testimonial-nav-next';
            nextBtn.innerHTML = ICONS.chevronRight;
            nextBtn.setAttribute('aria-label', 'Next testimonial');
            nextBtn.type = 'button';

            prevBtn.addEventListener('click', function() {
                goToSlide(currentIndex - 1);
            });

            nextBtn.addEventListener('click', function() {
                goToSlide(currentIndex + 1);
            });

            container.appendChild(prevBtn);
            container.appendChild(nextBtn);
        }

        // Create pagination dots
        var dots = [];
        if (config.showDots) {
            var dotsContainer = document.createElement('div');
            dotsContainer.className = 'rsl-testimonial-dots';
            dotsContainer.setAttribute('role', 'tablist');
            dotsContainer.setAttribute('aria-label', 'Testimonial slides');

            slidesArray.forEach(function(slide, index) {
                var dot = document.createElement('button');
                dot.className = 'rsl-testimonial-dot' + (index === 0 ? ' active' : '');
                dot.setAttribute('role', 'tab');
                dot.setAttribute('aria-selected', index === 0 ? 'true' : 'false');
                dot.type = 'button';

                // Get testimonial content for accessible label
                var testimonial = slide.querySelector('.rsl-testimonial');
                var authorEl = testimonial ? testimonial.querySelector('.rsl-testimonial-name, [class*="name"]') : null;
                var quoteEl = testimonial ? testimonial.querySelector('blockquote, .rsl-testimonial-quote') : null;
                var authorName = authorEl ? authorEl.textContent.trim() : 'Testimonial ' + (index + 1);
                var quoteText = quoteEl ? quoteEl.textContent.trim() : '';

                // Build descriptive aria-label with author and quote
                var ariaLabel = 'Slide ' + (index + 1) + ' of ' + slidesArray.length + ': ' + authorName;
                if (quoteText) {
                    // Truncate very long quotes for aria-label but keep enough for context
                    var truncatedQuote = quoteText.length > 150 ? quoteText.substring(0, 147) + '...' : quoteText;
                    ariaLabel += ' says "' + truncatedQuote + '"';
                }
                dot.setAttribute('aria-label', ariaLabel);

                dot.addEventListener('click', function() {
                    goToSlide(index);
                });

                // Pause autoplay when focus enters dots (ADA: let user navigate without slideshow changing)
                dot.addEventListener('focus', function() {
                    isPaused = true;
                    stopAutoplay();
                });

                dots.push(dot);
                dotsContainer.appendChild(dot);
            });

            // Resume autoplay when focus leaves the dots container entirely
            dotsContainer.addEventListener('focusout', function(e) {
                // Only resume if focus is leaving the dots container completely
                if (!dotsContainer.contains(e.relatedTarget)) {
                    isPaused = false;
                    if (config.autoplay) {
                        startAutoplay();
                    }
                }
            });

            container.appendChild(dotsContainer);
        }

        /**
         * Go to specific slide
         * @param {number} index - Slide index
         */
        function goToSlide(index) {
            // Handle wrap-around
            if (index < 0) {
                index = slidesArray.length - 1;
            } else if (index >= slidesArray.length) {
                index = 0;
            }

            currentIndex = index;

            // Move slides
            slidesWrapper.style.transform = 'translateX(-' + (currentIndex * 100) + '%)';

            // Update dots
            dots.forEach(function(dot, i) {
                dot.classList.toggle('active', i === currentIndex);
                dot.setAttribute('aria-selected', i === currentIndex ? 'true' : 'false');
            });

            // Announce to screen readers
            var currentSlide = slidesArray[currentIndex];
            var testimonial = currentSlide.querySelector('.rsl-testimonial');
            var authorEl = testimonial ? testimonial.querySelector('.rsl-testimonial-name') : null;
            var quoteEl = testimonial ? testimonial.querySelector('blockquote, .rsl-testimonial-quote') : null;
            var authorName = authorEl ? authorEl.textContent.trim() : 'Unknown';
            var quoteText = quoteEl ? quoteEl.textContent.trim() : '';

            // Build announcement with quote for better context
            var announcement = 'Testimonial ' + (currentIndex + 1) + ' of ' + slidesArray.length + ' from ' + authorName;
            if (quoteText) {
                announcement += ': "' + quoteText + '"';
            }
            liveRegion.textContent = announcement;

            // Reset autoplay timer
            if (config.autoplay && !isPaused) {
                startAutoplay();
            }
        }

        /**
         * Start autoplay
         */
        function startAutoplay() {
            stopAutoplay();
            autoplayTimer = setInterval(function() {
                if (!isPaused) {
                    goToSlide(currentIndex + 1);
                }
            }, config.autoplayInterval);
        }

        /**
         * Stop autoplay
         */
        function stopAutoplay() {
            if (autoplayTimer) {
                clearInterval(autoplayTimer);
                autoplayTimer = null;
            }
        }

        // Pause on hover
        if (config.pauseOnHover) {
            container.addEventListener('mouseenter', function() {
                isPaused = true;
            });

            container.addEventListener('mouseleave', function() {
                isPaused = false;
            });
        }

        // Keyboard navigation
        container.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowLeft') {
                e.preventDefault();
                goToSlide(currentIndex - 1);
            } else if (e.key === 'ArrowRight') {
                e.preventDefault();
                goToSlide(currentIndex + 1);
            } else if (e.key === 'Home') {
                e.preventDefault();
                goToSlide(0);
            } else if (e.key === 'End') {
                e.preventDefault();
                goToSlide(slidesArray.length - 1);
            }
        });

        // Start autoplay if enabled
        if (config.autoplay) {
            startAutoplay();

            // Stop on visibility change
            document.addEventListener('visibilitychange', function() {
                if (document.hidden) {
                    stopAutoplay();
                } else if (!isPaused) {
                    startAutoplay();
                }
            });
        }

        // Store instance data
        instances.set(container, {
            goToSlide: goToSlide,
            startAutoplay: startAutoplay,
            stopAutoplay: stopAutoplay,
            getCurrentIndex: function() { return currentIndex; },
            getSlideCount: function() { return slidesArray.length; }
        });
    }

    /**
     * Initialize animate on scroll
     * @param {HTMLElement} element - Testimonial element
     */
    function initAnimateOnScroll(element) {
        // Check for reduced motion preference
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            element.classList.add('rsl-testimonial-visible');
            return;
        }

        // Small delay to ensure initial styles are applied before observer can trigger
        // This prevents instant animation for elements already in viewport at page load
        setTimeout(function() {
            const observer = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('rsl-testimonial-visible');
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.2,
                rootMargin: '0px 0px -50px 0px'
            });

            observer.observe(element);
        }, 100);
    }

    /**
     * Initialize FilterBus integration
     * @param {HTMLElement} element - Testimonial element
     * @param {Object} config - Configuration
     */
    function initFilterBus(element, config) {
        if (!window.RSL || !window.RSL.FilterBus) return;

        const subscriberId = 'testimonial-' + generateId();

        // Find the target element to hide - prefer parent .slot-item for proper grid reflow
        const hideTarget = element.closest('.slot-item') || element;

        // Subscribe to category filter
        if (config.filterCategory) {
            window.RSL.FilterBus.subscribe(subscriberId + '-category', function(state) {
                const filterValue = state[config.filterCategory];
                if (!filterValue || filterValue === 'all') {
                    hideTarget.classList.remove('filterbus-hidden');
                } else {
                    const elementCategory = element.dataset.category || '';
                    if (elementCategory.toLowerCase() === filterValue.toLowerCase()) {
                        hideTarget.classList.remove('filterbus-hidden');
                    } else {
                        hideTarget.classList.add('filterbus-hidden');
                    }
                }
            }, { keys: [config.filterCategory] });
        }

        // Subscribe to rating filter
        if (config.filterRating) {
            window.RSL.FilterBus.subscribe(subscriberId + '-rating', function(state) {
                const minRating = state[config.filterRating] || 0;
                const elementRating = parseFloat(element.dataset.rating) || 0;

                if (minRating === 0 || elementRating >= minRating) {
                    hideTarget.classList.remove('filterbus-hidden');
                } else {
                    hideTarget.classList.add('filterbus-hidden');
                }
            }, { keys: [config.filterRating] });
        }
    }

    /**
     * Generate unique ID
     * @returns {string} Unique ID
     */
    function generateId() {
        return Math.random().toString(36).substring(2, 9);
    }

    /**
     * Initialize a single testimonial
     * @param {HTMLElement} element - The testimonial element
     */
    function initTestimonial(element) {
        if (instances.has(element)) return;

        const config = getConfig(element);

        // Check if this is a slideshow container
        if (config.slideshow) {
            // Build each slide's testimonial - look for both wrapped and direct children
            var testimonials = element.querySelectorAll('.rsl-testimonial-slide [data-rsl-testimonial]');
            if (testimonials.length === 0) {
                // No wrapped testimonials found, look for direct testimonial children
                testimonials = element.querySelectorAll(':scope > [data-rsl-testimonial]');
            }
            testimonials.forEach(function(testimonial) {
                const testimonialConfig = getConfig(testimonial);
                buildTestimonial(testimonial, testimonialConfig);
            });

            // Initialize slideshow
            element.classList.add('rsl-testimonial-slideshow');
            initSlideshow(element, config);
        } else {
            // Single testimonial
            buildTestimonial(element, config);

            // Initialize animate on scroll
            if (config.animate) {
                initAnimateOnScroll(element);
            }

            // Initialize FilterBus
            if (config.filterCategory || config.filterRating) {
                initFilterBus(element, config);
            }
        }

        instances.set(element, { config: config });
    }

    /**
     * Public API
     */
    window.RSL.Testimonial = {

        /**
         * Initialize all testimonials on page
         */
        init: function() {
            // First initialize slideshow containers (they handle their own inner testimonials)
            const slideshows = document.querySelectorAll('[data-testimonial-slideshow="true"]');
            slideshows.forEach(function(element) {
                if (!instances.has(element)) {
                    initTestimonial(element);
                }
            });

            // Then initialize standalone testimonials (skip those inside slideshows)
            const testimonials = document.querySelectorAll('[data-rsl-testimonial]');
            testimonials.forEach(function(element) {
                // Skip if already initialized or if inside a slideshow container
                if (instances.has(element)) return;
                if (element.closest('[data-testimonial-slideshow="true"]')) return;
                initTestimonial(element);
            });
        },

        /**
         * Create a testimonial instance
         * @param {HTMLElement|string} element - Element or selector
         * @param {Object} [options] - Configuration options
         * @returns {Object} Instance
         */
        create: function(element, options) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            if (!element) {
                console.error('[RSL.Testimonial] Element not found');
                return null;
            }

            // Apply options as data attributes
            if (options) {
                Object.keys(options).forEach(function(key) {
                    const attrName = 'data-testimonial-' + key.replace(/([A-Z])/g, '-$1').toLowerCase();
                    element.setAttribute(attrName, options[key]);
                });
            }

            initTestimonial(element);
            return instances.get(element);
        },

        /**
         * Destroy a testimonial instance
         * @param {HTMLElement|string} element - Element or selector
         */
        destroy: function(element) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            if (element && instances.has(element)) {
                instances.delete(element);
                element.dataset.testimonialBuilt = 'false';
            }
        },

        /**
         * Get instance for element
         * @param {HTMLElement|string} element
         * @returns {Object|null}
         */
        getInstance: function(element) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }
            return instances.get(element) || null;
        },

        /**
         * Go to specific slide in slideshow
         * @param {HTMLElement|string} element - Slideshow element
         * @param {number} index - Slide index
         */
        goToSlide: function(element, index) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            const instance = instances.get(element);
            if (instance && instance.goToSlide) {
                instance.goToSlide(index);
            }
        },

        /**
         * Get current slide index
         * @param {HTMLElement|string} element - Slideshow element
         * @returns {number} Current index
         */
        getCurrentSlide: function(element) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            const instance = instances.get(element);
            if (instance && instance.getCurrentIndex) {
                return instance.getCurrentIndex();
            }
            return 0;
        },

        /**
         * Pause slideshow autoplay
         * @param {HTMLElement|string} element - Slideshow element
         */
        pause: function(element) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            const instance = instances.get(element);
            if (instance && instance.stopAutoplay) {
                instance.stopAutoplay();
            }
        },

        /**
         * Resume slideshow autoplay
         * @param {HTMLElement|string} element - Slideshow element
         */
        play: function(element) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            const instance = instances.get(element);
            if (instance && instance.startAutoplay) {
                instance.startAutoplay();
            }
        }
    };

    // Auto-initialize on DOMContentLoaded
    document.addEventListener('DOMContentLoaded', function() {
        window.RSL.Testimonial.init();
    });

})();
