/**
 * Keeps the color-picker swatches in sync with the palette settings they're
 * built from (see Helper::add_field() in inc/customizer/class-helper.php),
 * so changing eg. Primary Color updates that swatch on every color field
 * instead of leaving it frozen at the theme.json default. Kirki's own
 * built-in swatches are appended after the palette ones and are left alone.
 */
(function () {
	'use strict';

	if ('undefined' === typeof wp || ! wp.customize || 'undefined' === typeof kubelioColorSwatches) {
		return;
	}

	var paletteSettings = kubelioColorSwatches.settings || [];

	if (! paletteSettings.length) {
		return;
	}

	wp.customize.bind('ready', function () {
		var refreshSwatches = function () {
			var liveColors = [];

			paletteSettings.forEach(function (id) {
				var setting = wp.customize(id);
				var value   = setting ? setting() : '';

				if (value) {
					liveColors.push(value);
				}
			});

			wp.customize.control.each(function (control) {
				var choices = control.params && control.params.choices;

				if (! choices || ! Array.isArray(choices.swatches)) {
					return;
				}

				choices.swatches = liveColors.concat(choices.swatches.slice(liveColors.length));

				var embedded = control.deferred && control.deferred.embedded;

				if (embedded && 'resolved' === embedded.state() && 'function' === typeof control.renderContent) {
					try {
						control.renderContent();
					} catch (e) {} // eslint-disable-line no-empty
				}
			});
		};

		paletteSettings.forEach(function (id) {
			var setting = wp.customize(id);

			if (setting) {
				setting.bind(refreshSwatches);
			}
		});

		// Controls embed lazily when their section first opens, so re-sync
		// once that happens to catch fields rendered after the initial pass.
		wp.customize.section.each(function (section) {
			section.expanded.bind(function (isExpanded) {
				if (isExpanded) {
					setTimeout(refreshSwatches, 0);
				}
			});
		});

		refreshSwatches();
	});
})();
