/**
 * Changeloger Setup Wizard
 *
 * Multi-step onboarding wizard with smooth transitions and REST API integration.
 *
 * @package Changeloger
 * @since   1.7.0
 */

( function () {
	'use strict';

	const TOTAL_STEPS = 5;
	let currentStep = 1;
	let wizardData = {
		productName: '',
		brandColor: '#6366f1',
		importedDemo: false,
	};

	const config = window.chaSetupWizard || {};
	const i18n = config.i18n || {};

	/**
	 * SVG icon templates used throughout the wizard.
	 */
	const icons = {
		rocket: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" /></svg>',
		tag: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" /></svg>',
		palette: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" /></svg>',
		download: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>',
		check: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>',
		arrowRight: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" /></svg>',
		arrowLeft: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" /></svg>',
		package: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" /></svg>',
		cog: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg>',
		book: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" /></svg>',
		chat: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" /></svg>',
		roadmap: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" /></svg>',
		bell: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" /></svg>',
		spinner: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" opacity="0.25" /><path d="M12 2a10 10 0 018.66 5" stroke="currentColor" stroke-width="3" stroke-linecap="round"><animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="1s" repeatCount="indefinite" /></path></svg>',
		plus: '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" /></svg>',
	};

	/**
	 * Build the progress bar HTML.
	 *
	 * @return {string} Progress bar markup.
	 */
	function renderProgressBar() {
		let html = '<div class="cha-wizard-progress">';
		for ( let i = 1; i <= TOTAL_STEPS; i++ ) {
			let cls = 'cha-wizard-progress-step';
			if ( i === currentStep ) {
				cls += ' active';
			} else if ( i < currentStep ) {
				cls += ' completed';
			}
			html += `<div class="${ cls }"></div>`;
		}
		html += '</div>';
		return html;
	}

	/**
	 * Render Step 1: Welcome.
	 *
	 * @return {string} Step HTML.
	 */
	function renderWelcomeStep() {
		return `
			<div class="cha-wizard-header">
				<div class="cha-wizard-icon">
					${ icons.rocket }
				</div>
				<h2 class="cha-wizard-title">${ i18n.welcome_title }</h2>
				<p class="cha-wizard-subtitle">${ i18n.welcome_subtitle }</p>
			</div>
			<div class="cha-wizard-features">
				<div class="cha-wizard-feature">
					<div class="cha-wizard-feature-icon" style="background: rgba(99, 102, 241, 0.15); color: #a5b4fc;">
						${ icons.tag }
					</div>
					<div class="cha-wizard-feature-text">
						<h4>Release Tracking</h4>
						<p>Manage version history with structured changelogs</p>
					</div>
				</div>
				<div class="cha-wizard-feature">
					<div class="cha-wizard-feature-icon" style="background: rgba(34, 197, 94, 0.15); color: #86efac;">
						${ icons.chat }
					</div>
					<div class="cha-wizard-feature-text">
						<h4>User Feedback</h4>
						<p>Collect and prioritize feature requests</p>
					</div>
				</div>
				<div class="cha-wizard-feature">
					<div class="cha-wizard-feature-icon" style="background: rgba(251, 146, 60, 0.15); color: #fdba74;">
						${ icons.roadmap }
					</div>
					<div class="cha-wizard-feature-text">
						<h4>Public Roadmap</h4>
						<p>Share your product direction with users</p>
					</div>
				</div>
				<div class="cha-wizard-feature">
					<div class="cha-wizard-feature-icon" style="background: rgba(168, 85, 247, 0.15); color: #c4b5fd;">
						${ icons.bell }
					</div>
					<div class="cha-wizard-feature-text">
						<h4>Notifications</h4>
						<p>Alert subscribers about new releases</p>
					</div>
				</div>
			</div>
			<div class="cha-wizard-actions">
				<div></div>
				<div class="cha-wizard-actions-right">
					<button type="button" class="cha-wizard-btn cha-wizard-btn-primary" id="cha-wizard-start">
						${ i18n.btn_get_started }
						${ icons.arrowRight }
					</button>
				</div>
			</div>
		`;
	}

	/**
	 * Render Step 2: Product Setup.
	 *
	 * @return {string} Step HTML.
	 */
	function renderProductStep() {
		return `
			<div class="cha-wizard-header">
				<div class="cha-wizard-icon">
					${ icons.package }
				</div>
				<h2 class="cha-wizard-title">${ i18n.product_title }</h2>
				<p class="cha-wizard-subtitle">${ i18n.product_subtitle }</p>
			</div>
			<div class="cha-wizard-form-group">
				<label class="cha-wizard-label" for="cha-product-name">${ i18n.product_label }</label>
				<input
					type="text"
					id="cha-product-name"
					class="cha-wizard-input"
					placeholder="${ i18n.product_placeholder }"
					value="${ escapeAttr( wizardData.productName ) }"
					autocomplete="off"
				/>
				<div class="cha-wizard-help">${ i18n.product_help }</div>
				<div id="cha-product-status"></div>
			</div>
			<div class="cha-wizard-actions">
				<button type="button" class="cha-wizard-btn cha-wizard-btn-ghost" id="cha-wizard-back">
					${ icons.arrowLeft }
					${ i18n.btn_back }
				</button>
				<div class="cha-wizard-actions-right">
					<button type="button" class="cha-wizard-btn cha-wizard-btn-ghost" id="cha-wizard-skip">
						${ i18n.btn_skip }
					</button>
					<button type="button" class="cha-wizard-btn cha-wizard-btn-primary" id="cha-wizard-next">
						${ i18n.btn_next }
						${ icons.arrowRight }
					</button>
				</div>
			</div>
		`;
	}

	/**
	 * Render Step 3: Brand Customization.
	 *
	 * @return {string} Step HTML.
	 */
	function renderBrandingStep() {
		const presetColors = [
			'#6366f1', '#8b5cf6', '#ec4899', '#ef4444',
			'#f97316', '#eab308', '#22c55e', '#14b8a6',
			'#06b6d4', '#3b82f6', '#1e293b', '#6b7280',
		];

		let presetsHtml = '';
		presetColors.forEach( function ( color ) {
			const activeClass = wizardData.brandColor === color ? ' active' : '';
			presetsHtml += `<button type="button" class="cha-wizard-color-preset${ activeClass }" style="background: ${ color };" data-color="${ color }" title="${ color }"></button>`;
		} );

		return `
			<div class="cha-wizard-header">
				<div class="cha-wizard-icon">
					${ icons.palette }
				</div>
				<h2 class="cha-wizard-title">${ i18n.branding_title }</h2>
				<p class="cha-wizard-subtitle">${ i18n.branding_subtitle }</p>
			</div>
			<div class="cha-wizard-form-group">
				<label class="cha-wizard-label">${ i18n.color_label }</label>
				<div class="cha-wizard-color-picker">
					<button type="button" class="cha-wizard-color-swatch" id="cha-color-swatch" style="background: ${ wizardData.brandColor };" title="Click to pick a custom color"></button>
					<input type="color" class="cha-wizard-color-native" id="cha-color-native" value="${ wizardData.brandColor }" />
					<div class="cha-wizard-color-input-wrap">
						<input
							type="text"
							id="cha-color-hex"
							class="cha-wizard-input"
							value="${ wizardData.brandColor }"
							maxlength="7"
							placeholder="#6366f1"
						/>
					</div>
				</div>
				<div class="cha-wizard-color-presets">
					${ presetsHtml }
				</div>
				<div class="cha-wizard-help">${ i18n.color_help }</div>
				<div id="cha-branding-status"></div>
			</div>
			<div class="cha-wizard-actions">
				<button type="button" class="cha-wizard-btn cha-wizard-btn-ghost" id="cha-wizard-back">
					${ icons.arrowLeft }
					${ i18n.btn_back }
				</button>
				<div class="cha-wizard-actions-right">
					<button type="button" class="cha-wizard-btn cha-wizard-btn-ghost" id="cha-wizard-skip">
						${ i18n.btn_skip }
					</button>
					<button type="button" class="cha-wizard-btn cha-wizard-btn-primary" id="cha-wizard-next">
						${ i18n.btn_next }
						${ icons.arrowRight }
					</button>
				</div>
			</div>
		`;
	}

	/**
	 * Render Step 4: Import Demo Data.
	 *
	 * @return {string} Step HTML.
	 */
	function renderImportStep() {
		return `
			<div class="cha-wizard-header">
				<div class="cha-wizard-icon">
					${ icons.download }
				</div>
				<h2 class="cha-wizard-title">${ i18n.import_title }</h2>
				<p class="cha-wizard-subtitle">${ i18n.import_subtitle }</p>
			</div>
			<div class="cha-wizard-import-card">
				<div class="cha-wizard-import-icon">
					${ icons.download }
				</div>
				<h4>Sample Releases & Products</h4>
				<p>Import example releases with version history so you can see how everything works right away.</p>
				<button type="button" class="cha-wizard-btn cha-wizard-btn-success" id="cha-wizard-import">
					${ icons.download }
					${ i18n.btn_import }
				</button>
				<div id="cha-import-status"></div>
			</div>
			<div class="cha-wizard-actions">
				<button type="button" class="cha-wizard-btn cha-wizard-btn-ghost" id="cha-wizard-back">
					${ icons.arrowLeft }
					${ i18n.btn_back }
				</button>
				<div class="cha-wizard-actions-right">
					<button type="button" class="cha-wizard-btn cha-wizard-btn-ghost" id="cha-wizard-skip">
						${ i18n.btn_skip_import }
					</button>
				</div>
			</div>
		`;
	}

	/**
	 * Render Step 5: Completion.
	 *
	 * @return {string} Step HTML.
	 */
	function renderDoneStep() {
		return `
			<div class="cha-wizard-header">
				<div class="cha-wizard-done-icon">
					${ icons.check }
				</div>
				<h2 class="cha-wizard-title">${ i18n.done_title }</h2>
				<p class="cha-wizard-subtitle">${ i18n.done_subtitle }</p>
			</div>
			<div class="cha-wizard-next-steps">
				<a href="${ config.releasesUrl }" class="cha-wizard-next-step">
					<div class="cha-wizard-next-step-icon" style="background: rgba(99, 102, 241, 0.15); color: #a5b4fc;">
						${ icons.plus }
					</div>
					<div class="cha-wizard-next-step-text">
						<h4>${ i18n.next_create_release }</h4>
						<p>Add your first version release with all the details</p>
					</div>
					<div class="cha-wizard-next-step-arrow">${ icons.arrowRight }</div>
				</a>
				<a href="${ config.settingsUrl }" class="cha-wizard-next-step">
					<div class="cha-wizard-next-step-icon" style="background: rgba(168, 85, 247, 0.15); color: #c4b5fd;">
						${ icons.cog }
					</div>
					<div class="cha-wizard-next-step-text">
						<h4>${ i18n.next_settings }</h4>
						<p>Fine-tune release categories, badges, and more</p>
					</div>
					<div class="cha-wizard-next-step-arrow">${ icons.arrowRight }</div>
				</a>
				<a href="https://helpdesk.spider-themes.net/docs/changeloger/" target="_blank" class="cha-wizard-next-step">
					<div class="cha-wizard-next-step-icon" style="background: rgba(34, 197, 94, 0.15); color: #86efac;">
						${ icons.book }
					</div>
					<div class="cha-wizard-next-step-text">
						<h4>${ i18n.next_docs }</h4>
						<p>Learn about all the features and options available</p>
					</div>
					<div class="cha-wizard-next-step-arrow">${ icons.arrowRight }</div>
				</a>
			</div>
			<div class="cha-wizard-actions">
				<div></div>
				<div class="cha-wizard-actions-right">
					<a href="${ config.dashboardUrl }" class="cha-wizard-btn cha-wizard-btn-primary" id="cha-wizard-finish">
						${ i18n.btn_finish }
						${ icons.arrowRight }
					</a>
				</div>
			</div>
		`;
	}

	/**
	 * Render the current step into the wizard container.
	 */
	function renderStep() {
		const container = document.getElementById( 'cha-setup-wizard' );
		if ( ! container ) {
			return;
		}

		let stepHtml = '';
		switch ( currentStep ) {
			case 1:
				stepHtml = renderWelcomeStep();
				break;
			case 2:
				stepHtml = renderProductStep();
				break;
			case 3:
				stepHtml = renderBrandingStep();
				break;
			case 4:
				stepHtml = renderImportStep();
				break;
			case 5:
				stepHtml = renderDoneStep();
				break;
		}

		const skipAllHtml = currentStep < 5
			? `<div class="cha-wizard-skip-all"><a href="${ config.dashboardUrl }" id="cha-wizard-skip-all">Skip setup wizard</a></div>`
			: '';

		container.innerHTML = `
			<div class="cha-wizard-container">
				${ renderProgressBar() }
				<div class="cha-wizard-card" key="step-${ currentStep }">
					${ stepHtml }
				</div>
				${ skipAllHtml }
			</div>
		`;

		bindStepEvents();
	}

	/**
	 * Bind event listeners for the current step's interactive elements.
	 */
	function bindStepEvents() {
		// Navigation buttons shared across steps.
		const startBtn = document.getElementById( 'cha-wizard-start' );
		const nextBtn = document.getElementById( 'cha-wizard-next' );
		const backBtn = document.getElementById( 'cha-wizard-back' );
		const skipBtn = document.getElementById( 'cha-wizard-skip' );
		const skipAllBtn = document.getElementById( 'cha-wizard-skip-all' );
		const finishBtn = document.getElementById( 'cha-wizard-finish' );

		if ( startBtn ) {
			startBtn.addEventListener( 'click', function () {
				goToStep( 2 );
			} );
		}

		if ( nextBtn ) {
			nextBtn.addEventListener( 'click', handleNext );
		}

		if ( backBtn ) {
			backBtn.addEventListener( 'click', function () {
				goToStep( currentStep - 1 );
			} );
		}

		if ( skipBtn ) {
			skipBtn.addEventListener( 'click', function () {
				goToStep( currentStep + 1 );
			} );
		}

		if ( skipAllBtn ) {
			skipAllBtn.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				completeWizard().then( function () {
					window.location.href = config.dashboardUrl;
				} );
			} );
		}

		if ( finishBtn ) {
			finishBtn.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				completeWizard().then( function () {
					window.location.href = config.dashboardUrl;
				} );
			} );
		}

		// Step-specific bindings.
		if ( currentStep === 2 ) {
			bindProductStep();
		} else if ( currentStep === 3 ) {
			bindBrandingStep();
		} else if ( currentStep === 4 ) {
			bindImportStep();
		}
	}

	/**
	 * Handle the "Next" button click based on the current step.
	 */
	function handleNext() {
		if ( currentStep === 2 ) {
			handleProductSubmit();
		} else if ( currentStep === 3 ) {
			handleBrandingSave();
		} else {
			goToStep( currentStep + 1 );
		}
	}

	/**
	 * Navigate to a specific step.
	 *
	 * @param {number} step The step number to navigate to.
	 */
	function goToStep( step ) {
		if ( step < 1 || step > TOTAL_STEPS ) {
			return;
		}
		currentStep = step;
		renderStep();
	}

	/**
	 * Bind events for the Product step (Step 2).
	 */
	function bindProductStep() {
		const input = document.getElementById( 'cha-product-name' );
		if ( input ) {
			input.focus();
			input.addEventListener( 'input', function () {
				wizardData.productName = input.value;
			} );
			input.addEventListener( 'keydown', function ( e ) {
				if ( e.key === 'Enter' ) {
					e.preventDefault();
					handleProductSubmit();
				}
			} );
		}
	}

	/**
	 * Handle product creation when the user clicks "Continue" on Step 2.
	 */
	function handleProductSubmit() {
		const name = wizardData.productName.trim();
		if ( ! name ) {
			// Skip if empty – user can create products later.
			goToStep( 3 );
			return;
		}

		const statusEl = document.getElementById( 'cha-product-status' );
		const nextBtn = document.getElementById( 'cha-wizard-next' );

		showStatus( statusEl, 'loading', i18n.creating_product );
		if ( nextBtn ) {
			nextBtn.disabled = true;
		}

		apiFetch( 'products', {
			method: 'POST',
			body: JSON.stringify( { name: name } ),
		} )
			.then( function () {
				showStatus( statusEl, 'success', i18n.product_created );
				setTimeout( function () {
					goToStep( 3 );
				}, 600 );
			} )
			.catch( function ( err ) {
				const msg = ( err && err.message ) ? err.message : i18n.product_error;
				showStatus( statusEl, 'error', msg );
				if ( nextBtn ) {
					nextBtn.disabled = false;
				}
			} );
	}

	/**
	 * Bind events for the Branding step (Step 3).
	 */
	function bindBrandingStep() {
		const swatchBtn = document.getElementById( 'cha-color-swatch' );
		const nativeInput = document.getElementById( 'cha-color-native' );
		const hexInput = document.getElementById( 'cha-color-hex' );
		const presetBtns = document.querySelectorAll( '.cha-wizard-color-preset' );

		/**
		 * Update the selected color across all UI elements.
		 *
		 * @param {string} color Hex color value.
		 */
		function updateColor( color ) {
			wizardData.brandColor = color;
			if ( swatchBtn ) {
				swatchBtn.style.background = color;
			}
			if ( hexInput && hexInput.value !== color ) {
				hexInput.value = color;
			}
			if ( nativeInput && nativeInput.value !== color ) {
				nativeInput.value = color;
			}

			// Update preset active states.
			presetBtns.forEach( function ( btn ) {
				btn.classList.toggle( 'active', btn.dataset.color === color );
			} );
		}

		if ( swatchBtn && nativeInput ) {
			swatchBtn.addEventListener( 'click', function () {
				nativeInput.click();
			} );
			nativeInput.addEventListener( 'input', function () {
				updateColor( nativeInput.value );
			} );
		}

		if ( hexInput ) {
			hexInput.addEventListener( 'input', function () {
				let val = hexInput.value;
				if ( /^#[0-9a-fA-F]{6}$/.test( val ) ) {
					updateColor( val );
				}
			} );
		}

		presetBtns.forEach( function ( btn ) {
			btn.addEventListener( 'click', function () {
				updateColor( btn.dataset.color );
			} );
		} );
	}

	/**
	 * Handle brand color save when user clicks "Continue" on Step 3.
	 */
	function handleBrandingSave() {
		const statusEl = document.getElementById( 'cha-branding-status' );
		const nextBtn = document.getElementById( 'cha-wizard-next' );

		showStatus( statusEl, 'loading', i18n.saving_settings );
		if ( nextBtn ) {
			nextBtn.disabled = true;
		}

		apiFetch( 'setup/save-settings', {
			method: 'POST',
			body: JSON.stringify( { brand_color: wizardData.brandColor } ),
		} )
			.then( function () {
				showStatus( statusEl, 'success', i18n.settings_saved );
				setTimeout( function () {
					goToStep( 4 );
				}, 400 );
			} )
			.catch( function () {
				// Non-critical – continue anyway.
				goToStep( 4 );
			} );
	}

	/**
	 * Bind events for the Import step (Step 4).
	 */
	function bindImportStep() {
		const importBtn = document.getElementById( 'cha-wizard-import' );
		if ( importBtn ) {
			importBtn.addEventListener( 'click', handleImport );
		}
	}

	/**
	 * Handle demo data import.
	 */
	function handleImport() {
		const statusEl = document.getElementById( 'cha-import-status' );
		const importBtn = document.getElementById( 'cha-wizard-import' );

		showStatus( statusEl, 'loading', i18n.importing );
		if ( importBtn ) {
			importBtn.disabled = true;
		}

		apiFetch( 'import-sample', {
			method: 'POST',
		} )
			.then( function ( res ) {
				const msg = ( res && res.message ) ? res.message : i18n.import_success;
				showStatus( statusEl, 'success', msg );
				wizardData.importedDemo = true;
				setTimeout( function () {
					goToStep( 5 );
				}, 800 );
			} )
			.catch( function () {
				showStatus( statusEl, 'error', i18n.import_error );
				if ( importBtn ) {
					importBtn.disabled = false;
				}
			} );
	}

	/**
	 * Mark the wizard as completed via REST API.
	 *
	 * @return {Promise} API response promise.
	 */
	function completeWizard() {
		return apiFetch( 'setup/complete', { method: 'POST' } ).catch( function () {
			// Ignore errors – wizard still works even if DB update fails.
		} );
	}

	/**
	 * Show a status message in the given container element.
	 *
	 * @param {Element} el      Container element.
	 * @param {string}  type    Status type: 'loading', 'success', or 'error'.
	 * @param {string}  message Message text.
	 */
	function showStatus( el, type, message ) {
		if ( ! el ) {
			return;
		}

		let icon = '';
		if ( type === 'loading' ) {
			icon = icons.spinner;
		} else if ( type === 'success' ) {
			icon = icons.check;
		} else if ( type === 'error' ) {
			icon = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>';
		}

		el.innerHTML = `<div class="cha-wizard-status cha-wizard-status-${ type }">${ icon }<span>${ escapeHtml( message ) }</span></div>`;
	}

	/**
	 * Make a fetch request to the Changeloger REST API.
	 *
	 * @param {string} endpoint API endpoint path (relative to base).
	 * @param {Object} options  Fetch options.
	 * @return {Promise} Response data promise.
	 */
	function apiFetch( endpoint, options ) {
		options = options || {};
		const url = config.restBase + endpoint;

		return fetch( url, {
			method: options.method || 'GET',
			headers: {
				'Content-Type': 'application/json',
				'X-WP-Nonce': config.nonce,
			},
			body: options.body || null,
		} ).then( function ( res ) {
			return res.json().then( function ( data ) {
				if ( ! res.ok ) {
					throw data;
				}
				return data;
			} );
		} );
	}

	/**
	 * Escape HTML entities in a string.
	 *
	 * @param {string} str Input string.
	 * @return {string} Escaped string.
	 */
	function escapeHtml( str ) {
		const div = document.createElement( 'div' );
		div.appendChild( document.createTextNode( str || '' ) );
		return div.innerHTML;
	}

	/**
	 * Escape a string for use in HTML attributes.
	 *
	 * @param {string} str Input string.
	 * @return {string} Attribute-safe string.
	 */
	function escapeAttr( str ) {
		return ( str || '' ).replace( /&/g, '&amp;' ).replace( /"/g, '&quot;' ).replace( /'/g, '&#39;' ).replace( /</g, '&lt;' ).replace( />/g, '&gt;' );
	}

	/**
	 * Initialize the wizard when the DOM is ready.
	 */
	function init() {
		if ( ! document.getElementById( 'cha-setup-wizard' ) ) {
			return;
		}
		renderStep();
	}

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