// Shared UI helpers (icons, toaster, range display, checkbox icons)
(function () {
	function tailwindIcon(name, cls = "w-4 h-4") {
		if (window.lucide && window.lucide.icons && window.lucide.icons[name]) {
			const svg = window.lucide.createElement(window.lucide.icons[name]);
			svg.setAttribute("class", cls);
			return svg.outerHTML;
		}
		return "";
	}
	window.tailwindIcon = tailwindIcon;

	class TailwindToaster {
		constructor() {
			this.container = document.createElement("div");
			this.container.className =
				"fixed bottom-5 right-5 z-50 flex flex-col gap-3 pointer-events-none max-w-sm w-full";
			document.body.appendChild(this.container);
		}
		createToast(message, type, iconName) {
			const styles = {
				success: {
					border: "border-green-500",
					icon: "text-green-500",
					bg: "bg-white dark:bg-slate-800",
					bar: "bg-green-500",
				},
				info: {
					border: "border-blue-500",
					icon: "text-blue-500",
					bg: "bg-white dark:bg-slate-800",
					bar: "bg-blue-500",
				},
				warning: {
					border: "border-yellow-500",
					icon: "text-yellow-500",
					bg: "bg-white dark:bg-slate-800",
					bar: "bg-yellow-500",
				},
				error: {
					border: "border-red-500",
					icon: "text-red-500",
					bg: "bg-white dark:bg-slate-800",
					bar: "bg-red-500",
				},
			};
			const s = styles[type] || styles.info;
			const toast = document.createElement("div");
			toast.className = `toast-enter pointer-events-auto relative overflow-hidden flex items-start gap-3 p-4 pb-5 rounded shadow-lg border-l-4 ${s.bg} ${s.border} dark:shadow-black/20 text-sm`;
			toast.innerHTML = `
        <div class="flex-shrink-0 pt-0.5">${tailwindIcon(
					iconName,
					`${s.icon} w-5 h-5`
				)}</div>
        <div class="flex-1">
          <p class="font-medium text-slate-800 dark:text-slate-100">${
						type[0].toUpperCase() + type.slice(1)
					}</p>
          <p class="text-slate-500 dark:text-slate-400 mt-0.5">${message}</p>
        </div>
        <button class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 transition-colors" onclick="this.parentElement.remove()">
          ${tailwindIcon("X", "w-4 h-4")}
        </button>
        <div class="absolute bottom-0 left-0 h-1 ${s.bar} toast-timer"></div>`;
			this.container.appendChild(toast);
			setTimeout(() => {
				if (toast.parentElement) {
					toast.style.opacity = "0";
					toast.style.transform = "translateX(100%)";
					toast.style.transition = "all 0.3s ease-in";
					setTimeout(() => toast.remove(), 300);
				}
			}, 4000);
		}
		success(msg) {
			this.createToast(msg, "success", "CheckCircle");
		}
		info(msg) {
			this.createToast(msg, "info", "Info");
		}
		warning(msg) {
			this.createToast(msg, "warning", "TriangleAlert");
		}
		error(msg) {
			this.createToast(msg, "error", "CircleX");
		}
	}
	window.toaster = new TailwindToaster();

	function initRangeDisplays() {
		document
			.querySelectorAll('input[type="range"][data-range-display]')
			.forEach((el) => {
				const target = document.querySelector(el.dataset.rangeDisplay);
				const input = el.dataset.rangeInput
					? document.querySelector(el.dataset.rangeInput)
					: null;
				const update = () => {
					const min = Number(el.min || 0);
					const max = Number(el.max || 100);
					const value = Number(el.value || 0);
					const percent = max > min ? ((value - min) / (max - min)) * 100 : 0;
					if (target) target.textContent = el.value + "%";
					if (input) input.value = el.value;
					el.style.accentColor = "hsl(var(--primary))";
					el.style.background = `linear-gradient(to right, hsl(var(--primary)) 0%, hsl(var(--primary)) ${percent}%, hsla(var(--foreground), 0.22) ${percent}%, hsla(var(--foreground), 0.22) 100%)`;
				};
				el.addEventListener("input", update);
				el.addEventListener("change", update);
				update();
			});
	}

	function initCheckboxIcons() {
		document.querySelectorAll(".checkbox-icon").forEach((el) => {
			el.innerHTML = tailwindIcon("Check", "w-3.5 h-3.5 transition-transform");
		});
	}

	function closeAllDropdowns(except) {
		document.querySelectorAll("[data-dropdown-menu]").forEach((menu) => {
			if (except && menu === except) return;
			menu.classList.add("hidden");
		});
	}

	function positionDropdown(wrapper, menu, toggle) {
		if (!wrapper || !menu || !toggle) return;

		const gap = 8;
		const toggleRect = toggle.getBoundingClientRect();
		const viewportHeight = window.innerHeight;
		const belowSpace = Math.max(0, viewportHeight - toggleRect.bottom - gap);
		const aboveSpace = Math.max(0, toggleRect.top - gap);
		const menuMaxHeight = Math.max(
			160,
			Math.min(Math.max(belowSpace, aboveSpace), viewportHeight - gap * 2)
		);

		menu.style.maxHeight = `${menuMaxHeight}px`;
		menu.style.overflowY = "auto";
	}

	function initDropdowns() {
		document.addEventListener("click", (e) => {
			const toggle = e.target.closest("[data-dropdown-toggle]");
			if (!toggle) {
				if (e.target.closest("[data-dropdown-menu]")) {
					return;
				}
				closeAllDropdowns();
				return;
			}
			const wrapper = toggle.closest("[data-dropdown]");
			if (!wrapper) return;
			const menu = wrapper.querySelector("[data-dropdown-menu]");
			if (!menu) return;
			const willOpen = menu.classList.contains("hidden");
			closeAllDropdowns(menu);
			if (willOpen) {
				menu.classList.remove("hidden");
				positionDropdown(wrapper, menu, toggle);
			} else {
				menu.classList.add("hidden");
			}
		});
		document.addEventListener("keydown", (e) => {
			if (e.key === "Escape") {
				closeAllDropdowns();
			}
		});
		window.addEventListener("resize", () => closeAllDropdowns());
		document.addEventListener("scroll", () => closeAllDropdowns(), true);
	}

	function togglePermissions(radio) {
		if (!radio) return;
		const root = radio.closest("[data-permission-root]") || document;
		root.querySelectorAll('input[name="permission"]').forEach((r) => {
			const label = r.parentElement;
			const check = label.querySelector(".check-icon");
			const uncheck = label.querySelector(".uncheck-icon");
			if (r.checked) {
				label.classList.add(
					"border-primary-700",
					"ring-1",
					"ring-primary-700",
					"bg-primary-50",
					"bg-opacity-10"
				);
				if (check) check.classList.remove("hidden");
				if (uncheck) uncheck.classList.add("hidden");
			} else {
				label.classList.remove(
					"border-primary-700",
					"ring-1",
					"ring-primary-700",
					"bg-primary-50",
					"bg-opacity-10"
				);
				if (check) check.classList.add("hidden");
				if (uncheck) uncheck.classList.remove("hidden");
			}
		});
		const customArea =
			root.querySelector("[data-permission-custom]") ||
			root.querySelector("#custom_permissions_area");
		if (customArea) {
			if (radio.value === "custom_permission") {
				customArea.classList.remove("hidden");
			} else {
				customArea.classList.add("hidden");
			}
		}
	}

	function refreshSelectpicker(select) {
		if (!select) return;
		if (window.refreshSelectpicker) {
			window.refreshSelectpicker(select);
		} else if (window.jQuery && window.jQuery.fn.selectpicker) {
			window.jQuery(select).selectpicker("refresh");
		}
	}

	function addUserRow(btn) {
		const root = btn ? btn.closest("[data-permission-root]") : document;
		const select =
			root.querySelector("[data-permission-user-select]") ||
			root.querySelector("#user_select");
		const container =
			root.querySelector("[data-permission-list]") ||
			root.querySelector("#permission_list_body");
		const emptyState =
			root.querySelector("[data-permission-empty]") ||
			root.querySelector("#empty_state_row");
		if (!select || !container) return;

		const userId = select.value;
		if (!userId) return;

		const option = select.options[select.selectedIndex];
		const userFullName = option?.dataset.name || option?.text || "";
		const avatar = option?.dataset.avatar || "";
		const userName = option?.dataset.username || "";
		const userDesignation = option?.dataset.designation || "";

		if (emptyState) emptyState.style.display = "none";
		if (root.querySelector(`[data-permission-card="${userId}"]`)) {
			window.toaster ? window.toaster.info("User already added.") : alert("User already added.");
			return;
		}

		const rowDiv = document.createElement("div");
		rowDiv.setAttribute("data-permission-card", userId);
		rowDiv.className =
			"flex flex-col 2xl:flex-wrap 2xl:items-center justify-between p-2 2xl:p-4 bg-white dark:bg-slate-800 border border-border rounded-xl shadow-sm hover:shadow-md transition-all animate-fade-in gap-1 2xl:gap-2";
		rowDiv.innerHTML = `
			<div class="flex items-center">
				<div class="flex-shrink-0 h-10 w-10 rounded-full bg-gray-100 flex items-center justify-center text-sm font-bold text-gray-600 border border-gray-200">
					${avatar ? `<img src="${base_url + avatar}" alt="${userFullName}" class="h-10 w-10 rounded-full object-cover">` : `${userFullName.charAt(0).toUpperCase()}`}
				</div>
				<div class="ml-3 truncate">
					<div class="text-sm font-semibold text-slate-900 dark:text-slate-100">${userFullName}</div>
					<div class="text-xs text-slate-500 dark:text-slate-400">
						<a target="_blank" href="${base_url}admin/users/user_details/${userId}" class="text-blue-600 dark:text-blue-400">@${userName}</a> - ${userDesignation}
					</div>
				</div>
				<input type="hidden" name="assigned_to[]" value="${userId}">
			</div>
			<div class="flex items-center space-x-2">
				<label class="cursor-pointer group">
					<input type="checkbox" name="perm_view_${userId}" value="1" checked class="peer sr-only">
					<div class="permission-pill-content flex items-center gap-1.5 px-2 py-1 rounded-lg border border-border bg-white dark:bg-slate-800 text-xs font-medium text-slate-500 dark:text-slate-400 hover:bg-gray-50 transition-all peer-checked:bg-blue-50 peer-checked:border-blue-200 peer-checked:text-blue-700">
						<i data-lucide="eye" class="w-3.5 h-3.5"></i>
						<span>View</span>
					</div>
				</label>
				<label class="cursor-pointer group">
					<input type="checkbox" name="perm_edit_${userId}" value="1" checked class="peer sr-only">
					<div class="permission-pill-content flex items-center gap-1.5 px-2 py-1 rounded-lg border border-border bg-white dark:bg-slate-800 text-xs font-medium text-slate-500 dark:text-slate-400 hover:bg-gray-50 transition-all peer-checked:bg-blue-50 peer-checked:border-blue-200 peer-checked:text-blue-700">
						<i data-lucide="edit-2" class="w-3.5 h-3.5"></i>
						<span>Edit</span>
					</div>
				</label>
				<label class="cursor-pointer group">
					<input type="checkbox" name="perm_delete_${userId}" value="1" checked class="peer sr-only">
					<div class="permission-pill-content flex items-center gap-1.5 px-2 py-1 rounded-lg border border-border bg-white dark:bg-slate-800 text-xs font-medium text-slate-500 dark:text-slate-400 hover:bg-gray-50 transition-all peer-checked:bg-red-50 peer-checked:border-red-200 peer-checked:text-red-700">
						<i data-lucide="trash" class="w-3.5 h-3.5"></i>
						<span>Delete</span>
					</div>
				</label>
				<div class="h-4 w-px bg-gray-200 mx-2 dark:bg-gray-600"></div>
				<button type="button" onclick="removeUserRow(this)" class="p-1 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors" title="Remove User">
					<i data-lucide="x" class="w-4 h-4"></i>
				</button>
			</div>
		`;
		container.appendChild(rowDiv);
		select.value = "";
		refreshSelectpicker(select);
		if (window.lucide && typeof window.lucide.createIcons === "function") {
			window.lucide.createIcons();
		}
	}

	function removeUserRow(btn) {
		const row = btn ? btn.closest("[data-permission-card]") : null;
		if (!row) return;
		const root = row.closest("[data-permission-root]") || document;
		const select =
			root.querySelector("[data-permission-user-select]") ||
			root.querySelector("#user_select");
		const container =
			root.querySelector("[data-permission-list]") ||
			root.querySelector("#permission_list_body");
		const emptyState =
			root.querySelector("[data-permission-empty]") ||
			root.querySelector("#empty_state_row");

		row.style.opacity = "0";
		row.style.transform = "scale(0.95)";
		setTimeout(() => {
			row.remove();
			if (select) {
				const option = select.querySelector(`option[value="${row.dataset.permissionCard}"]`);
				if (option) option.disabled = false;
				refreshSelectpicker(select);
			}
			if (container) {
				const rows = container.querySelectorAll("[data-permission-card]");
				if (!rows.length && emptyState) {
					emptyState.style.display = "block";
				}
			}
			if (window.lucide && typeof window.lucide.createIcons === "function") {
				window.lucide.createIcons();
			}
		}, 200);
	}

	function initPermissionUI(scope) {
		const rootList = (scope || document).querySelectorAll("[data-permission-root]");
		rootList.forEach((root) => {
			const checkedRadio = root.querySelector('input[name="permission"]:checked');
			if (checkedRadio) togglePermissions(checkedRadio);
		});
	}

	function initUI() {
		initRangeDisplays();
		initCheckboxIcons();
		initDropdowns();
		initPermissionUI(document);
		if (window.lucide && typeof window.lucide.createIcons === "function") {
			window.lucide.createIcons();
		}
	}

	function initDatatableLucide() {
		if (!window.jQuery) return;
		window.jQuery(document).on("draw.dt", function () {
			if (window.lucide && typeof window.lucide.createIcons === "function") {
				window.lucide.createIcons();
			}
		});
	}

	if (
		document.readyState === "interactive" ||
		document.readyState === "complete"
	) {
		initUI();
		initDatatableLucide();
	} else {
		document.addEventListener("DOMContentLoaded", initUI);
		document.addEventListener("DOMContentLoaded", initDatatableLucide);
	}

	window.togglePermissions = togglePermissions;
	window.addUserRow = addUserRow;
	window.removeUserRow = removeUserRow;
	window.initPermissionUI = initPermissionUI;
})();
