(function ($) {
	"use strict"

	$(document).ready(function () {

		$('.wpcb-page-form-input--color input').wpColorPicker();

		// Accordeon collapse

		waitForEl('.cf-separator.accordeon', function() {
			$('.cf-separator.accordeon').each(function(index, item) {
				if ( sessionStorage.getItem('wcb-accordeon-' + (index+1) ) ) {
					var collapsed = sessionStorage.getItem('wcb-accordeon-' + (index+1));
					if ( 'true' == collapsed ) {
						$(item).addClass('collapsed');
					}
				}
			});
		});

		$(document).on('click', '.cf-separator.accordeon', function () {
			$(this).toggleClass('collapsed');

			var allSameTypeElements = $('.cf-separator.accordeon');
			var globalNthOfTypeIndex = allSameTypeElements.index($(this)) + 1;

			sessionStorage.setItem('wcb-accordeon-' + globalNthOfTypeIndex, $(this).hasClass('collapsed'));
		});

		waitForEl('.cf-discount-rules', function() {
			
			// $('.cf-select-default-option:not([hidden])').each(function (index, option) {
			// 	filterAttributeSelectValues($(option).siblings('.cf-select-choice').find('select'), $(option).find('select'));
			// });

			if ( $(window).width() < 992 ) {
				// Mobile.
				$('.cf-discount-rules .cf-select-default-option select').one('focus', function () {
					filterAttributeSelectValues( 
						$(this).closest('.cf-select-default-option').siblings('.cf-select-choice').find('select'), 
						$(this)
					);
				});
			} else {
				// Desktop.
				$('.cf-discount-rules .cf-select-default-option').one('mouseover', function () {
					filterAttributeSelectValues( $(this).siblings('.cf-select-choice').find('select'), $(this).find('select') );
				});
			}
		});

		waitForEl('.cf-complex-rules', function() {
			if ( $(window).width() < 992 ) {
				// Mobile.
				$('.cf-complex-rules .wpcb-rule-choice-option select').one('focus', function() {
					filterAttributeSelectValues( 
						$(this).closest('.wpcb-rule-choice-option').siblings('.wpcb-rule-choice').find('select'),
						$(this)
					);
				});

				$('.cf-select-default-option select').one('focus', function() {
					filterAttributeSelectValues( 
						$(this).closest('.cf-select-default-option').siblings('.cf-select-choice').find('select'),
						$(this)
					);
				});

				$('.cf-complex-option-rules .wpcb-rule-choice-option-value select').one('focus', function () {
					filterAttributeSelectValues(
						$(this).closest('.cf-block__fields').find('.cf-select-choice select'),
						$(this)
					);
				});
			} else {
				// Desktop.
				$('.cf-complex-rules .wpcb-rule-choice-option').one('mouseover', function() {
					filterAttributeSelectValues($(this).siblings('.wpcb-rule-choice').find('select'), $(this).find('select') );
				});

				$('.cf-select-default-option').one('mouseover', function() {
					filterAttributeSelectValues( $(this).siblings('.cf-select-choice').find('select'), $(this).find('select') );
				});

				$('.cf-complex-option-rules .wpcb-rule-choice-option-value').one('mouseover', function () {
					filterAttributeSelectValues( $(this).closest('.cf-block__fields').find('.cf-select-choice select'), $(this).find('select') );
				});
			}
		});

		// waitForEl('.cf-complex-rules', function() {
		// 	// Conditional rules old
		// 	$('.cf-complex-rules:not([hidden]) .wpcb-rule-choice').each(function (index, select) {
		// 		filterAttributeSelectValues($(select).find('select'), $(select).siblings('.wpcb-rule-choice-option').find('select') );
		// 	});

		// 	$('.cf-select-default-option:not([hidden])').each(function (index, option) {
		// 		filterAttributeSelectValues($(option).siblings('.cf-select-choice').find('select'), $(option).find('select'));
		// 	});

		// 	$('.cf-complex-option-rules:not([hidden]) .wpcb-rule-choice-option-value').each(function (index, option) {
		// 		filterAttributeSelectValues($(option).closest('.cf-block__fields').find('.cf-select-choice select'), $(option).find('select'));
		// 	});
		// });

		$(document).on('change', '.cf-complex-rules .wpcb-rule-choice select', function () {
			populateAttributeSelectValues($(this), $(this).closest('.wpcb-rule-choice').siblings('.wpcb-rule-choice-option').find('select'));
		});

		$(document).on('change', '.cf-checkbox-default-option input', function () {
			if ( $(this).parents('.cf-checkbox-default-option').siblings('.cf-select-default-option').length ) {
				populateAttributeSelectValues(
					$(this).closest('.cf-checkbox-default-option').siblings('.cf-select-choice').find('select'), 
					$(this).closest('.cf-checkbox-default-option').siblings('.cf-select-default-option').find('select')
				);
			}
		});

		$(document).on('change', '.cf-select-choice select', function () {
			if ( $(this).closest('.cf-select-choice').siblings('.cf-select-default-option:not([hidden])').length ) {
				populateAttributeSelectValues($(this), $(this).parents('.cf-select-choice').siblings('.cf-select-default-option').find('select') );
			}

			if ( $(this).closest('.cf-select-choice').siblings('.cf-complex-option-rules:not([hidden])').length ) {
				var $select = $(this);

				$(this).closest('.cf-select-choice')
					.siblings('.cf-complex-option-rules:not([hidden])')
					.find('.wpcb-rule-choice-option-value select')
					.each(function(index,optionSelect) {

					populateAttributeSelectValues(
						$select,
						$(optionSelect)
					);
				});
			}
		});

		$(document).on('click', '.cf-complex__inserter-button', function () {
			$.event.trigger({
				type: 'newComplexGroupAdded'
			});
		});

		$(document).on('newComplexGroupAdded', function() {
			setTimeout(function() {
				$('.cf-complex-option-rules').each(function(index,optionRules) {
					var $attributeSelect = $(optionRules).siblings('.cf-select-choice').find('select');
	
					$(optionRules).find('.wpcb-rule-choice-option-value select:not(.populated)').each(function(index,optionSelect) {
						populateAttributeSelectValues(
							$attributeSelect,
							$(optionSelect)
						);
					});
				});
			}, 10);
		});

		function filterAttributeSelectValues($groupSelect, $select) {
			var groupId = $groupSelect.val();

			$select.prop('disabled',true);
	
			$.post(ajaxurl, {
				action: 'wpcb_get_configurator_attribute_values',
				choice_id: groupId
			}).done(function (response) {
				var selectItems = JSON.parse(response);
				var entries = Object.entries(selectItems);
				var entryKeys = new Array();
	
				entries.map(([key, val] = entry) => {
					entryKeys.push(key);
				});
	
				$select.find('option').each(function (index, option) {
					if (!entryKeys.includes($(option).val())) {
						$(option).remove();
					}
				});
			}).fail(function (error) {
				console.error(error);
			}).always(function() {
				$select.addClass('populated');
				$select.prop('disabled',false);
			});
		}
	
		function populateAttributeSelectValues($groupSelect, $select) {
			var groupId = $groupSelect.val();
	
			$select.prop('disabled',true);
	
			$.post(ajaxurl, {
				action: 'wpcb_get_configurator_attribute_values',
				choice_id: groupId,
			}).done(function (response) {
				var selectItems = JSON.parse(response);
				var entries = Object.entries(selectItems);
	
				$select.html('');
				entries.map(([key, val] = entry) => {
					if ( val ) {
						$select.append('<option value="' + key + '">' + val + '</option>');
					}
				});
			}).fail(function (error) {
				console.error(error);
			}).always(function() {
				$select.addClass('populated');
				$select.prop('disabled',false);
			});
		}
	});

	var waitForEl = function (selector, callback) {
		if (jQuery(selector).length) {
			callback();
		} else {
			setTimeout(function () {
				waitForEl(selector, callback);
			}, 100);
		}
	};

	// Check for the Gutenberg header and editor data
	const interval = setInterval(() => {
		const header = document.querySelector('.editor-header__settings');
		if (!header || !window.wp || !wp.data) return;

		const postId = wp.data.select('core/editor').getCurrentPostId();
		if (!postId) return;

		// Avoid injecting the button more than once
		if (document.getElementById('custom-preview-button')) {
			clearInterval(interval);
			return;
		}

		const url = `${window.location.origin}?page=wpcb_configuration_preview&id=${postId}`;
		const button = document.createElement('a');
		button.id = 'custom-preview-button';
		button.href = url;
		button.target = '_blank';
		button.className = 'components-button is-compact has-icon';
		button.setAttribute('aria-label', 'Preview');
		button.innerHTML = `
			<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false">
				<path d="M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z"></path>
			</svg>
		`;
		header.prepend(button);
		clearInterval(interval);
	}, 500);

})(jQuery);