/**
 * File Path: assets/js/adminjs/mbs-onix-metabox.js
 *
 * ONIX Distribution Data Metabox — admin JS
 *
 * Handles:
 *   - Show/hide the country grid based on territory type radio selection
 *   - Select-all / Clear-all per regional group
 *   - Updates the hint paragraph text between "included" and "excluded"
 *
 * @package MyBookShowroom
 * @since   1.2.0
 */

/* global jQuery */
( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;

	// -------------------------------------------------------------------------
	// Territory type radios — show/hide grid
	// -------------------------------------------------------------------------

	/**
	 * Update territory grid visibility and hint text based on current radio value.
	 *
	 * @param {string} type - 'world' | 'include' | 'exclude'
	 * @return {void}
	 */
	function updateTerritoryGrid( type ) {
		var $grid = $( '#mbs-territory-grid' );
		var $hint = $grid.find( '.mbs-territory-hint' );

		if ( 'world' === type ) {
			$grid.addClass( 'mbs-territory-hidden' ).attr( 'aria-hidden', 'true' );
		} else {
			$grid.removeClass( 'mbs-territory-hidden' ).attr( 'aria-hidden', 'false' );
			if ( 'exclude' === type ) {
				$hint.text( __( 'Check countries where this book is NOT for sale.', 'my-book-showroom' ) );
			} else {
				$hint.text( __( 'Check countries where this book is for sale.', 'my-book-showroom' ) );
			}
		}
	}

	// -------------------------------------------------------------------------
	// Select-all / Clear-all toggle buttons
	// -------------------------------------------------------------------------

	/**
	 * Toggle all checkboxes in a regional group.
	 *
	 * @param {jQuery} $btn   - The clicked toggle button.
	 * @return {void}
	 */
	function handleGroupToggle( $btn ) {
		var action     = $btn.data( 'action' );
		var $group     = $btn.closest( '.mbs-territory-group' );
		var $checkboxes = $group.find( 'input[type="checkbox"]' );

		if ( 'select' === action ) {
			$checkboxes.prop( 'checked', true );
		} else {
			$checkboxes.prop( 'checked', false );
		}
	}

	// -------------------------------------------------------------------------
	// Document-ready initialization
	// -------------------------------------------------------------------------

	$( function () {

		// Initialize grid state on page load.
		var currentType = $( 'input[name="mbs_territory_type"]:checked' ).val() || 'world';
		updateTerritoryGrid( currentType );

		// Listen for radio changes.
		$( document ).on( 'change', 'input[name="mbs_territory_type"]', function () {
			updateTerritoryGrid( $( this ).val() );
		} );

		// Select-all / Clear-all buttons.
		$( document ).on( 'click', '.mbs-territory-toggle', function () {
			handleGroupToggle( $( this ) );
		} );

	} );

}( jQuery ) );
