/**
 * File Path: assets/js/adminjs/mbs-editor-shell.js
 *
 * Book Editor Shell — Hash Router
 *
 * Manages tab/section activation for the WooCommerce-style Book Editor shell.
 * Attaches to window.MBS.EditorShell (sibling to window.MBS.BookEditor owned by
 * the foundational script — never writes to window.MBS.BookEditor).
 *
 * Handle: mbs-editor-shell
 * Dependencies: jquery, mbs-book-editor
 * Footer: true
 *
 * Hash format: #domain-key/section-key
 * All navigation goes through location.hash — click/keyboard handlers set
 * location.hash only; the hashchange listener calls activate(). Calling
 * activate() directly from click handlers would cause double invocation.
 *
 * @package My_Book_Showroom
 * @since   1.2.0
 */

window.MBS            = window.MBS            || {};
window.MBS.EditorShell = window.MBS.EditorShell || {};

window.MBS.EditorShell = ( function ( $ ) {
	'use strict';

	/* ── Private helpers ────────────────────────────────────────────────────── */

	/**
	 * Parse a location.hash string into [ domainKey, sectionKey ].
	 *
	 * Reads registered DOM data to determine defaults rather than hard-coding
	 * domain or section names. Covers four cases:
	 *   1. Hash absent or empty          → first tab href supplies both keys.
	 *   2. domain only, no section       → first section of matched domain.
	 *   3. Unrecognized domain           → fall back to first tab.
	 *   4. Both domain and section given → return as-is.
	 *
	 * @param {string} hash  Value of location.hash (may include leading #).
	 * @returns {string[]}   [ domainKey, sectionKey ]
	 */
	function parseHash( hash ) {
		var parts = hash.replace( /^#/, '' ).split( '/' );
		var dk    = parts[ 0 ] || '';
		var sk    = parts[ 1 ] || '';

		// Check whether dk maps to a registered domain sub-nav.
		var domainExists = dk && $( 'ul.mbs-editor-subnav[data-mbs-domain="' + dk + '"]' ).length > 0;

		if ( ! dk || ! domainExists ) {
			// Fall back to the first registered tab's href.
			var firstHref = $( '.mbs-editor-tab-bar [role="tab"]' ).first().attr( 'href' ) || '';
			var fallback  = firstHref.replace( /^#/, '' ).split( '/' );
			return [ fallback[ 0 ] || '', fallback[ 1 ] || '' ];
		}

		if ( ! sk ) {
			// Domain recognized but no section — use first section of that domain.
			sk = $( 'ul.mbs-editor-subnav[data-mbs-domain="' + dk + '"]' )
				.find( 'li[data-mbs-section]' )
				.first()
				.data( 'mbs-section' ) || '';
		}

		return [ dk, sk ];
	}

	/* ── Public: activate ───────────────────────────────────────────────────── */

	/**
	 * Activate the tab and panel for the given domain and section keys.
	 *
	 * Updates: nav-tab-active class, aria-selected on tab links, current class on
	 * sub-nav <li> elements, display on panels and sub-nav <ul> elements, aria-hidden
	 * on panels, tabindex on panels.
	 *
	 * All tab and sub-nav operations are scoped to .mbs-editor-tab-bar and
	 * .mbs-editor-subnav to avoid affecting other WP admin nav elements.
	 *
	 * @param {string} domainKey  Domain key.
	 * @param {string} sectionKey Section key.
	 * @returns {void}
	 */
	function activate( domainKey, sectionKey ) {
		if ( ! domainKey || ! sectionKey ) {
			return;
		}

		// ── Tab bar ──
		$( '.mbs-editor-tab-bar .nav-tab' ).removeClass( 'nav-tab-active' );
		$( '.mbs-editor-tab-bar [data-mbs-domain="' + domainKey + '"]' ).addClass( 'nav-tab-active' );

		// ── aria-selected on tab links ──
		$( '.mbs-editor-tab-bar [role="tab"]' ).attr( 'aria-selected', 'false' );
		$( '.mbs-editor-tab-bar [data-mbs-domain="' + domainKey + '"]' ).attr( 'aria-selected', 'true' );

		// ── Section sub-nav: hide all, reveal active domain's <ul> ──
		$( 'ul.mbs-editor-subnav' ).css( 'display', 'none' );
		$( 'ul.mbs-editor-subnav[data-mbs-domain="' + domainKey + '"]' ).css( 'display', 'block' );

		// ── current class on <li> — scoped to active domain's sub-nav ──
		$( 'ul.mbs-editor-subnav li' ).removeClass( 'current' );
		$( 'ul.mbs-editor-subnav[data-mbs-domain="' + domainKey + '"]' )
			.find( 'li[data-mbs-section="' + sectionKey + '"]' )
			.addClass( 'current' );

		// ── Panels: hide all, reveal target ──
		$( '.mbs-editor-panel' ).css( 'display', 'none' ).attr( 'aria-hidden', 'true' ).attr( 'tabindex', '-1' );
		$( '.mbs-editor-panel[data-mbs-panel="' + domainKey + '/' + sectionKey + '"]' )
			.css( 'display', 'block' )
			.attr( 'aria-hidden', 'false' )
			.attr( 'tabindex', '0' );

		// ── Persist active tab so save redirect can restore it ──
		var inp = document.getElementById( 'mbs-editor-active-tab' );
		if ( inp ) { inp.value = domainKey + '/' + sectionKey; }
	}

	/* ── Public: init ───────────────────────────────────────────────────────── */

	/**
	 * Initialize the router on DOM ready.
	 *
	 * Reads the current hash (or falls back to the first domain/section), activates
	 * the correct tab and panel, then wires hashchange, click, and keyboard handlers.
	 *
	 * @returns {void}
	 */
	/**
	 * Initialize the router.
	 *
	 * Called from the footer — the DOM is guaranteed ready at that point.
	 * The $( document ).ready() wrapper is intentionally omitted: jQuery 3
	 * resolves its ready deferred asynchronously (via a microtask/promise tick)
	 * even when the document is already ready, which would delay the initial
	 * activate() call past other code that resets panel styles.
	 *
	 * @returns {void}
	 */
	function init() {
		// ── Initial activation ──
		var keys = parseHash( location.hash );
		activate( keys[ 0 ], keys[ 1 ] );

		// ── hashchange: back/forward + link navigation ──
		$( window ).on( 'hashchange.mbs-editor', function () {
			var k = parseHash( location.hash );
			activate( k[ 0 ], k[ 1 ] );
		} );

		// ── Tab click: update hash only; hashchange calls activate() ──
		$( '.mbs-editor-tab-bar' ).on( 'click.mbs-editor', '[role="tab"]', function ( e ) {
			e.preventDefault();
			var href = $( this ).attr( 'href' ) || '';
			location.hash = href.replace( /^#/, '' );
		} );

		// ── Sub-nav click: update hash only; hashchange calls activate() ──
		$( '.mbs-editor-subnav' ).on( 'click.mbs-editor', 'a', function ( e ) {
			e.preventDefault();
			var href = $( this ).attr( 'href' ) || '';
			location.hash = href.replace( /^#/, '' );
		} );

		// ── Keyboard navigation on tab bar ──
		$( '.mbs-editor-tab-bar' ).on( 'keydown.mbs-editor', '[role="tab"]', function ( e ) {
			var tabs    = $( '.mbs-editor-tab-bar [role="tab"]' );
			var current = tabs.index( this );
			var target  = -1;
			var key     = e.key;

			if ( key === 'ArrowRight' || key === 'ArrowDown' ) {
				e.preventDefault();
				target = ( current + 1 ) % tabs.length;
			} else if ( key === 'ArrowLeft' || key === 'ArrowUp' ) {
				e.preventDefault();
				target = ( current - 1 + tabs.length ) % tabs.length;
			} else if ( key === 'Home' ) {
				e.preventDefault();
				target = 0;
			} else if ( key === 'End' ) {
				e.preventDefault();
				target = tabs.length - 1;
			}

			if ( target >= 0 ) {
				tabs.eq( target ).focus();
				var href = tabs.eq( target ).attr( 'href' ) || '';
				location.hash = href.replace( /^#/, '' );
			}
		} );
	}

	return {
		init:     init,
		activate: activate,
	};

}( jQuery ) );

// Kick off the router on every page load.
window.MBS.EditorShell.init();
