/**
 * ActiveTrail Checkout Script
 *
 * @package ActiveTrail_WooCommerce
 * @since 1.0.0
 */

(function ($) {
	'use strict';

	var ActiveTrailCheckout = {

		/**
		 * Initialize
		 */
		init: function () {
			this.bindEvents();
			this.enhanceConsentField();
			this.enhanceRegistrationConsentField();
		},

		/**
		 * Bind events
		 */
		bindEvents: function () {
			// Handle consent checkbox changes (by name – WooCommerce submits by name; id can change after update_checkout)
			$( document ).on( 'change', 'input[name="activetrail_consent"], input[name="billing_activetrail_consent"]', this.handleConsentChange );

			// Handle registration consent checkbox changes
			$( document ).on( 'change', '#activetrail_registration_consent', this.handleRegistrationConsentChange );

			// Handle checkout form updates
			$( document.body ).on( 'updated_checkout', this.onCheckoutUpdated );

			// Handle checkout validation
			$( document ).on( 'checkout_error', this.onCheckoutError );

			// Block checkout submit when consent is required but not given
			$( document.body ).on( 'checkout_place_order', this.validateCheckoutConsent );

			// Block registration form submit when consent is required but not given
			$( document ).on( 'submit', 'form.woocommerce-form-register, form.register', this.validateRegistrationConsent );
		},

		/**
		 * Get consent checkbox (by name – stable across WooCommerce / update_checkout).
		 */
		getConsentCheckbox: function () {
			return $( 'input[name="activetrail_consent"], input[name="billing_activetrail_consent"]' ).first();
		},

		/**
		 * Check if consent checkbox exists and is checked.
		 */
		hasConsent: function () {
			var $checkbox = this.getConsentCheckbox();
			return $checkbox.length && $checkbox.is( ':checked' );
		},

		/**
		 * Clear consent error UI.
		 */
		clearConsentError: function () {
			var $cb = this.getConsentCheckbox();
			if ( $cb.length ) {
				$cb.closest( '.form-row' ).removeClass( 'woocommerce-invalid' );
			}
			$( '.activetrail-consent-error' ).remove();
		},

		/**
		 * Show consent required error and block checkout.
		 */
		showConsentError: function () {
			var $consentField = this.getConsentCheckbox();
			if ( ! $consentField.length ) {
				return;
			}
			var $row = $consentField.closest( '.form-row' );
			$row.addClass( 'woocommerce-invalid' );
			$( '.activetrail-consent-error' ).remove();
			var message = ( typeof activetrail_params !== 'undefined' && activetrail_params.consent_required_message )
				? activetrail_params.consent_required_message
				: 'You must approve marketing emails in order to continue.';
			var $err = $( '<div class="activetrail-consent-error woocommerce-error" role="alert"></div>' ).text( message );
			$row.after( $err );
			$( document.body ).trigger( 'checkout_error' );
		},

		/**
		 * Replace native checkbox rendering with a custom visual span.
		 * The native <input> is hidden (opacity:0) but stays in the DOM for
		 * form submission and accessibility. The visual <span class="at-visual-cb">
		 * is fully CSS-controlled so no theme or plugin can override it.
		 */
		fixCheckboxAppearance: function ( el ) {
			if ( ! el ) { return; }

			// Find existing visual span (already inserted before the input)
			var visual = el.previousElementSibling;
			if ( ! visual || ! visual.classList.contains( 'at-visual-cb' ) ) {
				// First run: create the visual span and hide the native input
				visual = document.createElement( 'span' );
				visual.className = 'at-visual-cb';
				visual.setAttribute( 'aria-hidden', 'true' );
				el.parentNode.insertBefore( visual, el );

				// Hide native input visually; keep it in DOM for a11y + form submit
				el.style.setProperty( 'position', 'absolute', 'important' );
				el.style.setProperty( 'opacity',  '0',        'important' );
				el.style.setProperty( 'width',    '1px',      'important' );
				el.style.setProperty( 'height',   '1px',      'important' );
				el.style.setProperty( 'margin',   '0',        'important' );
				el.style.setProperty( 'padding',  '0',        'important' );

				// Show focus ring on visual span when keyboard-navigated
				el.addEventListener( 'focus', function () { visual.classList.add( 'at-focused' ); } );
				el.addEventListener( 'blur',  function () { visual.classList.remove( 'at-focused' ); } );
			}

			// Sync visual checked state
			visual.classList.toggle( 'at-checked', !! el.checked );
		},

		/**
		 * Enhance consent field
		 */
		enhanceConsentField: function () {
			var $consentField = this.getConsentCheckbox();

			if ( $consentField.length ) {
				// Track initial state
				this.trackConsentState( $consentField.is( ':checked' ) );
			}
		},

		/**
		 * Enhance registration consent field
		 */
		enhanceRegistrationConsentField: function () {
			var $consentField = $( '#activetrail_registration_consent' );

			if ($consentField.length) {
				// Add custom styling
				$consentField.closest( '.form-row' ).addClass( 'activetrail-consent-row' );

				// Track initial state
				this.trackRegistrationConsentState( $consentField.is( ':checked' ) );
			}
		},

		/**
		 * Handle consent checkbox change
		 */
		handleConsentChange: function () {
			var $checkbox = $( this );
			var isChecked = $checkbox.is( ':checked' );

			// Clear consent error when user checks (by name selector – stable after update_checkout)
			ActiveTrailCheckout.clearConsentError();

			// Track consent change
			ActiveTrailCheckout.trackConsentState( isChecked );

			// Update UI if needed
			ActiveTrailCheckout.updateConsentUI( isChecked );
		},

		/**
		 * Handle registration consent checkbox change
		 */
		handleRegistrationConsentChange: function () {
			var $checkbox = $( this );
			var isChecked = $checkbox.is( ':checked' );

			// Clear inline consent error when user checks
			$checkbox.closest( '.form-row' ).removeClass( 'woocommerce-invalid' );
			$( '.activetrail-consent-error' ).remove();

			// Track registration consent change
			ActiveTrailCheckout.trackRegistrationConsentState( isChecked );

			// Update UI if needed
			ActiveTrailCheckout.updateRegistrationConsentUI( isChecked );

			// For my-account page, use form submission instead of AJAX
			if (window.location.href.indexOf( 'my-account' ) > -1) {
				// Don't send AJAX, let the form handle it
				console.log( 'Consent checkbox changed on my-account page, will be handled by form submission' );
			} else {
				// Send AJAX request to update consent status if user is logged in
				if (typeof ActiveTrailAjax !== 'undefined') {
					ActiveTrailAjax.updateConsent(
						isChecked,
						function (response) {
							if (response.success) {
								console.log( 'Consent updated successfully' );
							} else {
								console.error( 'Failed to update consent:', response.data.message );
							}
						}
					);
				}
			}
		},

		/**
		 * Track consent state
		 */
		trackConsentState: function (consented) {
			// Store consent state for analytics
			if (typeof gtag !== 'undefined') {
				gtag(
					'event',
					'marketing_consent',
					{
						'consent_given': consented,
						'source': 'activetrail_checkout'
					}
				);
			}

			// Store in session storage for persistence
			try {
				sessionStorage.setItem( 'activetrail_consent', consented ? '1' : '0' );
			} catch (e) {
				// Session storage not available
			}
		},

		/**
		 * Track registration consent state
		 */
		trackRegistrationConsentState: function (consented) {
			// Store registration consent state for analytics
			if (typeof gtag !== 'undefined') {
				gtag(
					'event',
					'registration_marketing_consent',
					{
						'consent_given': consented,
						'source': 'activetrail_checkout'
					}
				);
			}

			// Store in session storage for persistence
			try {
				sessionStorage.setItem( 'activetrail_registration_consent', consented ? '1' : '0' );
			} catch (e) {
				// Session storage not available
			}
		},

		/**
		 * Update consent UI (no green/yellow styling; row stays neutral).
		 */
		updateConsentUI: function (/* consented */) {
			// Row stays neutral; only checkbox state toggles.
		},

		/**
		 * Update registration consent UI (no green/yellow styling; row stays neutral).
		 */
		updateRegistrationConsentUI: function (/* consented */) {
			// Row stays neutral; only checkbox state toggles.
		},

		/**
		 * Handle checkout updated
		 */
		onCheckoutUpdated: function () {
			// Re-enhance consent field after checkout update
			ActiveTrailCheckout.enhanceConsentField();
			ActiveTrailCheckout.enhanceRegistrationConsentField();
		},

		/**
		 * Validate checkout consent before place order. Return true to allow submit, false to block.
		 * Uses name selector so it stays correct after update_checkout / AJAX refresh.
		 */
		validateCheckoutConsent: function () {
			if ( typeof activetrail_params === 'undefined' || ! activetrail_params.consent_required ) {
				return true;
			}
			if ( ActiveTrailCheckout.hasConsent() ) {
				ActiveTrailCheckout.clearConsentError();
				return true;
			}
			ActiveTrailCheckout.showConsentError();
			return false;
		},

		/**
		 * Validate registration consent before form submit. Return false to block submit.
		 */
		validateRegistrationConsent: function ( e ) {
			if ( typeof activetrail_params === 'undefined' || ! activetrail_params.consent_required ) {
				return;
			}
			var $consentField = $( '#activetrail_registration_consent' );
			if ( ! $consentField.length || $consentField.is( ':checked' ) ) {
				return;
			}
			e.preventDefault();
			var $row = $consentField.closest( '.form-row' );
			$row.addClass( 'woocommerce-invalid' );
			$( '.activetrail-consent-error' ).remove();
			var message = ( typeof activetrail_params !== 'undefined' && activetrail_params.consent_required_message )
				? activetrail_params.consent_required_message
				: 'You must approve marketing emails in order to continue.';
			var $err = $( '<div class="activetrail-consent-error woocommerce-error" role="alert"></div>' ).text( message );
			$row.after( $err );
		},

		/**
		 * Handle checkout error
		 */
		onCheckoutError: function () {
			// Highlight consent field if there's an error (by name – stable after update_checkout)
			var $consentField = ActiveTrailCheckout.getConsentCheckbox();
			if ( $consentField.length ) {
				$consentField.closest( '.form-row' ).addClass( 'woocommerce-invalid' );
			}

			// Handle any registration errors related to consent
			var $registrationConsentField = $( '#activetrail_registration_consent' );

			if ($registrationConsentField.length) {
				// Highlight registration consent field if there's an error
				$registrationConsentField.closest( '.form-row' ).addClass( 'woocommerce-invalid' );
			}
		},

		/**
		 * Get consent status
		 */
		getConsentStatus: function () {
			return this.hasConsent();
		},

		/**
		 * Get registration consent status
		 */
		getRegistrationConsentStatus: function () {
			var $consentField = $( '#activetrail_registration_consent' );

			if ($consentField.length) {
				return $consentField.is( ':checked' );
			}

			return false;
		}
	};

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

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

})( jQuery );
