/* global jQuery */

(function($) {
	'use strict';

	$(document).ready(function() {
		if (!$.fn.wpColorPicker) {
			return;
		}

		function normalizeHex(value) {
			if (!value) {
				return '';
			}
			value = String(value).trim();
			if (value && value.charAt(0) !== '#') {
				value = '#' + value;
			}
			return value;
		}

		function isValidHex(value) {
			return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(value);
		}

		function getPickerInputById(id) {
			return $('#' + id + '.foodord-color-picker');
		}

		function updateColorCode($pickerInput) {
			const id = $pickerInput.attr('id');
			if (!id) {
				return;
			}
			const $hexInput = $('.foodord-color-code-input[data-foodord-color-input-for="' + id + '"]');
			if ($hexInput.length) {
				// Don't overwrite the user's typing.
				if ($hexInput.get(0) === document.activeElement) {
					return;
				}
				$hexInput.val($pickerInput.val() || '');
			}
		}

		$('.foodord-color-picker').each(function() {
			updateColorCode($(this));
		});

		$('.foodord-color-picker').wpColorPicker({
			change: function(event) {
				updateColorCode($(event.target));
			},
			clear: function(event) {
				updateColorCode($(event.target));
			}
		});

		$(document).on('input', '.foodord-color-code-input', function() {
			// While typing, do not auto-apply 3-digit hex codes (#abc) because wpColorPicker will
			// normalize them (e.g. #abc -> #aabbcc) and overwrite the input mid-typing.
			const $hexInput = $(this);
			const raw = normalizeHex($hexInput.val());
			if (raw.length !== 7) {
				return;
			}
			applyHexToPicker($hexInput);
		});

		// Apply on blur/change to support 3-digit hex codes and pastes without interfering while typing.
		$(document).on('change blur', '.foodord-color-code-input', function() {
			applyHexToPicker($(this));
		});

		function applyHexToPicker($hexInput) {
			const targetId = $hexInput.data('foodord-color-input-for');
			if (!targetId) {
				return;
			}

			const hex = normalizeHex($hexInput.val());
			if (!isValidHex(hex)) {
				return;
			}

			const $pickerInput = getPickerInputById(targetId);
			if (!$pickerInput.length) {
				return;
			}

			try {
				$pickerInput.wpColorPicker('color', hex);
			} catch (err) {
				void err;
				$pickerInput.val(hex);
				$pickerInput.trigger('change');
			}
		}

	});
})(jQuery);
