/**
 * 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 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 );
		scrollToCheckout( $root );
	}

	function showPlans( $root ) {
		$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 );
		exitCheckoutMode( $root );
	}

	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 () {
		$( '.lucrsure-public' ).each( function () {
			var $root           = $( this );
			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 );
			}
		} );

		$( 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-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 );
			}
		} );
	} );
}( jQuery ) );
