/**
 * OrderCarry admin.
 *
 * @package Ordsync
 */

( function ( $ ) {
	'use strict';

	$( function () {

		/**
		 * Send Test Order.
		 */
		$( document ).on( 'click', '.ordsync-test', function ( e ) {
			e.preventDefault();

			var $button = $( this );

			/*
			 * Scope to this destination. A global $('.ordsync-test-result')
			 * wrote the answer into every destination's result span at once,
			 * so with more than one sheet configured the user saw the same
			 * "✓ sent" under all of them regardless of which was tested.
			 */
			var $slot   = $button.closest( '.ordsync-slot' );
			var $result = $slot.length
				? $slot.find( '.ordsync-test-result' ).first()
				: $( '.ordsync-test-result' ).first();

			var dest = $button.data( 'dest' );

			$button.prop( 'disabled', true );
			$result
				.removeClass( 'is-success is-error' )
				.addClass( 'is-working' )
				.text( ordsyncData.testing );

			$.post( ordsyncData.ajaxUrl, {
				action: 'ordsync_test',
				nonce:  ordsyncData.nonce,
				dest:   dest
			} )
				.done( function ( response ) {
					var ok  = response && response.success;
					var msg = response && response.data && response.data.message
						? response.data.message
						: 'Unexpected response.';

					$result
						.removeClass( 'is-working' )
						.addClass( ok ? 'is-success' : 'is-error' )
						.text( ( ok ? '✓ ' : '✗ ' ) + msg );
				} )
				.fail( function ( xhr ) {
					$result
						.removeClass( 'is-working' )
						.addClass( 'is-error' )
						.text( '✗ ' + ( xhr.status ? 'HTTP ' + xhr.status : 'Request failed.' ) );
				} )
				.always( function () {
					$button.prop( 'disabled', false );
				} );
		} );

		/**
		 * Queue one failed row again.
		 *
		 * Scoped to the row it was clicked in, for the same reason the test
		 * button is scoped to its card: a global selector writes the answer
		 * into every row at once.
		 */
		$( document ).on( 'click', '.ordsync-retry', function ( e ) {
			e.preventDefault();

			var $button = $( this );
			var $result = $button.closest( 'td' ).find( '.ordsync-retry-result' ).first();

			$button.prop( 'disabled', true );
			$result
				.removeClass( 'is-success is-error' )
				.addClass( 'is-working' )
				.text( ordsyncData.retrying );

			$.post( ordsyncData.ajaxUrl, {
				action: 'ordsync_retry',
				nonce:  ordsyncData.nonce,
				order:  $button.data( 'order' ),
				dest:   $button.data( 'dest' )
			} )
				.done( function ( response ) {
					var ok  = response && response.success;
					var msg = response && response.data && response.data.message
						? response.data.message
						: 'Unexpected response.';

					$result
						.removeClass( 'is-working' )
						.addClass( ok ? 'is-success' : 'is-error' )
						.text( ( ok ? '✓ ' : '✗ ' ) + msg );
				} )
				.fail( function ( xhr ) {
					$result
						.removeClass( 'is-working' )
						.addClass( 'is-error' )
						.text( '✗ ' + ( xhr.status ? 'HTTP ' + xhr.status : 'Request failed.' ) );
					$button.prop( 'disabled', false );
				} );
		} );

		/**
		 * Import past orders into one destination.
		 */
		$( document ).on( 'click', '.ordsync-import-run', function ( e ) {
			e.preventDefault();

			var $button = $( this );
			var $row    = $button.closest( '.ordsync-import' );
			var $result = $row.find( '.ordsync-import-result' );

			if ( ! window.confirm( ordsyncData.confirmImport ) ) {
				return;
			}

			$button.prop( 'disabled', true );
			$result
				.removeClass( 'is-success is-error' )
				.addClass( 'is-working' )
				.text( ordsyncData.importing );

			$.post( ordsyncData.ajaxUrl, {
				action: 'ordsync_import',
				nonce:  ordsyncData.nonce,
				dest:   $button.data( 'dest' ),
				limit:  $row.find( '.ordsync-import-limit' ).val(),
				status: $row.find( '.ordsync-import-status' ).val()
			} )
				.done( function ( response ) {
					var ok  = response && response.success;
					var msg = response && response.data && response.data.message
						? response.data.message
						: 'Unexpected response.';

					$result
						.removeClass( 'is-working' )
						.addClass( ok ? 'is-success' : 'is-error' )
						.text( ( ok ? '✓ ' : '✗ ' ) + msg );
				} )
				.fail( function ( xhr ) {
					$result
						.removeClass( 'is-working' )
						.addClass( 'is-error' )
						.text( '✗ ' + ( xhr.status ? 'HTTP ' + xhr.status : 'Request failed.' ) );
				} )
				.always( function () {
					$button.prop( 'disabled', false );
				} );
		} );

		/**
		 * Add another destination.
		 *
		 * Rather than cloning a whole settings block client-side, this posts
		 * one empty slot and lets PHP render it. Fewer moving parts, and the
		 * new block is guaranteed to match what the server actually stored.
		 */
		$( document ).on( 'click', '.ordsync-add-slot', function ( e ) {
			e.preventDefault();

			var $button = $( this );
			var $form   = $button.closest( 'form' );
			var tab     = $form.find( 'input[name="tab"]' ).val();
			var next    = parseInt( $button.data( 'next' ), 10 ) || 0;

			$( '<input>' )
				.attr( 'type', 'hidden' )
				.attr( 'name', 'ordsync[' + tab + '][' + next + '][enabled]' )
				.val( 'no' )
				.appendTo( $form );

			HTMLFormElement.prototype.submit.call( $form[ 0 ] );
		} );

		/**
		 * Delete a destination.
		 *
		 * Removing the block removes its fields, so the save rebuilds the
		 * list without it.
		 */
		$( document ).on( 'click', '.ordsync-remove-slot', function ( e ) {
			e.preventDefault();

			if ( ! window.confirm( ordsyncData.confirmDelete ) ) {
				return;
			}

			var $slot = $( this ).closest( '.ordsync-slot' );
			var $form = $slot.closest( 'form' );

			$slot.remove();
			HTMLFormElement.prototype.submit.call( $form[ 0 ] );
		} );

		/**
		 * Add a conditional rule.
		 *
		 * The template row's inputs use data-name rather than name, so an
		 * empty hidden row can never be submitted. Cloning swaps it back and
		 * substitutes the row index.
		 */
		$( document ).on( 'click', '.ordsync-add-rule', function ( e ) {
			e.preventDefault();

			var $button = $( this );

			/*
			 * Scope to this rule set. A global $('.ordsync-rules') would
			 * clone every template on the page and append to every list,
			 * so a second rule set would silently double every added row.
			 */
			var $scope    = $button.closest( '.ordsync-conditions' );
			var $template = $scope.find( '.ordsync-rule-template' ).first();
			var $list     = $scope.find( '.ordsync-rules' ).first();

			if ( ! $template.length || ! $list.length ) {
				return;
			}

			// Keep counting past any rows already on the page.
			var next = parseInt( $button.data( 'next' ), 10 );
			if ( isNaN( next ) ) {
				next = parseInt( $button.data( 'start' ), 10 ) || 0;
			}

			var $row = $template.clone();
			$row.removeClass( 'ordsync-rule-template' );

			$row.find( '[data-name]' ).each( function () {
				var $field = $( this );
				$field.attr( 'name', String( $field.data( 'name' ) ).replace( '__i__', next ) );
				$field.removeAttr( 'data-name' );
			} );

			$list.append( $row );
			$button.data( 'next', next + 1 );
		} );

		/**
		 * Remove a conditional rule.
		 */
		$( document ).on( 'click', '.ordsync-remove-rule', function ( e ) {
			e.preventDefault();
			$( this ).closest( '.ordsync-rule' ).remove();
		} );

		/**
		 * Keep the On/Off wording beside the switch honest.
		 *
		 * The colour alone is not enough -- it fails for colour-blind users
		 * and in high-contrast mode, so the state is written out in words.
		 */
		$( document ).on( 'change', '.ordsync-switch input', function () {
			var $input = $( this );
			var on     = $input.is( ':checked' );

			$input.closest( '.ordsync-switch' )
				.find( '.ordsync-switch-text' )
				.text( on ? ordsyncData.switchOn : ordsyncData.switchOff );

			$input.closest( '.ordsync-slot' )
				.toggleClass( 'is-on', on )
				.toggleClass( 'is-off', ! on );
		} );

		/**
		 * Copy the Apps Script.
		 */
		$( document ).on( 'click', '.ordsync-copy', function ( e ) {
			e.preventDefault();

			var $button  = $( this );
			var original = $button.text();
			var field    = document.getElementById( $button.data( 'target' ) );

			if ( ! field ) {
				return;
			}

			field.select();
			field.setSelectionRange( 0, 99999 );

			var done = function ( ok ) {
				$button.text( ok ? ordsyncData.copied : ordsyncData.copyFail );
				window.setTimeout( function () {
					$button.text( original );
				}, 2000 );
			};

			if ( navigator.clipboard && navigator.clipboard.writeText ) {
				navigator.clipboard.writeText( field.value ).then(
					function () { done( true ); },
					function () { done( false ); }
				);
				return;
			}

			try {
				done( document.execCommand( 'copy' ) );
			} catch ( err ) {
				done( false );
			}
		} );

	} );

}( jQuery ) );
