/**
 * ActiveTrail AJAX Handler
 *
 * @package ActiveTrail_WooCommerce
 * @since 1.0.0
 */

(function ($) {
	'use strict';

	// Ensure activetrail_params exists (localized by PHP; fallback if script loads in unexpected context).
	if ( typeof activetrail_params === 'undefined' ) {
		window.activetrail_params = { ajaxurl: '', nonce: '', consent_required: false, consent_required_message: '' };
	}

	// Make ajaxurl available to our scripts
	window.ajaxurl = activetrail_params.ajaxurl;

	// Store nonce for AJAX requests
	window.activetrail_nonce = activetrail_params.nonce;

	// Initialize AJAX handlers
	var ActiveTrailAjax = {

		/**
		 * Initialize
		 */
		init: function () {
			// Nothing to initialize yet
		},

		/**
		 * Update consent status
		 *
		 * @param {boolean} consent Consent status
		 * @param {Function} callback Callback function
		 */
		updateConsent: function (consent, callback) {
			$.ajax(
				{
					url: ajaxurl,
					type: 'POST',
					data: {
						action: 'activetrail_update_consent',
						consent: consent,
						nonce: activetrail_nonce
					},
					success: function (response) {
						if (typeof callback === 'function') {
							callback( response );
						}
					},
					error: function (xhr, status, error) {
						console.error( 'AJAX error:', error );
						if (typeof callback === 'function') {
							callback(
								{
									success: false,
									data: {
										message: error
									}
								}
							);
						}
					}
				}
			);
		}
	};

	// Initialize when document is ready
	$( document ).ready(
		function () {
			ActiveTrailAjax.init();
		}
	);

	// Make ActiveTrailAjax globally available
	window.ActiveTrailAjax = ActiveTrailAjax;

})( jQuery );
