( function () {
	'use strict';

	function updateTotal( form ) {
		const select   = form.querySelector( '.plugoza-ett-ticket-select' );
		const quantity = form.querySelector( '.plugoza-ett-ticket-quantity' );
		const output   = form.querySelector( '.plugoza-ett-total span' );

		if ( ! select || ! quantity || ! output ) {
			return;
		}

		const price    = parseFloat( select.options[ select.selectedIndex ].getAttribute( 'data-price' ) ) || 0;
		const count    = parseInt( quantity.value, 10 ) || 0;
		const currency = output.textContent.trim().split( /\s+/ ).pop();

		output.textContent = ( price * count ).toFixed( 2 ) + ' ' + currency;
	}

	function setupForm( form ) {
		const select   = form.querySelector( '.plugoza-ett-ticket-select' );
		const quantity = form.querySelector( '.plugoza-ett-ticket-quantity' );
		const radio    = form.querySelector( 'input[name="payment_method"][value="free_registration"]' );

		if ( select ) {
			select.addEventListener( 'change', function () {
				updateTotal( form );
			} );
		}

		if ( quantity ) {
			quantity.addEventListener( 'input', function () {
				updateTotal( form );
			} );
		}

		if ( radio ) {
			const label = radio.closest( 'label' );

			if ( label && label.lastChild ) {
				label.lastChild.textContent = ' Manual Pay';
			}

			if ( window.plugozaEventTicketing && window.plugozaEventTicketing.manualMessage && ! form.querySelector( '.plugoza-ett-manual-pay-message' ) ) {
				const message = document.createElement( 'p' );
				message.className = 'plugoza-ett-manual-pay-message';
				message.textContent = window.plugozaEventTicketing.manualMessage;
				radio.closest( 'fieldset' ).appendChild( message );
			}
		}

		updateTotal( form );
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		document.querySelectorAll( '.plugoza-ett-booking-form' ).forEach( setupForm );
	} );
}() );
