/**
 * Wishlist Module — Frontend Script
 *
 * Handles add/remove toggle, button state updates, cookie-aware
 * optimistic UI, and the share-URL workflow.
 */
( function ( $ ) {
	'use strict';

	var cfg = window.jwpStkWishlist || {};

	/**
	 * In-memory set of wishlisted product IDs.
	 * Initialised from PHP-localised data so the first render is instant.
	 */
	var wishlistIds = ( cfg.currentWishlist || [] ).map( Number );

	// ──────────────────────────────────────────────────────────────────
	// Helpers
	// ──────────────────────────────────────────────────────────────────

	function isWishlisted( productId ) {
		return wishlistIds.indexOf( Number( productId ) ) !== -1;
	}

	function syncLocalState( ids ) {
		wishlistIds = ( ids || [] ).map( Number );
	}

	/**
	 * Apply active/inactive visual state to a button element.
	 *
	 * @param {jQuery} $btn
	 * @param {boolean} active
	 */
	function applyButtonState( $btn, active ) {
		var labelAdd     = $btn.data( 'label-add' )    || cfg.labelAdd    || '';
		var labelAdded   = $btn.data( 'label-added' )  || cfg.labelAdded  || '';
		var bgColor      = $btn.data( 'bg' )            || '';
		var textColor    = $btn.data( 'text' )          || '';
		var activeBg     = $btn.data( 'active-bg' )    || '';
		var activeText   = $btn.data( 'active-text' )  || '';

		$btn.toggleClass( 'is-wishlisted', active );
		$btn.find( '.jwp-stk-wl-btn-text' ).text( active ? labelAdded : labelAdd );
		$btn.attr( 'aria-label', active ? labelAdded : labelAdd );

		// Inline color swap.
		var newBg   = active && activeBg   ? activeBg   : bgColor;
		var newText = active && activeText ? activeText : textColor;
		var style   = '';
		if ( newBg )   { style += 'background-color:' + newBg + ';border-color:' + newBg + ';'; }
		if ( newText ) { style += 'color:' + newText + ';'; }
		$btn.attr( 'style', style );
	}

	/**
	 * Update all buttons on the page for a given product.
	 *
	 * @param {number}  productId
	 * @param {boolean} active
	 */
	function updateAllButtons( productId, active ) {
		$( '.jwp-stk-wishlist-btn[data-product-id="' + productId + '"]' ).each( function () {
			applyButtonState( $( this ), active );
		} );
	}

	// ──────────────────────────────────────────────────────────────────
	// Initialise button states on page load
	// ──────────────────────────────────────────────────────────────────

	function initButtons() {
		$( '.jwp-stk-wishlist-btn' ).each( function () {
			var $btn      = $( this );
			var productId = Number( $btn.data( 'product-id' ) );
			applyButtonState( $btn, isWishlisted( productId ) );
		} );
	}

	// ──────────────────────────────────────────────────────────────────
	// Toggle handler
	// ──────────────────────────────────────────────────────────────────

	function handleToggle( e ) {
		e.preventDefault();

		var $btn      = $( this );
		var productId = Number( $btn.data( 'product-id' ) );

		if ( $btn.hasClass( 'is-loading' ) ) {
			return;
		}

		$btn.addClass( 'is-loading' ).prop( 'disabled', true );

		// Optimistic UI.
		var optimisticActive = ! isWishlisted( productId );
		updateAllButtons( productId, optimisticActive );

		$.ajax( {
			url:    cfg.ajaxUrl,
			method: 'POST',
			data:   {
				action:     'jwp_stk_wishlist_toggle',
				nonce:      cfg.nonce,
				product_id: productId,
			},
			success: function ( res ) {
				if ( res.success ) {
					syncLocalState( res.data.ids );
					var confirmed = res.data.in_wishlist;
					updateAllButtons( productId, confirmed );

					if ( confirmed && res.data.redirect_url ) {
						window.location.href = res.data.redirect_url;
					}
				} else {
					// Roll back optimistic change on error.
					updateAllButtons( productId, ! optimisticActive );
					syncLocalState( wishlistIds );
				}
			},
			error: function () {
				updateAllButtons( productId, ! optimisticActive );
			},
			complete: function () {
				$btn.removeClass( 'is-loading' ).prop( 'disabled', false );
			},
		} );
	}

	// ──────────────────────────────────────────────────────────────────
	// Wishlist table: remove row
	// ──────────────────────────────────────────────────────────────────

	function handleTableRemove( e ) {
		e.preventDefault();

		var $btn      = $( this );
		var productId = Number( $btn.data( 'product-id' ) );
		var $row      = $btn.closest( '.jwp-stk-wl-row' );

		$btn.prop( 'disabled', true );
		$row.addClass( 'is-removing' );

		$.ajax( {
			url:    cfg.ajaxUrl,
			method: 'POST',
			data:   {
				action:     'jwp_stk_wishlist_toggle',
				nonce:      cfg.nonce,
				product_id: productId,
			},
			success: function ( res ) {
				if ( res.success && ! res.data.in_wishlist ) {
					syncLocalState( res.data.ids );
					updateAllButtons( productId, false );

					setTimeout( function () {
						$row.remove();

						// Show empty state if no rows remain.
						var $tbody = $( '.jwp-stk-wishlist-table tbody' );
						if ( $tbody.find( '.jwp-stk-wl-row' ).length === 0 ) {
							location.reload();
						}
					}, 320 );
				} else {
					$row.removeClass( 'is-removing' );
					$btn.prop( 'disabled', false );
				}
			},
			error: function () {
				$row.removeClass( 'is-removing' );
				$btn.prop( 'disabled', false );
			},
		} );
	}

	// ──────────────────────────────────────────────────────────────────
	// Share URL
	// ──────────────────────────────────────────────────────────────────

	function handleShareBtn( e ) {
		e.preventDefault();

		var $wrap = $( this ).closest( '.jwp-stk-wl-footer' ).find( '.jwp-stk-wl-share-url-wrap' );
		var $input = $wrap.find( '.jwp-stk-wl-share-url' );

		if ( $input.val() ) {
			$wrap.toggle();
			return;
		}

		var $btn = $( this ).prop( 'disabled', true );

		$.ajax( {
			url:    cfg.ajaxUrl,
			method: 'POST',
			data:   {
				action: 'jwp_stk_wishlist_get_share_url',
				nonce:  cfg.nonce,
			},
			success: function ( res ) {
				if ( res.success ) {
					$input.val( res.data.url );
					$wrap.show();
				}
			},
			complete: function () {
				$btn.prop( 'disabled', false );
			},
		} );
	}

	function handleCopyUrl( e ) {
		e.preventDefault();

		var $input = $( this ).closest( '.jwp-stk-wl-share-url-wrap' ).find( '.jwp-stk-wl-share-url' );
		var url    = $input.val();

		if ( ! url ) { return; }

		if ( navigator.clipboard && navigator.clipboard.writeText ) {
			navigator.clipboard.writeText( url ).then( function () {
				showCopiedFeedback( $( this ) );
			}.bind( this ) );
		} else {
			// Fallback for older browsers.
			$input[ 0 ].select();
			document.execCommand( 'copy' );
			showCopiedFeedback( $( this ) );
		}
	}

	function showCopiedFeedback( $btn ) {
		var original = $btn.text();
		$btn.text( 'Copied!' );
		setTimeout( function () {
			$btn.text( original );
		}, 2000 );
	}

	// ──────────────────────────────────────────────────────────────────
	// Boot
	// ──────────────────────────────────────────────────────────────────

	$( function () {
		initButtons();

		// Delegated: handles buttons injected later (e.g. AJAX page refresh).
		$( document ).on( 'click', '.jwp-stk-wishlist-btn', handleToggle );
		$( document ).on( 'click', '.jwp-stk-wl-remove-btn', handleTableRemove );
		$( document ).on( 'click', '.jwp-stk-wl-share-btn', handleShareBtn );
		$( document ).on( 'click', '.jwp-stk-wl-copy-url', handleCopyUrl );

		// Re-init after WooCommerce AJAX product list updates.
		$( document ).on( 'wc_fragments_refreshed wc_fragments_loaded', initButtons );
	} );
} )( jQuery );
