/**
 * Donatico — Upgrade to Pro page checkout integration
 *
 * Wires up the "Get Pro" buttons on the Upgrade page so that clicking
 * each one opens the Freemius Checkout modal with the corresponding
 * plan pre-selected. Loads only on the Upgrade admin page.
 *
 * Depends on the Freemius Checkout JS SDK loaded separately via
 * https://checkout.freemius.com/checkout.min.js — see Assets.php.
 *
 * @package Donatico
 */

( function () {
	'use strict';

	/**
	 * Wait for the page to be ready, then bind click handlers.
	 */
	function init() {
		if ( typeof window.FS === 'undefined' || typeof window.FS.Checkout === 'undefined' ) {
			// SDK didn't load — log once for diagnostics, do nothing.
			// Users on the page would just see buttons that do nothing,
			// which is the same as the pre-wiring state. Not catastrophic.
			if ( window.console && window.console.warn ) {
				window.console.warn( 'Donatico: Freemius Checkout SDK not available.' );
			}
			return;
		}

		var buttons = document.querySelectorAll( '.donatico-cta-button' );
		if ( ! buttons.length ) {
			return;
		}

		// One shared FS.Checkout instance reused across all three buttons.
		// We pass plan_id at open() time per button click rather than
		// configuring it here.
		var handle = window.FS.Checkout.configure( {
			plugin_id: '30154',
			plan_id: '52115', // Default to Starter; overridden per click.
			public_key: 'pk_bf92d92704c1722fff51836617e97',
			image: ''
		} );

		Array.prototype.forEach.call( buttons, function ( button ) {
			button.addEventListener( 'click', function ( event ) {
				event.preventDefault();

				var pluginId = button.getAttribute( 'data-fs-plugin-id' );
				var planId = button.getAttribute( 'data-fs-plan-id' );
				var licensesAttr = button.getAttribute( 'data-fs-licenses' );
				var licenses = ( licensesAttr !== null && licensesAttr !== '' ) ? parseInt( licensesAttr, 10 ) : 1;

				if ( ! pluginId || ! planId ) {
					return;
				}

				handle.open( {
					plugin_id: pluginId,
					plan_id: planId,
					licenses: licenses
				} );
			} );
		} );
	}

	// Run after DOM is interactive.
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
