(function($) {
    'use strict';

    $(document).ready(function() {
        initPurityTooltips();
        initCardAnimations();
        initAutoRefresh();
        initUpdateConfirmation();
        initPurityFactors();
        initLivePricePreview();
        initMetalTabs();
        initMetalTypeSelector();
    });

    /**
     * Initialize metal tabs on dashboard
     */
    function initMetalTabs() {
        $('.gspsync-metal-tab').on('click', function() {
            var metal = $(this).data('metal');

            // Update active tab
            $('.gspsync-metal-tab').removeClass('active');
            $(this).addClass('active');

            // Show corresponding panel
            $('.gspsync-metal-panel').removeClass('active');
            $('#gspsync-panel-' + metal).addClass('active');
        });
    }

    /**
     * Metal type selector in product metabox - updates purity dropdown
     */
    function initMetalTypeSelector() {
        var $metalSelect = $('#gspsync-metal-type');
        var $puritySelect = $('#gspsync-purity-select');

        if (!$metalSelect.length || !$puritySelect.length) {
            return;
        }

        function updatePurityOptions() {
            var metal = $metalSelect.val();

            // Show/hide purity optgroups based on metal type
            $puritySelect.find('optgroup').hide();

            if (metal === 'gold') {
                $puritySelect.find('.gspsync-purity-gold').show();
                $puritySelect.prop('disabled', false);
            } else if (metal === 'silver') {
                $puritySelect.find('.gspsync-purity-silver').show();
                $puritySelect.prop('disabled', false);
            } else {
                $puritySelect.find('optgroup').show();
                $puritySelect.prop('disabled', false);
            }
        }

        $metalSelect.on('change', updatePurityOptions);

        // Initialize on load
        updatePurityOptions();
    }

    /**
     * Purity tooltips for all metals
     */
    function initPurityTooltips() {
        var purityInfo = {
            // Gold
            '24k': 'Pure gold 99.9%',
            '22k': 'Gold 91.7% - High quality jewelry',
            '18k': 'Gold 75% - Standard fine jewelry',
            '14k': 'Gold 58.3% - Good balance of purity and durability',
            '10k': 'Gold 41.7% - More durable, less pure',
            // Silver
            '.999': 'Fine Silver 99.9%',
            '.925': 'Sterling Silver 92.5%',
            '.900': 'Silver 90%',
            '.800': 'Silver 80%'
        };

        $('.gspsync-purity-badge').each(function() {
            var purity = $(this).text().toLowerCase();
            if (purityInfo[purity]) {
                $(this).attr('title', purityInfo[purity]);
            }
        });
    }

    /**
     * Card animations
     */
    function initCardAnimations() {
        $('.gspsync-card').each(function(index) {
            $(this).css({
                'opacity': '0',
                'transform': 'translateY(20px)'
            });

            setTimeout(function() {
                $(this).animate({
                    'opacity': '1'
                }, 300).css('transform', 'translateY(0)');
            }.bind(this), index * 100);
        });
    }

    /**
     * Auto-refresh metal prices every 5 minutes
     */
    function initAutoRefresh() {
        var refreshInterval;

        function startAutoRefresh() {
            refreshInterval = setInterval(function() {
                refreshMetalPrices();
            }, 300000);
        }

        function refreshMetalPrices() {
            var priceCard = $('.gspsync-price-info .gspsync-card-content');
            priceCard.prepend('<div class="gspsync-loading"><span class="dashicons dashicons-update spin"></span> Updating prices...</div>');

            setTimeout(function() {
                $('.gspsync-loading').fadeOut(300, function() {
                    $(this).remove();
                });
                console.log('Metal prices auto-refreshed');
            }, 2000);
        }

        if ($('.gspsync-admin-wrap').length) {
            startAutoRefresh();
        }

        $(window).on('beforeunload', function() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        });
    }

    /**
     * Manual update confirmation
     */
    function initUpdateConfirmation() {
        $('input[name="update_prices_now"]').closest('form').on('submit', function(e) {
            var productCount = $('.gspsync-products-table tbody tr').length;

            if (productCount > 0) {
                var confirmed = confirm(
                    'Update prices for ' + productCount + ' product' + (productCount > 1 ? 's' : '') + '?'
                );

                if (!confirmed) {
                    e.preventDefault();
                    return false;
                }
            }

            var submitBtn = $(this).find('input[type="submit"]');
            submitBtn.val('Updating...').prop('disabled', true);
        });
    }

    /**
     * Purity factor inputs validation
     */
    function initPurityFactors() {
        $('.gspsync-purity-input').on('input', function() {
            var value = parseFloat($(this).val());
            var purity = $(this).data('purity');
            var $percentage = $(this).siblings('.gspsync-percentage');

            if (!isNaN(value) && value >= 0.1 && value <= 1.0) {
                $percentage.text((value * 100).toFixed(1) + '%');
                $(this).removeClass('error');
            } else {
                $percentage.text('Error');
                $(this).addClass('error');
            }
        });

        $('.gspsync-purity-input').on('blur', function() {
            var value = parseFloat($(this).val());
            if (isNaN(value) || value < 0.1 || value > 1.0) {
                $(this).addClass('error');
                alert('Value must be between 0.1 and 1.0');
                $(this).focus();
            }
        });
    }

    /**
     * Live Price Preview for Variation Fields (multi-metal aware)
     */
    function initLivePricePreview() {
        if (!$('#woocommerce-product-data').length) {
            return;
        }

        if (typeof gspsync_admin_params === 'undefined') {
            return;
        }

        function debounce(func, wait) {
            var timeout;
            return function() {
                var context = this, args = arguments;
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    func.apply(context, args);
                }, wait);
            };
        }

        /**
         * Format an amount the way PHP does, using the shop's currency settings.
         */
        function formatPrice(amount) {
            var currency = gspsync_admin_params.currency || {};
            var symbol = currency.symbol || '';
            var decimalSep = currency.decimal_sep || ',';
            var thousandSep = typeof currency.thousand_sep === 'string' ? currency.thousand_sep : '.';

            var parts = Math.abs(amount).toFixed(2).split('.');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep);

            var formatted = (amount < 0 ? '-' : '') + parts.join(decimalSep);

            switch (currency.position) {
                case 'right':
                    return formatted + symbol;
                case 'right_space':
                    return formatted + ' ' + symbol;
                case 'left_space':
                    return symbol + ' ' + formatted;
                default:
                    return symbol + formatted;
            }
        }

        /**
         * Calculate price client-side using the correct metal price
         */
        function calculatePriceLocally(weight, purity, markup, metalType) {
            var metalPrices = gspsync_admin_params.metal_prices || {};
            var pricePerGram = parseFloat(metalPrices[metalType]) || 0;
            var profitMargin = parseFloat(gspsync_admin_params.profit_margin) || 20;
            var allPurities = gspsync_admin_params.purity_factors || {};
            var purities = allPurities[metalType] || {};

            // Default purity
            if (!purity || purity === '') {
                var keys = Object.keys(purities);
                purity = keys.length > 0 ? keys[0] : '';
            }

            var purityFactor = parseFloat(purities[purity]) || 1.0;

            var basePrice = weight * pricePerGram * purityFactor;
            var marginAmount = basePrice * (profitMargin / 100);
            var finalPrice = basePrice + marginAmount + markup;

            return {
                price: finalPrice.toFixed(2),
                formatted_price: formatPrice(finalPrice),
                base_price: formatPrice(basePrice),
                margin: formatPrice(marginAmount),
                markup: formatPrice(markup),
                purity_used: purity
            };
        }

        function updatePricePreview($container) {
            var variationId = $container.data('variation-id');
            var metalType = $container.data('metal-type') || 'gold';
            var $variationPanel = $container.closest('.woocommerce_variation');

            var $weightInput = $variationPanel.find('input[name="_gspsync_weight_grams[' + variationId + ']"]');
            var $puritySelect = $variationPanel.find('select[name="_gspsync_purity[' + variationId + ']"]');
            var $markupInput = $variationPanel.find('input[name="_gspsync_markup[' + variationId + ']"]');

            var weight = parseFloat($weightInput.val()) || 0;
            var purity = $puritySelect.length ? $puritySelect.val() || '' : '';
            var markup = parseFloat($markupInput.val()) || 0;

            if (weight <= 0) {
                $container.html(
                    '<div class="gspsync-price-placeholder" style="color: #666; font-style: italic;">' +
                    (gspsync_admin_params.i18n.enter_weight || 'Enter a weight to see the estimated price') +
                    '</div>'
                );
                return;
            }

            var result = calculatePriceLocally(weight, purity, markup, metalType);

            var html = '<div class="gspsync-price-display">' +
                '<strong style="color: #0073aa;">' + (gspsync_admin_params.i18n.estimated_price || 'Estimated price:') + '</strong> ' +
                '<span class="gspsync-calculated-price" style="font-size: 1.1em; font-weight: bold; color: #2e7d32;">' +
                result.formatted_price +
                '</span>' +
                '</div>' +
                '<div class="gspsync-price-breakdown" style="margin-top: 5px; font-size: 0.85em; color: #666;">' +
                '(' + (gspsync_admin_params.i18n.base || 'Base') + ': ' + result.base_price +
                ' + ' + (gspsync_admin_params.i18n.margin || 'Margin') + ': ' + result.margin +
                ' + ' + (gspsync_admin_params.i18n.markup || 'Markup') + ': ' + result.markup + ')' +
                '</div>';

            $container.html(html);
        }

        var debouncedUpdate = debounce(function($container) {
            updatePricePreview($container);
        }, 300);

        // Event delegation for dynamically loaded variation panels
        $(document).on('input change', 'input[name^="_gspsync_weight_grams"], input[name^="_gspsync_markup"], select[name^="_gspsync_purity"]', function() {
            var $variationPanel = $(this).closest('.woocommerce_variation');
            var $previewContainer = $variationPanel.find('.gspsync-live-price-preview');

            if ($previewContainer.length) {
                debouncedUpdate($previewContainer);
            }
        });

        $(document).on('woocommerce_variations_loaded', function() {
            $('.gspsync-live-price-preview').each(function() {
                updatePricePreview($(this));
            });
        });

        setTimeout(function() {
            $('.gspsync-live-price-preview').each(function() {
                var $container = $(this);
                var $variationPanel = $container.closest('.woocommerce_variation');
                var variationId = $container.data('variation-id');
                var $weightInput = $variationPanel.find('input[name="_gspsync_weight_grams[' + variationId + ']"]');

                if ($weightInput.length && parseFloat($weightInput.val()) > 0) {
                    updatePricePreview($container);
                }
            });
        }, 500);
    }

})(jQuery);

// Spin animation CSS
var gspsyncStyle = document.createElement('style');
gspsyncStyle.textContent = [
    '.gspsync-loading {',
    '    background: #fff3cd;',
    '    padding: 15px;',
    '    border-radius: 6px;',
    '    margin-bottom: 15px;',
    '    color: #856404;',
    '    font-weight: 600;',
    '    text-align: center;',
    '}',
    '.spin {',
    '    animation: gspsync-spin 1s linear infinite;',
    '}',
    '@keyframes gspsync-spin {',
    '    0% { transform: rotate(0deg); }',
    '    100% { transform: rotate(360deg); }',
    '}'
].join('\n');
document.head.appendChild(gspsyncStyle);
