/* global donaticoData */
/**
 * Donatico — donation form interactions.
 * Pure vanilla JS, no framework dependency.
 * Supports multiple forms on the same page via window.donaticoForms.
 */
( function () {
	'use strict';

	/** Localised config injected by wp_localize_script. */
	var cfg = window.donaticoData || {};
	var i18n = cfg.i18n || {};

	// -------------------------------------------------------------------------
	// Per-form initialisation
	// -------------------------------------------------------------------------

	/**
	 * Wire up all interactions for a single .donatico-form-element.
	 *
	 * @param {HTMLFormElement} formEl
	 */
	function initForm( formEl ) {
		var wrap         = formEl.closest( '.donatico-form' );
		var formId       = wrap ? wrap.dataset.formId : null;
		var currency     = wrap ? ( wrap.dataset.currency || cfg.currency || 'USD' ) : 'USD';
		var symbol       = wrap ? ( wrap.dataset.currencySymbol || cfg.currencySymbol || '$' ) : '$';

		// DOM references.
		var amountBtns   = formEl.querySelectorAll( '.donatico-amount-btn:not(.donatico-amount-btn--custom)' );
		var customBtn    = formEl.querySelector( '.donatico-amount-btn--custom' );
		var customWrap   = formEl.querySelector( '.donatico-custom-amount-wrap' );
		var customInput  = formEl.querySelector( '.donatico-custom-input' );
		var submitBtn    = formEl.querySelector( '.donatico-submit-btn' );
		var nameInput    = formEl.querySelector( '.donatico-input-name' );
		var emailInput   = formEl.querySelector( '.donatico-input-email' );
		var messageInput = formEl.querySelector( '.donatico-input-message' );
		var anonCheck    = formEl.querySelector( '.donatico-input-anonymous' );
		var nonceInput   = formEl.querySelector( '.donatico-nonce' );
		var errorDiv     = formEl.querySelector( '.donatico-form-error' );

		// State.
		var selectedAmount = 0;
		var isCustom       = false;

		// ---- Helpers ----

		function getCurrentAmount() {
			if ( isCustom ) {
				return parseFloat( customInput ? customInput.value : '0' ) || 0;
			}
			return selectedAmount;
		}

		function updateSubmitBtn() {
			var amount = getCurrentAmount();
			if ( ! submitBtn ) return;

			if ( amount >= ( cfg.minAmount || 1 ) ) {
				submitBtn.disabled = false;
				submitBtn.textContent = ( i18n.donate || 'Donate' ) + ' ' + symbol + amount.toFixed( 2 );
			} else {
				submitBtn.disabled = true;
				submitBtn.textContent = i18n.donate || 'Donate Now';
			}
		}

		function deselectAll() {
			var all = formEl.querySelectorAll( '.donatico-amount-btn' );
			all.forEach( function ( btn ) {
				btn.classList.remove( 'is-selected' );
				btn.setAttribute( 'aria-pressed', 'false' );
			} );
		}

		function selectBtn( btn ) {
			deselectAll();
			btn.classList.add( 'is-selected' );
			btn.setAttribute( 'aria-pressed', 'true' );
		}

		function showError( msg ) {
			if ( ! errorDiv ) return;
			errorDiv.textContent = msg;
			errorDiv.hidden = false;
			errorDiv.scrollIntoView( { behavior: 'smooth', block: 'nearest' } );
		}

		function hideError() {
			if ( ! errorDiv ) return;
			errorDiv.hidden = true;
			errorDiv.textContent = '';
		}

		function setLoading( loading ) {
			if ( ! submitBtn ) return;
			submitBtn.disabled = loading;
			submitBtn.classList.toggle( 'is-loading', loading );
			if ( loading ) {
				submitBtn.textContent = i18n.processing || 'Processing…';
			} else {
				updateSubmitBtn();
			}
		}

		function isValidEmail( email ) {
			return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test( email );
		}

		// ---- Amount button clicks ----

		amountBtns.forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				isCustom = false;
				selectedAmount = parseFloat( btn.dataset.amount ) || 0;

				if ( customWrap ) customWrap.hidden = true;
				if ( customInput ) customInput.value = '';

				selectBtn( btn );
				updateSubmitBtn();
			} );
		} );

		if ( customBtn ) {
			customBtn.addEventListener( 'click', function () {
				isCustom = true;
				selectedAmount = 0;

				if ( customWrap ) customWrap.hidden = false;
				if ( customInput ) customInput.focus();

				selectBtn( customBtn );
				updateSubmitBtn();
			} );
		}

		if ( customInput ) {
			customInput.addEventListener( 'input', updateSubmitBtn );
		}

		// ---- Form submission ----

		formEl.addEventListener( 'submit', function ( e ) {
			e.preventDefault();

			var amount   = getCurrentAmount();
			var name     = nameInput  ? nameInput.value.trim()  : '';
			var email    = emailInput ? emailInput.value.trim() : '';
			var message  = messageInput ? messageInput.value.trim() : '';
			var isAnon   = anonCheck  ? ( anonCheck.checked ? 1 : 0 ) : 0;
			var nonce    = nonceInput ? nonceInput.value : '';

			// Client-side validation.
			if ( amount < ( cfg.minAmount || 1 ) ) {
				showError( i18n.amountMin || 'Please enter a valid amount (minimum 1).' );
				if ( customInput ) customInput.focus();
				return;
			}
			if ( ! name ) {
				showError( i18n.nameRequired || 'Please enter your name.' );
				if ( nameInput ) nameInput.focus();
				return;
			}
			if ( ! email || ! isValidEmail( email ) ) {
				showError( i18n.emailRequired || 'Please enter a valid email address.' );
				if ( emailInput ) emailInput.focus();
				return;
			}

			hideError();
			setLoading( true );

			// Mark inputs as valid (clear aria-invalid if set).
			[ nameInput, emailInput ].forEach( function ( el ) {
				if ( el ) el.removeAttribute( 'aria-invalid' );
			} );

			var body = new FormData();
			body.append( 'action',      'donatico_create_checkout' );
			body.append( 'nonce',       nonce );
			body.append( 'amount',      amount.toString() );
			body.append( 'donor_name',  name );
			body.append( 'donor_email', email );
			body.append( 'message',     message );
			body.append( 'is_anonymous', isAnon.toString() );
			body.append( 'currency',    currency );
			if ( formId ) body.append( 'form_id', formId );

			// Forward any extra fields registered by add-on plugins.
			// Inputs with data-donatico-extra="<key>" are auto-included in
			// the POST body. Used by Pro for tribute fields, donor wall opt-in, etc.
			var extras = formEl.querySelectorAll( '[data-donatico-extra]' );
			extras.forEach( function ( el ) {
				var key = el.getAttribute( 'data-donatico-extra' );
				if ( ! key ) return;

				var value = '';
				if ( el.type === 'checkbox' || el.type === 'radio' ) {
					// For checkboxes/radios, send '1' when checked, '' when not.
					// For radio groups, only the checked one matches the
					// querySelector pattern if you used :checked, but since
					// we're iterating all, this loop will see all of them —
					// we only append the checked one.
					if ( ! el.checked ) return;
					value = el.value || '1';
				} else {
					value = el.value || '';
				}

				body.append( key, value );
			} );

			fetch( cfg.ajaxUrl || '/wp-admin/admin-ajax.php', {
				method:      'POST',
				body:        body,
				credentials: 'same-origin',
			} )
				.then( function ( response ) {
					return response.json();
				} )
				.then( function ( data ) {
					if ( data.success && data.data && data.data.redirect_url ) {
						window.location.href = data.data.redirect_url;
					} else {
						var msg = ( data.data && data.data.message )
							|| ( i18n.error || 'Something went wrong. Please try again.' );
						showError( msg );
						setLoading( false );
					}
				} )
				.catch( function () {
					showError( i18n.error || 'Something went wrong. Please try again.' );
					setLoading( false );
				} );
		} );

		// Set initial button state.
		updateSubmitBtn();
	}

	// -------------------------------------------------------------------------
	// Boot — initialise all forms on the page
	// -------------------------------------------------------------------------

	function boot() {
		document.querySelectorAll( '.donatico-form-element' ).forEach( initForm );
	}

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

	// Expose for programmatic use (e.g. after dynamically inserting a form).
	window.donaticoForms = { init: initForm, boot: boot };

} )();
