/**
 * Settings tab navigation (show/hide).
 *
 * The whole settings form is a single <form> with one Save button; every tab
 * panel stays in the DOM so all fields submit together. This script only toggles
 * which panel is visible. Adding the .acrwd-tabs-js class is what enables the
 * "hide inactive panels" CSS — without JS the panels stack and everything still
 * works. Vanilla JS, no build.
 */
( function () {
	'use strict';

	var container = document.querySelector( '.acrwd-settings-tabs' );
	if ( ! container ) {
		return;
	}

	var tabs = container.querySelectorAll( '.acrwd-tab-nav .nav-tab' );
	var panels = container.querySelectorAll( '.acrwd-tab-panel' );
	if ( ! tabs.length || ! panels.length ) {
		return;
	}

	container.classList.add( 'acrwd-tabs-js' );

	function activate( id ) {
		tabs.forEach( function ( tab ) {
			tab.classList.toggle( 'nav-tab-active', tab.getAttribute( 'data-acrwd-tab' ) === id );
		} );
		panels.forEach( function ( panel ) {
			panel.classList.toggle( 'is-active', panel.getAttribute( 'data-acrwd-panel' ) === id );
		} );
		if ( window.history && window.history.replaceState ) {
			window.history.replaceState( null, '', '#acrwd-tab-' + id );
		}
	}

	tabs.forEach( function ( tab ) {
		tab.addEventListener( 'click', function ( event ) {
			event.preventDefault();
			activate( tab.getAttribute( 'data-acrwd-tab' ) );
		} );
	} );

	// Honor a deep link (#acrwd-tab-display); otherwise start on the first tab.
	var ids = Array.prototype.map.call( tabs, function ( tab ) {
		return tab.getAttribute( 'data-acrwd-tab' );
	} );
	var requested = window.location.hash.replace( '#acrwd-tab-', '' );
	activate( ids.indexOf( requested ) !== -1 ? requested : ids[ 0 ] );
}() );
