( function ( window, document ) {
	'use strict';

	var data = window.AROnboardingData || {};
	data.user = data.user || {};

	var context = data.content && data.content.context ? data.content.context : 'wordpress';
	var strings = data.strings || {};
	var tourInstance = null;

	var state = {
		panel: null,
		toggle: null,
		filterItems: [],
		groups: [],
		empty: null,
		search: null,
		aiAssistantVisible: false,
		aiAssistantContainer: null,
	};

	function ready( fn ) {
		if ( document.readyState !== 'loading' ) {
			fn();
			return;
		}
		document.addEventListener( 'DOMContentLoaded', fn, { once: true } );
	}

	function registerFilterItem( element, text, group ) {
		if ( ! element ) {
			return;
		}

		element.dataset.onboardingFilterItem = 'true';

		state.filterItems.push( {
			element: element,
			text: ( text || '' ).toLowerCase(),
			group: group || null,
		} );

		if ( group && state.groups.indexOf( group ) === -1 ) {
			state.groups.push( group );
		}
	}

	function filterContent( query ) {
		var term = ( query || '' ).trim().toLowerCase();
		var visibleCount = 0;

		state.filterItems.forEach( function ( item ) {
			var match = ! term || -1 !== item.text.indexOf( term );
			item.element.style.display = match ? '' : 'none';

			if ( match ) {
				visibleCount++;
			}
		} );

		state.groups.forEach( function ( group ) {
			var hasVisible = false;
			var items = group.querySelectorAll( '[data-onboarding-filter-item]' );

			for ( var i = 0; i < items.length; i++ ) {
				if ( '' !== items[ i ].style.display ) {
					continue;
				}
				hasVisible = true;
				break;
			}

			group.style.display = hasVisible ? '' : 'none';
		} );

		if ( state.empty ) {
			state.empty.style.display = visibleCount ? 'none' : '';
		}
	}

	function isElementHidden( element ) {
		if ( ! element ) {
			return true;
		}

		var style = window.getComputedStyle( element );

		if ( 'none' === style.display ) {
			return true;
		}

		if ( '0px' === style.maxHeight ) {
			return true;
		}

		return element.offsetParent === null && 'fixed' !== style.position;
	}

	function runStepActions( actions ) {
		if ( ! Array.isArray( actions ) || ! actions.length ) {
			return;
		}

		actions.forEach( function ( action ) {
			if ( ! action || ! action.type ) {
				return;
			}

			switch ( action.type ) {
				case 'expand': {
					var trigger = document.querySelector( action.trigger );
					var panel = action.panel ? document.querySelector( action.panel ) : null;

					if ( trigger ) {
						var shouldClick = true;

						if ( panel && ! isElementHidden( panel ) ) {
							shouldClick = false;
						}

						if ( shouldClick ) {
							trigger.click();
						}
					}
					break;
				}
				case 'click': {
					var target = document.querySelector( action.selector );
					if ( ! target ) {
						break;
					}

					var performClick = true;

					if ( action.onlyIfHidden ) {
						var conditionElement = document.querySelector( action.onlyIfHidden );
						if ( conditionElement && ! isElementHidden( conditionElement ) ) {
							performClick = false;
						}
					}

					if ( performClick ) {
						target.click();
					}
					break;
				}
				case 'focus': {
					var focusTarget = document.querySelector( action.selector );
					if ( focusTarget ) {
						focusTarget.focus( { preventScroll: true } );
					}
					break;
				}
				default:
					break;
			}
		} );
	}

	function openGuidesSection() {
		if ( ! state.panel ) {
			return;
		}

		var accordion = state.panel.querySelector( '.ar-onboarding__accordion' );
		if ( ! accordion ) {
			return;
		}

		var firstItem = accordion.querySelector( '.ar-onboarding__accordion-item' );
		if ( firstItem ) {
			var trigger = firstItem.querySelector( '.ar-onboarding__accordion-trigger' );
			if ( trigger && 'false' === trigger.getAttribute( 'aria-expanded' ) ) {
				trigger.click();
			}
		}

		accordion.scrollIntoView( { behavior: 'smooth', block: 'start' } );
	}

	function createAccordionGuides( container ) {
		var guides = data.content && Array.isArray( data.content.guides ) ? data.content.guides : null;

		if ( ! guides || ! guides.length ) {
			return;
		}

		guides.forEach( function ( guide ) {
			var section = document.createElement( 'section' );
			section.className = 'ar-onboarding__section';

			if ( guide.title ) {
				var heading = document.createElement( 'h3' );
				heading.className = 'ar-onboarding__section-title';
				heading.textContent = guide.title;
				section.appendChild( heading );
			}

			var accordion = document.createElement( 'div' );
			accordion.className = 'ar-onboarding__accordion';

			( guide.panels || [] ).forEach( function ( panel, index ) {
				var item = document.createElement( 'div' );
				item.className = 'ar-onboarding__accordion-item';

				var trigger = document.createElement( 'button' );
				trigger.type = 'button';
				trigger.className = 'ar-onboarding__accordion-trigger';
				trigger.setAttribute( 'aria-expanded', 'false' );
				trigger.setAttribute( 'aria-controls', 'ar-onboarding-accordion-' + context + '-' + index );
				var triggerLabel = document.createElement( 'span' );
				triggerLabel.className = 'ar-onboarding__accordion-label';
				triggerLabel.textContent = panel.title || '';

				var triggerIcon = document.createElement( 'span' );
				triggerIcon.className = 'ar-onboarding__accordion-icon';
				triggerIcon.setAttribute( 'aria-hidden', 'true' );

				trigger.appendChild( triggerLabel );
				trigger.appendChild( triggerIcon );

				var body = document.createElement( 'div' );
				body.className = 'ar-onboarding__accordion-body';
				body.id = 'ar-onboarding-accordion-' + context + '-' + index;
				body.setAttribute( 'hidden', '' );

				var list = document.createElement( 'ul' );
				list.className = 'ar-onboarding__accordion-list';

				( panel.items || [] ).forEach( function ( text ) {
					var listItem = document.createElement( 'li' );
					listItem.textContent = text;
					list.appendChild( listItem );

					var filterText = ( text || '' ) + ' ' + ( panel.title || '' ) + ' ' + ( guide.title || '' );
					registerFilterItem( listItem, filterText, item );
				} );

				body.appendChild( list );
				item.appendChild( trigger );
				item.appendChild( body );
				accordion.appendChild( item );

				trigger.addEventListener( 'click', function () {
					var expanded = 'true' === trigger.getAttribute( 'aria-expanded' );
					trigger.setAttribute( 'aria-expanded', String( ! expanded ) );
					item.classList.toggle( 'is-open', ! expanded );
					if ( expanded ) {
						body.setAttribute( 'hidden', '' );
					} else {
						body.removeAttribute( 'hidden' );
					}
				} );
			} );

			section.appendChild( accordion );
			container.appendChild( section );
		} );
	}

	function postTourState( dismissed ) {
		if ( ! data.ajax || ! data.ajax.url || ! data.ajax.action ) {
			return Promise.resolve();
		}

		var params = new window.URLSearchParams();
		params.append( 'action', data.ajax.action );
		params.append( 'dismissed', dismissed ? '1' : '0' );
		params.append( 'nonce', data.ajax.nonce || '' );

		return window.fetch( data.ajax.url, {
			method: 'POST',
			credentials: 'same-origin',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			},
			body: params.toString(),
		} ).catch( function ( error ) {
			console.warn( '[AR Onboarding] Failed to persist tour state.', error );
		} );
	}

	function buildStepButtons( index, totalSteps ) {
		var buttons = [];

		if ( totalSteps > 1 && index > 0 ) {
			buttons.push( {
				text: strings.previous || 'Back',
				secondary: true,
				action: function () {
					tourInstance.back();
				},
			} );
		}

		if ( index < totalSteps - 1 ) {
			buttons.push( {
				text: strings.next || 'Next',
				action: function () {
					tourInstance.next();
				},
			} );
		} else {
			buttons.push( {
				text: strings.finish || 'Finish',
				action: function () {
					tourInstance.complete();
				},
			} );
		}

		return buttons;
	}

	function buildTour() {
		if ( tourInstance || ! window.Shepherd ) {
			return tourInstance;
		}

		var steps = ( data.content && data.content.tourSteps ) || [];

		if ( ! steps.length ) {
			return null;
		}

		tourInstance = new window.Shepherd.Tour( {
			useModalOverlay: true,
			defaultStepOptions: {
				cancelIcon: {
					enabled: true,
				},
				scrollTo: {
					behavior: 'smooth',
					block: 'center',
				},
				classes: 'shepherd-theme-default',
			},
		} );

		steps.forEach( function ( step, index ) {
			var attachTo = null;

			if ( step.target ) {
				var element = document.querySelector( step.target );

				if ( element ) {
					attachTo = {
						element: element,
						on: step.placement || 'bottom',
					};
				} else {
					console.warn( '[AR Onboarding] Could not find target for step', step.id || index, step.target );
				}
			}

			var stepConfig = {
				id: step.id || 'ar-onboarding-step-' + index,
				title: step.title || '',
				text: step.content || '',
				attachTo: attachTo,
				buttons: buildStepButtons( index, steps.length ),
			};

			if ( Array.isArray( step.actions ) && step.actions.length ) {
				stepConfig.when = stepConfig.when || {};
				stepConfig.when.show = function () {
					runStepActions( step.actions );
				};
			}

			tourInstance.addStep( stepConfig );
		} );

		tourInstance.on( 'complete', function () {
			data.user.tourDismissed = true;
			postTourState( true );
		} );

		tourInstance.on( 'cancel', function () {
			data.user.tourDismissed = true;
			postTourState( true );
		} );

		return tourInstance;
	}

	function closeHelpPanel() {
		if ( ! state.panel ) {
			return;
		}

		state.panel.classList.remove( 'ar-onboarding__panel--visible' );

		if ( state.toggle ) {
			state.toggle.setAttribute( 'aria-expanded', 'false' );
		}

		if ( state.search && state.search.value ) {
			state.search.value = '';
			filterContent( '' );
		}

		// Hide AI assistant iframe when panel is closed
		if ( state.aiAssistantContainer ) {
			state.aiAssistantContainer.style.display = 'none';
			state.aiAssistantVisible = false;
		}
	}

	function startTour( force, stepId ) {
		if ( ! buildTour() ) {
			return;
		}

		closeHelpPanel();
		data.user.tourDismissed = false;
		postTourState( false );
		tourInstance.start();

		if ( stepId ) {
			window.setTimeout( function () {
				try {
					tourInstance.show( stepId );
				} catch ( error ) {
					console.warn( '[AR Onboarding] Unable to jump to step', stepId, error );
				}
			}, 50 );
		}
	}

	function createQuickActions( container ) {
		var actions = document.createElement( 'div' );
		actions.className = 'ar-onboarding__quick-actions';

		var quickLinks = ( data.content && data.content.quickLinks ) || [];
		var instructionLink = null;

		for ( var i = 0; i < quickLinks.length; i++ ) {
			if ( quickLinks[ i ] && quickLinks[ i ].link === 'accordion' ) {
				instructionLink = quickLinks[ i ];
				break;
			}
		}

		var tourButton = document.createElement( 'button' );
		tourButton.type = 'button';
		tourButton.className = 'button button-primary';
		tourButton.textContent = strings.startTour || 'Start guided tour';
		tourButton.addEventListener( 'click', function () {
			startTour( true );
		} );
		actions.appendChild( tourButton );

		if ( instructionLink ) {
			var instructionsButton = document.createElement( 'button' );
			instructionsButton.type = 'button';
			instructionsButton.className = 'button button-secondary';
			instructionsButton.textContent = instructionLink.label || strings.instructions || 'Instructions';
			instructionsButton.addEventListener( 'click', function () {
				openGuidesSection();
			} );
			actions.appendChild( instructionsButton );
		} else {
			var docsButton = document.createElement( 'a' );
			docsButton.className = 'button button-secondary';
			docsButton.textContent = strings.openDocs || 'View documentation';
			docsButton.href = 'https://augmentedrealityplugins.com/support/';
			docsButton.target = '_blank';
			docsButton.rel = 'noopener noreferrer';
			actions.appendChild( docsButton );
		}

		container.appendChild( actions );
	}

	function createSearch( container ) {
		var wrapper = document.createElement( 'div' );
		wrapper.className = 'ar-onboarding__search';

		var icon = document.createElement( 'span' );
		icon.className = 'dashicons dashicons-search';
		wrapper.appendChild( icon );

		var input = document.createElement( 'input' );
		input.type = 'search';
		input.placeholder = strings.searchDocs || 'Search documentation…';
		input.setAttribute( 'aria-label', strings.searchDocs || 'Search documentation…' );
		input.addEventListener( 'input', function () {
			filterContent( input.value );
		} );
		wrapper.appendChild( input );

		state.search = input;

		container.appendChild( wrapper );

		// Add "Ask the AR AI Assistant" button
		var aiButtonWrapper = document.createElement( 'div' );
		aiButtonWrapper.className = 'ar-onboarding__ai-button-wrapper';

		var aiButton = document.createElement( 'button' );
		aiButton.type = 'button';
		aiButton.className = 'button button-secondary ar-onboarding__ai-button';
		aiButton.textContent = 'Ask the AR AI Assistant';
		aiButton.addEventListener( 'click', function () {
			toggleAiAssistant();
		} );
		aiButtonWrapper.appendChild( aiButton );

		container.appendChild( aiButtonWrapper );

		// Create iframe container (initially hidden)
		var aiContainer = document.createElement( 'div' );
		aiContainer.className = 'ar-onboarding__ai-container';
		aiContainer.style.display = 'none';

		var iframe = document.createElement( 'iframe' );
		iframe.setAttribute( 'scrolling', 'yes' );
		iframe.setAttribute( 'frameborder', '0' );
		iframe.setAttribute( 'allowtransparency', 'true' );
		iframe.style.width = '100%';
		iframe.style.height = '600px';
		iframe.style.display = 'block';
		iframe.style.border = 'none';
		iframe.src = 'https://augmentedrealityplugins.com/?wapd_aikit_embed=1';

		aiContainer.appendChild( iframe );
		container.appendChild( aiContainer );

		state.aiAssistantContainer = aiContainer;
	}

	function toggleAiAssistant() {
		if ( ! state.aiAssistantContainer ) {
			return;
		}

		state.aiAssistantVisible = ! state.aiAssistantVisible;

		if ( state.aiAssistantVisible ) {
			state.aiAssistantContainer.style.display = 'block';
		} else {
			state.aiAssistantContainer.style.display = 'none';
		}
	}

	function createQuickStartSection( container ) {
		var steps = ( data.content && data.content.tourSteps ) || [];

		if ( ! steps.length ) {
			return;
		}

		var section = document.createElement( 'section' );
		section.className = 'ar-onboarding__section';

		var title = document.createElement( 'h3' );
		title.className = 'ar-onboarding__section-title';
		title.textContent = strings.quickStart || 'Quick start';
		section.appendChild( title );

		var list = document.createElement( 'ul' );
		list.className = 'ar-onboarding__list';
		section.appendChild( list );

		steps.forEach( function ( step, index ) {
			var item = document.createElement( 'li' );
			item.className = 'ar-onboarding__list-item';

			var itemTitle = document.createElement( 'span' );
			itemTitle.className = 'ar-onboarding__list-item-title';
			itemTitle.textContent = step.title || '';
			item.appendChild( itemTitle );

			if ( step.content ) {
				var description = document.createElement( 'p' );
				description.className = 'ar-onboarding__list-item-description';
				description.textContent = step.content;
				item.appendChild( description );
			}

			var actions = document.createElement( 'div' );
			actions.className = 'ar-onboarding__list-item-actions';

			var jumpButton = document.createElement( 'button' );
			jumpButton.type = 'button';
			jumpButton.className = 'button button-link ar-onboarding__list-item-action';
			jumpButton.textContent = strings.viewInTour || 'Show in tour';
			jumpButton.addEventListener( 'click', function () {
				var stepId = step.id || 'ar-onboarding-step-' + index;
				startTour( true, stepId );
			} );

			actions.appendChild( jumpButton );
			item.appendChild( actions );

			list.appendChild( item );
			registerFilterItem( item, ( step.title || '' ) + ' ' + ( step.content || '' ), section );
		} );

		container.appendChild( section );
	}

	function createFaqSections( container ) {
		var sections = ( data.content && data.content.faqSections ) || [];

		if ( ! sections.length ) {
			return;
		}

		sections.forEach( function ( block ) {
			var section = document.createElement( 'section' );
			section.className = 'ar-onboarding__section';

			var title = document.createElement( 'h3' );
			title.className = 'ar-onboarding__section-title';
			title.textContent = block.title || '';
			section.appendChild( title );

			var list = document.createElement( 'ul' );
			list.className = 'ar-onboarding__list';
			section.appendChild( list );

			( block.items || [] ).forEach( function ( item ) {
				var listItem = document.createElement( 'li' );
				listItem.className = 'ar-onboarding__list-item';

				if ( item.url ) {
					var link = document.createElement( 'a' );
					link.href = item.url;
					link.textContent = item.label || item.url;
					link.target = '_blank';
					link.rel = 'noopener noreferrer';
					listItem.appendChild( link );
				} else {
					var text = item.text || item.label || '';
					var paragraph = document.createElement( 'p' );
					paragraph.className = 'ar-onboarding__list-item-description';
					paragraph.textContent = text;
					listItem.appendChild( paragraph );
				}

				list.appendChild( listItem );

				var filterText = ( item.label || '' ) + ' ' + ( item.text || '' ) + ' ' + ( block.title || '' );
				registerFilterItem( listItem, filterText, section );
			} );

			container.appendChild( section );
		} );
	}

	function createQuickLinksSection( container ) {
		var links = ( data.content && data.content.quickLinks ) || [];

		links = links.filter( function ( link ) {
			return ! link || link.link !== 'accordion';
		} );

		if ( ! links.length ) {
			return;
		}

		var section = document.createElement( 'section' );
		section.className = 'ar-onboarding__section';

		var title = document.createElement( 'h3' );
		title.className = 'ar-onboarding__section-title';
		title.textContent = strings.resources || 'Resources';
		section.appendChild( title );

		var list = document.createElement( 'ul' );
		list.className = 'ar-onboarding__list';
		section.appendChild( list );

		links.forEach( function ( link ) {
			var item = document.createElement( 'li' );
			item.className = 'ar-onboarding__list-item';

			var anchor = document.createElement( 'a' );
			anchor.href = link.url || '#';
			anchor.textContent = link.label || link.url || '';
			anchor.target = '_blank';
			anchor.rel = 'noopener noreferrer';

			item.appendChild( anchor );
			list.appendChild( item );

			registerFilterItem( item, link.label || '', section );
		} );

		container.appendChild( section );
	}

	function createHelpPanel() {
		if ( state.panel ) {
			return state.panel;
		}

		var panel = document.createElement( 'aside' );
		panel.className = 'ar-onboarding__panel';
		panel.dataset.context = context;
		panel.setAttribute( 'aria-hidden', 'true' );

		var header = document.createElement( 'div' );
		header.className = 'ar-onboarding__panel-header';

		var title = document.createElement( 'h2' );
		title.className = 'ar-onboarding__panel-title';
		title.textContent = strings.panelTitle || 'AR Assistant';
		header.appendChild( title );

		var closeButton = document.createElement( 'button' );
		closeButton.type = 'button';
		closeButton.className = 'ar-onboarding__close button button-link';
		closeButton.setAttribute( 'aria-label', strings.close || 'Close panel' );
		closeButton.innerHTML = '<span class="dashicons dashicons-no-alt"></span>';
		closeButton.addEventListener( 'click', function () {
			closeHelpPanel();
			if ( state.toggle ) {
				state.toggle.focus();
			}
		} );
		header.appendChild( closeButton );

		panel.appendChild( header );

		var content = document.createElement( 'div' );
		content.className = 'ar-onboarding__panel-content';

		createQuickActions( content );
		createSearch( content );
		createQuickStartSection( content );
		createAccordionGuides( content );
		createFaqSections( content );
		createQuickLinksSection( content );

		state.empty = document.createElement( 'div' );
		state.empty.className = 'ar-onboarding__empty';
		state.empty.textContent = strings.noResults || 'No matches found.';
		state.empty.style.display = 'none';
		content.appendChild( state.empty );

		panel.appendChild( content );

		var footer = document.createElement( 'div' );
		footer.className = 'ar-onboarding__panel-footer';

		var supportUrl = 'https://augmentedrealityplugins.com/contact/';
		var supportLabel = strings.contactSupport || 'Contact support';

		if ( data.content && data.content.quickLinks ) {
			data.content.quickLinks.some( function ( link ) {
				var label = ( link.label || '' ).toLowerCase();
				if ( -1 !== label.indexOf( 'contact' ) || ( link.url && -1 !== link.url.indexOf( 'contact' ) ) ) {
					supportUrl   = link.url || supportUrl;
					supportLabel = link.label || supportLabel;
					return true;
				}
				return false;
			} );
		}

		var supportLink = document.createElement( 'a' );
		supportLink.href = supportUrl;
		supportLink.target = '_blank';
		supportLink.rel = 'noopener noreferrer';
		supportLink.textContent = supportLabel;

		footer.appendChild( supportLink );
		panel.appendChild( footer );

		panel.addEventListener( 'keydown', function ( event ) {
			if ( 'Escape' === event.key ) {
				closeHelpPanel();
				if ( state.toggle ) {
					state.toggle.focus();
				}
			}
		} );

		document.body.appendChild( panel );
		state.panel = panel;

		return panel;
	}

	function openHelpPanel() {
		if ( ! data.user || ! data.user.canManage ) {
			return;
		}

		var panel = createHelpPanel();
		panel.classList.add( 'ar-onboarding__panel--visible' );
		panel.setAttribute( 'aria-hidden', 'false' );

		if ( state.toggle ) {
			state.toggle.setAttribute( 'aria-expanded', 'true' );
		}

		window.setTimeout( function () {
			if ( state.search ) {
				state.search.focus();
			}
		}, 120 );

		filterContent( state.search ? state.search.value : '' );
	}

	function toggleHelpPanel() {
		if ( state.panel && state.panel.classList.contains( 'ar-onboarding__panel--visible' ) ) {
			closeHelpPanel();
			return;
		}
		openHelpPanel();
	}

	function createToggle() {
		if ( ! data.user || ! data.user.canManage ) {
			return;
		}

		if ( state.toggle ) {
			return;
		}

		var toggle = document.createElement( 'button' );
		toggle.type = 'button';
		toggle.className = 'ar-onboarding__toggle';
		toggle.dataset.context = context;
		toggle.setAttribute( 'aria-label', strings.openHelp || 'Open help panel' );
		toggle.setAttribute( 'aria-expanded', 'false' );
		toggle.title = strings.openHelp || strings.startTour || 'Open help panel';
		toggle.innerHTML = '<span class="dashicons dashicons-editor-help"></span>';
		toggle.addEventListener( 'click', function () {
			toggleHelpPanel();
		} );

		document.body.appendChild( toggle );
		state.toggle = toggle;
	}

	function init() {
		if ( ! window.AROnboardingData ) {
			console.warn( '[AR Onboarding] No data supplied. Skipping bootstrap.' );
			return;
		}

		window.AROnboardingRegistry = window.AROnboardingRegistry || {};

		if ( window.AROnboardingRegistry[ context ] ) {
			return;
		}

		var api = {
			version: '0.2.0',
			context: context,
			data: window.AROnboardingData,
			openHelpPanel: openHelpPanel,
			closeHelpPanel: closeHelpPanel,
			startTour: function () {
				startTour( true );
			},
			resetTourState: function () {
				data.user.tourDismissed = false;
				postTourState( false );
			},
			isTourAvailable: function () {
				return !! ( data.content && data.content.tourSteps && data.content.tourSteps.length );
			},
		};

		window.AROnboardingRegistry[ context ] = api;
		window.AROnboarding = api;

		console.info( '[AR Onboarding] Assistant initialised for screen:', data.screen );

		createToggle();

		if ( data.user && false === data.user.tourDismissed ) {
			window.setTimeout( function () {
				startTour( false );
			}, 600 );
		}
	}

	ready( init );
}( window, document ) );

