(function () {
	function getUiNonce() {
		var el = document.querySelector(".serpiq-settings-tabs");
		if (el && el.getAttribute) {
			var n = el.getAttribute("data-settings-ui-nonce");
			if (n) return n;
		}
		return "";
	}

	function getBaseUrl() {
		var el = document.querySelector(".serpiq-settings-tabs");
		if (el && el.getAttribute) {
			var base = el.getAttribute("data-base-url");
			if (base) return base;
		}
		try {
			var u = new URL(window.location.href);
			u.searchParams.delete("tab");
			u.searchParams.delete("_wpnonce");
			return u.toString();
		} catch (e) {
			return window.location.href;
		}
	}

	function show(tabId) {
		var tabs = document.querySelectorAll(".serpiq-settings-tab");
		var panels = document.querySelectorAll(".serpiq-settings-panel");
		for (var i = 0; i < tabs.length; i++) {
			var t = tabs[i];
			var isActive = t.getAttribute("data-tab") === tabId;
			if (t.classList) t.classList.toggle("serpiq-settings-tab-active", isActive);
		}
		for (var j = 0; j < panels.length; j++) {
			var p = panels[j];
			var isPanelActive = p.getAttribute("data-panel") === tabId;
			if (p.classList) p.classList.toggle("serpiq-settings-panel-active", isPanelActive);
		}

		var nonce = getUiNonce();
		if (!nonce) return;

		var base = getBaseUrl();
		var sep = base.indexOf("?") >= 0 ? "&" : "?";
		var next =
			base +
			sep +
			"tab=" +
			encodeURIComponent(tabId) +
			"&_wpnonce=" +
			encodeURIComponent(nonce);
		if (window.history && window.history.replaceState) {
			window.history.replaceState(null, "", next);
		}
	}

	function onClick(e) {
		var target = e.target;
		if (!target) return;
		if (target.closest) target = target.closest(".serpiq-settings-tab");
		if (!target || !target.getAttribute) return;
		var tabId = target.getAttribute("data-tab");
		if (!tabId) return;
		var nonce = getUiNonce();
		if (!nonce) return;
		if (e.preventDefault) e.preventDefault();
		show(tabId);
	}

	var list = document.querySelector(".serpiq-settings-tabs");
	if (list && list.addEventListener) {
		list.addEventListener("click", onClick);
	}
})();
