/**
 * Donation Form Block - Frontend JavaScript
 *
 * Handles donation submission through the REST API.
 *
 * @package AmbassadorHub\Fundraiser\Fundraisers\Blocks\DonationForm
 */

(function() {
	'use strict';

	// Wait for DOM to be ready
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}

	function init() {
		const formBlocks = document.querySelectorAll('.donation-form-block');

		formBlocks.forEach(function(block) {
			const form = block.querySelector('.donation-form');
			if (!form) return;

			initSteps(form);
			initPredefinedAmounts(form);
			initAnonymousDonation(form);
		});
	}

	function initSteps(form) {
		const steps = form.querySelectorAll('.ambh-form-step');
		if (steps.length < 2) return;

		const pips    = form.querySelectorAll('.ambh-step-pip');
		const nextBtn = form.querySelector('.ambh-btn-next');
		const backBtn = form.querySelector('.ambh-btn-back');

		// Activate step UI (CSS hides non-active steps only when this class is present).
		form.classList.add('ambh-steps-enabled');

		nextBtn.addEventListener('click', function() {
			const step1   = form.querySelector('.ambh-form-step[data-step="1"]');
			const inputs  = Array.from(step1.querySelectorAll('input, select, textarea'));
			const invalid = inputs.find(function(el) { return !el.checkValidity(); });

			if (invalid) {
				invalid.reportValidity();
				return;
			}

			form.classList.remove('ambh-going-back');
			activateStep(2);
		});

		backBtn.addEventListener('click', function() {
			form.classList.add('ambh-going-back');
			activateStep(1);
		});

		function activateStep(num) {
			steps.forEach(function(step) {
				step.classList.remove('ambh-form-step--active');
			});
			pips.forEach(function(pip, i) {
				pip.classList.toggle('ambh-step-pip--active', i + 1 === num);
			});
			const target = form.querySelector('.ambh-form-step[data-step="' + num + '"]');
			if (target) target.classList.add('ambh-form-step--active');
		}
	}
	
	function initAnonymousDonation(form) {
		// The anonymous checkbox only sets the is_anonymous flag sent to the server.
		// Donor info fields remain visible and required so contact details are always
		// collected for admin / CRM purposes. The flag controls frontend display only.
	}

	function initPredefinedAmounts(form) {
		const amountButtons = form.querySelectorAll('.amount-btn');
		const customAmountField = form.querySelector('.custom-amount-field');
		const selectedAmountInput = form.querySelector('#selected-amount');
		const amountInput = form.querySelector('#amount');
		const currency = window.ambhCurrencyInput || { symbol: '€', decimal: ',', parseAmount: parseFloat };
		const minAmount = parseFloat(form.dataset.minAmount || 1);
		const i18n = (window.ambhDonationFormConfig && window.ambhDonationFormConfig.i18n) || {};

		// Hide predefined buttons below the minimum and fix preselection if needed.
		amountButtons.forEach(function(button) {
			const amt = parseFloat(button.dataset.amount);
			if (!isNaN(amt) && amt < minAmount) {
				button.style.display = 'none';
				button.classList.remove('active');
			}
		});
		// If the active button was hidden, activate the first still-visible non-custom button.
		if (!form.querySelector('.amount-btn.active')) {
			const firstValid = form.querySelector('.amount-btn:not([data-amount="custom"]):not([style*="display: none"])');
			if (firstValid) {
				firstValid.classList.add('active');
				if (selectedAmountInput) selectedAmountInput.value = firstValid.dataset.amount;
			}
		}

		// The custom amount field starts hidden, so its input must not be required initially.
		if (amountInput && customAmountField && customAmountField.style.display === 'none') {
			amountInput.required = false;
		}

		amountButtons.forEach(function(button) {
			button.addEventListener('click', function() {
				// Remove active class from all buttons
				amountButtons.forEach(function(btn) {
					btn.classList.remove('active');
				});

				// Add active class to clicked button
				button.classList.add('active');

				const amount = button.dataset.amount;

				if (amount === 'custom') {
					// Show custom amount field
					if (customAmountField) {
						customAmountField.style.display = 'block';
					}
					if (amountInput) {
						amountInput.required = true;
						amountInput.focus();
					}
					if (selectedAmountInput) {
						selectedAmountInput.value = '';
					}
				} else {
					// Hide custom amount field
					if (customAmountField) {
						customAmountField.style.display = 'none';
					}
					if (amountInput) {
						amountInput.required = false;
					}
					// Set selected amount
					if (selectedAmountInput) {
						selectedAmountInput.value = amount;
					}
				}
			});
		});

		// Update selected amount when custom amount changes
		if (amountInput) {
			amountInput.addEventListener('input', function() {
				const value = currency.parseAmount(this.value);
				if (selectedAmountInput && !isNaN(value) && value >= minAmount) {
					selectedAmountInput.value = value;
				}
			});
		}

		// Form validation
		if (form.querySelector('.predefined-amounts')) {
			form.addEventListener('submit', function(e) {
				if (selectedAmountInput) {
					const selectedAmount = parseFloat(selectedAmountInput.value);
					if (!selectedAmount || selectedAmount < minAmount) {
						e.preventDefault();
						const template = i18n.errorAmount || 'Please select or enter a valid donation amount (minimum: %s).';
						const minAmountText = currency.symbol + minAmount.toFixed(2).replace('.', currency.decimal);
						alert(template.replace('%s', minAmountText));
						return false;
					}
				}
			});
		}
	}
})();
