/**
 * RSL Pricing Table Component
 * Version: 1.0.0
 *
 * A premium, accessible pricing table component supporting:
 * - Multiple variants (cards, comparison, compact, horizontal)
 * - Monthly/Annual billing toggle with savings calculation
 * - Feature states (included, excluded, partial with tooltips)
 * - Animated entrance effects
 * - FilterBus integration
 * - Full keyboard navigation
 *
 * WCAG 2.1 AA Compliant:
 * - Semantic HTML structure
 * - Full keyboard navigation
 * - Screen reader announcements via aria-live
 * - Visible focus indicators
 * - Respects prefers-reduced-motion
 *
 * @namespace RSL.PricingTable
 */

(function() {
    'use strict';

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

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

    // SVG Icons
    const ICONS = {
        check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg>',
        cross: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>',
        partial: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>',
        info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>',
        chevronDown: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>'
    };

    /**
     * Default configuration
     */
    const DEFAULTS = {
        variant: 'cards',           // cards, comparison, compact, horizontal
        currency: '$',
        currencyPosition: 'before', // before, after
        billingPeriod: 'mo',        // Display text for period
        toggleMonthly: 'Monthly',
        toggleAnnual: 'Annual',
        savingsTemplate: 'Save {{percent}}%',
        animate: false,
        stickyHeader: false,
        mobileAccordion: false,
        filterKey: null             // FilterBus key for filtering
    };

    /**
     * Get configuration from data attributes
     * @param {HTMLElement} element - The pricing table element
     * @returns {Object} Configuration object
     */
    function getConfig(element) {
        return {
            variant: element.dataset.pricingVariant || DEFAULTS.variant,
            currency: element.dataset.pricingCurrency || DEFAULTS.currency,
            currencyPosition: element.dataset.pricingCurrencyPosition || DEFAULTS.currencyPosition,
            billingPeriod: element.dataset.pricingPeriod || DEFAULTS.billingPeriod,
            toggleMonthly: element.dataset.pricingToggleMonthly || DEFAULTS.toggleMonthly,
            toggleAnnual: element.dataset.pricingToggleAnnual || DEFAULTS.toggleAnnual,
            savingsTemplate: element.dataset.pricingSavingsTemplate || DEFAULTS.savingsTemplate,
            animate: element.dataset.pricingAnimate === 'true',
            stickyHeader: element.dataset.pricingStickyHeader === 'true',
            mobileAccordion: element.dataset.pricingMobileAccordion === 'true',
            filterKey: element.dataset.filterbusKey || DEFAULTS.filterKey
        };
    }

    /**
     * Get tier configuration from data attributes
     * @param {HTMLElement} tierEl - The tier element
     * @returns {Object} Tier configuration
     */
    function getTierConfig(tierEl) {
        return {
            name: tierEl.dataset.tierName || '',
            description: tierEl.dataset.tierDescription || '',
            priceMonthly: parseFloat(tierEl.dataset.tierPriceMonthly) || null,
            priceAnnual: parseFloat(tierEl.dataset.tierPriceAnnual) || null,
            originalPrice: parseFloat(tierEl.dataset.tierOriginalPrice) || null,
            customPrice: tierEl.dataset.tierCustomPrice || null,
            badge: tierEl.dataset.tierBadge || null,
            badgeVariant: tierEl.dataset.tierBadgeVariant || null,
            highlighted: tierEl.dataset.tierHighlighted === 'true',
            ctaText: tierEl.dataset.tierCtaText || 'Get Started',
            ctaUrl: tierEl.dataset.tierCtaUrl || '#',
            ctaVariant: tierEl.dataset.tierCtaVariant || null,
            priceNote: tierEl.dataset.tierPriceNote || null,
            filterValue: tierEl.dataset.filterValue || null
        };
    }

    /**
     * Get feature configuration from data attributes
     * @param {HTMLElement} featureEl - The feature element
     * @returns {Object} Feature configuration
     */
    function getFeatureConfig(featureEl) {
        const included = featureEl.dataset.featureIncluded;
        return {
            text: featureEl.dataset.featureText || featureEl.textContent.trim(),
            included: included === 'true' ? true : included === 'false' ? false : included,
            tooltip: featureEl.dataset.featureTooltip || null,
            category: featureEl.dataset.featureCategory || null
        };
    }

    /**
     * Format price for display
     * @param {number} price - The price value
     * @param {Object} config - Configuration
     * @returns {string} Formatted price HTML
     */
    function formatPrice(price, config) {
        if (price === null || price === undefined) return '';

        const priceStr = Math.floor(price) === price ?
            price.toString() :
            price.toFixed(2);

        return priceStr;
    }

    /**
     * Calculate savings percentage
     * @param {number} monthly - Monthly price
     * @param {number} annual - Annual price
     * @returns {number} Savings percentage
     */
    function calculateSavings(monthly, annual) {
        if (!monthly || !annual || monthly <= 0) return 0;
        const yearlyCostMonthly = monthly * 12;
        const yearlyCostAnnual = annual * 12;
        const savings = ((yearlyCostMonthly - yearlyCostAnnual) / yearlyCostMonthly) * 100;
        return Math.round(savings);
    }

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

    /**
     * Create live region for screen reader announcements
     * @param {HTMLElement} container - Container element
     * @returns {HTMLElement} Live region element
     */
    function createLiveRegion(container) {
        const region = document.createElement('div');
        region.className = 'rsl-pricing-live';
        region.setAttribute('role', 'status');
        region.setAttribute('aria-live', 'polite');
        region.setAttribute('aria-atomic', 'true');
        container.appendChild(region);
        return region;
    }

    /**
     * Announce to screen readers
     * @param {HTMLElement} liveRegion - Live region element
     * @param {string} message - Message to announce
     */
    function announce(liveRegion, message) {
        if (!liveRegion) return;
        liveRegion.textContent = '';
        // Force reflow
        void liveRegion.offsetHeight;
        liveRegion.textContent = message;
    }

    /**
     * Build the billing toggle
     * @param {HTMLElement} container - Container element
     * @param {Object} config - Configuration
     * @param {Object} state - Component state
     * @returns {Object} Toggle elements
     */
    function buildBillingToggle(container, config, state) {
        const wrapper = document.createElement('div');
        wrapper.className = 'rsl-pricing-toggle-wrapper';
        wrapper.setAttribute('role', 'group');
        wrapper.setAttribute('aria-label', 'Billing period');

        // Monthly label
        const monthlyLabel = document.createElement('span');
        monthlyLabel.className = 'rsl-pricing-toggle-label active';
        monthlyLabel.textContent = config.toggleMonthly;
        monthlyLabel.setAttribute('tabindex', '0');
        monthlyLabel.setAttribute('role', 'button');
        monthlyLabel.setAttribute('aria-pressed', 'true');
        monthlyLabel.id = 'pricing-toggle-monthly-' + generateId();

        // Toggle button
        const toggle = document.createElement('button');
        toggle.className = 'rsl-pricing-toggle';
        toggle.setAttribute('type', 'button');
        toggle.setAttribute('role', 'switch');
        toggle.setAttribute('aria-checked', 'false');
        toggle.setAttribute('aria-label', 'Switch between monthly and annual billing');

        const knob = document.createElement('span');
        knob.className = 'rsl-pricing-toggle-knob';
        knob.setAttribute('aria-hidden', 'true');
        toggle.appendChild(knob);

        // Annual label with savings
        const annualLabel = document.createElement('span');
        annualLabel.className = 'rsl-pricing-toggle-label';
        annualLabel.setAttribute('tabindex', '0');
        annualLabel.setAttribute('role', 'button');
        annualLabel.setAttribute('aria-pressed', 'false');
        annualLabel.id = 'pricing-toggle-annual-' + generateId();

        const annualText = document.createElement('span');
        annualText.textContent = config.toggleAnnual;
        annualLabel.appendChild(annualText);

        // Calculate max savings across tiers
        let maxSavings = 0;
        const tiers = container.querySelectorAll('[data-tier-price-monthly][data-tier-price-annual]');
        tiers.forEach(function(tier) {
            const monthly = parseFloat(tier.dataset.tierPriceMonthly);
            const annual = parseFloat(tier.dataset.tierPriceAnnual);
            const savings = calculateSavings(monthly, annual);
            if (savings > maxSavings) maxSavings = savings;
        });

        if (maxSavings > 0) {
            const savingsBadge = document.createElement('span');
            savingsBadge.className = 'rsl-pricing-savings';
            const savingsText = config.savingsTemplate.replace('{{percent}}', maxSavings);
            savingsBadge.textContent = savingsText;
            annualLabel.appendChild(savingsBadge);
        }

        wrapper.appendChild(monthlyLabel);
        wrapper.appendChild(toggle);
        wrapper.appendChild(annualLabel);

        // Event handlers
        function setAnnual(isAnnual) {
            state.isAnnual = isAnnual;
            toggle.setAttribute('aria-checked', String(isAnnual));
            monthlyLabel.classList.toggle('active', !isAnnual);
            monthlyLabel.setAttribute('aria-pressed', String(!isAnnual));
            annualLabel.classList.toggle('active', isAnnual);
            annualLabel.setAttribute('aria-pressed', String(isAnnual));

            // Update prices
            updatePrices(container, config, state);

            // Announce change
            const period = isAnnual ? config.toggleAnnual : config.toggleMonthly;
            announce(state.liveRegion, 'Billing changed to ' + period);

            // Dispatch event
            container.dispatchEvent(new CustomEvent('rsl-pricing-toggle', {
                bubbles: true,
                detail: { isAnnual: isAnnual, period: period }
            }));
        }

        toggle.addEventListener('click', function() {
            setAnnual(!state.isAnnual);
        });

        monthlyLabel.addEventListener('click', function() {
            setAnnual(false);
        });

        monthlyLabel.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                setAnnual(false);
            }
        });

        annualLabel.addEventListener('click', function() {
            setAnnual(true);
        });

        annualLabel.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                setAnnual(true);
            }
        });

        toggle.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                e.preventDefault();
                setAnnual(false);
            } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                e.preventDefault();
                setAnnual(true);
            }
        });

        return { wrapper: wrapper, toggle: toggle, monthlyLabel: monthlyLabel, annualLabel: annualLabel };
    }

    /**
     * Update prices based on billing toggle state
     * @param {HTMLElement} container - Container element
     * @param {Object} config - Configuration
     * @param {Object} state - Component state
     */
    function updatePrices(container, config, state) {
        const tiers = container.querySelectorAll('.rsl-pricing-tier');
        const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

        tiers.forEach(function(tier) {
            const priceEl = tier.querySelector('.rsl-pricing-price');
            const noteEl = tier.querySelector('.rsl-pricing-price-note');

            if (!priceEl) return;

            const monthly = parseFloat(tier.dataset.tierPriceMonthly);
            const annual = parseFloat(tier.dataset.tierPriceAnnual);

            if (monthly && annual) {
                const price = state.isAnnual ? annual : monthly;
                priceEl.textContent = formatPrice(price, config);

                // Update aria-label
                const priceWrapper = tier.querySelector('.rsl-pricing-price-wrapper');
                if (priceWrapper) {
                    const periodText = state.isAnnual ? 'per month, billed annually' : 'per month';
                    priceWrapper.setAttribute('aria-label',
                        config.currency + price + ' ' + periodText);
                }

                // Add animation class
                if (!reducedMotion) {
                    priceEl.classList.add('rsl-pricing-price-animate');
                    setTimeout(function() {
                        priceEl.classList.remove('rsl-pricing-price-animate');
                    }, 400);
                }

                // Update note
                if (noteEl) {
                    noteEl.textContent = state.isAnnual ? 'billed annually' : 'billed monthly';
                }
            }
        });
    }

    /**
     * Build a tier card
     * @param {HTMLElement} tierEl - Original tier element
     * @param {Object} config - Configuration
     * @param {Object} state - Component state
     */
    function buildTierCard(tierEl, config, state) {
        const tierConfig = getTierConfig(tierEl);

        // Don't rebuild if already built
        if (tierEl.dataset.pricingBuilt === 'true') return;

        // Apply classes
        tierEl.classList.add('rsl-pricing-tier');
        if (tierConfig.highlighted) {
            tierEl.classList.add('rsl-pricing-tier-highlighted');
        }

        // Save original features
        const originalFeatures = tierEl.querySelectorAll('[data-feature-text], [data-feature-included]');
        const featuresData = Array.from(originalFeatures).map(getFeatureConfig);

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

        // Badge
        if (tierConfig.badge) {
            const badge = document.createElement('div');
            badge.className = 'rsl-pricing-badge';
            badge.textContent = tierConfig.badge;
            if (tierConfig.badgeVariant) {
                badge.setAttribute('data-badge-variant', tierConfig.badgeVariant);
            }
            tierEl.appendChild(badge);
        }

        // Header
        const header = document.createElement('div');
        header.className = 'rsl-pricing-tier-header';

        const name = document.createElement('h3');
        name.className = 'rsl-pricing-tier-name';
        name.textContent = tierConfig.name;
        name.id = 'tier-' + generateId();
        header.appendChild(name);

        if (tierConfig.description) {
            const desc = document.createElement('p');
            desc.className = 'rsl-pricing-tier-description';
            desc.textContent = tierConfig.description;
            header.appendChild(desc);
        }

        tierEl.appendChild(header);

        // Price
        const priceWrapper = document.createElement('div');
        priceWrapper.className = 'rsl-pricing-price-wrapper';

        if (tierConfig.customPrice) {
            // Custom price text (Free, Contact Sales, etc.)
            const customPrice = document.createElement('div');
            customPrice.className = 'rsl-pricing-custom-price';
            customPrice.textContent = tierConfig.customPrice;
            priceWrapper.appendChild(customPrice);
            priceWrapper.setAttribute('aria-label', tierConfig.customPrice);
        } else if (tierConfig.priceMonthly !== null || tierConfig.priceAnnual !== null) {
            const priceContainer = document.createElement('div');
            priceContainer.className = 'rsl-pricing-price-container';

            const currency = document.createElement('span');
            currency.className = 'rsl-pricing-currency';
            currency.textContent = config.currency;
            currency.setAttribute('aria-hidden', 'true');

            const price = document.createElement('span');
            price.className = 'rsl-pricing-price';
            const currentPrice = state.isAnnual && tierConfig.priceAnnual ?
                tierConfig.priceAnnual : tierConfig.priceMonthly;
            price.textContent = formatPrice(currentPrice, config);

            const period = document.createElement('span');
            period.className = 'rsl-pricing-price-period';
            period.textContent = '/' + config.billingPeriod;
            period.setAttribute('aria-hidden', 'true');

            if (config.currencyPosition === 'before') {
                priceContainer.appendChild(currency);
            }
            priceContainer.appendChild(price);
            priceContainer.appendChild(period);
            if (config.currencyPosition === 'after') {
                priceContainer.appendChild(currency);
            }

            priceWrapper.appendChild(priceContainer);

            // Set aria-label
            const periodText = state.isAnnual ? 'per month, billed annually' : 'per month';
            priceWrapper.setAttribute('aria-label',
                config.currency + currentPrice + ' ' + periodText);

            // Original price (strikethrough)
            if (tierConfig.originalPrice) {
                const original = document.createElement('div');
                original.className = 'rsl-pricing-original-price';
                original.textContent = config.currency + formatPrice(tierConfig.originalPrice, config);
                original.setAttribute('aria-label', 'Originally ' + config.currency + tierConfig.originalPrice);
                priceWrapper.appendChild(original);
            }

            // Price note
            if (tierConfig.priceNote || (tierConfig.priceMonthly && tierConfig.priceAnnual)) {
                const note = document.createElement('div');
                note.className = 'rsl-pricing-price-note';
                note.textContent = tierConfig.priceNote || (state.isAnnual ? 'billed annually' : 'billed monthly');
                priceWrapper.appendChild(note);
            }
        }

        tierEl.appendChild(priceWrapper);

        // Features
        if (featuresData.length > 0) {
            const featuresList = document.createElement('ul');
            featuresList.className = 'rsl-pricing-features';
            featuresList.setAttribute('role', 'list');
            featuresList.setAttribute('aria-label', 'Features included in ' + tierConfig.name + ' plan');

            let currentCategory = null;

            featuresData.forEach(function(featureData) {
                // Category header
                if (featureData.category && featureData.category !== currentCategory) {
                    currentCategory = featureData.category;
                    const categoryLi = document.createElement('li');
                    categoryLi.className = 'rsl-pricing-feature-category';
                    categoryLi.textContent = featureData.category;
                    categoryLi.setAttribute('role', 'presentation');
                    featuresList.appendChild(categoryLi);
                }

                const li = document.createElement('li');
                li.className = 'rsl-pricing-feature';

                // Determine included state
                let includedState = 'included';
                let iconHtml = ICONS.check;
                let srText = 'Included: ';

                if (featureData.included === false) {
                    includedState = 'excluded';
                    iconHtml = ICONS.cross;
                    srText = 'Not included: ';
                    li.classList.add('excluded');
                } else if (featureData.included !== true && featureData.included !== 'true') {
                    includedState = 'partial';
                    iconHtml = ICONS.partial;
                    srText = 'Partially included: ';
                }

                // Icon
                const icon = document.createElement('span');
                icon.className = 'rsl-pricing-feature-icon ' + includedState;
                icon.innerHTML = iconHtml;
                icon.setAttribute('aria-hidden', 'true');
                li.appendChild(icon);

                // Text with optional tooltip
                const textWrapper = document.createElement('span');
                textWrapper.className = 'rsl-pricing-feature-text';

                // Screen reader text
                const srOnly = document.createElement('span');
                srOnly.className = 'rsl-pricing-sr-only';
                srOnly.textContent = srText;
                textWrapper.appendChild(srOnly);

                if (featureData.tooltip) {
                    const tooltipWrapper = document.createElement('span');
                    tooltipWrapper.className = 'rsl-pricing-feature-tooltip';
                    tooltipWrapper.setAttribute('tabindex', '0');
                    tooltipWrapper.setAttribute('aria-describedby', 'tooltip-' + generateId());

                    const text = document.createElement('span');
                    text.textContent = featureData.text;
                    tooltipWrapper.appendChild(text);

                    const tooltipIcon = document.createElement('span');
                    tooltipIcon.className = 'rsl-pricing-feature-tooltip-icon';
                    tooltipIcon.innerHTML = ICONS.info;
                    tooltipWrapper.appendChild(tooltipIcon);

                    const tooltipContent = document.createElement('span');
                    tooltipContent.className = 'rsl-pricing-feature-tooltip-content';
                    tooltipContent.id = tooltipWrapper.getAttribute('aria-describedby');
                    tooltipContent.textContent = featureData.tooltip;
                    tooltipContent.setAttribute('role', 'tooltip');
                    tooltipWrapper.appendChild(tooltipContent);

                    textWrapper.appendChild(tooltipWrapper);
                } else {
                    textWrapper.appendChild(document.createTextNode(featureData.text));
                }

                li.appendChild(textWrapper);
                featuresList.appendChild(li);
            });

            tierEl.appendChild(featuresList);
        }

        // CTA Button
        const cta = document.createElement('a');
        cta.className = 'rsl-pricing-cta';
        cta.href = tierConfig.ctaUrl;
        cta.textContent = tierConfig.ctaText;

        if (tierConfig.ctaVariant === 'primary' || tierConfig.highlighted) {
            cta.classList.add('rsl-pricing-cta-primary');
        } else if (tierConfig.ctaVariant === 'secondary') {
            cta.classList.add('rsl-pricing-cta-secondary');
        }

        // Accessible label
        cta.setAttribute('aria-label', tierConfig.ctaText + ' for ' + tierConfig.name + ' plan');

        tierEl.appendChild(cta);

        // Set aria-labelledby
        tierEl.setAttribute('aria-labelledby', name.id);

        // Mark as built
        tierEl.dataset.pricingBuilt = 'true';
    }

    /**
     * Initialize animate on scroll
     * @param {HTMLElement} container - Container element
     * @param {Object} config - Configuration
     */
    function initAnimateOnScroll(container, config) {
        if (!config.animate) return;

        // Check for reduced motion preference
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            const tiers = container.querySelectorAll('.rsl-pricing-tier');
            tiers.forEach(function(tier) {
                tier.classList.add('rsl-pricing-visible');
            });
            return;
        }

        container.classList.add('rsl-pricing-animate');

        // Small delay to ensure initial styles are applied
        setTimeout(function() {
            const observer = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('rsl-pricing-visible');
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.2,
                rootMargin: '0px 0px -50px 0px'
            });

            const tiers = container.querySelectorAll('.rsl-pricing-tier');
            tiers.forEach(function(tier) {
                observer.observe(tier);
            });
        }, 100);
    }

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

        const subscriberId = 'pricing-table-' + generateId();

        window.RSL.FilterBus.subscribe(subscriberId, function(state) {
            const filterValue = state[config.filterKey];
            const tiers = container.querySelectorAll('.rsl-pricing-tier');

            tiers.forEach(function(tier) {
                const tierFilterValue = tier.dataset.filterValue;

                if (!filterValue || filterValue === 'all' || !tierFilterValue) {
                    tier.classList.remove('rsl-pricing-filterbus-hidden');
                } else {
                    const tierValues = tierFilterValue.split(',').map(function(v) {
                        return v.trim().toLowerCase();
                    });
                    const matches = tierValues.indexOf(filterValue.toLowerCase()) !== -1;
                    tier.classList.toggle('rsl-pricing-filterbus-hidden', !matches);
                }
            });
        }, { keys: [config.filterKey] });
    }

    /**
     * Initialize mobile accordion mode
     * @param {HTMLElement} container - Container element
     * @param {Object} config - Configuration
     */
    function initMobileAccordion(container, config) {
        if (!config.mobileAccordion) return;

        function checkMobile() {
            const isMobile = window.innerWidth < 768;

            if (isMobile && !container.classList.contains('rsl-pricing-accordion')) {
                container.classList.add('rsl-pricing-accordion');
                initAccordionBehavior(container);
            } else if (!isMobile && container.classList.contains('rsl-pricing-accordion')) {
                container.classList.remove('rsl-pricing-accordion');
                removeAccordionBehavior(container);
            }
        }

        checkMobile();
        window.addEventListener('resize', checkMobile);
    }

    /**
     * Initialize accordion behavior for mobile
     * @param {HTMLElement} container - Container element
     */
    function initAccordionBehavior(container) {
        const tiers = container.querySelectorAll('.rsl-pricing-tier');

        tiers.forEach(function(tier, index) {
            const header = tier.querySelector('.rsl-pricing-tier-header');
            if (!header) return;

            // Add accordion icon
            const icon = document.createElement('span');
            icon.className = 'rsl-pricing-accordion-icon';
            icon.innerHTML = ICONS.chevronDown;
            header.appendChild(icon);

            // Wrap content
            const content = document.createElement('div');
            content.className = 'rsl-pricing-tier-content';

            const children = Array.from(tier.children).filter(function(child) {
                return child !== header && !child.classList.contains('rsl-pricing-badge');
            });

            children.forEach(function(child) {
                content.appendChild(child);
            });

            tier.appendChild(content);

            // Set initial state
            const isFirst = index === 0;
            tier.setAttribute('aria-expanded', String(isFirst));
            tier.setAttribute('tabindex', '0');
            tier.setAttribute('role', 'button');

            // Click handler
            function toggleTier() {
                const isExpanded = tier.getAttribute('aria-expanded') === 'true';
                tier.setAttribute('aria-expanded', String(!isExpanded));
            }

            header.addEventListener('click', toggleTier);
            tier.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    toggleTier();
                }
            });
        });
    }

    /**
     * Remove accordion behavior
     * @param {HTMLElement} container - Container element
     */
    function removeAccordionBehavior(container) {
        const tiers = container.querySelectorAll('.rsl-pricing-tier');

        tiers.forEach(function(tier) {
            const icon = tier.querySelector('.rsl-pricing-accordion-icon');
            if (icon) icon.remove();

            const content = tier.querySelector('.rsl-pricing-tier-content');
            if (content) {
                Array.from(content.children).forEach(function(child) {
                    tier.appendChild(child);
                });
                content.remove();
            }

            tier.removeAttribute('aria-expanded');
            tier.removeAttribute('tabindex');
            tier.removeAttribute('role');
        });
    }

    /**
     * Initialize a pricing table
     * @param {HTMLElement} element - The pricing table element
     */
    function initPricingTable(element) {
        if (instances.has(element)) return;

        const config = getConfig(element);
        const state = {
            isAnnual: false,
            liveRegion: null
        };

        // Add variant class
        if (config.variant) {
            element.classList.add('rsl-pricing-table-' + config.variant);
        }

        // Create live region
        state.liveRegion = createLiveRegion(element);

        // Check if toggle is needed
        const hasBillingToggle = element.querySelector('[data-tier-price-monthly][data-tier-price-annual]');

        if (hasBillingToggle) {
            const toggleElements = buildBillingToggle(element, config, state);
            element.insertBefore(toggleElements.wrapper, element.firstChild);
        }

        // Build tiers container
        const tiers = element.querySelectorAll('[data-tier-name]');
        let tiersContainer = element.querySelector('.rsl-pricing-tiers');

        if (!tiersContainer && tiers.length > 0) {
            tiersContainer = document.createElement('div');
            tiersContainer.className = 'rsl-pricing-tiers';
            tiersContainer.setAttribute('data-tier-count', tiers.length.toString());

            tiers.forEach(function(tier) {
                buildTierCard(tier, config, state);
                tiersContainer.appendChild(tier);
            });

            element.appendChild(tiersContainer);
        } else if (tiersContainer) {
            tiersContainer.setAttribute('data-tier-count', tiers.length.toString());
            tiers.forEach(function(tier) {
                buildTierCard(tier, config, state);
            });
        }

        // Initialize features
        initAnimateOnScroll(element, config);
        initFilterBus(element, config);
        initMobileAccordion(element, config);

        // Store instance
        instances.set(element, { config: config, state: state });
    }

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

        /**
         * Initialize all pricing tables on page
         */
        init: function() {
            const tables = document.querySelectorAll('[data-rsl-pricing-table]');
            tables.forEach(function(element) {
                initPricingTable(element);
            });
        },

        /**
         * Create a pricing table 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.PricingTable] Element not found');
                return null;
            }

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

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

        /**
         * Destroy a pricing table 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);
            }
        },

        /**
         * 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;
        },

        /**
         * Set billing period programmatically
         * @param {HTMLElement|string} element - Pricing table element
         * @param {boolean} isAnnual - True for annual, false for monthly
         */
        setBilling: function(element, isAnnual) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            const instance = instances.get(element);
            if (!instance) return;

            const toggle = element.querySelector('.rsl-pricing-toggle');
            if (toggle) {
                instance.state.isAnnual = isAnnual;
                toggle.setAttribute('aria-checked', String(isAnnual));

                const monthlyLabel = element.querySelector('.rsl-pricing-toggle-label:first-of-type');
                const annualLabel = element.querySelector('.rsl-pricing-toggle-label:last-of-type');

                if (monthlyLabel) {
                    monthlyLabel.classList.toggle('active', !isAnnual);
                    monthlyLabel.setAttribute('aria-pressed', String(!isAnnual));
                }
                if (annualLabel) {
                    annualLabel.classList.toggle('active', isAnnual);
                    annualLabel.setAttribute('aria-pressed', String(isAnnual));
                }

                updatePrices(element, instance.config, instance.state);
            }
        },

        /**
         * Get current billing period
         * @param {HTMLElement|string} element - Pricing table element
         * @returns {boolean} True if annual, false if monthly
         */
        isAnnual: function(element) {
            if (typeof element === 'string') {
                element = document.querySelector(element);
            }

            const instance = instances.get(element);
            return instance ? instance.state.isAnnual : false;
        }
    };

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

})();
