/**
 * Color picker for the Customizer (with Alpha). Uses https://narsenico.github.io/a-color-picker
 */
wp.customize.bind('ready', function () {
	const colorControls = document.querySelectorAll('.multi-color-control');
	colorControls.forEach((control) => {
		const input = control.querySelector('.multi-color-control-input');
		const colorPicker = AColorPicker.createPicker({
			attachTo: control.querySelector('.multi-color-control-picker'),
			color: input.value || '',
			showHSL: false,
			showHEX: false,
			showRGB: false,
			showAlpha: true
		});

		control.addEventListener('click', (event) => {
			event.stopPropagation();
			control.querySelector('.multi-color-control-picker').classList.add('show');
		});

		const updateSetting = function (picker, color) {
			input.value = AColorPicker.parseColor(color, 'rgbacss');
			input.dispatchEvent(new Event('change'));
		}

		colorPicker.on('change', updateSetting);

		input.addEventListener('input', (event) => {
			let color = AColorPicker.parseColor(event.target.value);
			if (color) {
				colorPicker.off('change');
				colorPicker.color = color;
				colorPicker.on('change', updateSetting);
			}
		})
	});
	document.body.addEventListener('click', () => {
		const colorPickers = document.querySelectorAll('.multi-color-control-picker');
		colorPickers.forEach((picker) => picker.classList.remove('show'));
	});
});

