/**
 * Sync color picker swatch with hex text fields in admin forms.
 */
(function () {
	'use strict';

	function init(root) {
		var picker = root.querySelector('[data-wmk-color-picker]');
		var hex = root.querySelector('[data-wmk-color-hex]');
		var swatch = root.querySelector('.wmk-color-swatch');
		if (!picker || !hex || !swatch) {
			return;
		}
		function setSwatch(v) {
			swatch.style.setProperty('--swatch', v);
		}
		picker.addEventListener('input', function () {
			hex.value = picker.value.toUpperCase();
			setSwatch(picker.value);
			hex.dispatchEvent(new Event('change', { bubbles: true }));
		});
		hex.addEventListener('input', function () {
			var v = hex.value.trim();
			if (/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/.test(v)) {
				picker.value = v.length === 4 ? ('#' + v[1] + v[1] + v[2] + v[2] + v[3] + v[3]) : v;
				setSwatch(v);
			}
		});
	}

	function boot() {
		document.querySelectorAll('[data-wmk-color]').forEach(init);
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', boot);
	} else {
		boot();
	}
})();
