function dhl_polska_run_on_ready( callback ) {
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', callback );
	} else {
		callback();
	}
}

function dhl_polska_settings_change_event() {
	var envField = document.querySelector( '.js--environment-field' );
	if ( ! envField ) {
		return;
	}

	var isSandbox = envField.checked;
	var sandboxFields = document.querySelectorAll( '.js--sandbox-field' );
	var productionFields = document.querySelectorAll( '.js--production-field' );

	sandboxFields.forEach(
		function ( field ) {
			field.required = isSandbox;
			field.closest( 'tr' ).style.display = isSandbox ? 'table-row' : 'none';
		}
	);

	productionFields.forEach(
		function ( field ) {
			field.required = ! isSandbox;
			field.closest( 'tr' ).style.display = ! isSandbox ? 'table-row' : 'none';
		}
	);
}

function dhl_polska_render_connection_status( configuration ) {
	var resultField = document.getElementById( configuration.result_field_id );
	if ( ! resultField ) {
		return;
	}

	var request = new XMLHttpRequest();
	var params = new FormData();

	params.append( 'action', configuration.action );
	params.append( '_wpnonce', configuration.nonce );
	request.open( 'POST', configuration.url, true );

	request.onload = function () {
		if ( this.status < 200 || this.status >= 400 ) {
			return;
		}

		var response = null;
		try {
			response = JSON.parse( this.response );
		} catch ( e ) {
			return;
		}

		if ( ! response || ! response.data || typeof response.data.message === 'undefined' ) {
			return;
		}

		resultField.style.color = response.success ? 'green' : 'red';
		resultField.textContent = response.data.message;
	};

	request.send( params );
}

dhl_polska_run_on_ready(
	function () {
		var envField = document.querySelector( '.js--environment-field' );
		if ( envField ) {
			envField.addEventListener( 'change', dhl_polska_settings_change_event );
			dhl_polska_settings_change_event();
		}

		var connectionStatuses = window.dhlPolskaConnectionStatusQueue || [];
		connectionStatuses.forEach(
			function ( configuration ) {
				dhl_polska_render_connection_status( configuration );
			}
		);
	}
);
