/**
 * NR Brief Builder — front-end stepper form logic.
 * Vanilla JS, no dependencies. Generalized from the "[portfolio_quote_form]"
 * prototype to support any number of instances and any preset template.
 */
( function () {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {
		var wraps = document.querySelectorAll( '[data-briefify]' );
		wraps.forEach( initBriefify );
	} );

	function initBriefify( wrap ) {
		var form = wrap.querySelector( '[data-briefify-form]' );
		if ( ! form ) {
			return;
		}

		var totalSteps  = parseInt( wrap.getAttribute( 'data-total-steps' ), 10 ) || 1;
		var currentStep = 1;
		var i18n        = ( window.briefifyData && window.briefifyData.i18n ) || {};

		bindTypeGrid();
		bindChips();
		bindNav();

		function stepEl( step ) {
			return form.querySelector( '[data-briefify-step="' + step + '"]' );
		}

		function bindTypeGrid() {
			wrap.querySelectorAll( '.briefify-type-card' ).forEach( function ( card ) {
				card.addEventListener( 'click', function () {
					var grid = card.closest( '[data-briefify-type-grid]' );
					if ( ! grid ) {
						return;
					}
					grid.querySelectorAll( '.briefify-type-card' ).forEach( function ( c ) {
						c.classList.remove( 'is-selected' );
					} );
					card.classList.add( 'is-selected' );
					var radio = card.querySelector( 'input[type="radio"]' );
					if ( radio ) {
						radio.checked = true;
					}
				} );
			} );
		}

		function bindChips() {
			wrap.querySelectorAll( '[data-briefify-chips]' ).forEach( function ( group ) {
				var isMulti     = '1' === group.getAttribute( 'data-multi' );
				var fieldId     = group.getAttribute( 'data-field' );
				var hiddenInput = fieldId ? document.getElementById( fieldId ) : null;

				group.querySelectorAll( '.briefify-chip' ).forEach( function ( chip ) {
					chip.addEventListener( 'click', function () {
						if ( isMulti ) {
							chip.classList.toggle( 'is-selected' );
						} else {
							group.querySelectorAll( '.briefify-chip' ).forEach( function ( c ) {
								c.classList.remove( 'is-selected' );
							} );
							chip.classList.add( 'is-selected' );
						}

						if ( hiddenInput ) {
							var selected = [];
							group.querySelectorAll( '.briefify-chip.is-selected' ).forEach( function ( c ) {
								selected.push( c.getAttribute( 'data-value' ) );
							} );
							hiddenInput.value = selected.join( ', ' );
						}
					} );
				} );
			} );
		}

		function bindNav() {
			wrap.querySelectorAll( '[data-briefify-next]' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var next = parseInt( btn.getAttribute( 'data-briefify-next' ), 10 );
					if ( ! validateStep( currentStep ) ) {
						return;
					}
					goToStep( next );
				} );
			} );

			wrap.querySelectorAll( '[data-briefify-back]' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var back = parseInt( btn.getAttribute( 'data-briefify-back' ), 10 );
					goToStep( back );
				} );
			} );

			form.addEventListener( 'submit', handleSubmit );
		}

		function goToStep( step ) {
			form.querySelectorAll( '[data-briefify-step]' ).forEach( function ( s ) {
				s.classList.add( 'briefify-step--hidden' );
			} );

			var target = stepEl( step );
			if ( target ) {
				target.classList.remove( 'briefify-step--hidden' );
				if ( step === totalSteps ) {
					updateRecap();
				}
				wrap.scrollIntoView( { behavior: 'smooth', block: 'start' } );
			}

			currentStep = step;
			wrap.setAttribute( 'data-step', step );
			updateStepperHeader( step );
			updateProgress( step );
		}

		function updateProgress( step ) {
			var fill = wrap.querySelector( '[data-briefify-progress]' );
			if ( fill ) {
				fill.style.width = Math.round( ( step / totalSteps ) * 100 ) + '%';
			}
		}

		function updateStepperHeader( active ) {
			var items = wrap.querySelectorAll( '[data-briefify-step-item]' );
			items.forEach( function ( item ) {
				var num    = parseInt( item.getAttribute( 'data-briefify-step-item' ), 10 );
				var bubble = item.querySelector( '[data-briefify-bubble]' );
				var label  = item.querySelector( '[data-briefify-step-label]' );

				bubble.classList.remove( 'briefify-bubble--active', 'briefify-bubble--done' );
				if ( label ) {
					label.classList.remove( 'briefify-step-label--muted' );
				}

				if ( num < active ) {
					bubble.classList.add( 'briefify-bubble--done' );
					bubble.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>';
					if ( label ) {
						label.classList.add( 'briefify-step-label--muted' );
					}
				} else if ( num === active ) {
					bubble.classList.add( 'briefify-bubble--active' );
					bubble.textContent = num;
				} else {
					bubble.textContent = num;
					if ( label ) {
						label.classList.add( 'briefify-step-label--muted' );
					}
				}
			} );

			wrap.querySelectorAll( '[data-briefify-connector]' ).forEach( function ( connector, index ) {
				connector.classList.toggle( 'briefify-connector--done', ( index + 1 ) < active );
			} );
		}

		function validateStep( step ) {
			var el = stepEl( step );
			if ( ! el ) {
				return true;
			}

			removeError( step );

			var typeGrid = el.querySelector( '[data-briefify-type-grid]' );
			if ( typeGrid ) {
				var selected = typeGrid.querySelector( '.briefify-type-card.is-selected' );
				if ( ! selected ) {
					showError( step, i18n.selectRequired || 'Please select an option to continue.' );
					return false;
				}
			}

			var invalid = false;
			el.querySelectorAll( '.briefify-input[required]' ).forEach( function ( input ) {
				input.classList.remove( 'briefify-input--invalid' );
				var value = input.value.trim();
				if ( ! value ) {
					input.classList.add( 'briefify-input--invalid' );
					invalid = true;
				} else if ( 'email' === input.type && ! /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test( value ) ) {
					input.classList.add( 'briefify-input--invalid' );
					invalid = true;
				}
			} );

			if ( invalid ) {
				showError( step, i18n.fieldRequired || 'Please fill in the required fields.' );
				return false;
			}

			return true;
		}

		function showError( step, message ) {
			var el = stepEl( step );
			if ( ! el ) {
				return;
			}
			var existing = el.querySelector( '.briefify-step-error' );
			if ( existing ) {
				existing.textContent = message;
				return;
			}
			var err = document.createElement( 'p' );
			err.className   = 'briefify-step-error';
			err.textContent = message;

			var anchor = el.querySelector( '[data-briefify-type-grid]' ) || el.querySelector( '.briefify-step-title' );
			if ( anchor ) {
				anchor.insertAdjacentElement( 'afterend', err );
			} else {
				el.appendChild( err );
			}
		}

		function removeError( step ) {
			var el = stepEl( step );
			if ( ! el ) {
				return;
			}
			var err = el.querySelector( '.briefify-step-error' );
			if ( err ) {
				err.remove();
			}
		}

		function updateRecap() {
			var rows  = wrap.querySelector( '[data-briefify-recap-rows]' );
			var empty = wrap.querySelector( '[data-briefify-recap-empty]' );
			if ( ! rows ) {
				return;
			}

			var entries = [];

			var typeGrid = wrap.querySelector( '[data-briefify-type-grid]' );
			if ( typeGrid ) {
				var selectedType = typeGrid.querySelector( '.briefify-type-card.is-selected .briefify-type-label' );
				entries.push( {
					label: typeGrid.getAttribute( 'data-recap-label' ) || 'Type',
					value: selectedType ? selectedType.textContent : ''
				} );
			}

			wrap.querySelectorAll( '.briefify-field-group[data-recap="1"]' ).forEach( function ( group ) {
				var input = group.querySelector( 'input[type="hidden"]' );
				entries.push( {
					label: group.getAttribute( 'data-recap-label' ) || '',
					value: input ? input.value : ''
				} );
			} );

			rows.querySelectorAll( '.briefify-recap-row' ).forEach( function ( row ) {
				row.remove();
			} );

			var hasValue = false;
			entries.forEach( function ( entry ) {
				if ( entry.value ) {
					hasValue = true;
				}
				var row = document.createElement( 'div' );
				row.className = 'briefify-recap-row';
				row.innerHTML =
					'<span class="briefify-recap-key"></span>' +
					'<span class="briefify-recap-val"></span>';
				row.querySelector( '.briefify-recap-key' ).textContent = entry.label;
				row.querySelector( '.briefify-recap-val' ).textContent = entry.value || ( i18n.empty || '—' );
				rows.appendChild( row );
			} );

			if ( empty ) {
				empty.hidden = hasValue;
			}
		}

		function handleSubmit( event ) {
			event.preventDefault();

			if ( ! validateStep( totalSteps ) ) {
				return;
			}

			var submitBtn = form.querySelector( '[data-briefify-submit]' );
			var label     = submitBtn ? submitBtn.querySelector( '.briefify-btn-submit-label' ) : null;
			var original  = label ? label.textContent : '';

			if ( submitBtn ) {
				submitBtn.disabled = true;
			}
			if ( label ) {
				label.textContent = i18n.sending || 'Sending…';
			}

			var formData = new FormData( form );
			formData.append( 'action', 'briefify_submit' );
			formData.append( 'nonce', ( window.briefifyData && window.briefifyData.nonce ) || '' );

			fetch( ( window.briefifyData && window.briefifyData.ajaxUrl ) || '', {
				method: 'POST',
				credentials: 'same-origin',
				body: formData
			} )
				.then( function ( response ) {
					return response.json();
				} )
				.then( function ( json ) {
					if ( json && json.success ) {
						showSuccess( json.data && json.data.message );
					} else {
						resetSubmit();
						showError( totalSteps, ( json && json.data && json.data.message ) || i18n.error || 'Something went wrong.' );
					}
				} )
				.catch( function () {
					resetSubmit();
					showError( totalSteps, i18n.error || 'Something went wrong.' );
				} );

			function resetSubmit() {
				if ( submitBtn ) {
					submitBtn.disabled = false;
				}
				if ( label ) {
					label.textContent = original;
				}
			}
		}

		function showSuccess( message ) {
			var successEl = wrap.querySelector( '[data-briefify-success]' );
			var messageEl = wrap.querySelector( '[data-briefify-success-message]' );

			if ( messageEl ) {
				messageEl.textContent = message || '';
			}
			if ( successEl ) {
				successEl.hidden = false;
			}
			form.hidden = true;
		}
	}
} )();
