/**
 * admin-email-tab.js -- My Book Showroom
 *
 * Email / Newsletter Tab (Tab 14) UI logic:
 *  - Show/hide Account URL field based on selected platform.
 *  - Show/hide Sendy no-tag notice.
 *  - Test Connection AJAX call -- populates list dropdowns on success.
 *
 * Sprint F-026: Email Channel Integration.
 */
( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;

	var cfg = window.MBS_EmailTab || {};
	var urlPlatforms = cfg.urlPlatforms || [];

	function platformRequiresUrl( platform ) {
		return urlPlatforms.indexOf( platform ) !== -1;
	}

	function updatePlatformUI( platform ) {
		var urlRow     = $( '.mbs-esp-url-row' );
		var sendyNote  = $( '.mbs-esp-sendy-no-tag-notice' );
		if ( platformRequiresUrl( platform ) ) {
			urlRow.show();
		} else {
			urlRow.hide();
		}
		if ( platform === 'sendy' ) {
			sendyNote.show();
		} else {
			sendyNote.hide();
		}
	}

	// Initialize UI state based on pre-selected platform.
	var initialPlatform = cfg.platform || '';
	updatePlatformUI( initialPlatform );

	// Re-evaluate when platform dropdown changes.
	$( document ).on( 'change', '.mbs-esp-platform-select', function () {
		updatePlatformUI( $( this ).val() );
	} );

	// ── Test Connection ──────────────────────────────────────────────────────
	$( document ).on( 'click', '#mbs-esp-test-btn', function () {
		var btn      = $( this );
		var status   = $( '#mbs-esp-test-status' );
		var platform  = $( '#mbs_email_platform' ).val() || '';
		var apiKey    = $( '#mbs_email_api_key' ).val() || '';
		var acctUrl   = $( '#mbs_email_account_url' ).val() || '';

		btn.prop( 'disabled', true ).text( __( 'Testing...', 'my-book-showroom' ) );
		status.text( '' ).removeClass( 'mbs-esp-status-ok mbs-esp-status-err' );

		$.ajax( {
			url:    cfg.ajaxUrl,
			type:   'POST',
			data:   {
				action:      'mbs_esp_test_connection',
				nonce:       cfg.testNonce,
				platform:    platform,
				api_key:     apiKey,
				account_url: acctUrl,
			},
			success: function ( resp ) {
				if ( resp.success ) {
					status.text( resp.data.message || __( 'Connected successfully.', 'my-book-showroom' ) ).addClass( 'mbs-esp-status-ok' );
					populateLists( resp.data.lists || [] );
				} else {
					var msg = ( resp.data && resp.data.message ) ? resp.data.message : __( 'Connection failed.', 'my-book-showroom' );
					status.text( msg ).addClass( 'mbs-esp-status-err' );
				}
			},
			error: function () {
				status.text( __( 'Request error.', 'my-book-showroom' ) ).addClass( 'mbs-esp-status-err' );
			},
			complete: function () {
				btn.prop( 'disabled', false ).text( __( 'Test Connection', 'my-book-showroom' ) );
			},
		} );
	} );

	/**
	 * Populate all three list dropdowns from a lists array.
	 * @param {Array} lists  [{id, name}, ...]
	 */
	function populateLists( lists ) {
		var selects = $( '.mbs-esp-list-select' );
		selects.each( function () {
			var sel      = $( this );
			var currentVal = sel.val();
			sel.empty();
			if ( lists.length === 0 ) {
				sel.append( $( '<option>' ).val( '' ).text( __( '-- connect first --', 'my-book-showroom' ) ) );
				return;
			}
			for ( var i = 0; i < lists.length; i++ ) {
				var opt = $( '<option>' ).val( lists[ i ].id ).text( lists[ i ].name );
				if ( lists[ i ].id === currentVal ) {
					opt.prop( 'selected', true );
				}
				sel.append( opt );
			}
		} );
	}

	// ---- CAPTCHA provider show/hide ----------------------------------------
	function updateCaptchaUI( provider ) {
		$( '.mbs-captcha-keys-section' ).each( function () {
			if ( $( this ).data( 'provider' ) === provider ) {
				$( this ).show();
			} else {
				$( this ).hide();
			}
		} );
	}

	// Initialize based on pre-selected provider.
	updateCaptchaUI( $( '#mbs_email_captcha_provider' ).val() || '' );

	// Re-evaluate on change.
	$( document ).on( 'change', '.mbs-captcha-provider-select', function () {
		updateCaptchaUI( $( this ).val() );
	} );

} ( jQuery ) );
