/**
 * @file assets/js/adminjs/mbs-imp-exp-panel-switcher.js
 * Import/Export card-click panel switcher with active state and smooth-scroll on Settings Import / Export.
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';

	/**
	 * Activate a panel by its ID string.
	 *
	 * Finding 10.1 (CR3): panelId is validated against a strict whitelist regex
	 * before being interpolated into a jQuery selector to prevent XSS via a
	 * crafted data-panel attribute value.
	 *
	 * Finding 10.2 (CR1): DRY helper extracted from the two formerly-identical
	 * card-click and panel-link handler bodies.
	 *
	 * @param {string} panelId The panel identifier (e.g. 'export-zip').
	 */
	function activatePanel( panelId ) {
		// Whitelist: only word chars and hyphens are valid panel IDs.
		if ( ! /^[\w-]+$/.test( panelId ) ) {
			return;
		}

		// Deactivate all cards.
		$( '.mbs-imp-exp-card' )
			.removeClass( 'is-active' )
			.attr( 'aria-selected', 'false' );

		// Activate the card whose data-panel matches the target panel.
		$( '.mbs-imp-exp-card[data-panel="' + panelId + '"]' )
			.addClass( 'is-active' )
			.attr( 'aria-selected', 'true' );

		// Hide all panels.
		$( '.mbs-imp-exp-panel' ).attr( 'hidden', '' );

		// Show the target panel.
		var $panel = $( '#mbs-panel-' + panelId );
		$panel.removeAttr( 'hidden' );

		// Smooth-scroll so the panel is visible below the card grid.
		var offset = $panel.offset();
		if ( offset ) {
			$( 'html, body' ).animate( {
				scrollTop: offset.top - 72
			}, 180 );
		}
	}

	// ── Card-click handler ───────────────────────────────────────────────────
	$( '.mbs-imp-exp-card:not(.is-locked)' ).on( 'click', function () {
		activatePanel( $( this ).data( 'panel' ) );
	} );

	// ── Panel-link relay ─────────────────────────────────────────────────────
	// Handles <button class="mbs-panel-link" data-panel="..."> elements that
	// appear inside panels (e.g. the "Export Catalog + Media as ZIP" link
	// inside the Export Books panel). Delegates to activatePanel().
	$( document ).on( 'click', '.mbs-panel-link[data-panel]', function () {
		activatePanel( $( this ).data( 'panel' ) );
	} );

} )( jQuery );
