/**
 * TrustLens persistent admin header.
 *
 * Wires popovers, ⌘K command palette, mobile drawer, keyboard navigation.
 * No jQuery dependency — pure vanilla. Reads data from window.TrustLensHeader
 * (localized server-side in TrustLens_Admin_Header::enqueue_assets).
 *
 * @since 1.2.2
 */
(function(){
	'use strict';

	// Guard: if the header markup isn't on the page (not a plugin admin page)
	// or data failed to localize, bail silently.
	if ( typeof window.TrustLensHeader !== 'object' || ! document.getElementById( 'wstl-hdr' ) ) {
		return;
	}

	var data = window.TrustLensHeader;
	var $  = function( id ) { return document.getElementById( id ); };

	/* -----------------------------------------------------------
	   Popovers — status, notifications, avatar
	   ----------------------------------------------------------- */
	var popoverTriggers = [
		{ btn: 'wstl-hdr-statusbtn',  pop: 'wstl-hdr-statuspop' },
		{ btn: 'wstl-hdr-bellbtn',    pop: 'wstl-hdr-bellpop' },
		{ btn: 'wstl-hdr-avatarbtn',  pop: 'wstl-hdr-avatarpop' }
	];

	// Remembered trigger so Escape-close and outside-click-close return focus
	// to the same button the user opened the popover from.
	var lastPopTrigger = null;

	function closeAllPops( restoreFocus ) {
		var wasOpen = false;
		popoverTriggers.forEach( function( t ) {
			var p = $( t.pop );
			var b = $( t.btn );
			if ( p && p.classList.contains( 'open' ) ) { wasOpen = true; }
			if ( p ) p.classList.remove( 'open' );
			if ( b ) b.setAttribute( 'aria-expanded', 'false' );
		} );
		if ( wasOpen && restoreFocus && lastPopTrigger ) {
			try { lastPopTrigger.focus(); } catch ( _e ) {}
		}
		lastPopTrigger = null;
	}

	popoverTriggers.forEach( function( t ) {
		var btn = $( t.btn );
		var pop = $( t.pop );
		if ( ! btn || ! pop ) return;
		btn.addEventListener( 'click', function( e ) {
			e.stopPropagation();
			var wasOpen = pop.classList.contains( 'open' );
			closeAllPops();
			if ( ! wasOpen ) {
				pop.classList.add( 'open' );
				btn.setAttribute( 'aria-expanded', 'true' );
				lastPopTrigger = btn;
			}
		} );
	} );

	// Close popovers when clicking anywhere outside them
	document.addEventListener( 'click', function( e ) {
		var t = e.target;
		if ( ! t.closest ) return;
		if ( t.closest( '.wstl-hdr-pop' ) ) return;
		var insideTrigger = popoverTriggers.some( function( x ) {
			return t.closest && t.closest( '#' + x.btn );
		} );
		// Outside-click: don't steal focus back to the trigger — the user
		// meant to move elsewhere. Focus restore is for Escape only.
		if ( ! insideTrigger ) closeAllPops( false );
	} );

	/* -----------------------------------------------------------
	   Mobile drawer — burger toggles the primary nav
	   ----------------------------------------------------------- */
	var burger  = $( 'wstl-hdr-burger' );
	var navWrap = $( 'wstl-hdr-navwrap' );

	function setDrawer( open ) {
		if ( ! navWrap || ! burger ) return;
		navWrap.classList.toggle( 'open', !! open );
		burger.setAttribute( 'aria-expanded', open ? 'true' : 'false' );
	}

	function isDrawerOpen() {
		return !! ( navWrap && navWrap.classList.contains( 'open' ) );
	}

	if ( burger && navWrap ) {
		burger.setAttribute( 'aria-expanded', 'false' );
		burger.addEventListener( 'click', function( e ) {
			e.stopPropagation();
			setDrawer( ! isDrawerOpen() );
		} );
		// Tapping a nav link inside the drawer — close it so the user isn't
		// left with an open drawer on the next page load.
		navWrap.addEventListener( 'click', function( e ) {
			if ( e.target && e.target.closest && e.target.closest( '.wstl-hdr-tab' ) ) {
				setDrawer( false );
			}
		} );
		// Outside-click dismiss (only matters when drawer is actually open).
		document.addEventListener( 'click', function( e ) {
			if ( ! isDrawerOpen() ) return;
			var t = e.target;
			if ( ! t.closest ) return;
			if ( t.closest( '#wstl-hdr-navwrap' ) || t.closest( '#wstl-hdr-burger' ) ) return;
			setDrawer( false );
		} );
	}

	/* -----------------------------------------------------------
	   Command palette (⌘K / Ctrl+K)
	   ----------------------------------------------------------- */
	var cmdp             = $( 'wstl-cmdp' );
	var cmdpOverlay      = $( 'wstl-cmdp-overlay' );
	var cmdpInput        = $( 'wstl-cmdp-input' );
	var cmdpResults      = $( 'wstl-cmdp-results' );
	var cmdpTrigger      = $( 'wstl-hdr-search' );
	var cmdpTriggerMobile = $( 'wstl-hdr-search-mobile' );
	var items = Array.isArray( data.commandItems ) ? data.commandItems : [];
	var activeIdx = 0;
	var filteredCache = [];
	// Remember which element opened the palette so Escape restores focus there.
	var lastCmdpOpener = null;
	// Async customer lookup (results for the last query) + debounce timer.
	var customerResults = [];
	var customerQuery   = '';
	var searchTimer     = null;

	// Customer matches for the current query, shaped as palette items.
	function customerItems( filter ) {
		var q = ( filter || '' ).trim();
		if ( q.length < 2 || q !== customerQuery || ! customerResults.length ) {
			return [];
		}
		var grp = ( data.i18n && data.i18n.customers ) || 'Customers';
		return customerResults.map( function( c ) {
			return {
				group: grp,
				icon:  'i-users',
				label: c.email,
				sub:   ( c.segment || '' ) + ( ( c.score === 0 || c.score ) ? ' · ' + c.score : '' ),
				href:  c.href
			};
		} );
	}

	// Debounced AJAX customer search; re-renders when results arrive.
	function fetchCustomers( raw ) {
		var q = ( raw || '' ).trim();
		if ( q.length < 2 || ! data.ajaxUrl || ! data.nonce ) {
			customerResults = [];
			customerQuery = '';
			return;
		}
		var body = new FormData();
		body.append( 'action', 'wstl_customer_search' );
		body.append( 'nonce', data.nonce );
		body.append( 'q', q );
		fetch( data.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body } )
			.then( function( r ) { return r.json(); } )
			.then( function( res ) {
				if ( ! res || ! res.success || ! res.data ) { return; }
				customerResults = Array.isArray( res.data.results ) ? res.data.results : [];
				customerQuery = q;
				if ( cmdp && cmdp.classList.contains( 'open' ) ) {
					renderCmdp( cmdpInput.value );
				}
			} )
			.catch( function() {} );
	}

	function escapeHtml( s ) {
		return String( s ).replace( /[&<>"'`]/g, function( ch ) {
			return ( { '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','`':'&#96;' } )[ ch ];
		} );
	}

	function renderCmdp( filter ) {
		var q = ( filter || '' ).trim().toLowerCase();
		var filtered = q
			? items.filter( function( i ) {
				// Label + group are shown in the UI; keywords are hidden
				// synonyms (e.g., "slack" → Set up Slack / email alerts).
				var hay = ( i.label + ' ' + ( i.group || '' ) + ' ' + ( i.keywords || '' ) ).toLowerCase();
				return hay.indexOf( q ) !== -1;
			} )
			: items;
		var combined = customerItems( filter ).concat( filtered );
		filteredCache = combined;

		if ( ! combined.length ) {
			cmdpResults.innerHTML = '<div class="wstl-cmdp-empty">' + escapeHtml( data.i18n && data.i18n.empty || 'No results' ) + '</div>';
			return;
		}

		var groups = {};
		combined.forEach( function( i ) {
			var g = i.group || '';
			groups[ g ] = groups[ g ] || [];
			groups[ g ].push( i );
		} );

		var idx = 0;
		var html = '';
		Object.keys( groups ).forEach( function( g ) {
			html += '<div class="wstl-cmdp-grp">';
			if ( g ) html += '<div class="wstl-cmdp-grp-t">' + escapeHtml( g ) + '</div>';
			groups[ g ].forEach( function( i ) {
				var cls = 'wstl-cmdp-item' + ( idx === activeIdx ? ' active' : '' );
				var pro = i.pro
					? '<span class="wstl-hdr-tag-pro wstl-cmdp-tag-pro">PRO</span>'
					: '';
				html += '<a class="' + cls + '" data-idx="' + idx + '" href="' + escapeHtml( i.href || '#' ) + '">'
					+ '<svg class="wstl-hdr-icon"><use href="#tl-' + escapeHtml( i.icon || 'i-home' ) + '"/></svg>'
					+ '<span class="wstl-cmdp-item-label">' + escapeHtml( i.label || '' ) + '</span>'
					+ ( i.sub ? '<span class="wstl-cmdp-item-sub">' + escapeHtml( i.sub ) + '</span>' : '' )
					+ pro
					+ '</a>';
				idx++;
			} );
			html += '</div>';
		} );
		cmdpResults.innerHTML = html;

		// Hover updates active index so keyboard + mouse stay consistent.
		cmdpResults.querySelectorAll( '.wstl-cmdp-item' ).forEach( function( el ) {
			el.addEventListener( 'mouseenter', function() {
				activeIdx = parseInt( el.getAttribute( 'data-idx' ), 10 );
				cmdpResults.querySelectorAll( '.wstl-cmdp-item' ).forEach( function( x ) {
					x.classList.toggle( 'active', x === el );
				} );
			} );
		} );
	}

	function openCmdp( opener ) {
		if ( ! cmdp ) return;
		lastCmdpOpener = opener || document.activeElement || null;
		cmdpOverlay.classList.add( 'open' );
		cmdp.classList.add( 'open' );
		cmdpInput.value = '';
		activeIdx = 0;
		renderCmdp( '' );
		setTimeout( function() { cmdpInput.focus(); }, 40 );
	}
	function closeCmdp( restoreFocus ) {
		if ( ! cmdp ) return;
		var wasOpen = cmdp.classList.contains( 'open' );
		cmdp.classList.remove( 'open' );
		cmdpOverlay.classList.remove( 'open' );
		if ( wasOpen && restoreFocus && lastCmdpOpener ) {
			try { lastCmdpOpener.focus(); } catch ( _e ) {}
		}
		lastCmdpOpener = null;
	}

	if ( cmdpTrigger )       cmdpTrigger.addEventListener( 'click', function() { openCmdp( cmdpTrigger ); } );
	if ( cmdpTriggerMobile ) cmdpTriggerMobile.addEventListener( 'click', function() { openCmdp( cmdpTriggerMobile ); } );
	if ( cmdpOverlay )       cmdpOverlay.addEventListener( 'click', function() { closeCmdp( false ); } );
	if ( cmdpInput ) {
		cmdpInput.addEventListener( 'input', function() {
			activeIdx = 0;
			renderCmdp( cmdpInput.value );
			clearTimeout( searchTimer );
			searchTimer = setTimeout( function() { fetchCustomers( cmdpInput.value ); }, 200 );
		} );
		cmdpInput.addEventListener( 'keydown', function( e ) {
			var links = cmdpResults.querySelectorAll( '.wstl-cmdp-item' );
			if ( 'ArrowDown' === e.key ) {
				e.preventDefault();
				activeIdx = Math.min( links.length - 1, activeIdx + 1 );
				renderCmdp( cmdpInput.value );
			} else if ( 'ArrowUp' === e.key ) {
				e.preventDefault();
				activeIdx = Math.max( 0, activeIdx - 1 );
				renderCmdp( cmdpInput.value );
			} else if ( 'Enter' === e.key ) {
				e.preventDefault();
				var chosen = filteredCache[ activeIdx ];
				if ( chosen && chosen.href ) {
					window.location.href = chosen.href;
				}
			}
		} );
	}

	// Global Cmd/Ctrl+K + Esc
	document.addEventListener( 'keydown', function( e ) {
		var key = ( e.key || '' ).toLowerCase();
		if ( ( e.metaKey || e.ctrlKey ) && 'k' === key ) {
			// Don't hijack when user is typing in a form field other than our palette input.
			var tag = document.activeElement && document.activeElement.tagName;
			var inOurInput = document.activeElement === cmdpInput;
			var inFormField = tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
			if ( inFormField && ! inOurInput ) return;
			e.preventDefault();
			if ( cmdp && cmdp.classList.contains( 'open' ) ) {
				closeCmdp( true );
			} else {
				openCmdp( document.activeElement );
			}
		} else if ( 'Escape' === e.key ) {
			// Escape closes any open chrome in this order: palette → popovers → drawer.
			// Return focus to whatever opened it so keyboard users land back on the trigger.
			if ( cmdp && cmdp.classList.contains( 'open' ) ) { closeCmdp( true ); return; }
			closeAllPops( true );
			if ( isDrawerOpen() ) { setDrawer( false ); if ( burger ) { try { burger.focus(); } catch ( _e ) {} } }
		}
	} );
})();
