/**
 * @file assets/js/adminjs/admin-general-currency.js
 * Currency dropdown / custom-text toggle and Use WP Timezone button for the General tab.
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';

	/**
	 * Bind a dropdown → custom-input visibility toggle.
	 *
	 * @param {string} selectSelector jQuery selector for the dropdown.
	 * @param {string} customSelector jQuery selector for the paired custom input.
	 */
	function bindToggle( selectSelector, customSelector ) {
		var $select = $( selectSelector );
		var $custom = $( customSelector );

		if ( ! $select.length || ! $custom.length ) {
			return;
		}

		function apply() {
			$custom.css( 'display', ( 'other' === $select.val() ) ? 'block' : 'none' );
		}

		$select.on( 'change', function () {
			apply();
			if ( 'other' === $select.val() ) {
				$custom.trigger( 'focus' );
			}
		} );

		apply();
	}

	/**
	 * Bind the "Use WP Timezone" button.
	 *
	 * F-009: When clicked, sets the timezone dropdown to the IANA zone resolved
	 * from the WordPress site setting. The resolved zone is localised from PHP
	 * via MBS_Tab_General::enqueue() → wp_localize_script into MBS_GeneralCurrency.
	 *
	 * A small hint label beside the button shows the WP timezone so the admin
	 * knows what value will be applied before clicking.
	 */
	function bindWpTimezoneButton() {
		var data  = window.MBS_GeneralCurrency || {};
		var wpTz  = data.wpTimezone || '';
		var $btn  = $( '#mbs-use-wp-timezone' );
		var $hint = $( '#mbs-wp-timezone-hint' );
		var $sel  = $( '#mbs_general_timezone' );

		if ( ! $btn.length || ! wpTz ) {
			return;
		}
		var origText = $btn.text().trim();

		// Show the WP timezone in the hint label for discoverability.
		$hint.text( '(' + wpTz + ')' );

		$btn.on( 'click', function () {
			$sel.val( wpTz ).trigger( 'change' );
			$btn.text( $btn.data( 'done-label' ) || 'Applied' );
			setTimeout( function () {
				$btn.text( origText );
			}, 1500 );
		} );
	}

	// Phase 4b (2026-04-19): locale field deprecated and removed from the
	// Currency renderer. The corresponding bindToggle() call has been removed
	// because the DOM targets (#mbs_general_locale_select, #mbs_general_locale_custom)
	// no longer exist. Saved mbs_setting_general_locale values remain in
	// wp_options pending a future cleanup migration.
	bindToggle( '#mbs_general_currency_select', '#mbs_general_currency_custom' );

	// F-009: Timezone auto-populate from WordPress setting.
	bindWpTimezoneButton();

} )( jQuery );
