<%
local api = require "luci.passwall.api"
-%>
<script type="text/javascript">
	//<![CDATA[
	(function () {
		const startTime = Date.now();
		const TIMEOUT = 3000;

		const waitForDnsSelect = () => {
			const dns_select = document.querySelector("select[id*='dns_shunt']");
			if (dns_select) {
				initDnsSelect(dns_select);
				return;
			}
			if (Date.now() - startTime >= TIMEOUT) {
				return;
			}
			requestAnimationFrame(waitForDnsSelect);
		};
		waitForDnsSelect();

		const initDnsSelect = (dns_select) => {
			if (dns_select.value === "chinadns-ng") {
				addLogLink(dns_select);
			}
			if (dns_select._dnsLogBinded) return;
			dns_select._dnsLogBinded = true;

			dns_select.addEventListener("change", () => {
				const existingLogLink = dns_select.parentElement.querySelector("a.dns-log-link");
				if (existingLogLink) {
					existingLogLink.remove();
				}
				if (dns_select.value === "chinadns-ng") {
					addLogLink(dns_select);
				}
			});
		};

		const addLogLink = (select) => {
			if (select.parentElement.querySelector("a.dns-log-link")) {
				return;
			}
			const logLink = document.createElement("a");
			logLink.innerHTML = "<%:Log%>";
			logLink.href = "#";
			logLink.className = "dns-log-link";
			logLink.style.marginLeft = "10px";
			logLink.setAttribute("onclick", "window.open('" + '<%=api.url("get_chinadns_log") .. "?flag=" .. section%>' + "', '_blank')");
			select.insertAdjacentElement("afterend", logLink);
		};
	})();
	//]]>
</script>
