jQuery(document).ready(function($) {
    var $container = $('#saa-metabox-container .saa-products');

    function nextIndex() {
        return $container.find('.saa-product-row').not('.saa-template').length;
    }

    // Add product
    $('.saa-add-product').on('click', function(e) {
        e.preventDefault();

        var index = nextIndex();
        var $template = $container.find('.saa-template').first().clone(true, true);

        if (!$template.length) {
            alert('Template not found. Please make sure the template row exists.');
            return;
        }

        $template.removeClass('saa-template').show();

        // Assign names using data-field attributes + reset values
        $template.find('input, textarea').each(function() {
            var $field = $(this);
            var key = $field.data('field');

            // sanitize: remove any existing name attr on the template
            $field.removeAttr('name');

            if (key) {
                $field.attr('name', 'saa_products[' + index + '][' + key + ']');
            }

            if ($field.is(':checkbox')) {
                $field.prop('checked', false);
            } else {
                $field.val('');
            }
        });

        // Hide manual fields by default in new row
        $template.find('.saa-manual-fields').hide();

        // Update heading
        $template.find('h4').text('Product ' + (index + 1));

        // Reset shortcode preview
        $template.find('.saa-shortcode-line code').text('[amazon_product asin=""]');

        $container.append($template);
    });

    // Remove product
    $(document).on('click', '.saa-remove-product', function(e) {
        e.preventDefault();
        var $row = $(this).closest('.saa-product-row');
        if (confirm('Remove this product?')) {
            $row.remove();
            // (Optional) Re-number headings after removal
            $container.find('.saa-product-row').not('.saa-template').each(function(i) {
                $(this).find('h4').text('Product ' + (i + 1));
            });
        }
    });

    // Toggle manual fields (delegated)
    $container.on('change', 'input[type="checkbox"][data-field="manual"]', function() {
        var $row = $(this).closest('.saa-product-row');
        if ($(this).is(':checked')) {
            $row.find('.saa-manual-fields').slideDown();
        } else {
            $row.find('.saa-manual-fields').slideUp();
        }
    });

    // Update shortcode preview when ASIN changes (delegated)
    $container.on('input', 'input[data-field="asin"]', function() {
        var $row = $(this).closest('.saa-product-row');
        var val = $(this).val() || '';
        // If a full URL is pasted, we leave extraction to PHP on save,
        // but for preview we can try to extract quickly:
        var m = val.match(/(?:dp|gp\/product)\/([A-Z0-9]{10})/i);
        var asin = m ? m[1].toUpperCase() : val.trim().toUpperCase();
        $row.find('.saa-shortcode-line code').text('[amazon_product asin="' + asin + '"]');
    });

    // Copy shortcode
    $container.on('click', '.saa-copy-shortcode', function(e) {
        e.preventDefault();
        var $code = $(this).siblings('code');
        var text = $code.text();

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(() => {
                flashCopyFeedback($(this));
            }).catch(() => {
                legacyCopy(text, $(this));
            });
        } else {
            legacyCopy(text, $(this));
        }
    });

    function legacyCopy(text, $btn) {
        var $temp = $('<input type="text" style="position:absolute;left:-9999px;">');
        $('body').append($temp);
        $temp.val(text).select();
        document.execCommand('copy');
        $temp.remove();
        flashCopyFeedback($btn);
    }

    function flashCopyFeedback($btn) {
        var original = $btn.text();
        $btn.text(saaMetabox.copy_text || 'Copied!');
        setTimeout(function() {
            $btn.text(original);
        }, 1500);
    }

    // Media uploader
    $container.on('click', '.saa-upload-image', function(e) {
        e.preventDefault();
        var $input = $(this).siblings('input[type="text"]');
        var frame = wp.media({
            title: 'Select or Upload Image',
            button: { text: 'Use this image' },
            multiple: false
        });

        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            $input.val(attachment.url).trigger('input');
        });

        frame.open();
    });
});
