/**
 * Kramar — Tab navigation for the modules page.
 *
 * @package Kramar
 * @since   1.0.0
 */

( function () {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {
		var tabs    = document.querySelectorAll( '.kramar-tab' );
		var panels  = document.querySelectorAll( '.kramar-tab-panel' );
		var input   = document.getElementById( 'kramar-active-tab' );

		if ( ! tabs.length ) {
			return;
		}

		tabs.forEach( function ( tab ) {
			tab.addEventListener( 'click', function ( e ) {
				e.preventDefault();

				var target = tab.dataset.tab;

				// Update tab states.
				tabs.forEach( function ( t ) {
					t.classList.toggle( 'kramar-tab--active', t.dataset.tab === target );
				} );

				// Update panel visibility.
				panels.forEach( function ( panel ) {
					var panelTab = panel.dataset.tab || panel.id.replace( 'kramar-tab-', '' );
					panel.classList.toggle( 'kramar-tab-panel--active', panelTab === target );
				} );

				// Track active tab so the form submit can restore it.
				if ( input ) {
					input.value = target;
				}
			} );
		} );
	} );
}() );
