/**
 * Northmill Tabs Helper.
 *
 * @package northmill-online-shared
 */

jQuery( document ).on(
	'ready',
	function () {
		nm_tabs.document_ready();
	}
);

/**
 * Tabs helper.
 */
class NM_Tabs {
	constructor() {
		// Bindings.
		this.document_ready = this.document_ready.bind( this );
		this.click_tab      = this.click_tab.bind( this );
	}

	document_ready() {
		jQuery( '#nm-tabs a' ).on( 'click', this.click_tab );

		this.check_current_tab();
	}

	// On page load, read the query parameter and show the corresponding tab.
	check_current_tab() {
		const urlParams = new URLSearchParams( window.location.search );
		const tabParam  = urlParams.get( 'tab' );
		if (tabParam) {
			const $tabLink = jQuery( '#nm-tabs a[href="#' + tabParam + '"]' );
			if ($tabLink.length) {
				$tabLink.click();
			}
		}
	}

	/**
	 * Tab navigation
	 */
	click_tab( event ) {
		event.preventDefault();

		const $target = jQuery( event.currentTarget );

		jQuery( '#nm-tabs a' ).removeClass( 'active' );
		$target.addClass( 'active' );
		jQuery( '.nm-tab' ).hide();

		const $tab_id = $target.attr( 'href' );
		const $tab    = jQuery( $tab_id );

		$tab.show();

		jQuery( '#nm-toc > div' ).removeClass( 'active' );
		jQuery( '#nm-toc div[data-id="' + $tab_id + '"]' ).addClass( 'active' );

		// Add query parameter to URL.
		const url = new URL( window.location );
		url.searchParams.set( 'tab', $tab_id.substring( 1 ) ); // Remove the '#' from the tab_id.
		window.history.pushState( {}, '', url );
	}
}
let nm_tabs = new NM_Tabs();
