jQuery(document).ready(function($) {
    // Open Modal and safely map data from our centralized registry profile object
    $(document).on('click', '.agq-btn', function(e) {
        e.preventDefault();
        
        var productId = $(this).data('product-id');
        
        // Safety validation fallback if product tracking key is somehow missing
        if (!productId || !agq_ajax.registry || !agq_ajax.registry[productId]) {
            console.error("Armeditech Engine Error: Product context parameters missing for ID: " + productId);
            return;
        }

        var selectedProduct = agq_ajax.registry[productId];

        // Map cached data profiles directly into visual nodes
        $('#agq-display-img').attr('src', selectedProduct.image);
        $('#agq-display-title').text(selectedProduct.title);
        
        if (selectedProduct.attrs) {
            $('#agq-display-attrs').html(selectedProduct.attrs).show();
        } else {
            $('#agq-display-attrs').hide();
        }

        // Assemble tracking package string for processing
        var cleanSummary = "Product Name: " + selectedProduct.title + "\nProduct URL: " + selectedProduct.url;
        $('#agq-product').val(cleanSummary);

        // Reset display structures and fade in
        $('#agq-message').html('');
        $('#agq-form')[0].reset();
        $('#agq-popup').fadeIn(200);
    });

    // Close Modal Container Hooks
    $(document).on('click', '.agq-close, #agq-popup', function(e) {
        if (e.target === this || $(e.target).hasClass('agq-close')) {
            $('#agq-popup').fadeOut(200);
        }
    });

    // Handle AJAX Form Post Submission Engine
    $('#agq-form').on('submit', function(e) {
        e.preventDefault();
        var $submitBtn = $(this).find('.agq-submit-btn');
        $submitBtn.prop('disabled', true).text('Processing...');

        var formData = {
            action: 'agq_send_quote',
            security: agq_ajax.nonce,
            full_name: $(this).find('input[name="full_name"]').val(),
            mobile_no: $(this).find('input[name="mobile_no"]').val(),
            email: $(this).find('input[name="email"]').val(),
            product_summary: $('#agq-product').val()
        };

        $.post(agq_ajax.ajax_url, formData, function(response) {
            if (response.success) {
                $('#agq-message').html('<span style="color: #00a296; display:block; margin-top:10px;">' + response.data + '</span>');
                setTimeout(function() {
                    $('#agq-popup').fadeOut(300);
                }, 2000);
            } else {
                $('#agq-message').html('<span style="color: #d9534f; display:block; margin-top:10px;">' + response.data + '</span>');
                $submitBtn.prop('disabled', false).text('Contact Now');
            }
        });
    });
});