/**
 * Limit Login Attempts — logs admin screen.
 *
 * @package LimitLoginAttempts
 */
( function ( $ ) {
	'use strict';

	var config = window.wppsLimitLoginLogs || {};
	var moduleId = config.moduleId || 'limit-login-attempts';

	function i18n( key, fallback ) {
		return ( config.i18n && config.i18n[ key ] ) || fallback;
	}

	function getModal() {
		return document.getElementById( 'wp-powersuite-modal' );
	}

	function collectSettings( settingsRoot ) {
		var settingsObj = {};
		var radioGroups = {};
		var inputs = settingsRoot.querySelectorAll( '.wp-powersuite-advanced-setting' );

		inputs.forEach( function ( input ) {
			var key = input.dataset.settingKey;
			if ( ! key ) {
				return;
			}

			if ( input.type === 'radio' ) {
				if ( ! radioGroups[ key ] ) {
					radioGroups[ key ] = [];
				}
				radioGroups[ key ].push( input );
				return;
			}

			if ( input.type === 'checkbox' ) {
				settingsObj[ key ] = input.checked ? '1' : '0';
				return;
			}

			if ( input.tagName === 'TEXTAREA' ) {
				settingsObj[ key ] = input.value || '';
				return;
			}

			settingsObj[ key ] = input.value || '';
		} );

		Object.keys( radioGroups ).forEach( function ( key ) {
			var checked = radioGroups[ key ].find( function ( radio ) {
				return radio.checked;
			} );
			if ( checked ) {
				settingsObj[ key ] = checked.value || '';
			}
		} );

		return settingsObj;
	}

	function appendSettingsToFormData( formData, settingsObj ) {
		Object.keys( settingsObj ).forEach( function ( key ) {
			var value = settingsObj[ key ];
			var fieldPrefix = 'settings[' + key + ']';

			if ( Array.isArray( value ) ) {
				if ( value.length === 0 ) {
					formData.append( fieldPrefix + '[]', '' );
					return;
				}
				value.forEach( function ( item ) {
					formData.append( fieldPrefix + '[]', item );
				} );
				return;
			}

			formData.append( fieldPrefix, value !== undefined && value !== null ? value : '' );
		} );
	}

	function openModuleSettingsModal() {
		var modal = getModal();
		if ( ! modal || ! window.wpPowerSuite || ! window.wpPowerSuite.ajaxUrl ) {
			window.alert( i18n( 'loadSettingsError', 'Error loading module settings.' ) );
			return;
		}

		var loading = modal.querySelector( '.wp-powersuite-modal__loading' );
		var settings = modal.querySelector( '.wp-powersuite-modal__settings' );
		var moduleNameEl = modal.querySelector( '.wp-powersuite-modal__module-name' );

		modal.dataset.currentModuleId = moduleId;
		if ( moduleNameEl ) {
			moduleNameEl.textContent = ': ' + ( config.moduleName || moduleId );
		}

		modal.style.display = 'flex';
		modal.setAttribute( 'aria-hidden', 'false' );
		document.body.classList.add( 'wp-powersuite-modal-open' );
		document.body.style.overflow = 'hidden';

		if ( loading ) {
			loading.style.display = 'block';
		}
		if ( settings ) {
			settings.style.display = 'none';
			settings.innerHTML = '';
		}

		var formData = new FormData();
		formData.append( 'action', 'wp_powersuite_load_module_settings' );
		formData.append( 'module_id', moduleId );
		formData.append( 'nonce', window.wpPowerSuite.nonce );

		fetch( window.wpPowerSuite.ajaxUrl, { method: 'POST', body: formData } )
			.then( function ( response ) {
				return response.json();
			} )
			.then( function ( data ) {
				if ( loading ) {
					loading.style.display = 'none';
				}
				if ( ! settings ) {
					return;
				}
				if ( data.success && data.data && data.data.html ) {
					settings.innerHTML = data.data.html;
					settings.style.display = 'block';
					$( document ).trigger( 'wp-powersuite-modal-loaded', [ moduleId ] );
					return;
				}
				closeModuleSettingsModal();
				window.alert( ( data.data && data.data.message ) || i18n( 'loadSettingsError', 'Error loading module settings.' ) );
			} )
			.catch( function () {
				if ( loading ) {
					loading.style.display = 'none';
				}
				closeModuleSettingsModal();
				window.alert( i18n( 'loadSettingsError', 'Error loading module settings.' ) );
			} );
	}

	function closeModuleSettingsModal() {
		var modal = getModal();
		if ( ! modal ) {
			return;
		}

		modal.style.display = 'none';
		modal.setAttribute( 'aria-hidden', 'true' );
		document.body.classList.remove( 'wp-powersuite-modal-open' );
		document.body.style.overflow = '';
		delete modal.dataset.currentModuleId;
	}

	function saveModuleSettingsModal() {
		var modal = getModal();
		if ( ! modal || ! window.wpPowerSuite || ! window.wpPowerSuite.ajaxUrl ) {
			return;
		}

		var settingsRoot = modal.querySelector( '.wp-powersuite-modal__settings' );
		var saveBtn = modal.querySelector( '.wp-powersuite-modal__save' );
		if ( ! settingsRoot || ! saveBtn ) {
			return;
		}

		var settingsObj = collectSettings( settingsRoot );
		var formData = new FormData();
		formData.append( 'action', 'wp_powersuite_save_module_settings' );
		formData.append( 'module_id', moduleId );
		formData.append( 'nonce', window.wpPowerSuite.nonce );
		appendSettingsToFormData( formData, settingsObj );

		saveBtn.disabled = true;
		saveBtn.textContent = i18n( 'saving', 'Saving...' );

		fetch( window.wpPowerSuite.ajaxUrl, { method: 'POST', body: formData } )
			.then( function ( response ) {
				return response.json();
			} )
			.then( function ( data ) {
				saveBtn.disabled = false;
				saveBtn.textContent = i18n( 'saveSettings', 'Save Settings' );
				if ( data.success ) {
					closeModuleSettingsModal();
					return;
				}
				window.alert( ( data.data && data.data.message ) || i18n( 'saveSettingsError', 'Error saving module settings.' ) );
			} )
			.catch( function () {
				saveBtn.disabled = false;
				saveBtn.textContent = i18n( 'saveSettings', 'Save Settings' );
				window.alert( i18n( 'saveSettingsError', 'Error saving module settings.' ) );
			} );
	}

	$( document ).ready( function () {
		$( '#wpps-ll-open-settings' ).on( 'click', function ( e ) {
			e.preventDefault();
			openModuleSettingsModal();
		} );

		$( document ).on( 'click', '#wp-powersuite-modal .wp-powersuite-modal__close, #wp-powersuite-modal .wp-powersuite-modal__cancel, #wp-powersuite-modal .wp-powersuite-modal__overlay', function ( e ) {
			e.preventDefault();
			closeModuleSettingsModal();
		} );

		$( document ).on( 'click', '#wp-powersuite-modal .wp-powersuite-modal__save', function ( e ) {
			e.preventDefault();
			saveModuleSettingsModal();
		} );

		$( document ).on( 'keydown', function ( e ) {
			if ( e.key === 'Escape' && getModal() && getModal().style.display !== 'none' ) {
				closeModuleSettingsModal();
			}
		} );

		$( '.wpps-ll-clear-btn' ).on( 'click', function ( e ) {
			e.preventDefault();

			if ( ! window.confirm( i18n( 'confirmClear', 'Are you sure you want to clear all logs? This action cannot be undone.' ) ) ) {
				return;
			}

			var $button = $( this );
			var nonce = $button.data( 'nonce' );

			$button.prop( 'disabled', true ).text( i18n( 'clearing', 'Clearing...' ) );

			$.ajax( {
				url: ajaxurl,
				type: 'POST',
				data: {
					action: 'wpps_limit_login_attempts_clear',
					nonce: nonce,
				},
				success: function ( response ) {
					if ( response.success && config.clearedUrl ) {
						window.location.href = config.clearedUrl;
						return;
					}

					window.alert( ( response.data && response.data.message ) || i18n( 'errorClear', 'Error clearing logs.' ) );
					$button.prop( 'disabled', false ).text( i18n( 'clearAll', 'Clear All Logs' ) );
				},
				error: function () {
					window.alert( i18n( 'errorClear', 'Error clearing logs.' ) );
					$button.prop( 'disabled', false ).text( i18n( 'clearAll', 'Clear All Logs' ) );
				},
			} );
		} );
	} );
}( jQuery ) );
