jQuery(function($) {
    // Run on page load and when payment method changes
    $(document.body).on('payment_method_selected updated_checkout', function() {
        validateAhapayMinimum();
    });

    // Check if order meets minimum requirements for AhaPay
    function validateAhapayMinimum() {
        const selectedPayment = $('input[name="payment_method"]:checked').val();

        if (selectedPayment === 'ahapaybuynowpaylater') {
            // If below minimum, disable place order button
            if (ahapay_data_minimum.disabled) {
                $('#place_order').prop('disabled', true);

                // Add notice if not exists
                // Remove any existing notices first
                $('.ahapay-minimum-notice').remove();

                // Add the notice next to the Place Order button
                $('#place_order').after(
                    '<div class="ahapay-minimum-notice">' +
                    ahapay_data_minimum.disabled_message +
                    '</div>'
                );
            } else {
                $('#place_order').prop('disabled', false);
                $('.ahapay-minimum-notice').remove();
            }
        } else {
            // Always enable button for other payment methods
            $('#place_order').prop('disabled', false);
            $('.ahapay-minimum-notice').remove();
        }
    }
});