<%
local api = require "luci.passwall.api"
-%>

<script type="text/javascript">
	//<![CDATA[
	function ajax_add_node(link, group) {
		const chunkSize = 1000;  // 分片发送以突破uhttpd的限制，每块1000字符
		const totalChunks = Math.ceil(link.length / chunkSize);
		let currentChunk = 0;

		function sendNextChunk() {
			if (currentChunk < totalChunks) {
				const chunk = link.substring(currentChunk * chunkSize, (currentChunk + 1) * chunkSize);
				const xhr = new XMLHttpRequest();
				xhr.open('POST', '<%=api.url("link_add_node")%>', true);
				xhr.onload = function () {
					if (xhr.status === 200) {
						currentChunk++;
						sendNextChunk();
					} else {
						alert("<%:Error%>");
						return;
					}
				};
				xhr.onerror = function () {
					alert("<%:Network Error%>");
					return;
				};
				const formData = new FormData();
				formData.append("chunk", chunk);
				formData.append("chunk_index", currentChunk);
				formData.append("total_chunks", totalChunks);
				formData.append("group", group);
				xhr.send(formData);
			} else {
				window.location.href = '<%=api.url("node_list")%>';
			}
		}
		sendNextChunk();
	}

	function getBg(el) {
		if (!el) return null;
		const style = getComputedStyle(el);
		const bgImage = style.backgroundImage;
		const bgColor = style.backgroundColor;
		return (bgImage !== 'none' || !/rgba\([^,]+,[^,]+,[^,]+,\s*0\)/.test(bgColor) && bgColor !== 'transparent')
			? style.background
			: null;
	};

	function open_add_link_div() {
		document.body.classList.add('modal-open');
		document.getElementById('modal-mask').style.display = 'block';
		const addLinkDiv = document.getElementById("add_link_div");
		addLinkDiv.style.background = getBg(document.querySelector('.cbi-section')) || getBg(document.body) || '';
		addLinkDiv.style.display = "block";
		if (!addLinkDiv._dropdown_inited) {
			addLinkDiv._dropdown_inited = true;
			dropdown_list_fun("addlink_group_custom");
		}
		document.getElementById("nodes_link").focus();
	}

	function close_add_link_div() {
		document.getElementById('modal-mask').style.display = 'none';
		document.getElementById("add_link_div").style.display = "none";
		document.body.classList.remove('modal-open');
	}

	function add_node() {
		let nodes_link = document.getElementById("nodes_link").value;
		const group = (document.querySelector('#addlink_group_custom input[type="hidden"]')?.value || "default");
		nodes_link = nodes_link.replace(/\t/g, "").replace(/\r\n|\r/g, "\n").replace(/<[^>]*>/g, '').trim();
		if (nodes_link != "") {
			let s = nodes_link.split('://');
			if (s.length > 1) {
				ajax_add_node(nodes_link, group);
			}
			else {
				alert("<%:Please enter the correct link.%>");
			}
		}
		else {
			document.getElementById("nodes_link").focus();
		}
	}

	function clear_all_nodes() {
		if (confirm('<%:Are you sure to clear all nodes?%>') == true){
			XHR.get('<%=api.url("clear_all_nodes")%>', null,
			function(x, data) {
				if(x && x.status == 200) {
					window.location.href = '<%=api.url("node_list")%>';
				}
				else {
					alert("<%:Error%>");
				}
			});
		}
	}

	function open_reassign_group_div() {
		const ids = [];
		const visibleContainer = document.querySelector('#cbi-passwall-nodes > .cbi-tabcontainer[style*="display:block"], #cbi-passwall-nodes > .cbi-tabcontainer[style*="display: block"]');
		if (!visibleContainer) return;
		const doms = visibleContainer.getElementsByClassName("nodes_select");
		if (doms && doms.length > 0) {
			for (let i = 0 ; i < doms.length; i++) {
				if (doms[i].checked) {
					ids.push(doms[i].getAttribute("cbid"))
				}
			}
			if (ids.length > 0) {
				document.body.classList.add('modal-open');
				document.getElementById('modal-mask').style.display = 'block';
				const reassignGroupDiv = document.getElementById("reassign_group_div");
				reassignGroupDiv.style.background = getBg(document.querySelector('.cbi-section')) || getBg(document.body) || '';
				reassignGroupDiv.style.display = "block";
				if (!reassignGroupDiv._dropdown_inited) {
					reassignGroupDiv._dropdown_inited = true;
					dropdown_list_fun("reassign_group_custom");
				}
			} else {
				alert("<%:You no select nodes !%>");
			}
		}
	}

	function close_reassign_group_div() {
		document.getElementById('modal-mask').style.display = 'none';
		document.getElementById("reassign_group_div").style.display = "none";
		document.body.classList.remove('modal-open');
	}

	function reassign_group() {
		const ids = [];
		const group = (document.querySelector('#reassign_group_custom input[type="hidden"]')?.value || "default");
		const visibleContainer = document.querySelector('#cbi-passwall-nodes > .cbi-tabcontainer[style*="display:block"], #cbi-passwall-nodes > .cbi-tabcontainer[style*="display: block"]');
		if (!visibleContainer) return;
		const doms = visibleContainer.getElementsByClassName("nodes_select");
		if (doms && doms.length > 0) {
			for (let i = 0 ; i < doms.length; i++) {
				if (doms[i].checked) {
					ids.push(doms[i].getAttribute("cbid"))
				}
			}
			if (ids.length > 0) {
				XHR.get('<%=api.url("reassign_group")%>', {
					group: group,
					ids: ids.join(",")
				},
				function(x, data) {
					if (x && x.status == 200) {
						window.location.href = '<%=api.url("node_list")%>';
					}
					else {
						alert("<%:Error%>");
					}
				});
			}
		}
	}

	//自定义分组下拉列表事件
	function dropdown_list_fun(div_id) {
		const dropdown = document.getElementById(div_id);
		if (!dropdown) return;

		const display = dropdown.querySelector(".selected-display");
		const displayText = display.querySelector(".text");
		const list = dropdown.querySelector(".dropdown-list");
		const hidden = dropdown.querySelector('input[type="hidden"]');
		const input = dropdown.querySelector(".create-item-input");

		display.addEventListener("click", function() {
			list.style.display = list.style.display === "none" ? "block" : "none";
			input.value = "";
			//input.focus();
		});

		function selectItem(li) {
			list.querySelectorAll(".dropdown-item").forEach(function(el){
				el.classList.remove("selected");
			});
			li.classList.add("selected");
			hidden.value = li.dataset.value;
			displayText.textContent = li.dataset.value || "<%:default%>";
			list.style.display = "none";
		}

		list.addEventListener("click", function(e){
			const li = e.target.closest(".dropdown-item");
			if (!li || li.classList.contains("custom-input")) return;
			selectItem(li);
		});

		input.addEventListener("keydown", function(e){
			const isEnter = e.key === "Enter" || e.keyCode === 13;
			if (!isEnter) return;
			e.stopPropagation();
			e.preventDefault();

			const val = input.value.trim();
			if (!val) return;

			if (val.toLowerCase() === "default") {
				const emptyLi = Array.from(list.querySelectorAll(".dropdown-item"))
					.find(function(el){ return !el.dataset.value; });
				if (emptyLi) selectItem(emptyLi);
				input.value = "";
				return;
			}

			let li = Array.from(list.querySelectorAll(".dropdown-item")).find(function(el){
				return el.dataset.value && el.dataset.value.toLowerCase() === val.toLowerCase();
			});
			if (!li) {
				li = document.createElement("li");
				li.className = "dropdown-item";
				li.dataset.value = val;
				li.textContent = val;
				list.insertBefore(li, input.parentNode); 
			}

			input.value = "";
			selectItem(li);
		});
		// 从tab中读取分组名称
		function InsertGroup(list, input) {
			const tabs = document.querySelectorAll(".cbi-tabmenu li");
			if (!tabs.length) {
				setTimeout(() => InsertGroup(list, input), 50);
				return;
			}

			tabs.forEach(function(li){
				const group = li.id.split('.').pop();
				if(group === "default") return;
				if(Array.from(list.querySelectorAll(".dropdown-item")).some(el => el.dataset.value === group)) return;
				const newLi = document.createElement("li");
				newLi.className = "dropdown-item";
				newLi.dataset.value = group;
				newLi.textContent = group;
				list.insertBefore(newLi, input.parentNode);
			});
		}
		InsertGroup(list, input);

		// 点击外部时自动收起
		document.addEventListener("click", function(e) {
			if (!dropdown.contains(e.target)) {
				list.style.display = "none";
			}
		});
	}
	//]]>
