(function($) {
	'use strict';

	var config = window.seovaultseo_general || {};
	var i18n = config.i18n || {};

	function setStatus(element, message, state) {
		if (!element) {
			return;
		}
		element.textContent = message || '';
		element.style.color = 'error' === state ? '#d63638' : ('pending' === state ? '#2271b1' : '#00a32a');
	}

	function post(params) {
		return fetch(config.ajax_url, {
			method: 'POST',
			headers: {'Content-Type': 'application/x-www-form-urlencoded'},
			body: new URLSearchParams(params).toString(),
			credentials: 'same-origin'
		}).then(function(response) { return response.json(); });
	}

	function initTabs() {
		var links = document.querySelectorAll('.seovaultseo-vtab-link');
		var panels = document.querySelectorAll('.seovaultseo-vtab-panel');
		var activeTabInput = document.getElementById('seovaultseo-active-tab');
		var form = document.getElementById('seovaultseo-general-form');
		var validTargets = {};

		links.forEach(function(link) { validTargets[link.getAttribute('href')] = true; });

		function normalizeTarget(target) {
			if (!target) {
				return '';
			}
			if ('#' !== target.charAt(0)) {
				target = '#' + target;
			}
			return validTargets[target] ? target : '';
		}

		function activateTab(targetSelector, updateHash) {
			targetSelector = normalizeTarget(targetSelector);
			if (!targetSelector) {
				return;
			}
			var target = document.querySelector(targetSelector);
			var targetLink = document.querySelector('.seovaultseo-vtab-link[href="' + targetSelector + '"]');
			if (!target || !targetLink) {
				return;
			}
			links.forEach(function(item) { item.classList.remove('seovaultseo-vtab-active'); });
			panels.forEach(function(panel) { panel.classList.remove('is-active'); });
			targetLink.classList.add('seovaultseo-vtab-active');
			target.classList.add('is-active');
			if (activeTabInput) {
				activeTabInput.value = targetSelector.substring(1);
			}
			if (updateHash && window.history && window.history.replaceState) {
				var url = new URL(window.location.href);
				url.searchParams.set('tab', targetSelector.substring(1));
				url.hash = targetSelector;
				window.history.replaceState(null, '', url.pathname + url.search + url.hash);
			}
		}

		links.forEach(function(link) {
			link.addEventListener('click', function(event) {
				event.preventDefault();
				activateTab(link.getAttribute('href'), true);
			});
		});
		if (form) {
			form.addEventListener('submit', function() {
				var submitTarget = normalizeTarget(activeTabInput ? activeTabInput.value : window.location.hash) || '#vtab-connection';
				if (activeTabInput) {
					activeTabInput.value = submitTarget.substring(1);
				}
				form.action = form.action.replace(/#.*$/, '') + submitTarget;
			});
		}
		var initialTarget = normalizeTarget(window.location.hash);
		if (!initialTarget) {
			initialTarget = normalizeTarget(new URLSearchParams(window.location.search).get('tab'));
		}
		if (!initialTarget && activeTabInput) {
			initialTarget = normalizeTarget(activeTabInput.value);
		}
		if (initialTarget) {
			activateTab(initialTarget, false);
		}
	}

	function init404Exclusions() {
		var container = document.getElementById('seovaultseo-404-excludes');
		var addButton = document.getElementById('seovaultseo-404-add-exclude');
		if (!container || !addButton) {
			return;
		}
		var index = container.querySelectorAll('.seovaultseo-404-exclude-row').length;
		addButton.addEventListener('click', function() {
			var row = document.createElement('div');
			row.className = 'seovaultseo-404-exclude-row';
			row.style.cssText = 'display:flex;gap:8px;margin-bottom:8px;align-items:center;';

			var input = document.createElement('input');
			input.type = 'text';
			input.name = 'monitor404_excludes[' + index + '][pattern]';
			input.placeholder = 'e.g. /wp-content/';
			input.className = 'regular-text';

			var select = document.createElement('select');
			select.name = 'monitor404_excludes[' + index + '][comparison]';
			select.className = 'seovaultseo-select seovaultseo-select-small';
			[['contains', i18n.contains], ['exact', i18n.exact], ['starts', i18n.starts], ['ends', i18n.ends], ['regex', i18n.regex]].forEach(function(item) {
				var option = document.createElement('option');
				option.value = item[0];
				option.textContent = item[1];
				select.appendChild(option);
			});

			var remove = document.createElement('button');
			remove.type = 'button';
			remove.className = 'button seovaultseo-404-exclude-remove';
			remove.textContent = i18n.remove;
			row.appendChild(input);
			row.appendChild(select);
			row.appendChild(remove);
			container.appendChild(row);
			index += 1;
			if (window.seovaultInitSelects) {
				window.seovaultInitSelects($(row));
			}
		});
		container.addEventListener('click', function(event) {
			var remove = event.target.closest('.seovaultseo-404-exclude-remove');
			if (remove) {
				remove.closest('.seovaultseo-404-exclude-row').remove();
			}
		});

		var filter = document.getElementById('seovaultseo-404-filter');
		if (filter) {
			filter.querySelectorAll('input[name="s"], input[type="submit"]').forEach(function(element) {
				element.setAttribute('form', 'seovaultseo-404-filter-form');
			});
		}
	}

	function initConditionalRows() {
		var scorePosition = document.getElementById('frontend_score_position');
		var scoreInfo = document.getElementById('seovault-seo-score-shortcode-info');
		if (scorePosition && scoreInfo) {
			var toggleScoreInfo = function() { scoreInfo.style.display = 'custom' === scorePosition.value ? 'block' : 'none'; };
			scorePosition.addEventListener('change', toggleScoreInfo);
			toggleScoreInfo();
		}

		var policy = document.getElementById('robots_policy');
		var robotsRow = document.getElementById('robots-custom-content-row');
		if (policy && robotsRow) {
			policy.addEventListener('change', function() { robotsRow.style.display = 'custom' === policy.value ? '' : 'none'; });
		}
	}

	function initRobotsPreview() {
		var button = document.getElementById('seovaultseo-robots-preview-btn');
		var output = document.getElementById('seovaultseo-robots-preview-output');
		var link = document.getElementById('seovaultseo-robots-preview-link');
		if (!button || !output || !config.ajax_url || !config.robots_nonce) {
			return;
		}
		button.addEventListener('click', function(event) {
			event.preventDefault();
			button.disabled = true;
			output.style.display = 'none';
			if (link) { link.style.display = 'none'; }
			var policy = document.getElementById('robots_policy');
			var custom = document.getElementById('robots_custom_content');
			post({
				action: 'seovaultseo_robots_preview',
				nonce: config.robots_nonce,
				policy: policy ? policy.value : '',
				custom_content: custom ? custom.value : ''
			}).then(function(response) {
				button.disabled = false;
				if (response.success && response.data && 'undefined' !== typeof response.data.preview) {
					output.textContent = response.data.preview || i18n.no_custom_rules;
					if (link) { link.style.display = 'block'; }
				} else {
					output.textContent = i18n.preview_failed;
				}
				output.style.display = 'block';
			}).catch(function() {
				button.disabled = false;
				output.textContent = i18n.request_failed;
				output.style.display = 'block';
			});
		});
	}

	function initIndexNow() {
		var submit = document.getElementById('seovaultseo-indexnow-submit-btn');
		var textarea = document.getElementById('seovaultseo-indexnow-urls');
		var result = document.getElementById('seovaultseo-indexnow-submit-result');
		if (submit && textarea && result && config.indexnow_nonce) {
			submit.addEventListener('click', function(event) {
				event.preventDefault();
				if (!textarea.value.trim()) {
					setStatus(result, i18n.enter_url, 'error');
					return;
				}
				submit.disabled = true;
				setStatus(result, i18n.submitting, 'pending');
				post({action: 'seovaultseo_indexnow_submit', nonce: config.indexnow_nonce, urls: textarea.value})
					.then(function(response) {
						submit.disabled = false;
						if (response.success) {
							setStatus(result, response.data.message, 'success');
							textarea.value = '';
						} else {
							setStatus(result, (response.data && response.data.message) || i18n.submission_failed, 'error');
						}
					})
					.catch(function() {
						submit.disabled = false;
						setStatus(result, i18n.request_failed, 'error');
					});
			});
		}

		var clear = document.getElementById('seovaultseo-indexnow-clear-log-btn');
		if (clear && config.indexnow_nonce) {
			clear.addEventListener('click', function(event) {
				event.preventDefault();
				clear.disabled = true;
				post({action: 'seovaultseo_indexnow_clear_log', nonce: config.indexnow_nonce})
					.then(function(response) {
						if (response.success) {
							window.location.reload();
						} else {
							clear.disabled = false;
						}
					})
					.catch(function() { clear.disabled = false; });
			});
		}
	}

	document.addEventListener('click', function(event) {
		var confirmTarget = event.target.closest('[data-seovaultseo-confirm]');
		if (confirmTarget && !window.confirm(confirmTarget.getAttribute('data-seovaultseo-confirm'))) {
			event.preventDefault();
			return;
		}
		var selectTarget = event.target.closest('.seovaultseo-select-on-click');
		if (selectTarget) {
			selectTarget.select();
		}
		var shortcode = event.target.closest('.seovaultseo-copy-shortcode');
		if (shortcode && navigator.clipboard) {
			navigator.clipboard.writeText(shortcode.textContent.trim());
			shortcode.style.background = '#e0e0e0';
			window.setTimeout(function() { shortcode.style.background = '#f0f0f1'; }, 1000);
		}
	});

	document.addEventListener('DOMContentLoaded', function() {
		initTabs();
		init404Exclusions();
		initConditionalRows();
		initRobotsPreview();
		initIndexNow();
	});
}(jQuery));
