/**
 * AIEO Command Palette — Ctrl/Cmd+K overlay.
 *
 * Vanilla JS. Listens for Ctrl+K / Cmd+K on every admin page, opens a
 * centered modal with a search input, fuzzy-filters the localized
 * command list, navigates with arrow keys + Enter.
 */

( function () {
	'use strict';

	var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
	var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
	var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
	var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

	if ( typeof window.aieoCommandPalette === 'undefined' ) { return; }

	var state = {
		open: false,
		query: '',
		filtered: [],
		highlight: 0,
		root: null,
		input: null,
		list: null,
	};

	var commands = window.aieoCommandPalette.commands || [];
	var i18n     = window.aieoCommandPalette.i18n     || {};

	// ---------------------------------------------------------------
	// Fuzzy / substring scoring. Cheap but works well for ~50 commands.
	// Order: exact label hits first, then label-prefix, then any
	// substring across label+context+keywords. Within a tier, shorter
	// labels rank higher so "Web Push" beats "Web Push (Phase 5+ todo)".
	// ---------------------------------------------------------------
	function score( cmd, q ) {
		if ( ! q ) { return 0; }
		var label = ( cmd.label   || '' ).toLowerCase();
		var ctx   = ( cmd.context || '' ).toLowerCase();
		var kw    = ( cmd.keywords|| '' ).toLowerCase();
		var hay   = label + ' ' + ctx + ' ' + kw;
		if ( hay.indexOf( q ) === -1 ) { return -1; }
		var s = 0;
		if ( label === q )                   { s += 1000; }
		if ( label.indexOf( q ) === 0 )      { s += 500;  }
		if ( label.indexOf( q ) !== -1 )     { s += 100 - label.length; }
		if ( ctx.indexOf( q ) === 0 )        { s += 50;   }
		if ( kw.indexOf( q ) !== -1 )        { s += 10;   }
		return s;
	}

	function refilter() {
		var q = state.query.trim().toLowerCase();
		if ( ! q ) {
			state.filtered = commands.slice();
		} else {
			state.filtered = commands
				.map( function ( c ) { return { c: c, s: score( c, q ) }; } )
				.filter( function ( x ) { return x.s >= 0; } )
				.sort( function ( a, b ) { return b.s - a.s; } )
				.map( function ( x ) { return x.c; } );
		}
		state.highlight = 0;
		render();
	}

	// ---------------------------------------------------------------
	// DOM
	// ---------------------------------------------------------------
	function build() {
		if ( state.root ) { return; }

		var root = document.createElement( 'div' );
		root.className = 'aieo-cmdp-root';
		root.setAttribute( 'role', 'dialog' );
		root.setAttribute( 'aria-modal', 'true' );
		root.style.display = 'none';

		var backdrop = document.createElement( 'div' );
		backdrop.className = 'aieo-cmdp-backdrop';
		backdrop.addEventListener( 'click', close );

		var modal = document.createElement( 'div' );
		modal.className = 'aieo-cmdp-modal';

		var input = document.createElement( 'input' );
		input.type = 'text';
		input.className = 'aieo-cmdp-input';
		input.placeholder = i18n.placeholder || __( 'Search…', 'ai-eshop-optimizer' );
		input.autocomplete = 'off';
		input.spellcheck = false;
		input.addEventListener( 'input', function () {
			state.query = input.value;
			refilter();
		} );

		var list = document.createElement( 'div' );
		list.className = 'aieo-cmdp-list';

		var hint = document.createElement( 'div' );
		hint.className = 'aieo-cmdp-hint';
		hint.textContent = i18n.hint || '';

		modal.appendChild( input );
		modal.appendChild( list );
		modal.appendChild( hint );
		root.appendChild( backdrop );
		root.appendChild( modal );
		document.body.appendChild( root );

		state.root  = root;
		state.input = input;
		state.list  = list;
	}

	function render() {
		if ( ! state.list ) { return; }
		state.list.innerHTML = '';

		if ( state.filtered.length === 0 ) {
			var empty = document.createElement( 'div' );
			empty.className = 'aieo-cmdp-empty';
			empty.textContent = i18n.noResults || __( 'No matches.', 'ai-eshop-optimizer' );
			state.list.appendChild( empty );
			return;
		}

		state.filtered.forEach( function ( cmd, idx ) {
			var row = document.createElement( 'a' );
			row.href = cmd.url;
			row.className = 'aieo-cmdp-row' + ( idx === state.highlight ? ' is-highlighted' : '' );
			row.dataset.idx = String( idx );

			if ( cmd.context ) {
				var ctx = document.createElement( 'span' );
				ctx.className = 'aieo-cmdp-ctx';
				ctx.textContent = cmd.context;
				row.appendChild( ctx );
			}

			var lbl = document.createElement( 'span' );
			lbl.className = 'aieo-cmdp-lbl';
			lbl.textContent = cmd.label;
			row.appendChild( lbl );

			row.addEventListener( 'mouseover', function () {
				if ( state.highlight !== idx ) {
					state.highlight = idx;
					updateHighlight();
				}
			} );
			row.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				navigate( cmd );
			} );
			state.list.appendChild( row );
		} );
	}

	function updateHighlight() {
		if ( ! state.list ) { return; }
		var rows = state.list.querySelectorAll( '.aieo-cmdp-row' );
		rows.forEach( function ( r, i ) {
			if ( i === state.highlight ) {
				r.classList.add( 'is-highlighted' );
				// keep highlight in view
				var rb = r.getBoundingClientRect();
				var lb = state.list.getBoundingClientRect();
				if ( rb.top < lb.top )       { r.scrollIntoView( { block: 'start' } ); }
				else if ( rb.bottom > lb.bottom ) { r.scrollIntoView( { block: 'end' } ); }
			} else {
				r.classList.remove( 'is-highlighted' );
			}
		} );
	}

	function open() {
		build();
		state.open  = true;
		state.query = '';
		state.input.value = '';
		state.root.style.display = 'block';
		refilter();
		// focus after the visibility tick so iOS / VoiceOver pick it up
		setTimeout( function () { state.input.focus(); }, 0 );
	}

	function close() {
		if ( ! state.open ) { return; }
		state.open = false;
		state.root.style.display = 'none';
	}

	function navigate( cmd ) {
		if ( ! cmd ) { return; }
		close();
		window.location.href = cmd.url;
	}

	// ---------------------------------------------------------------
	// Global keybindings
	// ---------------------------------------------------------------
	document.addEventListener( 'keydown', function ( e ) {
		// Ctrl+K / Cmd+K toggle. Skip if user is mid-edit in a textarea
		// to avoid stealing legitimate Ctrl+K (link insertion etc.).
		var isToggle = ( e.ctrlKey || e.metaKey ) && ( e.key === 'k' || e.key === 'K' );
		if ( isToggle ) {
			var tag = ( e.target && e.target.tagName ) ? e.target.tagName.toUpperCase() : '';
			var ce  = e.target && e.target.isContentEditable;
			// Allow inputs (so toggling from search works) but block on
			// textareas / rich-text editors to preserve native shortcuts.
			if ( tag === 'TEXTAREA' || ce ) { return; }
			e.preventDefault();
			state.open ? close() : open();
			return;
		}

		if ( ! state.open ) { return; }

		if ( e.key === 'Escape' ) {
			e.preventDefault();
			close();
			return;
		}
		if ( e.key === 'ArrowDown' ) {
			e.preventDefault();
			if ( state.highlight < state.filtered.length - 1 ) {
				state.highlight++;
				updateHighlight();
			}
			return;
		}
		if ( e.key === 'ArrowUp' ) {
			e.preventDefault();
			if ( state.highlight > 0 ) {
				state.highlight--;
				updateHighlight();
			}
			return;
		}
		if ( e.key === 'Enter' ) {
			e.preventDefault();
			navigate( state.filtered[ state.highlight ] );
			return;
		}
	} );

	// -------------------------------------------------------------------
	// Visible trigger pill — floating top-right so the palette is
	// discoverable on every AIEO admin tab (Analytics, e-shop Manager,
	// AI Chat). Without this, users who don't know Cmd/Ctrl+K never
	// realise the palette exists.
	// -------------------------------------------------------------------
	function injectTriggerButton() {
		if ( document.querySelector( '.aieo-cmd-trigger' ) ) { return; }
		var btn = document.createElement( 'button' );
		btn.type = 'button';
		btn.className = 'aieo-cmd-trigger';
		var shortcut = navigator.platform.indexOf( 'Mac' ) >= 0 ? '⌘K' : 'Ctrl+K';
		btn.innerHTML = '<span style="margin-right:6px;">⌕</span>'
			+ '<span>' + __( 'Quick navigator', 'ai-eshop-optimizer' ) + '</span>'
			+ '<span style="margin-left:8px;font-size:10px;background:rgba(255,255,255,0.18);padding:2px 6px;border-radius:4px;font-weight:500;">'
			+ shortcut + '</span>';
		/* translators: %s is the keyboard shortcut */
		btn.title = _sprintf( __( 'Open with %s', 'ai-eshop-optimizer' ), shortcut );
		btn.style.cssText = ''
			+ 'position:fixed;top:42px;right:20px;z-index:9999;'
			+ 'background:#1f2937;color:#fff;border:1px solid #1f2937;'
			+ 'border-radius:999px;padding:7px 14px;font-size:12px;'
			+ 'font-weight:600;letter-spacing:.02em;cursor:pointer;'
			+ 'box-shadow:0 4px 12px rgba(0,0,0,0.18);'
			+ 'transition:transform .15s ease, box-shadow .15s ease;'
			+ 'display:inline-flex;align-items:center;';
		btn.addEventListener( 'mouseenter', function () {
			btn.style.transform = 'translateY(-1px)';
			btn.style.boxShadow = '0 6px 16px rgba(0,0,0,0.22)';
		} );
		btn.addEventListener( 'mouseleave', function () {
			btn.style.transform = '';
			btn.style.boxShadow = '0 4px 12px rgba(0,0,0,0.18)';
		} );
		btn.addEventListener( 'click', function () {
			state.open ? close() : open();
		} );
		document.body.appendChild( btn );
	}
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', injectTriggerButton );
	} else {
		injectTriggerButton();
	}
} )();
