/**
 * SiteStaffr — Shared tabs behavior.
 *
 * Auto-initializes every `.sitestaffr-agent-tabs` tablist on the page:
 * click activation, arrow-key navigation, aria-selected/tabindex bookkeeping,
 * and per-tablist localStorage persistence via data-tab-storage="<key>"
 * (omit the attribute to skip persistence).
 *
 * Markup contract: a role="tablist" container holding role="tab" buttons
 * whose aria-controls point at panel ids; the active tab carries .is-active,
 * inactive panels carry [hidden].
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      1.33.9
 */
( function () {
	'use strict';

	function activate( tabs, tab ) {
		tabs.forEach( function ( t ) {
			var panel = document.getElementById( t.getAttribute( 'aria-controls' ) );
			var active = t === tab;
			t.classList.toggle( 'is-active', active );
			t.setAttribute( 'aria-selected', active ? 'true' : 'false' );
			t.setAttribute( 'tabindex', active ? '0' : '-1' );
			if ( panel ) {
				panel.hidden = ! active;
			}
		} );
	}

	function init( tablist ) {
		// Idempotent — safe to call again on markup rendered after load.
		if ( tablist.dataset.sitestaffrTabsInit ) {
			return;
		}
		tablist.dataset.sitestaffrTabsInit = '1';
		var tabs = Array.prototype.slice.call( tablist.querySelectorAll( '.sitestaffr-agent-tab' ) );
		if ( ! tabs.length ) {
			return;
		}
		var storageKey = tablist.getAttribute( 'data-tab-storage' );

		if ( storageKey ) {
			var saved = null;
			try {
				saved = localStorage.getItem( storageKey );
			} catch ( e ) {}
			if ( saved ) {
				var savedTab = tabs.filter( function ( t ) {
					return t.getAttribute( 'aria-controls' ) === saved;
				} )[ 0 ];
				if ( savedTab ) {
					activate( tabs, savedTab );
				}
			}
		}

		tablist.addEventListener( 'click', function ( e ) {
			var tab = e.target.closest( '.sitestaffr-agent-tab' );
			if ( ! tab ) {
				return;
			}
			activate( tabs, tab );
			if ( storageKey ) {
				try {
					localStorage.setItem( storageKey, tab.getAttribute( 'aria-controls' ) );
				} catch ( e2 ) {}
			}
		} );

		tablist.addEventListener( 'keydown', function ( e ) {
			var from = e.target.closest( '.sitestaffr-agent-tab' );
			var index = tabs.indexOf( from );
			if ( index === -1 ) {
				return;
			}
			var next = -1;
			if ( 'ArrowRight' === e.key || 'ArrowDown' === e.key ) {
				next = ( index + 1 ) % tabs.length;
			} else if ( 'ArrowLeft' === e.key || 'ArrowUp' === e.key ) {
				next = ( index - 1 + tabs.length ) % tabs.length;
			}
			if ( next >= 0 ) {
				e.preventDefault();
				tabs[ next ].click();
				tabs[ next ].focus();
			}
		} );
	}

	document.querySelectorAll( '.sitestaffr-agent-tabs' ).forEach( init );

	// Programmatic hook for tablists rendered after load (e.g. via AJAX).
	window.SiteStaffrTabs = { init: init };
} )();
