/*
 * FindAstra — admin settings page glue.
 *
 * Two responsibilities:
 *   1. Switch between tab panels when a `.fnda-tab` button is clicked.
 *   2. Sync the credential fields to the currently-selected engine radio.
 *
 * Vanilla DOM only; no dependencies. Loaded as a classic script on the
 * FindAstra settings screen only — keep it small.
 */

( function () {
	'use strict';

	function initTabs() {
		var tabs   = document.querySelectorAll( '[data-fnda-tab]' );
		var panels = document.querySelectorAll( '[data-fnda-tab-panel]' );
		if ( ! tabs.length || ! panels.length ) { return; }

		function activate( name ) {
			tabs.forEach( function ( btn ) {
				var on = btn.getAttribute( 'data-fnda-tab' ) === name;
				btn.classList.toggle( 'is-active', on );
				btn.setAttribute( 'aria-selected', on ? 'true' : 'false' );
			} );
			panels.forEach( function ( panel ) {
				var on = panel.getAttribute( 'data-fnda-tab-panel' ) === name;
				if ( on ) {
					panel.removeAttribute( 'hidden' );
				} else {
					panel.setAttribute( 'hidden', '' );
				}
			} );
			try {
				history.replaceState( null, '', '#' + name );
			} catch ( e ) { /* swallow — happens on file:// */ }
		}

		tabs.forEach( function ( btn ) {
			btn.addEventListener( 'click', function ( ev ) {
				ev.preventDefault();
				activate( btn.getAttribute( 'data-fnda-tab' ) );
			} );
		} );

		// Open the tab named in the URL hash if present, else default to the
		// first one. Lets buyers bookmark e.g. #analytics.
		var hash = ( window.location.hash || '' ).replace( /^#/, '' );
		var has  = hash && document.querySelector( '[data-fnda-tab-panel="' + hash + '"]' );
		activate( has ? hash : ( tabs[0].getAttribute( 'data-fnda-tab' ) || 'general' ) );
	}

	function initEnginePicker() {
		var radios = document.querySelectorAll( '[data-findastra-tier-radio]' );
		var fields = document.querySelector( '[data-findastra-credential-fields]' );
		if ( ! radios.length ) { return; }

		function sync() {
			var checked = document.querySelector( '[data-findastra-tier-radio]:checked' );
			var active  = checked ? checked.value : 'local';

			if ( fields ) {
				fields.setAttribute( 'data-active-provider', active );
				fields.querySelectorAll( '[data-tier-field]' ).forEach( function ( row ) {
					row.hidden = row.getAttribute( 'data-tier-field' ) !== active;
				} );
			}

			document.querySelectorAll( '[data-fnda-engine]' ).forEach( function ( tile ) {
				tile.classList.toggle( 'is-active', tile.getAttribute( 'data-fnda-engine' ) === active );
			} );
		}

		radios.forEach( function ( r ) {
			r.addEventListener( 'change', sync );
		} );
		sync();
	}

	function boot() {
		initTabs();
		initEnginePicker();
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', boot );
	} else {
		boot();
	}
} )();