</script>

<div id="modal-mask"></div>

<div id="add_link_div">
	<div id="add_link_modal_container">
		<h3><%:Add the node via the link%></h3>
		<div class="value-custom">
			<textarea id="nodes_link" rows="10"></textarea>
			<p id="nodes_link_text"><%:Enter share links, one per line. Subscription links are not supported!%></p>
		</div>
		<div class="value-custom">
			<div class="value-field-custom">
				<label class="value-title-custom" for="addlink_group_custom"><%:Group Name%></label>
				<div id="addlink_group_custom" class="custom-dropdown">
					<div class="selected-display">
						<span class="text"><%:default%></span>
						<span class="arrow-down-small"></span>
					</div>
					<ul class="dropdown-list" style="display:none;">
						<li class="dropdown-item selected" data-value=""><%:default%></li>
						<li class="dropdown-item custom-input">
							<input type="text" placeholder="-- <%:custom%> --" class="create-item-input" inputmode="text" enterkeyhint="done">
						</li>
					</ul>
					<input type="hidden" name="addlink_group" value="">
				</div>
			</div>
		</div>
		<div id="add_link_button_container">
			<input class="btn cbi-button cbi-button-add" type="button" onclick="add_node()" value="<%:Add%>" />
			<input class="btn cbi-button cbi-button-remove" type="button" onclick="close_add_link_div()" value="<%:Close%>" />
		</div>
	</div>
