( function ( $ ) {
	'use strict';

	const cfg     = window.wcattio || {};
	const ajaxUrl = cfg.ajax_url || '';
	const nonce   = cfg.nonce   || '';
	const i18n    = cfg.i18n    || {};

	function getValidateNonce() {
		const el = document.getElementById( 'wcattio-validate-nonce' );
		return el ? el.value : '';
	}

	function setConnectionStatus( text, modifier ) {
		const el = document.getElementById( 'wcattio-connection-status' );
		if ( ! el ) {
			return;
		}
		el.textContent = text;
		el.className   = 'wcattio-connection-status' + ( modifier ? ' ' + modifier : '' );
	}

	function setSyncStatus( spanId, text, cssClass, actionsUrl ) {
		const el = document.getElementById( spanId );
		if ( ! el ) {
			return;
		}
		el.className = 'wcattio-sync-status' + ( cssClass ? ' ' + cssClass : '' );

		if ( actionsUrl ) {
			el.innerHTML = '';
			el.appendChild( document.createTextNode( text + ' ' ) );
			const link = document.createElement( 'a' );
			link.href        = actionsUrl;
			link.textContent = i18n.view_progress || 'View progress in Scheduled Actions';
			link.target      = '_blank';
			link.rel         = 'noopener noreferrer';
			el.appendChild( link );
		} else {
			el.textContent = text;
		}
	}

	function setButtonLoading( $btn, isLoading ) {
		if ( isLoading ) {
			$btn.prop( 'disabled', true ).addClass( 'wcattio-loading' );
		} else {
			$btn.prop( 'disabled', false ).removeClass( 'wcattio-loading' );
		}
	}

	function runBulkSync( $btn, action, statusId ) {
		setButtonLoading( $btn, true );
		setSyncStatus( statusId, i18n.sync_started || 'Starting…', '' );

		$.post(
			ajaxUrl,
			{ action: action, nonce: nonce },
			function ( response ) {
				if ( response && response.success ) {
					setSyncStatus( statusId, response.data.message, 'success', response.data.scheduled_actions_url );
				} else {
					const msg = ( response && response.data && response.data.message )
						? response.data.message
						: ( i18n.error || 'An error occurred' );
					setSyncStatus( statusId, msg, 'error' );
				}
			}
		).fail( function () {
			setSyncStatus( statusId, i18n.error || 'An error occurred', 'error' );
		} ).always( function () {
			setButtonLoading( $btn, false );
		} );
	}

	$( document ).on( 'click', '#wcattio-test-connection', function () {
		const $btn = $( this );
		const key  = $( '#wcattio_api_key' ).val();

		setButtonLoading( $btn, true );
		setConnectionStatus( i18n.validating || 'Validating…', '' );

		$.post(
			ajaxUrl,
			{
				action:  'wcattio_validate_key',
				nonce:   getValidateNonce(),
				api_key: key,
			},
			function ( response ) {
				if ( response && response.success ) {
					setConnectionStatus( response.data.message || i18n.valid || 'Connected successfully', 'success' );
				} else {
					const msg = ( response && response.data && response.data.message )
						? response.data.message
						: ( i18n.invalid || 'Could not connect. Check your API key.' );
					setConnectionStatus( msg, 'error' );
				}
			}
		).fail( function () {
			setConnectionStatus( i18n.error || 'An error occurred', 'error' );
		} ).always( function () {
			setButtonLoading( $btn, false );
		} );
	} );

	// writes sentinel into the hidden field so the sanitize callback knows to erase the stored value on save
	$( document ).on( 'click', '#wcattio-clear-api-key', function () {
		const confirmMsg = $( this ).data( 'confirm' ) || 'Clear the saved API key?';
		if ( ! window.confirm( confirmMsg ) ) {
			return;
		}
		$( '#wcattio_api_key' ).val( '__CLEAR__' ).attr( 'placeholder', '' );
		$( this ).remove();
		setConnectionStatus( '', '' );
	} );

	$( document ).on( 'click', '#wcattio-bulk-sync-customers', function () {
		runBulkSync( $( this ), 'wcattio_bulk_sync', 'wcattio-bulk-customers-status' );
	} );

	$( document ).on( 'click', '#wcattio-bulk-sync-orders', function () {
		runBulkSync( $( this ), 'wcattio_bulk_sync_orders', 'wcattio-bulk-orders-status' );
	} );

	$( document ).on( 'submit', '#wcattio-settings-form', function () {
		const $submit = $( this ).find( '[type="submit"]' );
		$submit.prop( 'disabled', true ).val( i18n.saving || 'Saving…' );
	} );

	window.addEventListener( 'pageshow', function ( e ) {
		if ( e.persisted ) {
			const $submit = $( '#wcattio-settings-form [type="submit"]' );
			$submit.prop( 'disabled', false ).val( i18n.save || 'Save Settings' );
		}
	} );

	$( document ).on( 'click', '.wcattio-onboarding-notice .notice-dismiss', function () {
		$.post( ajaxUrl, { action: 'wcattio_dismiss_onboarding', nonce: cfg.dismiss_nonce || '' } );
	} );

} )( jQuery );
