jQuery(document).ready(function ($) {
    // Tab switching functionality
    $('.tab-button').on('click', function () {
        var tabId = $(this).data('tab');

        // Remove active class from all tabs and contents
        $('.tab-button').removeClass('active');
        $('.tab-content').removeClass('active');

        // Add active class to clicked tab and corresponding content
        $(this).addClass('active');
        $('#' + tabId).addClass('active');
    });

    // Auto-load previews when page loads (if they were previously saved)
    $(window).on('load', function () {
        // Check if previews were previously shown and reload them
        $('.widget-preview').each(function () {
            var $preview = $(this);
            if ($preview.is(':visible') && $preview.find('.preview-content').children().length > 0) {
                // Preview is already visible, keep it as is
                return;
            }
        });
    });

    // Form submission - keep previews visible after save
    $('form').on('submit', function () {
        // Store current preview states
        var previewStates = {};
        $('.widget-preview').each(function () {
            var previewId = $(this).attr('id');
            previewStates[previewId] = {
                visible: $(this).is(':visible'),
                content: $(this).find('.preview-content').html()
            };
        });

        // Store in sessionStorage to restore after page reload
        sessionStorage.setItem('widgetPreviewStates', JSON.stringify(previewStates));
    });

    // Restore preview states after page load
    var storedStates = sessionStorage.getItem('widgetPreviewStates');
    if (storedStates) {
        try {
            var previewStates = JSON.parse(storedStates);
            Object.keys(previewStates).forEach(function (previewId) {
                var state = previewStates[previewId];
                var $preview = $('#' + previewId);
                if (state.visible && state.content) {
                    $preview.show();
                    $preview.find('.preview-content').html(state.content);
                    // Re-trigger currency dropdown to initialize prices
                    $preview.find('.pmrcgold-currency-dropdown').trigger('change');
                }
            });
            // Clear stored states
            sessionStorage.removeItem('widgetPreviewStates');
        } catch (e) {

        }
    }

    // Auto-load previews on page load for all widgets
    setTimeout(function () {
        // Auto-load preview for Widget 1
        if ($('#widget1_preview').length) {
            updateWidgetPreview(1);
        }
        // Auto-load preview for Widget 2
        if ($('#widget2_preview').length) {
            updateWidgetPreview(2);
        }
        // Auto-load preview for Widget 3
        if ($('#widget3_preview').length) {
            updateWidgetPreview(3);
        }
        // Auto-load preview for Widget 4
        if ($('#widget4_preview').length) {
            updateWidgetPreview(4);
        }
    }, 500); // Small delay to ensure page is fully loaded

    // Real-time preview updates on form changes
    function updateWidgetPreview(widgetNumber) {
        var $previewContainer = $('#widget' + widgetNumber + '_preview');
        var $previewContent = $previewContainer.find('.preview-content');

        // Get current form values
        var currentMetals = $('#widget' + widgetNumber + '_metals').val() || [];
        var currentCurrencies = $('#widget' + widgetNumber + '_currencies').val() || [];
        var currentEnabled = $('#widget' + widgetNumber + '_enabled').val() || [];

        // Show loading state
        $previewContent.html('<p style="text-align: center; margin: 30px 0; opacity: 0.6;">Updating preview...</p>');
        $previewContainer.show();

        // Make AJAX call with current form values
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pmrcgold_widget' + widgetNumber + '_preview',
                nonce: pmrcgold_admin['widget' + widgetNumber + '_nonce'],
                metals: currentMetals,
                currencies: currentCurrencies,
                enabled: currentEnabled
            },
            success: function (response) {
                $previewContent.html(response);
                // $previewContent.find('.pmrcgold-currency-dropdown').trigger('change');
                if (widgetNumber === 3) {
                    // Give the DOM a moment to settle, then initialize widget3
                    setTimeout(function () {
                        if (typeof window.pmrcgold_init_widget3 === 'function') {
                            window.pmrcgold_init_widget3();
                        }
                    }, 50);
                } else {
                    $previewContent.find('.pmrcgold-currency-dropdown').trigger('change');
                }
            },
            error: function () {
                $previewContent.html('<p style="text-align: center; margin: 30px 0; color: #dc3545;">Error updating preview. Please try again.</p>');
            }
        });
    }

    // Widget 1 real-time updates
    $('#widget1_metals, #widget1_currencies, #widget1_enabled').on('change', function () {
        updateWidgetPreview(1);
    });

    // Widget 2 real-time updates
    $('#widget2_metals, #widget2_currencies').on('change', function () {
        updateWidgetPreview(2);
    });

    // Widget 3 real-time updates
    $('#widget3_metals, #widget3_currencies').on('change', function () {
        updateWidgetPreview(3);
    });

    // Widget 4 real-time updates
    $('#widget4_metals, #widget4_currencies').on('change', function () {
        updateWidgetPreview(4);
    });

    // Widget 1 Preview functionality
    $('#widget1_preview_btn').on('click', function () {
        var $previewContainer = $('#widget1_preview');
        var $previewContent = $previewContainer.find('.preview-content');

        $previewContent.html('<p style="text-align: center; margin: 30px 0; opacity: 0.6;">Loading preview...</p>');
        $previewContainer.show();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pmrcgold_widget1_preview',
                nonce: pmrcgold_admin.widget1_nonce
            },
            success: function (response) {
                $previewContent.html(response);
                // Trigger currency dropdown change to initialize prices in preview
                $previewContent.find('.pmrcgold-currency-dropdown').trigger('change');
            },
            error: function () {
                $previewContent.html('<p style="text-align: center; margin: 30px 0; color: #dc3545;">Error loading preview. Please try again.</p>');
            }
        });
    });


    $('#widget2_preview_btn').on('click', function () {
        var $previewContainer = $('#widget2_preview');
        var $previewContent = $previewContainer.find('.preview-content');

        $previewContent.html('<p style="text-align: center; margin: 30px 0; opacity: 0.6;">Loading preview...</p>');
        $previewContainer.show();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pmrcgold_widget2_preview',
                nonce: pmrcgold_admin.widget2_nonce
            },
            success: function (response) {
                $previewContent.html(response);
                // Trigger currency dropdown change to initialize prices in preview
                $previewContent.find('.pmrcgold-currency-dropdown').trigger('change');
            },
            error: function () {
                $previewContent.html('<p style="text-align: center; margin: 30px 0; color: #dc3545;">Error loading preview. Please try again.</p>');
            }
        });
    });


    $('#widget3_preview_btn').on('click', function () {
        var $previewContainer = $('#widget3_preview');
        var $previewContent = $previewContainer.find('.preview-content');

        $previewContent.html('<p style="text-align: center; margin: 30px 0; opacity: 0.6;">Loading preview...</p>');
        $previewContainer.show();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pmrcgold_widget3_preview',
                nonce: pmrcgold_admin.widget3_nonce
            },
            success: function (response) {
                $previewContent.html(response);
                // Trigger currency dropdown change to initialize prices in preview
                $previewContent.find('.pmrcgold-currency-dropdown').trigger('change');
            },
            error: function () {
                $previewContent.html('<p style="text-align: center; margin: 30px 0; color: #dc3545;">Error loading preview. Please try again.</p>');
            }
        });
    });

    $('#widget4_preview_btn').on('click', function () {
        var $previewContainer = $('#widget4_preview');
        var $previewContent = $previewContainer.find('.preview-content');

        $previewContent.html('<p style="text-align: center; margin: 30px 0; opacity: 0.6;">Loading preview...</p>');
        $previewContainer.show();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'pmrcgold_widget4_preview',
                nonce: pmrcgold_admin.widget4_nonce
            },
            success: function (response) {
                $previewContent.html(response);
                // Trigger currency dropdown change to initialize prices in preview
                $previewContent.find('.pmrcgold-currency-dropdown').trigger('change');
            },
            error: function () {
                $previewContent.html('<p style="text-align: center; margin: 30px 0; color: #dc3545;">Error loading preview. Please try again.</p>');
            }
        });
    });


    // Shortcode Widget 1 Currency Switching
    // $(document).on('change', '.pmrcgold-currency-dropdown', function() {
    //     var $widget = $(this).closest('.pmrcgold-shortcode-widget-1');
    //     var currency = $(this).val();

    //     $widget.find('.pmrcgold-metal-badge').each(function() {
    //         var metal = $(this).data('metal');
    //         var price = generateMockPrice(metal, currency);
    //         var change = (Math.random() * 50).toFixed(2);
    //         var isUp = Math.random() > 0.5;
    //         var symbol = getCurrencySymbol(currency);

    //         $(this).find('.metal-price').text(symbol + price);
    //         $(this).find('.metal-change')
    //             .text((isUp ? '↑ ' : '↓ ') + (isUp ? '+' : '-') + symbol + change)
    //             .removeClass('up down')
    //             .addClass(isUp ? 'up' : 'down');
    //     });
    // });

    // Initialize Shortcode Prices
    $('.pmrcgold-currency-dropdown').trigger('change');

    // Helper function to get currency symbol
    function getCurrencySymbol(currency) {
        var symbols = {
            'USD': '$',
            'EUR': '€',
            'GBP': '£',
            'JPY': '¥',
            'AUD': 'A$',
            'CAD': 'C$',
            'CHF': 'Fr',
            'CNY': '¥',
            'INR': '₹',
            'AED': 'د.إ'
        };
        return symbols[currency] || currency;
    }

    // Helper function to generate mock prices
    // function generateMockPrice(metal, currency) {
    //     var basePrices = {
    //         'gold': { 'USD': 1850, 'EUR': 1700, 'GBP': 1450, 'JPY': 275000, 'AUD': 2800, 'CAD': 2500, 'CHF': 1650, 'CNY': 13500, 'INR': 150000, 'AED': 6800 },
    //         'silver': { 'USD': 22.5, 'EUR': 20.8, 'GBP': 17.8, 'JPY': 3350, 'AUD': 34, 'CAD': 30, 'CHF': 20, 'CNY': 165, 'INR': 1850, 'AED': 83 },
    //         'platinum': { 'USD': 950, 'EUR': 875, 'GBP': 750, 'JPY': 140000, 'AUD': 1450, 'CAD': 1300, 'CHF': 850, 'CNY': 7000, 'INR': 78000, 'AED': 3500 }
    //     };

    //     var basePrice = basePrices[metal] && basePrices[metal][currency] ? basePrices[metal][currency] : 100;
    //     var variation = (Math.random() - 0.5) * 10; // ±5% variation
    //     var price = basePrice + variation;

    //     // Format price based on currency
    //     if (currency === 'JPY' || currency === 'INR') {
    //         return Math.round(price).toLocaleString();
    //     } else {
    //         return price.toFixed(2);
    //     }
    // }
});