</div>

<div id="reassign_group_div">
	<div id="reassign_group_modal_container">
		<h3><%:Reassign Node Group%></h3>
		<div class="value-custom">
			<div class="value-field-custom">
				<label class="value-title-custom" for="reassign_group_custom"><%:Group Name%></label>
				<div id="reassign_group_custom" class="custom-dropdown">
					<div class="selected-display">
						<span class="text"><%:default%></span>
						<span class="arrow-down-small"></span>
					</div>
					<ul class="dropdown-list" style="display:none;">
						<li class="dropdown-item selected" data-value=""><%:default%></li>
						<li class="dropdown-item custom-input">
							<input type="text" placeholder="-- <%:custom%> --" class="create-item-input" inputmode="text" enterkeyhint="done">
						</li>
					</ul>
					<input type="hidden" name="to_group" value="">
				</div>
			</div>
		</div>
		<div id="reassign_group_button_container">
			<input class="btn cbi-button cbi-button-edit" type="button" onclick="reassign_group()" value="<%:Save%>" />
			<input class="btn cbi-button cbi-button-remove" type="button" onclick="close_reassign_group_div()" value="<%:Close%>" />
		</div>
	</div>
</div>



<div class="pw-toolbar">
	<div class="pw-toolbar-field">
		<input class="btn cbi-button cbi-button-add" type="button" onclick="to_add_node()" value="<%:Add%>" />
		<input class="btn cbi-button cbi-button-add" type="button" onclick="open_add_link_div()" value="<%:Add the node via the link%>" />
		<input class="btn cbi-button cbi-button-add" type="button" onclick="to_add_node('shunt')" value="<%:Add shunt policy%>" />
		<input class="btn cbi-button cbi-button-remove" type="button" onclick="clear_all_nodes()" value="<%:Clear all nodes%>" />
		<input class="btn cbi-button cbi-button-remove" type="button" onclick="delete_select_nodes()" value="<%:Delete select nodes%>" />
		<input class="btn cbi-button cbi-button-edit" type="button" id="select_all_btn" onclick="checked_all_node(this)" value="<%:Select all%>" />
		<input class="btn cbi-button cbi-button-edit" type="button" onclick="open_reassign_group_div()" value="<%:Reassign Group%>" />
		<input class="btn cbi-button cbi-button-apply" type="submit" name="cbi.apply" value="<%:Save & Apply%>" />
		<!--<input class="btn cbi-button cbi-button-save" type="submit" name="cbi.save" value="<%:Save%>" />-->
		<!--<input class="btn cbi-button cbi-button-reset" type="button" value="<%:Reset%>" onclick="location.href='<%=REQUEST_URI%>'" />-->
	</div>
