jQuery(function($) {
    'use strict';

    // Currency Switcher functionality
    function initCurrencySwitcher() {
        const $switcher = $('#startbutton-currency-switcher');
        const $triggerButton = $('#currency-trigger-button');
        const $container = $('#currency-switcher-container');
        const $currentCurrency = $('#currency-trigger');
        const $dropdown = $('#currency-dropdown');
        const $overlay = $('#currency-overlay');
        const $currencyOptions = $('.currency-option');

        let isOpen = false;

        // Toggle currency switcher
        function toggleCurrencySwitcher() {
            if (isOpen) {
                closeCurrencySwitcher();
            } else {
                openCurrencySwitcher();
            }
        }

        // Open currency switcher
        function openCurrencySwitcher() {
            isOpen = true;
            $triggerButton.addClass('active').attr('aria-expanded', 'true');
            $container.addClass('show');
            $overlay.addClass('show');

            $container.css('right', $triggerButton.width() + 30 + 'px');
            
            // Simulate loading delay for smooth UX
            setTimeout(() => {
                $dropdown.addClass('show');
            }, 200);
        }

        // Close currency switcher
        function closeCurrencySwitcher() {
            isOpen = false;
            $triggerButton.removeClass('active').attr('aria-expanded', 'false');
            $dropdown.removeClass('show');
            $overlay.removeClass('show');
            
            // Delay hiding container for smooth animation
            setTimeout(() => {
                $container.removeClass('show');
            }, 200);
        }

        // Handle currency selection
        function handleCurrencySelection(currencyCode) {
            const $option = $currencyOptions.filter(`[data-currency="${currencyCode}"]`);
            const postData = $option.data('post');
            
            if (!postData) {
                console.error('No post data available for currency:', currencyCode);
                return;
            }

            // create a map for all the symbols from the currency-switcher-container id
            const symbols = {};
            const currencySwitcherContainer = document.getElementById('currency-switcher-container');
            const currencyOptions = currencySwitcherContainer.querySelectorAll('.currency-option');
            currencyOptions.forEach(option => {
                const currencyCode = option.getAttribute('data-currency');
                const symbol = option.querySelector('.currency-symbol').textContent;
                symbols[currencyCode] = symbol;
            });
            // console.log(symbols);

            // Add loading state
            $triggerButton.addClass('loading');
            console.log('startbutton_currency.ajax_url', startbutton_currency.ajax_url);
            // Submit currency change via AJAX
            $.ajax({
                url: startbutton_currency.ajax_url,
                type: 'POST',
                data: {
                    action: 'startbutton_switch_currency',
                    currency: currencyCode,
                    nonce: startbutton_currency.nonce,
                    post_data: postData
                },
                success: function(response) {
                    if (response.success) {
                        closeCurrencySwitcher();
                        
                        // Trigger cart fragment refresh instead of page reload
                        $(document.body).trigger('wc_fragment_refresh');
                        
                        setTimeout(() => location.reload(), 500);
                    } else {
                        console.error('Currency switch failed:', response.data);
                        alert('Failed to switch currency. Please try again.');
                    }
                },
                error: function() {
                    console.error('Currency switch request failed');
                    $triggerButton.removeClass('loading');
                    alert('Failed to switch currency. Please try again.');
                },
            });
        }

        // Event listeners
        $triggerButton.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            toggleCurrencySwitcher();
        });

        $currentCurrency.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            toggleCurrencySwitcher();
        });

        $currencyOptions.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const currencyCode = $(this).data('currency');
            if (currencyCode) {
                handleCurrencySelection(currencyCode);
            }
        });

        $overlay.on('click', function(e) {
            e.preventDefault();
            closeCurrencySwitcher();
        });

        // Keyboard navigation
        $triggerButton.on('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                toggleCurrencySwitcher();
            }
        });

        $currencyOptions.on('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                const currencyCode = $(this).data('currency');
                if (currencyCode) {
                    handleCurrencySelection(currencyCode);
                }
            }
        });

        // Close on escape key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && isOpen) {
                closeCurrencySwitcher();
            }
        });

        // Close on click outside
        $(document).on('click', function(e) {
            if (isOpen && !$switcher.has(e.target).length) {
                closeCurrencySwitcher();
            }
        });

        // Handle scroll events
        let scrollTimeout;
        $(window).on('scroll', function() {
            if (isOpen) {
                $container.addClass('scrolling');
                clearTimeout(scrollTimeout);
                scrollTimeout = setTimeout(() => {
                    $container.removeClass('scrolling');
                }, 150);
            }
        });

        // Accessibility improvements
        $triggerButton.on('focus', function() {
            $(this).addClass('hover');
        }).on('blur', function() {
            $(this).removeClass('hover');
        });

        // Initialize tooltips on mobile
        if (window.innerWidth <= 768) {
            $triggerButton.find('.trigger-tooltip').hide();
        }

        // Handle window resize
        $(window).on('resize', function() {
            if (window.innerWidth <= 768) {
                $triggerButton.find('.trigger-tooltip').hide();
            } else {
                $triggerButton.find('.trigger-tooltip').show();
            }
        });
    }

    // Initialize when DOM is ready
    if ($('#startbutton-currency-switcher').length) {
        initCurrencySwitcher();
    }

    // Re-initialize on AJAX content updates (for dynamic content)
    $(document.body).on('updated_checkout', function() {
        if ($('#startbutton-currency-switcher').length) {
            initCurrencySwitcher();
        }
    });
}); 