/**
 * Elementor frontend handler — Wishlist Button widget.
 *
 * Self-contained wishlist: product IDs are persisted in localStorage so the
 * button reflects "in wishlist" state across pages without a server round-trip.
 *
 * @package captain-widgets-kit
 * @since   1.2.0
 */
( function ( $, window, document ) {
	'use strict';

	var STORAGE_KEY = 'captwiki_wishlist';

	/**
	 * Read the stored wishlist IDs.
	 *
	 * @return {Array} Product IDs (strings).
	 */
	function getWishlist() {
		try {
			var raw = window.localStorage.getItem( STORAGE_KEY );
			var arr = raw ? JSON.parse( raw ) : [];
			return Array.isArray( arr ) ? arr : [];
		} catch ( e ) {
			return [];
		}
	}

	/**
	 * Persist the wishlist IDs.
	 *
	 * @param {Array} ids Product IDs.
	 */
	function saveWishlist( ids ) {
		try {
			window.localStorage.setItem( STORAGE_KEY, JSON.stringify( ids ) );
		} catch ( e ) {
			/* storage unavailable — fail silently */
		}
	}

	/**
	 * Reflect the active/inactive state on a button.
	 *
	 * @param {HTMLElement} btn    Button element.
	 * @param {boolean}     active Whether the product is in the wishlist.
	 */
	function paintState( btn, active ) {
		var textEl = btn.querySelector( '.captwiki-woo-wishlist__text' );

		btn.classList.toggle( 'is-active', active );
		btn.setAttribute( 'aria-pressed', active ? 'true' : 'false' );

		if ( textEl ) {
			textEl.textContent = active
				? ( btn.getAttribute( 'data-added-text' ) || textEl.textContent )
				: ( btn.getAttribute( 'data-add-text' ) || textEl.textContent );
		}
	}

	/**
	 * Per-instance handler.
	 *
	 * @param {jQuery} $scope Widget wrapper jQuery object.
	 */
	var CaptwikiWishlistHandler = function ( $scope ) {

		var btn = $scope[ 0 ].querySelector( '.captwiki-woo-wishlist__btn' );
		if ( ! btn ) {
			return;
		}

		var productId = btn.getAttribute( 'data-product-id' );
		if ( ! productId ) {
			return;
		}

		/**
		 * Sync the button with the stored state.
		 */
		function init() {
			paintState( btn, getWishlist().indexOf( productId ) !== -1 );
			btn.addEventListener( 'click', handleClick );
		}

		/**
		 * Toggle the product in/out of the wishlist.
		 *
		 * @param {Event} e Click event.
		 */
		function handleClick( e ) {
			e.preventDefault();

			var ids   = getWishlist();
			var index = ids.indexOf( productId );

			if ( index === -1 ) {
				ids.push( productId );
				paintState( btn, true );
			} else {
				ids.splice( index, 1 );
				paintState( btn, false );
			}

			saveWishlist( ids );
		}

		init();
	};

	$( window ).on( 'elementor/frontend/init', function () {
		elementorFrontend.hooks.addAction(
			'frontend/element_ready/captwiki-woo-wishlist.default',
			CaptwikiWishlistHandler
		);
	} );

} )( jQuery, window, document );
