/**
 * Vanquish Multiple Addresses — admin settings.
 *
 * The colour picker, and repeatable rows for the handling-fee ranges. The rows
 * post as parallel arrays, so plain DOM cloning is enough — no index bookkeeping
 * when adding or removing.
 */
( function () {
	'use strict';

	// WordPress' colour picker is a jQuery plugin, so this part needs jQuery;
	// the rest of the file stays dependency-free.
	if ( window.jQuery && window.jQuery.fn.wpColorPicker ) {
		window.jQuery( function ( $ ) {
			$( '.vanmuad-color-field' ).wpColorPicker();
		} );
	}

	/*
	 * Sub-options that only mean something while their parent toggle is on.
	 *
	 * Hidden rather than disabled: a hidden checkbox still posts nothing, which
	 * is the same as off, so a merchant who switches a feature off does not leave
	 * its settings quietly half-applied.
	 */
	document.addEventListener( 'DOMContentLoaded', function () {
		var parents = document.querySelectorAll( '[data-vanmuad-controls]' );

		Array.prototype.forEach.call( parents, function ( parent ) {
			var group = parent.getAttribute( 'data-vanmuad-controls' );
			var block = document.querySelector( '[data-vanmuad-group="' + group + '"]' );

			if ( ! block ) {
				return;
			}

			var sync = function () {
				block.hidden = ! parent.checked;
			};

			parent.addEventListener( 'change', sync );
			sync();
		} );
	} );

	document.addEventListener( 'DOMContentLoaded', function () {
		var table = document.querySelector( '[data-vanmuad-ranges]' );

		if ( ! table ) {
			return;
		}

		var body = table.querySelector( '[data-vanmuad-ranges-body]' );
		var addButton = document.querySelector( '[data-vanmuad-range-add]' );

		if ( ! body || ! addButton ) {
			return;
		}

		addButton.addEventListener( 'click', function () {
			var rows = body.querySelectorAll( '[data-vanmuad-range-row]' );

			if ( ! rows.length ) {
				return;
			}

			var clone = rows[ rows.length - 1 ].cloneNode( true );

			clone.querySelectorAll( 'input' ).forEach( function ( input ) {
				input.value = '';
			} );

			body.appendChild( clone );
		} );

		// Delegated so cloned rows work too.
		body.addEventListener( 'click', function ( event ) {
			if ( ! event.target.closest( '[data-vanmuad-range-remove]' ) ) {
				return;
			}

			var row = event.target.closest( '[data-vanmuad-range-row]' );
			var rows = body.querySelectorAll( '[data-vanmuad-range-row]' );

			// Keep one row on screen: removing the last one would leave no way to
			// add another.
			if ( rows.length > 1 ) {
				row.parentNode.removeChild( row );
				return;
			}

			row.querySelectorAll( 'input' ).forEach( function ( input ) {
				input.value = '';
			} );
		} );
	} );
} )();
