/**
 * Easy Search Replace — admin JS (v2.0)
 *
 * Handles:
 *   - Rule add / delete with clean re-indexing.
 *   - Per-rule collapse toggle (entire body).
 *   - Per-section collapse toggle (targeting, matching, schedule, audience).
 *   - Enable/disable toggle live UI updates.
 *   - Rule header preview (find → replace chips) updating on input.
 *   - Select2 initialization on post-type / role selects.
 */
(function ($) {
	'use strict';

	/* ================================================================
	 * Toast auto-dismiss (runs on all plugin pages, even without rules)
	 * ============================================================== */

	function initToasts() {
		$('.esr-toast').each(function () {
			var $t      = $(this);
			var timeout = parseInt($t.attr('data-auto-dismiss'), 10) || 0;

			// Manual close button.
			$t.on('click', '.esr-toast-close', function () {
				dismiss($t);
			});

			// Hover pauses the auto-dismiss so users can read long messages.
			var timer = null;
			function schedule() {
				if (timeout > 0) {
					timer = setTimeout(function () { dismiss($t); }, timeout);
				}
			}
			$t.on('mouseenter', function () { if (timer) { clearTimeout(timer); timer = null; } });
			$t.on('mouseleave', schedule);
			schedule();
		});

		function dismiss($t) {
			if ($t.hasClass('esr-toast-leaving')) {
				return;
			}
			$t.addClass('esr-toast-leaving');
			setTimeout(function () { $t.remove(); }, 220);
		}
	}

	$(function () {
		initToasts();

		var $rulesContainer = $('.esr-rules');
		if ($rulesContainer.length === 0) {
			// Not on the Rules tab - nothing else to wire up.
			return;
		}

		var L10N = (typeof window.esrnAdminL10n === 'object' && window.esrnAdminL10n) || {};
		var RULE_LABEL          = L10N.ruleLabel          || 'Rule %d';
		var SELECT2_PLACEHOLDER = L10N.select2Placeholder || 'Select…';

		var SELECT2_OPTS = {
			placeholder: SELECT2_PLACEHOLDER,
			width: '100%'
		};

		/* ============================================================
		 * Select2 init / destroy
		 * ========================================================== */

		function initSelect2($scope) {
			$scope.find('.esr-post-type-select, .esr-role-select').each(function () {
				var $sel = $(this);
				if (!$sel.hasClass('select2-hidden-accessible')) {
					$sel.select2(SELECT2_OPTS);
				}
			});
		}

		function destroySelect2($scope) {
			$scope.find('.esr-post-type-select.select2-hidden-accessible, .esr-role-select.select2-hidden-accessible').select2('destroy');
		}

		/* ============================================================
		 * Re-indexing after add / delete
		 * ========================================================== */

		function reindexRules() {
			$rulesContainer.find('.esr-rule').each(function (newIndex) {
				var $rule = $(this);
				$rule.attr('data-rule-index', newIndex);
				$rule.find('.esr-rule-badge').text(RULE_LABEL.replace('%d', newIndex + 1));

				$rule.find('input, textarea, select').each(function () {
					var name = this.getAttribute('name');
					if (name) {
						// Replace [N] (first occurrence only, since nested arrays share the prefix).
						this.setAttribute('name', name.replace(/\[\d+\]/, '[' + newIndex + ']'));
					}
					var id = this.getAttribute('id');
					if (id && /_\d+$/.test(id)) {
						this.setAttribute('id', id.replace(/_\d+$/, '_' + newIndex));
					}
				});

				$rule.find('label[for]').each(function () {
					var f = this.getAttribute('for');
					if (f && /_\d+$/.test(f)) {
						this.setAttribute('for', f.replace(/_\d+$/, '_' + newIndex));
					}
				});
			});
		}

		/* ============================================================
		 * Rule header preview (live)
		 * ========================================================== */

		function truncate(str, words) {
			var parts = (str || '').trim().split(/\s+/);
			if (parts.length <= words) {
				return parts.join(' ');
			}
			return parts.slice(0, words).join(' ') + '…';
		}

		function updatePreview($rule) {
			var $search  = $rule.find('textarea[name="esrn_search_replace_search[]"]');
			var $replace = $rule.find('textarea[name="esrn_search_replace_replace[]"]');
			var $preview = $rule.find('.esr-rule-preview');
			var s = $search.val() || '';
			var r = $replace.val() || '';
			if (!s) {
				$preview.empty();
				return;
			}
			var rhs = r ? $('<code/>').text(truncate(r, 6)) : $('<em/>').text('remove');
			$preview.empty()
				.append($('<code/>').text(truncate(s, 6)))
				.append($('<span class="esr-rule-arrow"/>').text('→'))
				.append(rhs);
		}

		/* ============================================================
		 * Initial setup
		 * ========================================================== */

		initSelect2($rulesContainer);
		$rulesContainer.find('.esr-rule').each(function () { updatePreview($(this)); });

		/* ============================================================
		 * Add rule
		 * ========================================================== */

		$(document).on('click', '#esr-add-field', function (e) {
			e.preventDefault();

			var $last = $rulesContainer.find('.esr-rule').last();
			if ($last.length === 0) {
				return;
			}

			destroySelect2($last);
			var $clone = $last.clone();
			initSelect2($last);

			// Blank out field values in the clone.
			$clone.find('textarea, input[type="text"], input[type="date"], input[type="time"]').val('');
			$clone.find('input[type="checkbox"]').prop('checked', false);
			$clone.find('select[multiple] option').prop('selected', false);
			$clone.find('select:not([multiple])').each(function () {
				this.selectedIndex = 0;
			});

			// But keep the rule itself enabled by default.
			$clone.find('.esr-rule-toggle-input').prop('checked', true);
			$clone.removeClass('esr-rule-disabled esr-rule-collapsed');
			$clone.find('.esr-rule-toggle-label').text('Enabled');
			$clone.find('.esr-rule-preview').empty();

			// Collapse all sections on the new card for cleanliness.
			$clone.find('.esr-section').not('.esr-section-main').removeClass('esr-section-open');
			// Between-mode fields default to hidden on a fresh rule.
			$clone.find('.esr-between-fields').hide();

			$clone.insertAfter($last);
			reindexRules();
			initSelect2($clone);
		});

		/* ============================================================
		 * Delete rule
		 * ========================================================== */

		$(document).on('click', '.esr-rule-delete', function (e) {
			e.preventDefault();
			var $rule = $(this).closest('.esr-rule');
			if ($rulesContainer.find('.esr-rule').length <= 1) {
				// Keep at least one rule on screen. Just clear it.
				$rule.find('textarea, input[type="text"], input[type="date"], input[type="time"]').val('');
				$rule.find('input[type="checkbox"]').prop('checked', false);
				$rule.find('.esr-rule-toggle-input').prop('checked', true);
				$rule.find('select[multiple] option').prop('selected', false);
				$rule.find('select:not([multiple])').each(function () { this.selectedIndex = 0; });
				$rule.find('.esr-post-type-select, .esr-role-select').trigger('change');
				$rule.find('.esr-rule-preview').empty();
				return;
			}
			destroySelect2($rule);
			$rule.remove();
			reindexRules();
		});

		/* ============================================================
		 * Rule body collapse / expand
		 * ========================================================== */

		$(document).on('click', '.esr-rule-collapse', function (e) {
			e.preventDefault();
			$(this).closest('.esr-rule').toggleClass('esr-rule-collapsed');
		});

		/* ============================================================
		 * Section collapse / expand
		 * ========================================================== */

		$(document).on('click', '.esr-section-head', function (e) {
			e.preventDefault();
			var $section = $(this).closest('.esr-section');
			if ($section.hasClass('esr-section-main')) {
				return; // Main section isn't collapsible.
			}
			$section.toggleClass('esr-section-open');
		});

		/* ============================================================
		 * Enable / disable toggle
		 * ========================================================== */

		$(document).on('change', '.esr-rule-toggle-input', function () {
			var $rule  = $(this).closest('.esr-rule');
			var $label = $rule.find('.esr-rule-toggle-label');
			if (this.checked) {
				$rule.removeClass('esr-rule-disabled');
				$label.text('Enabled');
			} else {
				$rule.addClass('esr-rule-disabled');
				$label.text('Disabled');
			}
		});

		/* ============================================================
		 * "Match between" toggle: show/hide its fields and mutually
		 * exclude with the regex checkbox in the same rule card.
		 * ========================================================== */

		$(document).on('change', '.esr-between-toggle', function () {
			var $rule    = $(this).closest('.esr-rule');
			var $fields  = $rule.find('.esr-between-fields');
			var $regexCb = $rule.find('.esr-regex-toggle');
			if (this.checked) {
				$fields.slideDown(150);
				if ($regexCb.length && $regexCb.prop('checked')) {
					$regexCb.prop('checked', false);
				}
			} else {
				$fields.slideUp(150);
			}
		});

		// Inverse direction: turning regex on disables "between".
		$(document).on('change', '.esr-regex-toggle', function () {
			if (!this.checked) {
				return;
			}
			var $rule      = $(this).closest('.esr-rule');
			var $betweenCb = $rule.find('.esr-between-toggle');
			if ($betweenCb.length && $betweenCb.prop('checked')) {
				$betweenCb.prop('checked', false).trigger('change');
			}
		});

		/* ============================================================
		 * Live preview as user types find / replace
		 * ========================================================== */

		$(document).on('input', 'textarea[name="esrn_search_replace_search[]"], textarea[name="esrn_search_replace_replace[]"]', function () {
			updatePreview($(this).closest('.esr-rule'));
		});

		/* ============================================================
		 * Post IDs — digits + commas only on blur
		 * ========================================================== */

		$(document).on('blur', 'input[name^="esrn_search_replace_post_ids"], input[name^="esrn_search_replace_exclude_post_ids"]', function () {
			var cleaned = ($(this).val() || '')
				.replace(/[^0-9,]/g, '')
				.replace(/,+/g, ',')
				.replace(/^,|,$/g, '');
			$(this).val(cleaned);
		});

		/* ============================================================
		 * URLs — trim lines, drop empties
		 * ========================================================== */

		$(document).on('blur', 'textarea[name^="esrn_search_replace_urls"], textarea[name^="esrn_search_replace_exclude_urls"]', function () {
			var lines = ($(this).val() || '').split(/\r?\n/)
				.map(function (l) { return $.trim(l); })
				.filter(function (l) { return l.length > 0; });
			$(this).val(lines.join('\n'));
		});

		/* ============================================================
		 * Auto-grow textareas
		 * ========================================================== */

		$(document).on('input', '.esr-wrap textarea', function () {
			this.style.height = 'auto';
			this.style.height = (this.scrollHeight + 2) + 'px';
		});
	});
})(jQuery);
