/* global CAFWPricing, FS */
/**
 * Craft Addons - Pricing page JS.
 *
 * Handles:
 *   - Annual / Lifetime billing toggle (swaps amount, period, sub-line from data-attrs).
 *   - FAQ accordion (one item open at a time, chevron rotates via CSS class).
 *   - Freemius checkout via FS.Checkout.
 *   - Scroll-to-pricing button in the ProUpgrade CTA.
 */
( function () {
	'use strict';

	var billing   = 'annual';
	var fsHandler = null;

	/* ── Freemius checkout ──────────────────────────────────────── */

	function buildHandler() {
		if ( typeof FS === 'undefined' || ! FS || ! FS.Checkout ) {
			return null;
		}
		if ( ! CAFWPricing || ! CAFWPricing.pluginId || ! CAFWPricing.publicKey ) {
			return null;
		}
		return new FS.Checkout( {
			plugin_id:  CAFWPricing.pluginId,
			public_key: CAFWPricing.publicKey,
		} );
	}

	function openCheckout( btn ) {
		var pricingId = btn.getAttribute( 'data-pricing-id' );
		var licenses  = parseInt( btn.getAttribute( 'data-licenses' ), 10 ) || 1;

		if ( ! fsHandler ) {
			fsHandler = buildHandler();
		}

		if ( ! fsHandler ) {
			if ( CAFWPricing && CAFWPricing.accountUrl ) {
				window.location.href = CAFWPricing.accountUrl;
			}
			return;
		}

		var opts = {
			plan_id:       CAFWPricing.planId,
			billing_cycle: billing,
			licenses:      licenses,
			success: function () {
				window.location.href = CAFWPricing.accountUrl;
			},
		};

		if ( pricingId ) {
			opts.pricing_id = pricingId;
		}

		fsHandler.open( opts );
	}

	/* ── Billing toggle ─────────────────────────────────────────── */

	function updateCards( newBilling ) {
		billing = newBilling;

		var cards = document.querySelectorAll( '.cafw-plan-card' );
		cards.forEach( function ( card ) {
			var amountEl = card.querySelector( '.js-cafw-amount' );
			var periodEl = card.querySelector( '.js-cafw-period' );
			var subEl    = card.querySelector( '.js-cafw-sub' );
			var btn      = card.querySelector( '.js-cafw-buy' );

			if ( ! amountEl ) {
				return;
			}

			var amount = card.getAttribute( 'data-' + newBilling + '-amount' );
			var period = card.getAttribute( 'data-' + newBilling + '-period' );
			var sub    = card.getAttribute( 'data-' + newBilling + '-sub' );

			if ( amount ) {
				amountEl.textContent = amount;
				if ( periodEl ) { periodEl.textContent = period || ''; }
				if ( subEl )    { subEl.textContent    = sub    || ''; }
			} else {
				amountEl.textContent = '-';
				if ( periodEl ) { periodEl.textContent = ''; }
				if ( subEl )    { subEl.textContent    = ''; }
			}

			if ( btn ) {
				btn.setAttribute( 'data-billing', newBilling );
			}
		} );
	}

	function initToggle() {
		var toggleBtns = document.querySelectorAll( '.cafw-upgrade-toggle__btn' );

		toggleBtns.forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				toggleBtns.forEach( function ( b ) {
					b.classList.remove( 'is-active' );
					b.setAttribute( 'aria-selected', 'false' );
				} );
				btn.classList.add( 'is-active' );
				btn.setAttribute( 'aria-selected', 'true' );
				updateCards( btn.getAttribute( 'data-billing' ) );
			} );
		} );
	}

	/* ── FAQ accordion ──────────────────────────────────────────── */

	function initFaq() {
		var faq = document.querySelector( '.js-cafw-faq' );
		if ( ! faq ) {
			return;
		}

		var items = faq.querySelectorAll( '.cafw-faq__item' );

		items.forEach( function ( item ) {
			var btn    = item.querySelector( '.cafw-faq__question' );
			var answer = item.querySelector( '.cafw-faq__answer' );

			if ( ! btn || ! answer ) {
				return;
			}

			btn.addEventListener( 'click', function () {
				var isOpen = item.classList.contains( 'is-open' );

				items.forEach( function ( other ) {
					other.classList.remove( 'is-open' );
					var otherBtn    = other.querySelector( '.cafw-faq__question' );
					var otherAnswer = other.querySelector( '.cafw-faq__answer' );
					if ( otherBtn )    { otherBtn.setAttribute( 'aria-expanded', 'false' ); }
					if ( otherAnswer ) { otherAnswer.hidden = true; }
				} );

				if ( ! isOpen ) {
					item.classList.add( 'is-open' );
					btn.setAttribute( 'aria-expanded', 'true' );
					answer.hidden = false;
				}
			} );
		} );
	}

	/* ── Scroll-to-pricing helper ────────────────────────────────── */

	function initScrollPricing() {
		var scrollBtn = document.querySelector( '.js-cafw-scroll-pricing' );
		if ( ! scrollBtn ) {
			return;
		}

		scrollBtn.addEventListener( 'click', function () {
			var pricingSection = document.querySelector( '.cafw-upgrade-pricing' );
			if ( pricingSection ) {
				pricingSection.scrollIntoView( { behavior: 'smooth', block: 'start' } );
			}
		} );
	}

	/* ── Buy buttons ────────────────────────────────────────────── */

	function initBuyButtons() {
		document.querySelectorAll( '.js-cafw-buy' ).forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				openCheckout( btn );
			} );
		} );
	}

	/* ── Boot ───────────────────────────────────────────────────── */

	function init() {
		initToggle();
		initFaq();
		initScrollPricing();
		initBuyButtons();
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
}() );
