/**
 * Elementor frontend handler — Mini Cart widget.
 *
 * Handles opening/closing the dropdown or slide-in drawer, auto-opening when a
 * product is added, and recalculating the free-shipping progress bar after each
 * cart change. Item add/remove + the count/subtotal badge are powered by
 * WooCommerce cart fragments, so this script only drives the UI around them.
 *
 * @package captain-widgets-kit
 * @since   1.3.0
 */
( function ( $, window, document ) {
	'use strict';

	var BODY_OPEN_CLASS = 'captwiki-mini-cart-open';
	var instances       = [];

	/**
	 * Format a number as a WooCommerce price string.
	 *
	 * @param {number} amount Raw amount.
	 * @return {string} Formatted price.
	 */
	function formatPrice( amount ) {
		var cfg = window.captwikiMiniCart || {};
		var decimals = typeof cfg.decimals !== 'undefined' ? parseInt( cfg.decimals, 10 ) : 2;
		var decimalSep = cfg.decimalSep || '.';
		var thousandSep = typeof cfg.thousandSep === 'string' ? cfg.thousandSep : ',';
		var symbol = cfg.currencySymbol || '';
		var format = cfg.priceFormat || '%1$s%2$s';

		var fixed = ( Math.round( amount * 100 ) / 100 ).toFixed( decimals );
		var parts = fixed.split( '.' );
		parts[ 0 ] = parts[ 0 ].replace( /\B(?=(\d{3})+(?!\d))/g, thousandSep );
		var number = parts.join( decimals > 0 ? decimalSep : '' );

		return format.replace( '%1$s', symbol ).replace( '%2$s', number );
	}

	/**
	 * Recalculate the free-shipping progress bar from the current subtotal.
	 *
	 * @param {HTMLElement} root Widget wrapper.
	 */
	function updateFreeShipping( root ) {
		var bar = root.querySelector( '.captwiki-mini-cart__fs' );
		if ( ! bar ) {
			return;
		}

		var goal = parseFloat( bar.getAttribute( 'data-goal' ) ) || 0;
		if ( goal <= 0 ) {
			bar.style.display = 'none';
			return;
		}

		var countEl  = root.querySelector( '.captwiki-mini-cart__count' );
		var subtotal = countEl ? parseFloat( countEl.getAttribute( 'data-subtotal' ) ) || 0 : 0;
		var remaining = Math.max( 0, goal - subtotal );
		var percent   = goal > 0 ? Math.min( 100, ( subtotal / goal ) * 100 ) : 0;

		var fill = bar.querySelector( '.captwiki-mini-cart__fs-fill' );
		var msg  = bar.querySelector( '.captwiki-mini-cart__fs-msg' );

		if ( fill ) {
			fill.style.width = percent + '%';
		}

		if ( remaining <= 0 ) {
			bar.classList.add( 'is-complete' );
			if ( msg ) {
				msg.textContent = bar.getAttribute( 'data-success-text' ) || msg.textContent;
			}
		} else {
			bar.classList.remove( 'is-complete' );
			if ( msg ) {
				var tpl = bar.getAttribute( 'data-progress-text' ) || '';
				msg.textContent = tpl.replace( '{amount}', formatPrice( remaining ) );
			}
		}
	}

	/**
	 * Reflect the empty / filled state on the wrapper.
	 *
	 * @param {HTMLElement} root Widget wrapper.
	 */
	function syncEmptyState( root ) {
		var countEl = root.querySelector( '.captwiki-mini-cart__count' );
		var count   = countEl ? parseInt( countEl.getAttribute( 'data-count' ), 10 ) || 0 : 0;
		root.classList.toggle( 'is-empty', count <= 0 );
	}

	/**
	 * Refresh every instance after a cart change.
	 */
	function refreshAll() {
		instances.forEach( function ( root ) {
			syncEmptyState( root );
			updateFreeShipping( root );
		} );
	}

	/**
	 * Per-instance UI handler.
	 *
	 * @param {HTMLElement} root Widget wrapper element.
	 */
	function setupInstance( root ) {
		if ( ! root || root.captwikiMiniCartReady ) {
			return;
		}
		root.captwikiMiniCartReady = true;
		instances.push( root );

		var toggle  = root.querySelector( '.captwiki-mini-cart__toggle' );
		var panel   = root.querySelector( '.captwiki-mini-cart__panel' );
		var overlay = root.querySelector( '.captwiki-mini-cart__overlay' );
		var closeEl = root.querySelector( '.captwiki-mini-cart__close' );

		function open() {
			root.classList.add( 'is-open' );
			document.body.classList.add( BODY_OPEN_CLASS );
			if ( toggle ) {
				toggle.setAttribute( 'aria-expanded', 'true' );
			}
		}

		function close() {
			root.classList.remove( 'is-open' );
			if ( ! document.querySelector( '.captwiki-mini-cart.is-open' ) ) {
				document.body.classList.remove( BODY_OPEN_CLASS );
			}
			if ( toggle ) {
				toggle.setAttribute( 'aria-expanded', 'false' );
			}
		}

		function toggleOpen( e ) {
			if ( e ) {
				e.preventDefault();
			}
			if ( root.classList.contains( 'is-open' ) ) {
				close();
			} else {
				open();
			}
		}

		if ( toggle ) {
			toggle.addEventListener( 'click', toggleOpen );
		}
		if ( overlay ) {
			overlay.addEventListener( 'click', close );
		}
		if ( closeEl ) {
			closeEl.addEventListener( 'click', close );
		}

		// Close on outside click for the dropdown layout.
		document.addEventListener( 'click', function ( e ) {
			if ( root.getAttribute( 'data-layout' ) !== 'dropdown' ) {
				return;
			}
			if ( root.classList.contains( 'is-open' ) && ! root.contains( e.target ) ) {
				close();
			}
		} );

		document.addEventListener( 'keyup', function ( e ) {
			if ( e.key === 'Escape' && root.classList.contains( 'is-open' ) ) {
				close();
			}
		} );

		// Expose for the global add-to-cart listener.
		root.captwikiOpen = open;

		syncEmptyState( root );
		updateFreeShipping( root );
	}

	/**
	 * Bind global WooCommerce cart events once.
	 */
	function bindCartEvents() {
		if ( bindCartEvents.done ) {
			return;
		}
		bindCartEvents.done = true;

		$( document.body ).on( 'added_to_cart', function () {
			refreshAll();
			instances.forEach( function ( root ) {
				if ( root.getAttribute( 'data-open-on-add' ) === '1' && typeof root.captwikiOpen === 'function' ) {
					root.captwikiOpen();
				}
			} );
		} );

		$( document.body ).on( 'removed_from_cart wc_fragments_refreshed wc_fragments_loaded', refreshAll );
	}

	$( window ).on( 'elementor/frontend/init', function () {
		elementorFrontend.hooks.addAction(
			'frontend/element_ready/captwiki-woo-mini-cart.default',
			function ( $scope ) {
				setupInstance( $scope[ 0 ].querySelector( '.captwiki-mini-cart' ) || $scope[ 0 ] );
				bindCartEvents();
			}
		);
	} );

	// Fallback for non-Elementor contexts (e.g. raw template parts).
	$( function () {
		bindCartEvents();
		document.querySelectorAll( '.captwiki-mini-cart' ).forEach( setupInstance );
	} );

} )( jQuery, window, document );
