jQuery(function ($) {

    // When a variation is selected by WooCommerce 
    $(document).on('found_variation', 'form.variations_form', function (event, variation) {
        // Set variation id on the visible button (if exists) and on the hidden form data
        $('.aramex-rate-calc-btn').data('variation_id', variation.variation_id);
        $('#aramex-rate-form').data('variation_id', variation.variation_id);
    });

    // When variation is reset (e.g., user changes options)
    $(document).on('reset_data', 'form.variations_form', function () {
        $('.aramex-rate-calc-btn').removeData('variation_id');
        $('#aramex-rate-form').removeData('variation_id');
    });

    //open popup
    $(document).on("click", ".aramex-rate-calc-btn", function () {
        const btn = $(this);
        const pid = btn.data("product_id") || 0;
        const qty = btn.closest("form.cart").find("input.qty").val() || 1;
        const variation_id = btn.data("variation_id") || 0;

        // store product, qty and variation on popup form
        $("#aramex-rate-form").data({ product_id: pid, qty: qty, variation_id: variation_id });
        $("#aramex-rate-popup").fadeIn();
    });


    //close popup
    $(document).on("click", "#aramex-rate-close", () => $("#aramex-rate-popup").fadeOut());


    // submit form and get rates
    $(document).on("submit", "#aramex-rate-form", function (e) {
        e.preventDefault();
        const f = $(this),
              result = $("#aramex-rate-result").html("<p>Calculating...</p>");

        // read variation id from form data
        const variation_id = f.data('variation_id') || 0;

        $.post(aramexRateCalc.ajax_url, {
            action: "aramex_rate_calc",
            security: aramexRateCalc.nonce,
            city: f.find("[name=aramex_city]").val(),
            postcode: f.find("[name=aramex_postcode]").val(),
            country: f.find("[name=aramex_country]").val(),
            product_id: f.data("product_id") || 0,
            qty: f.data("qty") || 1,
            variation_id: variation_id
        }, res => {
            if (res.success && res.data && res.data.rates && res.data.rates.length) {
                const html = res.data.rates.map(r =>
                    `<li>Aramex Shipping ${r.ProductGroup}/${r.ProductType}: ${r.Amount} ${r.Currency}</li>`
                ).join('');
                result.html(`<ul>${html}</ul>`);
            } else if (res.data && res.data.message) {
                // show error message from server
                result.html("<p>" + res.data.message + "</p>");
            } else {
                result.html("<p>No rates found.</p>");
            }
        }).fail(function(xhr){
            result.html("<p>Request failed. Try again.</p>");
        });
    });


    // Insert Rate Calculator button on Cart page
    if ($('body').hasClass('woocommerce-cart')) {
        const template = document.getElementById('aramex-rate-calc-template');
        if (!template) return;

        let attempts = 0;
        const interval = setInterval(function () {
            // --- For block-based cart ---
            const checkoutBlock = document.querySelector('.wc-block-cart__submit.wp-block-woocommerce-proceed-to-checkout-block');

            // --- For classic (non-block) cart ---
            const classicButton = document.querySelector('.wc-proceed-to-checkout');

            if (checkoutBlock) {
                checkoutBlock.insertAdjacentElement('afterend', template.firstElementChild);
                clearInterval(interval);
            } else if (classicButton) {
                classicButton.insertAdjacentElement('afterend', template.firstElementChild);
                clearInterval(interval);
            }

            // Safety stop after 15 seconds
            if (++attempts > 50) clearInterval(interval);
        }, 300); // poll every 300ms
    }

});
