
(function ($) {
	'use strict';

	$(document).on('click', '.nudgesells-tab-btn', function () {
		var $group = $(this).closest('.nudgesells-tabs').parent();
		var tab = $(this).data('tab');
		$group.find('.nudgesells-tab-btn').removeClass('active');
		$(this).addClass('active');
		$group.find('.nudgesells-tab-panel').hide();
		$group.find('.nudgesells-tab-panel[data-tab="' + tab + '"]').show();
	});

	if ($.fn.wpColorPicker) {
		$('.nudgesells-color-field').wpColorPicker();
	}

	$('input[name="nudgesells_settings[product_title_link_mode]"]').on('change', function () {
		$('#nudgesells-quick-view-class-wrap').toggle($('#nudgesells-title-link-quick-view').is(':checked'));
	});

	if ($.fn.datepicker) {
		$('.nudgesells-datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
	}

	if (typeof NudgeSells_Admin === 'undefined') {
		if (window.console) {
			console.warn('NudgeSells: admin data did not load (NudgeSells_Admin is undefined) - check for a plugin/theme JS conflict on this screen.');
		}
		return;
	}

	var state = {
		addons: (NudgeSells_Admin.rules && NudgeSells_Admin.rules.addons) || [],
		addons_selection_type: (NudgeSells_Admin.rules && NudgeSells_Admin.rules.addons_selection_type) || 'checkbox',
		bundle_discount: (NudgeSells_Admin.rules && NudgeSells_Admin.rules.bundle_discount) || { enabled: false, type: 'percent', value: 0, label: '' },
		tiers: (NudgeSells_Admin.rules && NudgeSells_Admin.rules.tiers) || [],
		tiers_repeat_scale: !! (NudgeSells_Admin.rules && NudgeSells_Admin.rules.tiers_repeat_scale),
		upgrades: (NudgeSells_Admin.rules && NudgeSells_Admin.rules.upgrades) || []
	};

	function productSelect(selected) {
		var $sel = $('<select class="nudgesells-product-search" style="width:100%"></select>');
		if (selected && Number(selected) > 0) {
			var label = NudgeSells_Admin.product_labels[selected] || ('#' + selected);
			$sel.append($('<option></option>').attr('value', selected).text(label));
		}
		return $sel;
	}

	function initProductSelect2($sel) {
		if (!$.fn.select2) {
			return;
		}
		$sel.select2({
			ajax: {
				url: NudgeSells_Admin.ajax_url,
				dataType: 'json',
				delay: 250,
				data: function (params) {
					return { term: params.term, action: 'woocommerce_json_search_products_and_variations', security: NudgeSells_Admin.search_nonce };
				},
				processResults: function (data) {
					var results = [];
					$.each(data, function (id, text) { results.push({ id: id, text: text }); });
					return { results: results };
				},
				cache: true
			},
			minimumInputLength: 2,
			placeholder: NudgeSells_Admin.i18n.select_product,
			width: '100%'
		});
	}

	function initScopeMultiSelect($sel, action, existingIds, existingLabels, placeholder) {
		var initial = [];
		(existingIds || []).forEach(function (id) {
			if (!id || Number(id) <= 0) {
				return;
			}
			var label = existingLabels[id] || ('#' + id);
			$sel.append($('<option selected></option>').attr('value', id).text(label));
			initial.push(id);
		});

		if (!$.fn.select2) {
			return;
		}

		// Scoping a campaign to one specific product variation
		var effectiveAction = action;
		if ('woocommerce_json_search_products_and_variations' === action && !NudgeSells_Admin.is_pro) {
			effectiveAction = 'woocommerce_json_search_products';
		}

		$sel.select2({
			ajax: {
				url: NudgeSells_Admin.ajax_url,
				dataType: 'json',
				delay: 250,
				data: function (params) {
					var data = { term: params.term, security: NudgeSells_Admin.search_nonce, action: effectiveAction };
					return data;
				},
				processResults: function (data) {
					var results = [];
					if ('woocommerce_json_search_products_and_variations' === effectiveAction || 'woocommerce_json_search_products' === effectiveAction) {
						$.each(data, function (id, text) { results.push({ id: id, text: text }); });
					} else {
						$.each(data, function (i, term) { results.push({ id: term.id, text: term.name }); });
					}
					return { results: results };
				},
				cache: true
			},
			minimumInputLength: 2,
			placeholder: placeholder,
			width: '100%'
		});
	}

	function currentScopeType() {
		return $('input[name="nudgesells_scope_type_display"]:checked').val() || 'products';
	}

	function refreshScopeVisibility() {
		var type = currentScopeType();
		$('.nudgesells-scope-sub').hide();
		if ('products' === type) {
			$('#nudgesells-scope-products-wrap').show();
		} else if ('categories' === type) {
			$('#nudgesells-scope-categories-wrap').show();
		} else if ('tags' === type) {
			$('#nudgesells-scope-tags-wrap').show();
		}
		$('#nudgesells-scope-type-hidden').val(type);

		$('#nudgesells-scope-exclude-wrap').toggle('products' !== type);
	}

	function initScope() {
		var scope = NudgeSells_Admin.scope || { type: 'products', ids: [], exclude_ids: [] };

		initScopeMultiSelect(
			$('#nudgesells-scope-products'),
			'woocommerce_json_search_products_and_variations',
			'products' === scope.type ? scope.ids : [],
			NudgeSells_Admin.product_labels,
			NudgeSells_Admin.i18n.select_product
		);
		initScopeMultiSelect(
			$('#nudgesells-scope-categories'),
			'nudgesells_search_product_categories',
			'categories' === scope.type ? scope.ids : [],
			NudgeSells_Admin.term_labels,
			NudgeSells_Admin.i18n.select_category
		);
		initScopeMultiSelect(
			$('#nudgesells-scope-tags'),
			'nudgesells_search_product_tags',
			'tags' === scope.type ? scope.ids : [],
			NudgeSells_Admin.term_labels,
			NudgeSells_Admin.i18n.select_tag
		);
		initScopeMultiSelect(
			$('#nudgesells-scope-exclude'),
			'woocommerce_json_search_products_and_variations',
			scope.exclude_ids || [],
			NudgeSells_Admin.product_labels,
			NudgeSells_Admin.i18n.select_product
		);

		refreshScopeVisibility();
	}

	$(document).on('change', 'input[name="nudgesells_scope_type_display"]', refreshScopeVisibility);

	function syncScopeHiddenFields() {
		var type = currentScopeType();
		var $activeSelect = 'products' === type ? $('#nudgesells-scope-products') : ('categories' === type ? $('#nudgesells-scope-categories') : ('tags' === type ? $('#nudgesells-scope-tags') : null));
		var ids = $activeSelect ? ($activeSelect.val() || []) : [];
		$('#nudgesells-scope-type-hidden').val(type);
		$('#nudgesells-scope-ids-hidden').val(ids.join(','));
		$('#nudgesells-exclude-ids-hidden').val(($('#nudgesells-scope-exclude').val() || []).join(','));
	}

	function renderAddons() {
		var $tbody = $('#nudgesells-addons-table tbody').empty();
		state.addons.forEach(function (row, i) {
			var $tr = $('<tr></tr>');
			var $prodTd = $('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_product).append(productSelect(row.product_id));
			var $typeTd = $('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_type).append($('<select class="f-type"><option value="percent">%</option><option value="fixed">' + NudgeSells_Admin.currency_symbol + '</option><option value="fixed_price">' + (NudgeSells_Admin.i18n.fixed_price || 'Fixed price') + '</option></select>').val(row.discount_type || 'percent'));
			var $valTd = $('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_value).append($('<input type="number" step="0.01" min="0" class="f-value" style="width:100%">').val(row.discount_value || 0));
			var $labelTd = $('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_label).append($('<input type="text" class="f-label" style="width:100%" placeholder="' + (NudgeSells_Admin.i18n.badge_placeholder || 'e.g. Bestseller') + '">').val(row.label || ''));
			var $sublineTd = $('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_subline).append($('<input type="text" class="f-subline" style="width:100%" placeholder="e.g. Fits all sizes">').val(row.subline || ''));
			var $defaultValueTd = $('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_default_value).append($('<input type="number" step="1" min="0" class="f-allow-qty" style="width:100%">').val(row.allow_qty || 0));
			var $removeTd = $('<td></td>').append($('<button type="button" class="button-link nudgesells-remove">✕</button>'));

			$tr.append($prodTd, $typeTd, $valTd, $labelTd, $sublineTd, $defaultValueTd, $removeTd);
			$tbody.append($tr);
			initProductSelect2($tr.find('.nudgesells-product-search'));

			$tr.find('.nudgesells-product-search').on('select2:select', function (e) {
				if (e.params && e.params.data) {
					NudgeSells_Admin.product_labels[e.params.data.id] = e.params.data.text;
				}
			});

			$tr.on('change input', 'select,input', function () {
				state.addons[i] = {
					product_id: parseInt($tr.find('.nudgesells-product-search').val(), 10) || 0,
					discount_type: $tr.find('.f-type').val(),
					discount_value: parseFloat($tr.find('.f-value').val()) || 0,
					label: $tr.find('.f-label').val(),
					subline: $tr.find('.f-subline').val(),
					allow_qty: parseInt($tr.find('.f-allow-qty').val(), 10) || 0
				};
			});
			$tr.find('.nudgesells-remove').on('click', function () { state.addons.splice(i, 1); renderAddons(); });
		});
	}
	$(document).on('click', '.nudgesells-add-row[data-repeater="addons"]', function () {
		state.addons.push({ product_id: 0, discount_type: 'percent', discount_value: 0, label: '', subline: '', allow_qty: 0 });
		renderAddons();
	});

	$(document).on('change', '#nudgesells-addons-selection-type', function () {
		state.addons_selection_type = $(this).val();
	});

	function renderBundleValueCell() {
		var type = $('#nudgesells-bundle-type').val();
		var $cell = $('#nudgesells-bundle-value-cell').empty();
		if ('free_product' === type) {
			$cell.append($('<select id="nudgesells-bundle-free-product" style="width:100%">' + giftProductOptionsHtml(state.bundle_discount.free_product_id) + '</select>'));
		} else {
			$cell.append($('<input type="number" step="0.01" min="0" id="nudgesells-bundle-value" style="width:100%">').val(state.bundle_discount.value || 0));
		}
	}
	function renderBundle() {
		$('#nudgesells-bundle-enabled').prop('checked', !!state.bundle_discount.enabled);
		$('#nudgesells-bundle-type').val(state.bundle_discount.type || 'percent');
		renderBundleValueCell();
		$('#nudgesells-bundle-label').val(state.bundle_discount.label || '');
		$('#nudgesells-bundle-progress-label').val(state.bundle_discount.progress_label || '');
		toggleBundleFields();
	}
	function toggleBundleFields() {
		$('#nudgesells-bundle-fields-wrap').toggle($('#nudgesells-bundle-enabled').is(':checked'));
	}
	function syncBundleState() {
		var type = $('#nudgesells-bundle-type').val();
		state.bundle_discount = {
			enabled: $('#nudgesells-bundle-enabled').is(':checked'),
			type: type,
			value: 'free_product' === type ? 0 : (parseFloat($('#nudgesells-bundle-value').val()) || 0),
			free_product_id: 'free_product' === type ? (parseInt($('#nudgesells-bundle-free-product').val(), 10) || 0) : 0,
			label: $('#nudgesells-bundle-label').val(),
			progress_label: $('#nudgesells-bundle-progress-label').val()
		};
	}
	$(document).on('change', '#nudgesells-bundle-type', function () {
		renderBundleValueCell();
		syncBundleState();
	});
	$(document).on('change input', '#nudgesells-bundle-enabled,#nudgesells-bundle-value,#nudgesells-bundle-free-product,#nudgesells-bundle-label,#nudgesells-bundle-progress-label', function () {
		syncBundleState();
		if ('nudgesells-bundle-enabled' === this.id) {
			toggleBundleFields();
		}
	});

	function giftProductOptionsHtml(selectedId) {
		var html = '<option value="0">' + (NudgeSells_Admin.i18n.select_gift_product || 'Select an add-on...') + '</option>';
		state.addons.forEach(function (addon) {
			if (! addon.product_id) {
				return;
			}
			var label = NudgeSells_Admin.product_labels[addon.product_id] || ('#' + addon.product_id);
			var selected = parseInt(selectedId, 10) === parseInt(addon.product_id, 10) ? ' selected' : '';
			html += '<option value="' + addon.product_id + '"' + selected + '>' + label + '</option>';
		});
		return html;
	}

	var TIER_UI_TYPES = {
		percent:            { reward_target: 'all_selected', reward_shape: 'percent' },
		fixed:              { reward_target: 'all_selected', reward_shape: 'fixed' },
		fixed_price:        { reward_target: 'all_selected', reward_shape: 'fixed_price' },
		free_gift:          { reward_target: 'specific_product', reward_shape: 'free_all' },
		free_units_gift:    { reward_target: 'specific_product', reward_shape: 'free_units' }
	};

	function tierUiType(row) {
		var target = row.reward_target || 'all_selected';
		var shape  = row.reward_shape || 'percent';
		if ('specific_product' === target) {
			return 'free_units' === shape ? 'free_units_gift' : 'free_gift';
		}
		return 'free_units' === shape ? 'percent' : shape;
	}

	function renderTierValueCell(row) {
		var uiType = tierUiType(row);
		if ('free_gift' === uiType) {
			return $('<select class="f-value f-gift-product" style="width:100%">' + giftProductOptionsHtml(row.gift_product_id) + '</select>');
		}
		if ('free_units_gift' === uiType) {
			return $('<div class="nudgesells-tier-gift-units" style="display:flex;gap:6px;align-items:center;"></div>').append(
				$('<select class="f-gift-product" style="flex:1 1 auto;min-width:0;">' + giftProductOptionsHtml(row.gift_product_id) + '</select>'),
				$('<input type="number" step="1" min="1" class="f-value f-free-qty" style="flex:0 0 70px;" placeholder="' + (NudgeSells_Admin.i18n.free_qty_placeholder || 'e.g. 2') + '">').val(row.free_qty || '')
			);
		}
		return $('<input type="number" step="0.01" min="0" class="f-value" style="width:100%">').val(row.discount_value || 0);
	}

	$(document).on('change', '#nudgesells-tiers-repeat-scale', function () {
		state.tiers_repeat_scale = $(this).is(':checked');
	});

	function renderTiers() {
		var $tbody = $('#nudgesells-tiers-table tbody').empty();
		state.tiers.forEach(function (row, i) {
			var $tr = $('<tr></tr>');
			var $valueTd = $('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_value).append(renderTierValueCell(row));
			var $typeSelect = $(
				'<select class="f-type">' +
				'<option value="percent">' + (NudgeSells_Admin.i18n.percent_off || '% off') + '</option>' +
				'<option value="fixed">' + (NudgeSells_Admin.i18n.fixed_off || NudgeSells_Admin.currency_symbol + ' off') + '</option>' +
				'<option value="fixed_price">' + (NudgeSells_Admin.i18n.fixed_price || 'Fixed price') + '</option>' +
				'<option value="free_gift">' + (NudgeSells_Admin.i18n.free_gift || 'Free gift (specific product)') + '</option>' +
				'<option value="free_units_gift">' + (NudgeSells_Admin.i18n.free_units_gift || 'Free units of a specific product') + '</option>' +
				'</select>'
			).val(tierUiType(row));
			$tr.append(
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_min_qty).append($('<input type="number" min="1" step="1" class="f-min" style="width:100%">').val(row.min_qty || 1)),
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_type).append($typeSelect),
				$valueTd,
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_tier_label).append($('<input type="text" class="f-label" style="width:100%" placeholder="e.g. Only {qty} left for free shipping!">').val(row.label || '')),
				$('<td></td>').append($('<button type="button" class="button-link nudgesells-remove">✕</button>'))
			);
			$tbody.append($tr);

			function syncRowState() {
				var uiType = $tr.find('.f-type').val();
				var mapping = TIER_UI_TYPES[uiType] || TIER_UI_TYPES.percent;
				var usesFreeQty = ('free_units' === uiType || 'free_units_gift' === uiType);
				state.tiers[i] = {
					min_qty: parseInt($tr.find('.f-min').val(), 10) || 1,
					reward_target: mapping.reward_target,
					reward_shape: mapping.reward_shape,
					discount_value: (! usesFreeQty && 'free_gift' !== uiType) ? (parseFloat($tr.find('.f-value').val()) || 0) : 0,
					free_qty: usesFreeQty ? (parseInt($tr.find('.f-free-qty').val(), 10) || 0) : 0,
					gift_product_id: ('free_gift' === uiType || 'free_units_gift' === uiType) ? (parseInt($tr.find('.f-gift-product').val(), 10) || 0) : 0,
					label: $tr.find('.f-label').val()
				};
			}

			$tr.on('change', '.f-type', function () {
				var mapping = TIER_UI_TYPES[$(this).val()] || TIER_UI_TYPES.percent;
				state.tiers[i].reward_target = mapping.reward_target;
				state.tiers[i].reward_shape  = mapping.reward_shape;
				$valueTd.empty().append(renderTierValueCell(state.tiers[i]));
				syncRowState();
			});
			$tr.on('change input', '.f-min,.f-value,.f-gift-product,.f-free-qty,.f-label', syncRowState);
			$tr.find('.nudgesells-remove').on('click', function () { state.tiers.splice(i, 1); renderTiers(); });
		});
	}
	$(document).on('click', '.nudgesells-add-row[data-repeater="tiers"]', function () {
		state.tiers.push({ min_qty: 1, reward_target: 'all_selected', reward_shape: 'percent', discount_value: 0, free_qty: 0, gift_product_id: 0, label: '' });
		renderTiers();
	});

	function renderUpgrades() {
		var $tbody = $('#nudgesells-upgrades-table tbody').empty();
		state.upgrades.forEach(function (row, i) {
			var $tr = $('<tr></tr>');
			$tr.append(
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_upgrade_product).append(productSelect(row.product_id)),
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_type).append($('<select class="f-type"><option value="percent">%</option><option value="fixed">' + NudgeSells_Admin.currency_symbol + '</option><option value="fixed_price">' + (NudgeSells_Admin.i18n.fixed_price || 'Fixed price') + '</option></select>').val(row.discount_type || 'percent')),
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_value).append($('<input type="number" step="0.01" min="0" class="f-value" style="width:100%">').val(row.discount_value || 0)),
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_label).append($('<input type="text" class="f-label" style="width:100%" placeholder="' + (NudgeSells_Admin.i18n.badge_placeholder || 'e.g. Bestseller') + '">').val(row.label || '')),
				$('<td></td>').attr('data-label', NudgeSells_Admin.i18n.col_sublabel).append($('<input type="text" class="f-sublabel" style="width:100%" placeholder="e.g. Save 20% + free shipping">').val(row.sublabel || '')),
				$('<td></td>').append($('<button type="button" class="button-link nudgesells-remove">✕</button>'))
			);
			$tbody.append($tr);
			initProductSelect2($tr.find('.nudgesells-product-search'));

			$tr.find('.nudgesells-product-search').on('select2:select', function (e) {
				if (e.params && e.params.data) {
					NudgeSells_Admin.product_labels[e.params.data.id] = e.params.data.text;
				}
			});

			$tr.on('change input', 'select,input', function () {
				state.upgrades[i] = {
					product_id: parseInt($tr.find('.nudgesells-product-search').val(), 10) || 0,
					discount_type: $tr.find('.f-type').val(),
					discount_value: parseFloat($tr.find('.f-value').val()) || 0,
					label: $tr.find('.f-label').val(),
					sublabel: $tr.find('.f-sublabel').val()
				};
			});
			$tr.find('.nudgesells-remove').on('click', function () { state.upgrades.splice(i, 1); renderUpgrades(); });
		});
	}
	$(document).on('click', '.nudgesells-add-row[data-repeater="upgrades"]', function () {
		state.upgrades.push({ product_id: 0, discount_type: 'percent', discount_value: 0, label: '', sublabel: '' });
		renderUpgrades();
	});

	var iconFrames = {};

	$(document).on('click', '.nudgesells-select-icon', function (e) {
		e.preventDefault();
		if (typeof wp === 'undefined' || !wp.media) {
			return;
		}
		var target = $(this).data('target');

		if (!iconFrames[target]) {
			iconFrames[target] = wp.media({
				title: NudgeSells_Admin.i18n.select_icon_title || 'Select Icon',
				button: { text: NudgeSells_Admin.i18n.select_icon_button || 'Use this icon' },
				multiple: false,
				library: { type: 'image' }
			});
			iconFrames[target].on('select', function () {
				var attachment = iconFrames[target].state().get('selection').first().toJSON();
				var previewUrl = (attachment.sizes && attachment.sizes.thumbnail) ? attachment.sizes.thumbnail.url : attachment.url;
				$('#nudgesells-' + target + '-icon-id').val(attachment.id);
				$('#nudgesells-' + target + '-icon-preview').attr('src', previewUrl).show();
				$('.nudgesells-remove-icon[data-target="' + target + '"]').show();
			});
		}
		iconFrames[target].open();
	});

	$(document).on('click', '.nudgesells-remove-icon', function (e) {
		e.preventDefault();
		var target = $(this).data('target');
		$('#nudgesells-' + target + '-icon-id').val('');
		$('#nudgesells-' + target + '-icon-preview').attr('src', '').hide();
		$(this).hide();
	});

	$('#post').on('submit', function () {
		var $selectionType = $('#nudgesells-addons-selection-type');
		if ($selectionType.length) {
			state.addons_selection_type = $selectionType.val();
		}
		var $repeatScale = $('#nudgesells-tiers-repeat-scale');
		if ($repeatScale.length) {
			state.tiers_repeat_scale = $repeatScale.is(':checked');
		}
		$('#nudgesells-rules-json').val(JSON.stringify(state));
		syncScopeHiddenFields();
	});

	renderAddons();
	renderBundle();
	renderTiers();
	renderUpgrades();
	initScope();
})(jQuery);
