/**
 * WooCommerce Cart Block Integration
 * Handles Share/Save button injection for the Cart Block (React-rendered).
 * Uses triple-defense approach for FSE theme compatibility.
 * Depends on lean-csns-frontend (lean_csns_params must be available).
 */
( function( $ ) {
	'use strict';

	var cartBlockDetection = {
		injectionTimeout: null,
		hasInjectedButtons: false,

		// Derived from lean_csns_params.button_position at init() time.
		// 'before_totals' maps to 'before-checkout-button'; everything else maps to 'after-cart-items'.
		insertionPoint: 'after-cart-items',

		/**
		 * Check if Cart Block exists and inject buttons if needed.
		 */
		checkAndInjectButtons: function() {
			if ( $( '.wc-block-cart' ).length > 0 ) {
				if ( $( '.wc-block-cart .lean-csns-buttons-wrapper' ).length === 0 ) {
					this.injectButtonsToCartBlock();
				}
			}
		},

		/**
		 * Inject buttons into Cart Block using pre-rendered HTML from PHP.
		 */
		injectButtonsToCartBlock: function() {
			var buttonsHtml = lean_csns_params.buttons_html;

			if ( ! buttonsHtml || buttonsHtml.trim() === '' ) {
				return;
			}

			var inserted = this.tryConfiguredInsertionPoint( buttonsHtml );

			if ( ! inserted ) {
				console.log( 'Lean Cart Share & Save: Could not find insertion point "' + this.insertionPoint + '"' );
			}
		},

		/**
		 * Try to inject buttons at the configured insertion point.
		 *
		 * @param {string} buttonsHtml Button HTML to inject.
		 * @return {boolean} True if injection was successful.
		 */
		tryConfiguredInsertionPoint: function( buttonsHtml ) {
			var insertionMap = {
				'after-cart-items': {
					selector: '.wc-block-cart-items',
					method:   'after'
				},
				'before-cart-totals-block': {
					selector: '.wp-block-woocommerce-cart-totals-block',
					method:   'prepend'
				},
				'before-checkout-button': {
					selector: '.wc-block-cart__submit-button, .wc-block-components-checkout-button',
					method:   'before-parent'
				}
			};

			var config = insertionMap[ this.insertionPoint ];
			if ( ! config ) {
				console.log( 'Lean Cart Share & Save: Invalid insertion point: ' + this.insertionPoint );
				return false;
			}

			var $target = $( config.selector ).first();
			if ( $target.length === 0 ) {
				return false;
			}

			if ( config.method === 'after' ) {
				$( buttonsHtml ).insertAfter( $target );
			} else if ( config.method === 'prepend' ) {
				$target.prepend( $( buttonsHtml ) );
			} else if ( config.method === 'before-parent' ) {
				$( buttonsHtml ).insertBefore( $target.parent() );
			}

			console.log( 'Lean Cart Share & Save: Buttons injected at "' + this.insertionPoint + '"' );
			return true;
		},

		/**
		 * Debounced injection to prevent duplicate button sets on rapid DOM changes.
		 */
		debouncedInjectButtons: function() {
			var self = this;
			clearTimeout( this.injectionTimeout );
			this.injectionTimeout = setTimeout( function() {
				if ( self.hasInjectedButtons ) {
					return;
				}
				self.hasInjectedButtons = true;
				self.checkAndInjectButtons();
			}, 300 );
		},

		/**
		 * Initialize triple-defense detection strategy.
		 */
		init: function() {
			var self = this;

			// Map the PHP button_position setting to the JS insertion point.
			var positionMap = {
				'default'       : 'after-cart-items',
				'after_table'   : 'after-cart-items',
				'before_totals' : 'before-cart-totals-block'
			};
			var pos = ( lean_csns_params && lean_csns_params.button_position )
				? lean_csns_params.button_position
				: 'default';
			this.insertionPoint = positionMap[ pos ] || 'after-cart-items';

			// Defense 1: initial detection.
			this.debouncedInjectButtons();

			// Defense 2: delayed detection for FSE render timing.
			setTimeout( function() {
				self.hasInjectedButtons = false;
				self.debouncedInjectButtons();
			}, 500 );

			// Defense 3a: WooCommerce block events.
			$( document.body ).on( 'updated_wc_block updated_cart_totals wc-blocks_render_blocks_frontend', function() {
				self.hasInjectedButtons = false;
				self.debouncedInjectButtons();
			} );

			// Defense 3b: MutationObserver (most reliable for FSE themes).
			if ( typeof MutationObserver !== 'undefined' ) {
				var observer = new MutationObserver( function( mutations ) {
					for ( var i = 0; i < mutations.length; i++ ) {
						if ( mutations[ i ].addedNodes.length > 0 ) {
							self.hasInjectedButtons = false;
							self.debouncedInjectButtons();
							break;
						}
					}
				} );

				observer.observe( document.body, { childList: true, subtree: true } );
			}
		}
	};

	$( document ).ready( function() {
		cartBlockDetection.init();
	} );

} )( jQuery );
