jQuery(document).ready(function($) {
    // Assuming CartController.checkbox_id is a string ID without the '#' prefix
    const consentCheckbox = document.getElementById(CartController.checkbox_id);

    if (consentCheckbox) {
        consentCheckbox.addEventListener('change', saveSubscriptionConsent);
    }

    // Execute functions on document ready
    removeRecoveryKeyParameter();
    saveSubscriptionConsentOnPageLoad();

    /**
     * When a user accesses our recover cart URL, remove the parameter from the URL
     *
     * @returns void
     */
    function removeRecoveryKeyParameter() {
        let url = new URL(window.location.href);
        let params = new URLSearchParams(url.search);

        // Check if the recovery parameters exist before attempting to delete
        if (params.has(CartController.recovery_param) || params.has(CartController.recovery_admin_param)) {
            params.delete(CartController.recovery_param);
            params.delete(CartController.recovery_admin_param);

            // Replace current URL in browser with the new one without recovery parameters
            window.history.replaceState({}, '', `${location.pathname}${params.toString() ? '?' + params : ''}`);
        }
    }

    /**
     * Save the subscription consent on page load
     *
     * @returns void
     */
    function saveSubscriptionConsentOnPageLoad() {
        if (consentCheckbox) {
            saveSubscriptionConsent({target: consentCheckbox});
        }
    }

    /**
     * Save the subscription consent
     *
     * @param {object} e - Event object or custom object mimicking event structure
     * @returns void
     */
    function saveSubscriptionConsent(e) {
        $.ajax({
            url: CartController.ajaxurl,
            data: {
                action: CartController.save_cart_consent_action,
                consent: e.target.checked,
                _ajax_nonce: CartController.save_cart_consent_nonce,
            },
            type: 'POST',
            dataType: 'json',
        }).done(function(response) {
            console.log('Consent saved', response);
            // Additional logic upon successfully saving consent can be added here
        }).fail(function(jqXHR, textStatus) {
            console.error('Failed to save consent: ', textStatus);
        });
    }
});
