(function ($) {
	'use strict';

	const settings = window.foodordTimedProductsAdmin || {};
	const i18n = settings.i18n || {};

	const scheduleTemplate = document.getElementById('foodord-timed-schedule-template');
	const conditionTemplate = document.getElementById('foodord-timed-condition-template');

	function templateContent(node) {
		if (!node) {
			return '';
		}
		return node.textContent || node.innerHTML || '';
	}

	function replacePlaceholders(template, replacements) {
		let output = template;
		Object.keys(replacements).forEach(function (token) {
			const re = new RegExp(token, 'g');
			output = output.replace(re, replacements[token]);
		});
		return output;
	}

	function refreshProductSearch(context) {
		const $context = context || $(document.body);
		const $selects = $context.find('select.wc-product-search');

		if (!$selects.length) {
			return;
		}

		if ('function' === typeof $.fn.wc_product_search) {
			$selects.each(function () {
				const $el = $(this);
				if ($el.hasClass('enhanced-select')) {
					return;
				}
				$el.wc_product_search();
			});
		} else {
			$(document.body).trigger('wc-enhanced-select-init');
		}
	}

	function refreshCategorySearch(context) {
		const $context = context || $(document.body);
		const $selects = $context.find('select.wc-category-search');

		if (!$selects.length) {
			return;
		}

		window.requestAnimationFrame(function () {
			$(document.body).trigger('wc-enhanced-select-init');
			window.requestAnimationFrame(function () {
				$selects.each(function () {
					const $select = $(this);
					const instance = $select.data('select2') || $select.data('selectWoo');
					if (instance && instance.$container) {
						instance.$container.css('width', '100%');
					}
				});
			});
		});
	}

	function confirmAction(messageKey) {
		const message = i18n[messageKey];
		if (!message) {
			return true;
		}
		return window.confirm(message);
	}

	function addScheduleRow($wrapper) {
		if (!$wrapper.length) {
			return;
		}

		const template = templateContent(scheduleTemplate);
		if (!template) {
			return;
		}

		const nextIndex = parseInt($wrapper.data('next-index'), 10) || $wrapper.children('.foodord-timed-schedule-item').length;
		const html = replacePlaceholders(template, { '__INDEX__': nextIndex });
		$wrapper.append(html);
		$wrapper.data('next-index', nextIndex + 1);

		const $item = $wrapper.find('.foodord-timed-schedule-item').last();
		toggleScheduleFields($item);
		refreshScheduleLogic($wrapper);
	}

	function addConditionRow($wrapper) {
		if (!$wrapper.length) {
			return;
		}

		const template = templateContent(conditionTemplate);
		if (!template) {
			return;
		}

		const nextIndex = parseInt($wrapper.data('next-index'), 10) || $wrapper.children('.foodord-condition-row').length;
		const html = replacePlaceholders(template, { '__INDEX__': nextIndex });
		$wrapper.append(html);
		$wrapper.data('next-index', nextIndex + 1);

		const $row = $wrapper.find('.foodord-condition-row').last();
		toggleConditionInputs($row);
		refreshConditionLogic($wrapper);
		$(document.body).trigger('wc-enhanced-select-init');
	}

	function toggleScheduleFields($item) {
		if (!$item || !$item.length) {
			return;
		}

		const type = $item.find('.foodord-schedule-type').val();
		$item.find('.foodord-schedule-field').each(function () {
			const $field = $(this);
			const targets = ($field.data('schedule-field') || '').toString().split(',').map(function (value) {
				return value.trim();
			});
			const matches = targets.indexOf(type) !== -1;
			if (matches) {
				$field.removeClass('is-hidden');
				$field.find('input, select, textarea').prop('disabled', false);
			} else {
				$field.addClass('is-hidden');
				$field.find('input, select, textarea').prop('disabled', true);
			}
		});
	}

	function toggleConditionInputs($row) {
		const subject = $row.find('.foodord-condition-subject').val();
		const isCategory = 'category' === subject;
		const $product = $row.find('.foodord-condition-product');
		const $category = $row.find('.foodord-condition-category');

		setHiddenState($product, isCategory);
		setHiddenState($category, !isCategory);

		$product.find('select').prop('disabled', isCategory);
		$category.find('select').prop('disabled', !isCategory);

		if (isCategory) {
			refreshCategorySearch($row);
		} else {
			refreshProductSearch($row);
		}
	}

	function refreshConditionLogic($wrapper) {
		const $rows = $wrapper.find('.foodord-condition-row');
		$rows.each(function (index) {
			const $logic = $(this).find('.foodord-condition-logic');
			if (!$logic.length) {
				return;
			}
			if (0 === index) {
				$logic.addClass('is-hidden');
			} else {
				$logic.removeClass('is-hidden');
			}
		});
	}

	function refreshScheduleLogic($wrapper) {
		const $items = $wrapper.find('.foodord-timed-schedule-item');
		$items.each(function (index) {
			const $logic = $(this).find('.foodord-schedule-logic');
			if (!$logic.length) {
				return;
			}
			if (0 === index) {
				$logic.addClass('is-hidden');
			} else {
				$logic.removeClass('is-hidden');
			}
		});
	}

	function setHiddenState($element, shouldHide) {
		if (!$element || !$element.length) {
			return;
		}

		if (shouldHide) {
			$element.addClass('is-hidden');
		} else {
			$element.removeClass('is-hidden');
		}
	}

	function toggleVisibleDefaultOptions() {
		const $option = $('[data-visible-default-options]');
		if (!$option.length) {
			return;
		}

		const action = $('input[name="foodord_timed_action"]:checked').val();
		setHiddenState($option, 'show' !== action);
	}

	$(function () {
		const $scheduleWrapper = $('.foodord-timed-schedule-wrapper');
		const $conditionsWrapper = $('.foodord-timed-condition-list');

		$('input[name="foodord_timed_action"]').on('change', toggleVisibleDefaultOptions);

		$('.foodord-add-schedule').on('click', function (event) {
			event.preventDefault();
			addScheduleRow($scheduleWrapper);
		});

		$scheduleWrapper.on('click', '.foodord-remove-schedule', function (event) {
			event.preventDefault();
			if (!confirmAction('confirmDeleteSchedule')) {
				return;
			}
			$(this).closest('.foodord-timed-schedule-item').remove();
			refreshScheduleLogic($scheduleWrapper);
		});

		$scheduleWrapper.on('change', '.foodord-schedule-type', function () {
			toggleScheduleFields($(this).closest('.foodord-timed-schedule-item'));
		});

		$('.foodord-add-condition').on('click', function (event) {
			event.preventDefault();
			addConditionRow($conditionsWrapper);
		});

		$conditionsWrapper.on('click', '.foodord-remove-condition', function (event) {
			event.preventDefault();
			if (!confirmAction('confirmDeleteCondition')) {
				return;
			}
			$(this).closest('.foodord-condition-row').remove();
			refreshConditionLogic($conditionsWrapper);
			if (!$conditionsWrapper.find('.foodord-condition-row').length) {
				addConditionRow($conditionsWrapper);
			}
		});

		$conditionsWrapper.on('change', '.foodord-condition-subject', function () {
			toggleConditionInputs($(this).closest('.foodord-condition-row'));
		});

		refreshProductSearch($conditionsWrapper);
		refreshCategorySearch($conditionsWrapper);
		$(document.body).trigger('wc-enhanced-select-init');
		$conditionsWrapper.find('.foodord-condition-row').each(function () {
			toggleConditionInputs($(this));
		});
		refreshConditionLogic($conditionsWrapper);

		$scheduleWrapper.find('.foodord-timed-schedule-item').each(function () {
			toggleScheduleFields($(this));
		});
		refreshScheduleLogic($scheduleWrapper);
		toggleVisibleDefaultOptions();
	});
})(jQuery);