</div>

<style>
	.pw-toolbar {
		width: 100%;
		text-align: center;
	}

	.pw-toolbar-field {
		width: 100%;
		text-align: center;
		display: inline-block;
		padding: 5px 0 5px;
	}

	#modal-mask {
		display: none;
		position: fixed;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		background: rgba(0,0,0,0.4);
		z-index: 999;
	}

	body.modal-open {
		overflow: hidden;
		pointer-events: none;
	}

	body.modal-open #add_link_div,
	body.modal-open #reassign_group_div {
		pointer-events: auto;
	}

	#add_link_div, #reassign_group_div {
		display: none;
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		background: white;
		padding: 20px;
		border: 2px solid #ccc;
		box-shadow: 0 0 10px rgba(0,0,0,0.5);
		z-index: 1000;
		width: 90%;
		max-width: 500px;
	}

	#add_link_modal_container, #reassign_group_modal_container {
		width: 100%;
		text-align: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: 20px;
	}

	#nodes_link {
		width: 100%;
		height: 180px;
		resize: vertical;
		font-family: monospace;
		padding: 5px;
		border: 1px solid #ccc;
		border-radius: 5px;
	}

	#add_link_div h3,
	#reassign_group_div h3 {
		background: inherit;
	}

	#nodes_link_text {
		color: red;
		font-size: 14px;
		margin-top: 5px;
		text-align: center;
		width: 100%;
	}

	#add_link_button_container, #reassign_group_button_container {
		display: flex;
		justify-content: space-between;
		width: 100%;
		max-width: 300px;
		margin-top: 10px;
	}

	.value-custom {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
		margin: 10px 0;
		padding: 0px 5px 0px 5px;
	}

	.value-field-custom {
		display: inline-flex;
		align-items: center;
		gap: 10px;
	}

	.value-title-custom {
		font-size: 13px;
		line-height: 28px;
		white-space: nowrap;
		text-align: right;
	}

	.custom-dropdown {
		position: relative;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		width: 180px;
		height: 28px;
		font-size: 13px;
		background: #fff;
		cursor: pointer;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}

	.selected-display {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 8px;
		width: 100%;
		height: 100%;
		box-sizing: border-box;
	}

	.selected-display:hover {
		background-color: #f7f7f7;
	}

	.selected-display {
		font-size: 12px;
		color: #666;
	}

	.dropdown-list {
		position: absolute;
		top: 100%;
		left: 0;
		width: 180px;
		border: 1px solid #d9d9d9;
		border-top: none;
		box-shadow: 0 1px 3px rgba(0,0,0,0.15);
		background: #fff;
		list-style: none;
		margin: 0;
		padding: 0;
		max-height: 200px;
		overflow-y: auto;
		overflow-x: hidden;
		z-index: 100;
		box-sizing: border-box;
	}

	.dropdown-item {
		padding: 4px 8px;
		line-height: 20px;
		cursor: pointer;
	}

	.dropdown-item.selected {
		background-color: #1e90ff;
		color: #fff;
	}

	.create-item-input::placeholder {
		text-align: center;
	}

	.dropdown-item.custom-input input {
		width: 100%;
		box-sizing: border-box;
		padding: 3px;
		font-size: 13px;
		line-height: 20px;
		border: 1px solid #ccc;
		text-align: left;
	}

	.arrow-down-small {
		width: 0;
		height: 0;
		border-left: 4px solid transparent;
		border-right: 4px solid transparent;
		border-top: 5px solid #555;
		display: inline-block;
		vertical-align: middle;
	}
</style>
