/**
 * Lucrativeit Subscription Plus — public shortcode scripts.
 */
( function ( $ ) {
	'use strict';

	var i18n = ( window.LUCRSUREPublic && window.LUCRSUREPublic.i18n ) || {};

	function getRoot( $el ) {
		return $el.closest( '.lucrsure-public' );
	}

	function getActivePanel( $root ) {
		return $root.find( '.lucrsure-public-plan-panel:not([hidden])' ).first();
	}

	function getSelectedCard( $root ) {
		return getActivePanel( $root ).find( '.lucrsure-public-plan-card.is-selected' ).first();
	}

	function getCheckoutConfig( $root ) {
		var global = window.LUCRSUREPublic || {};
		var ajaxUrl = $root.data( 'ajax-url' ) || global.ajaxUrl || '';
		var nonce = $root.data( 'checkout-nonce' ) || global.nonce || '';
		return {
			ajaxUrl: ajaxUrl,
			nonce: nonce
		};
	}

	function selectCard( $card ) {
		var $root  = getRoot( $card );
		var $panel = $card.closest( '.lucrsure-public-plan-panel' );
		$panel.find( '.lucrsure-public-plan-card' ).removeClass( 'is-selected' );
		$card.addClass( 'is-selected' );
	}

	function switchInterval( $root, interval ) {
		$root.find( '.lucrsure-public-interval' ).each( function () {
			var $btn   = $( this );
			var active = $btn.data( 'interval' ) === interval;
			$btn.toggleClass( 'is-active', active ).attr( 'aria-selected', active ? 'true' : 'false' );
		} );

		$root.find( '.lucrsure-public-plan-panel' ).each( function () {
			var $panel = $( this );
			$panel.prop( 'hidden', $panel.data( 'interval-panel' ) !== interval );
		} );

		var $panel    = $root.find( '.lucrsure-public-plan-panel[data-interval-panel="' + interval + '"]' );
		var $selected = $panel.find( '.lucrsure-public-plan-card.is-selected' );
		if ( ! $selected.length ) {
			var $popular = $panel.find( '.lucrsure-public-plan-card.is-popular' ).first();
			var $initial = $popular.length ? $popular : $panel.find( '.lucrsure-public-plan-card' ).first();
			if ( $initial.length ) {
				selectCard( $initial );
			}
		}
	}

	function updateSummary( $root, $card ) {
		var trial         = parseInt( $card.data( 'trial' ), 10 ) || 0;
		var price         = $card.data( 'price' );
		var intervalLabel = $card.data( 'interval-label' );
		var name          = $card.data( 'name' );
		var note          = trial > 0 ? trial + '-day free trial, then ' + price + '/' + intervalLabel + '.' : '';

		$root.find( '.lucrsure-public-summary-plan' ).text( name );
		$root.find( '.lucrsure-public-summary-price' ).text( price + '/' + intervalLabel );
		$root.find( '.lucrsure-public-summary-note' ).text( note );

		var $features = $card.find( '.lucrsure-public-features li' ).clone();
		$root.find( '.lucrsure-public-summary-features' ).empty().append( $features );
	}

	function getCategoryPage( $root ) {
		return $root.closest( '.lucrsure-category-page' );
	}

	function scrollToCheckout( $root ) {
		var $target = $root.find( '.lucrsure-public-checkout-step' );
		if ( ! $target.length ) {
			return;
		}
		$( 'html, body' ).animate( { scrollTop: $target.offset().top - 24 }, 300 );
	}

	function enterCheckoutMode( $root ) {
		var $page = getCategoryPage( $root );
		if ( $page.length ) {
			$page.addClass( 'is-checkout-mode' );
		}
		$root.addClass( 'is-checkout-active' );
	}

	function exitCheckoutMode( $root ) {
		var $page = getCategoryPage( $root );
		if ( $page.length ) {
			$page.removeClass( 'is-checkout-mode is-success-mode' );
		}
		$root.removeClass( 'is-checkout-active is-success-active' );
	}

	function getReturnUrl() {
		try {
			return String( new URLSearchParams( window.location.search ).get( 'lucrsure_return' ) || '' );
		} catch ( e ) {
			return '';
		}
	}

	function isSafeSameOriginUrl( url ) {
		if ( ! url ) {
			return false;
		}
		try {
			var target = new URL( url, window.location.href );
			return target.origin === window.location.origin;
		} catch ( e ) {
			return false;
		}
	}

	function isDifferentPage( url ) {
		if ( ! isSafeSameOriginUrl( url ) ) {
			return false;
		}
		try {
			var target = new URL( url, window.location.href );
			return target.pathname !== window.location.pathname;
		} catch ( e ) {
			return false;
		}
	}

	function clearCheckoutQuery() {
		if ( ! window.history || ! window.history.replaceState ) {
			return;
		}
		try {
			var url = new URL( window.location.href );
			url.searchParams.delete( 'lucrsure_plan' );
			url.searchParams.delete( 'lucrsure_return' );
			window.history.replaceState( {}, '', url );
		} catch ( e ) {}
	}

	function setGridVisible( visible ) {
		$( '.lucrsure-plan-grid' ).prop( 'hidden', ! visible );
	}

	function scrollToGrid() {
		var $grid = $( '.lucrsure-plan-grid' ).first();
		if ( ! $grid.length ) {
			return;
		}
		$( 'html, body' ).animate( { scrollTop: $grid.offset().top - 24 }, 300 );
	}

	function showCheckout( $root, $card ) {
		$root.find( '.lucrsure-public-plans-step' ).prop( 'hidden', true );
		$root.find( '.lucrsure-public-checkout-step' ).prop( 'hidden', false );
		$root.find( '.lucrsure-public-success' ).prop( 'hidden', true );
		$root.find( '.lucrsure-public-checkout-form input[name="plan_id"]' ).val( $card.data( 'plan-id' ) );
		$root.find( '.lucrsure-public-checkout-error' ).prop( 'hidden', true ).text( '' );
		updateSummary( $root, $card );
		enterCheckoutMode( $root );
		if ( $root.data( 'opened-from-grid' ) ) {
			setGridVisible( false );
		}
		scrollToCheckout( $root );
	}

	function showPlans( $root ) {
		var returnUrl = $root.data( 'return-url' ) || getReturnUrl();
		if ( ! returnUrl && $root.data( 'opened-from-grid' ) && isDifferentPage( document.referrer ) ) {
			returnUrl = document.referrer;
		}

		if ( isDifferentPage( returnUrl ) ) {
			window.location.href = returnUrl;
			return;
		}

		$root.find( '.lucrsure-public-checkout-step' ).prop( 'hidden', true );
		$root.find( '.lucrsure-public-success' ).prop( 'hidden', true );
		$root.find( '.lucrsure-public-plans-step' ).prop( 'hidden', false );
		setGridVisible( true );
		exitCheckoutMode( $root );
		clearCheckoutQuery();

		if ( $root.hasClass( 'lucrsure-public--template-grid' ) || $root.data( 'opened-from-grid' ) ) {
			scrollToGrid();
		}
	}

	function showSuccess( $root, message ) {
		$root.find( '.lucrsure-public-plans-step, .lucrsure-public-checkout-step' ).prop( 'hidden', true );
		$root.find( '.lucrsure-public-success-message' ).text( message );
		$root.find( '.lucrsure-public-success' ).prop( 'hidden', false );
		enterCheckoutMode( $root );
		getCategoryPage( $root ).addClass( 'is-success-mode' );
		$root.addClass( 'is-success-active' );
	}

	function getPlanIdFromHref( href ) {
		if ( ! href ) {
			return '';
		}
		try {
			var url = new URL( href, window.location.href );
			return String( url.searchParams.get( 'lucrsure_plan' ) || '' );
		} catch ( e ) {
			return '';
		}
	}

	function getRequestedPlanId() {
		try {
			return String( new URLSearchParams( window.location.search ).get( 'lucrsure_plan' ) || '' );
		} catch ( e ) {
			return '';
		}
	}

	function openCheckoutForPlan( planId, $fallbackCard, fromGrid ) {
		var $root = $( '.lucrsure-public' ).first();
		if ( ! $root.length || ! planId ) {
			return false;
		}

		var $card = $root.find( '.lucrsure-public-plan-card[data-plan-id="' + planId + '"]' ).first();
		if ( ! $card.length && $fallbackCard && $fallbackCard.length ) {
			$card = $fallbackCard;
		}
		if ( ! $card.length ) {
			return false;
		}

		var interval = String( $card.data( 'interval' ) || '' );
		if ( interval ) {
			switchInterval( $root, interval );
			$card = $root.find( '.lucrsure-public-plan-card[data-plan-id="' + planId + '"]' ).first().length
				? $root.find( '.lucrsure-public-plan-card[data-plan-id="' + planId + '"]' ).first()
				: $card;
		}

		if ( fromGrid ) {
			$root.data( 'opened-from-grid', true );
			$root.data( 'return-url', getReturnUrl() );
		}

		selectCard( $card );
		showCheckout( $root, $card );
		return true;
	}

	$( function () {
		$( '.lucrsure-public' ).each( function () {
			var $root           = $( this );
			var requestedPlanId = getRequestedPlanId();
			var defaultInterval = $root.data( 'default-interval' );
			switchInterval( $root, defaultInterval );

			var $panel   = getActivePanel( $root );
			var $popular = $panel.find( '.lucrsure-public-plan-card.is-popular' ).first();
			var $initial = $popular.length ? $popular : $panel.find( '.lucrsure-public-plan-card' ).first();
			if ( $initial.length ) {
				selectCard( $initial );
			}

			if ( requestedPlanId ) {
				openCheckoutForPlan( requestedPlanId, null, true );
			}
		} );

		$( document ).on( 'click', '.lucrsure-public-interval', function () {
			var $btn = $( this );
			if ( $btn.prop( 'disabled' ) ) {
				return;
			}
			switchInterval( getRoot( $btn ), $btn.data( 'interval' ) );
		} );

		$( document ).on( 'click', '.lucrsure-public-plan-card', function ( e ) {
			if ( $( e.target ).closest( '.lucrsure-public-plan-cta' ).length ) {
				return;
			}
			selectCard( $( this ) );
		} );

		$( document ).on( 'click', '.lucrsure-public-plan-cta', function ( e ) {
			e.preventDefault();
			e.stopPropagation();
			var $card = $( this ).closest( '.lucrsure-public-plan-card' );
			selectCard( $card );
			showCheckout( getRoot( $card ), $card );
		} );

		$( document ).on( 'click', '.lucrsure-public-back', function () {
			showPlans( getRoot( $( this ) ) );
		} );

		$( document ).on( 'submit', '.lucrsure-public-checkout-form', function ( e ) {
			e.preventDefault();
			var $form   = $( this );
			var $root   = getRoot( $form );
			var $error  = $root.find( '.lucrsure-public-checkout-error' );
			var $submit = $form.find( '.lucrsure-public-submit' );
			var name    = $.trim( $form.find( '[name="name"]' ).val() );
			var email   = $.trim( $form.find( '[name="email"]' ).val() );
			var planId  = $form.find( '[name="plan_id"]' ).val();
			var address1 = $.trim( $form.find( '[name="billing_address_1"]' ).val() );
			var city     = $.trim( $form.find( '[name="billing_city"]' ).val() );
			var postcode = $.trim( $form.find( '[name="billing_postcode"]' ).val() );
			var country  = $.trim( $form.find( '[name="billing_country"]' ).val() );

			$error.prop( 'hidden', true ).text( '' );
			if ( ! planId ) {
				$error.text( i18n.selectPlan || 'Please select a plan.' ).prop( 'hidden', false );
				return;
			}
			if ( ! name ) {
				$error.text( i18n.nameRequired || 'Full name is required.' ).prop( 'hidden', false );
				return;
			}
			if ( ! email || email.indexOf( '@' ) === -1 ) {
				$error.text( i18n.emailRequired || 'A valid email is required.' ).prop( 'hidden', false );
				return;
			}
			if ( ! address1 || ! city || ! postcode || ! country ) {
				$error.text( i18n.addressRequired || 'Please complete your billing address.' ).prop( 'hidden', false );
				return;
			}

			$submit.prop( 'disabled', true ).text( i18n.processing || 'Processing…' );

			var checkout = getCheckoutConfig( $root );
			if ( ! checkout.ajaxUrl ) {
				$error.text( i18n.checkoutFailed || 'Could not complete checkout.' ).prop( 'hidden', false );
				$submit.prop( 'disabled', false ).text( i18n.completeSub || 'Complete subscription' );
				return;
			}

			$.ajax( {
				url: checkout.ajaxUrl,
				type: 'POST',
				dataType: 'json',
				data: {
					action: 'lucrsure_public_checkout',
					nonce: checkout.nonce,
					plan_id: planId,
					name: name,
					email: email,
					phone: $form.find( '[name="phone"]' ).val(),
					billing_address_1: address1,
					billing_address_2: $form.find( '[name="billing_address_2"]' ).val(),
					billing_city: city,
					billing_state: $form.find( '[name="billing_state"]' ).val(),
					billing_postcode: postcode,
					billing_country: country,
					gateway: $form.find( '[name="gateway"]' ).val()
				}
			} ).done( function ( response ) {
				if ( ! response || ! response.success ) {
					var msg = response && response.data && response.data.message
						? response.data.message
						: ( i18n.checkoutFailed || 'Could not complete checkout.' );
					$error.text( msg ).prop( 'hidden', false );
					return;
				}
				if ( response.data && response.data.redirect ) {
					window.location.href = response.data.redirect;
					return;
				}
				showSuccess( $root, response.data.message || '' );
			} ).fail( function ( xhr ) {
				var msg = i18n.checkoutFailed || 'Could not complete checkout.';
				if ( xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ) {
					msg = xhr.responseJSON.data.message;
				} else if ( xhr.status === 404 ) {
					msg = i18n.ajaxNotFound || 'Checkout endpoint not found. Please refresh the page and try again.';
				} else if ( xhr.status === 403 || xhr.responseText === '-1' || xhr.responseText === '0' ) {
					msg = i18n.sessionExpired || 'Session expired. Please refresh the page and try again.';
				}
				$error.text( msg ).prop( 'hidden', false );
			} ).always( function () {
				$submit.prop( 'disabled', false ).text( i18n.completeSub || 'Complete subscription' );
			} );
		} );

		$( document ).on( 'click', '.lucrsure-faq-question', function () {
			var $btn    = $( this );
			var $item   = $btn.closest( '.lucrsure-faq-item' );
			var $answer = $item.find( '.lucrsure-faq-answer' );
			var open    = $btn.attr( 'aria-expanded' ) === 'true';

			$item.siblings( '.lucrsure-faq-item' ).each( function () {
				$( this ).find( '.lucrsure-faq-question' ).attr( 'aria-expanded', 'false' );
				$( this ).find( '.lucrsure-faq-answer' ).prop( 'hidden', true );
				$( this ).removeClass( 'is-open' );
			} );

			if ( open ) {
				$btn.attr( 'aria-expanded', 'false' );
				$answer.prop( 'hidden', true );
				$item.removeClass( 'is-open' );
				return;
			}

			$btn.attr( 'aria-expanded', 'true' );
			$answer.prop( 'hidden', false );
			$item.addClass( 'is-open' );
		} );

		$( document ).on( 'click', '.lucrsure-plan-grid-cta, a.lucrsure-plan-grid-media, .lucrsure-plan-grid-name a', function ( e ) {
			var $link = $( this );
			var href  = $link.attr( 'href' ) || '';
			var $card = $link.closest( '.lucrsure-plan-grid-card' );
			var planId = getPlanIdFromHref( href ) || String( $card.data( 'plan-id' ) || '' );

			if ( ! planId ) {
				return;
			}

			if ( openCheckoutForPlan( planId, $card, true ) ) {
				e.preventDefault();
			}
		} );

		$( document ).on( 'click', '.lucrsure-hero-cta[href="#lucrsure-plans"]', function ( e ) {
			var $target = $( '#lucrsure-plans' );
			if ( $target.length ) {
				e.preventDefault();
				$( 'html, body' ).animate( { scrollTop: $target.offset().top - 24 }, 400 );
			}
		} );

		$( document ).on( 'change', '.lucrsure-plan-grid-select', function () {
			var $select = $( this );
			var $root   = $select.closest( '.lucrsure-plan-grid' );
			var filter  = String( $select.data( 'filter' ) || 'branch' );

			if ( 'type' === filter ) {
				$root.data( 'active-type', String( $select.val() || '' ) );
			} else {
				$root.data( 'active-branch', String( $select.val() || '0' ) );
			}

			applyPlanGridFilters( $root );
		} );

		$( document ).on( 'click', '.lucrsure-plan-grid-reset', function () {
			var $root = $( this ).closest( '.lucrsure-plan-grid' );

			$root.find( '.lucrsure-plan-grid-select' ).each( function () {
				var $select = $( this );
				$select.val( $select.find( 'option' ).first().val() );
			} );

			$root.data( 'active-branch', '0' ).data( 'active-type', '' );
			applyPlanGridFilters( $root );
		} );

		function applyPlanGridFilters( $root ) {
			var branch       = String( $root.data( 'active-branch' ) || '0' );
			var type         = String( $root.data( 'active-type' ) || '' );
			var branchImages = $root.data( 'branchImages' ) || $root.data( 'branch-images' ) || {};
			var visible      = 0;

			$root.find( '.lucrsure-plan-grid-card' ).each( function () {
				var $card      = $( this );
				var cardBranch = String( $card.data( 'branch-id' ) || '0' );
				var cardType   = String( $card.data( 'type' ) || '' );
				var showBranch = branch === '0' || cardBranch === branch || cardBranch === '0';
				var showType   = type === '' || cardType === type;
				var show       = showBranch && showType;

				$card.prop( 'hidden', ! show );
				if ( show ) {
					visible += 1;
				}

				updatePlanGridCardImage( $card, branch, branchImages );
			} );

			$root.find( '.lucrsure-plan-grid-empty' ).prop( 'hidden', visible > 0 );
			$root.find( '.lucrsure-plan-grid-reset' ).prop( 'hidden', branch === '0' && type === '' );
			updatePlanGridCount( $root, visible );
		}

		function updatePlanGridCount( $root, visible ) {
			var $count = $root.find( '.lucrsure-plan-grid-count' );
			if ( ! $count.length ) {
				return;
			}
			var one  = String( $count.data( 'templateOne' ) || $count.data( 'template-one' ) || '%s plan' );
			var many = String( $count.data( 'templateMany' ) || $count.data( 'template-many' ) || '%s plans' );
			var template = 1 === visible ? one : many;
			$count.text( template.replace( '%s', String( visible ) ) );
		}

		function updatePlanGridCardImage( $card, branch, branchImages ) {
			if ( String( $card.data( 'has-plan-image' ) ) === '1' ) {
				return;
			}

			var cardBranch   = String( $card.data( 'branch-id' ) || '0' );
			var defaultImage = String( $card.data( 'default-image' ) || '' );
			var imageBranch  = branch !== '0' ? branch : cardBranch;
			var url          = '';

			if ( imageBranch !== '0' && branchImages && branchImages[ imageBranch ] ) {
				url = branchImages[ imageBranch ];
			} else if ( defaultImage ) {
				url = defaultImage;
			}

			var $img         = $card.find( '.lucrsure-plan-grid-photo' );
			var $placeholder = $card.find( '.lucrsure-plan-grid-media-placeholder' );

			if ( url ) {
				$img.attr( 'src', url ).prop( 'hidden', false );
				$placeholder.prop( 'hidden', true );
			} else {
				$img.removeAttr( 'src' ).prop( 'hidden', true );
				$placeholder.prop( 'hidden', false );
			}
		}
	} );
}( jQuery ) );
