jQuery(document).ready(function ($) {
    /** Variables dynamiques pour l'ajout de conditions (adapter si besoin) */
 const smapVariables = {
    "[order_id]": "The unique identifier of the order",
    "[order_status]": "The current status of the order",
    "[order_total]": "The total amount of the order including taxes and shipping",
    "[order_currency]": "The currency in which the order was placed",
    "[order_payment_method]": "The payment method used for the order",
    "[order_payment_title]": "The display title of the payment method used",
    "[order_transaction_id]": "The transaction ID associated with the payment",
    "[order_discount_total]": "The total discount applied to the order",
    "[order_discount_tax]": "The tax amount applied to the discount",
    "[order_shipping_total]": "The total shipping cost of the order",
    "[order_shipping_tax]": "The tax amount applied to the shipping cost",
    "[order_tax_total]": "The total tax amount applied to the order",
    "[order_subtotal]": "The subtotal of the order before taxes and shipping",
    "[order_key]": "A unique key assigned to the order",
    "[order_cart_hash]": "A hash representing the contents of the cart",
    "[order_created_via]": "How the order was created (e.g., store-api, admin, checkout)",
    "[order_ip_address]": "The IP address of the customer when placing the order",
    "[order_user_agent]": "The browser user agent of the customer",

    "[order_date_created]": "The date and time when the order was created",
    "[order_date_modified]": "The date and time when the order was last modified",
    "[order_date_paid]": "The date and time when the order was marked as paid",
    "[order_date_completed]": "The date and time when the order was marked as completed",

    "[customer_id]": "The unique identifier of the customer",
    "[customer_email]": "The email address of the customer",
    "[customer_phone]": "The phone number of the customer",

    "[billing_first_name]": "The first name in the billing address",
    "[billing_last_name]": "The last name in the billing address",
    "[billing_company]": "The company name in the billing address",
    "[billing_address_1]": "The primary address in the billing address",
    "[billing_address_2]": "The secondary address in the billing address",
    "[billing_city]": "The city in the billing address",
    "[billing_state]": "The state/region in the billing address",
    "[billing_postcode]": "The postal/ZIP code in the billing address",
    "[billing_country]": "The country in the billing address",

    "[shipping_first_name]": "The first name in the shipping address",
    "[shipping_last_name]": "The last name in the shipping address",
    "[shipping_company]": "The company name in the shipping address",
    "[shipping_address_1]": "The primary address in the shipping address",
    "[shipping_address_2]": "The secondary address in the shipping address",
    "[shipping_city]": "The city in the shipping address",
    "[shipping_state]": "The state/region in the shipping address",
    "[shipping_postcode]": "The postal/ZIP code in the shipping address",
    "[shipping_country]": "The country in the shipping address",
    "[shipping_phone]": "The phone number associated with the shipping address",

    "[order_items]": "List of ordered products with quantity",
    "[shipping_method]": "The shipping method used for the order",
    "[shipping_tracking_number]": "The tracking number for the shipment",

    "[customer_note]": "Any note provided by the customer",
    "[transaction_id]": "The transaction ID associated with the payment",
    "[order_notes]": "Internal order notes added by the store admin"
};

    function generateVariableOptions() {
        let options = '';
        for (const [key, value] of Object.entries(smapVariables)) {
            options += `<option value="${key}">${key} : ${value}</option>`;
        }
        return options;
    }

    /** Récupère et affiche la liste des règles */
    function fetchRules() {
        $.post(smap_ajax.ajax_url, { action: 'smap_fetch_rules' }, function (response) {
            if (response.success) {
                $('#smap-rules-list').html(response.html);
            } else {
                console.error('Error fetching rules:', response.message);
            }
        }, 'json');
    }

    /** Soumission du formulaire d'ajout de règle */
    $('#smap-rule-form').submit(function (e) {
        e.preventDefault();
        let formData = $(this).serialize();

        $.ajax({
            url: smap_ajax.ajax_url,
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    alert(response.message);
                    $('#smap-rule-form')[0].reset();
                    $('#conditions-container').html('');
                    fetchRules();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX Error:', xhr.responseText);
                alert('Unexpected error. Check console log for details.');
            }
        });
    });

    /** Ajout d'une condition */
    $(document).off('click', '#add-condition').on('click', '#add-condition', function (e) {
        e.preventDefault();

        let newCondition = `
            <div class="condition-row" style="margin-bottom: 10px; display: flex; align-items: center; gap: 10px;">
                <select name="variable[]" style="width: 30%;">${generateVariableOptions()}</select>
                <select name="operator[]" style="width: 25%;">
                    <option value="equal">Equal to</option>
                    <option value="not_equal">Not equal to</option>
                    <option value="greater_than">Greater than</option>
                    <option value="less_than">Less than</option>
                    <option value="contains">Contains</option>
                </select>
                <input type="text" name="comparison_value[]" style="width: 30%;" required>
                <button type="button" class="remove-condition">❌</button>
            </div>
        `;
        $('#conditions-container').append(newCondition);
    });

    /** Suppression d'une condition */
    $(document).on('click', '.remove-condition', function () {
        $(this).closest('.condition-row').remove();
    });

    /** Activation/Désactivation d'une règle (avec nonce par ligne) */
    $(document).on('click', '.smap-toggle-status', function () {
        var btn = $(this);
        var rule_id = btn.data('id');
        var status = btn.data('status');
        var smap_nonce = btn.data('nonce');

        $.post(smap_ajax.ajax_url, {
            action: 'smap_update_rule_status',
            rule_id: rule_id,
            status: status,
            smap_nonce: smap_nonce
        }, function(response) {
            if (response.success) {
                fetchRules();
            } else {
                alert(response.message || 'Error');
            }
        }, 'json');
    });

    /** Suppression d'une règle (avec nonce par ligne) */
    $(document).on('click', '.smap-delete-rule', function () {
        var btn = $(this);
        var rule_id = btn.data('id');
        var smap_nonce = btn.data('nonce');

        if (!confirm('Are you sure you want to delete this rule?')) return;

        $.post(smap_ajax.ajax_url, {
            action: 'smap_delete_rule',
            rule_id: rule_id,
            smap_nonce: smap_nonce
        }, function(response) {
            if (response.success) {
                fetchRules();
            } else {
                alert(response.message || 'Error');
            }
        }, 'json');
    });

    /** Chargement initial des règles */
    fetchRules();
});
