(() => {
	const baseUrl =
		window.base_url ||
		(window.appConfig && (window.appConfig.base_url || window.appConfig.baseUrl)) ||
		(typeof base_url !== "undefined" ? base_url : "");

	const qs = (sel, root = document) => root.querySelector(sel);
	const qsa = (sel, root = document) => Array.from(root.querySelectorAll(sel));
	let conversationSearchTimer = null;
	let conversationsPollTimer = null;
	let conversationState = {
		page: 1,
		search: "",
		selectedUserId: null,
	};
	let conversationHistoryLoading = false;
	let conversationLatestLoading = false;

	const fetchJson = async (url, options = {}) => {
		const res = await fetch(url, {
			...options,
			headers: {
				"X-Requested-With": "XMLHttpRequest",
				...(options.headers || {}),
			},
		});
		const text = await res.text();
		try {
			return JSON.parse(text);
		} catch (err) {
			return null;
		}
	};

	const fetchText = async (url) => {
		const res = await fetch(url, {
			headers: { "X-Requested-With": "XMLHttpRequest" },
		});
		return res.text();
	};

	const scrollChatBody = (el) => {
		if (!el) return;
		el.scrollTop = el.scrollHeight;
	};

	const refreshOpenChats = async () => {
		const container = qs("#chat_box");
		if (!container) return;
		const data = await fetchJson(`${baseUrl}chat/open_chats_boxes`);
		if (!data || !data.view) return;
		container.innerHTML = data.view;
		initChatBoxes(container);
	};

	const updateMessages = async () => {
		const data = await fetchJson(`${baseUrl}chat/all_chat_messages`);
		if (!data || !data.chats) return;
		data.chats.forEach((chat) => {
			const body = qs(`#open_chat_${chat.chatid}`);
			if (body && chat.messages_template) {
				body.innerHTML = chat.messages_template;
				scrollChatBody(body);
			}
			const badge = qs(`#open_chat_box_${chat.chatid}`);
			if (badge && chat.chat_badge && !qs(`#open_chat_${chat.chatid}`)) {
				badge.outerHTML = chat.chat_badge;
			}
		});
		if (window.lucide && typeof window.lucide.createIcons === "function") {
			window.lucide.createIcons();
		}
	};

	const openChatForUser = async (userId) => {
		if (!userId) return;
		const data = await fetchJson(`${baseUrl}chat/open_chat_box?user_id=${encodeURIComponent(userId)}`);
		if (!data || (!data.chatid && !data.exist && !data.success)) return;
		const chatId = data.chatid || data.chat_id;
		if (!chatId) return;
		await fetchJson(`${baseUrl}chat/active_chat_box/${chatId}`);
		await refreshOpenChats();
		await loadConversationThread(userId, true);
		await loadConversationContacts();
	};

	const activateChatBox = async (chatId) => {
		if (!chatId) return;
		await fetchJson(`${baseUrl}chat/active_chat_box/${chatId}`);
		await refreshOpenChats();
	};

	const minimizeChatBox = async (chatId) => {
		if (!chatId) return;
		await fetchJson(`${baseUrl}chat/minimize_chat_box/${chatId}`);
		await refreshOpenChats();
	};

	const closeChatBox = async (chatId) => {
		if (!chatId) return;
		await fetchJson(`${baseUrl}chat/close_chat_box/${chatId}`);
		await refreshOpenChats();
	};

	const deleteChatBox = async (chatId) => {
		if (!chatId) return;
		await fetchJson(`${baseUrl}chat/delete_chat_box/${chatId}`);
		await refreshOpenChats();
	};

	const sendMessage = async (chatId, message) => {
		if (!chatId || !message) return;
		const data = await fetchJson(
			`${baseUrl}chat/send_message/${chatId}?message=${encodeURIComponent(message)}`
		);
		if (data && data.success) {
			await updateMessages();
			if (conversationState.selectedUserId) {
				await loadConversationLatest(conversationState.selectedUserId, true);
			}
		}
	};

	const initChatBoxes = (scope = document) => {
		qsa("[data-chat-open]", scope).forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.preventDefault();
				const chatId = btn.dataset.chatOpen;
				activateChatBox(chatId);
			});
		});

		qsa("[data-chat-start]", scope).forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.preventDefault();
				const userId = btn.dataset.userId;
				openChatForUser(userId);
			});
		});

		qsa("[data-chat-input]", scope).forEach((input) => {
			input.addEventListener("keydown", (e) => {
				if (e.key === "Enter") {
					e.preventDefault();
					const chatId = input.dataset.chatInput;
					const message = input.value.trim();
					if (message.length) {
						input.value = "";
						sendMessage(chatId, message);
					}
				}
			});
		});

		qsa("[data-chat-minimize]", scope).forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.preventDefault();
				minimizeChatBox(btn.dataset.chatMinimize);
			});
		});

		qsa("[data-chat-close]", scope).forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.preventDefault();
				closeChatBox(btn.dataset.chatClose);
			});
		});

		qsa("[data-chat-delete]", scope).forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.preventDefault();
				deleteChatBox(btn.dataset.chatDelete);
			});
		});

		qsa("[data-chat-body]", scope).forEach((body) => scrollChatBody(body));
	};

	const initChatListToggle = () => {
		const openBtn = qs("#open_chat_list");
		const closeBtn = qs("#close_chat_list");
		const list = qs("#chat_list");
		if (!openBtn || !closeBtn || !list) return;

		openBtn.addEventListener("click", () => {
			list.classList.remove("hidden");
			openBtn.classList.add("hidden");
		});
		closeBtn.addEventListener("click", () => {
			list.classList.add("hidden");
			openBtn.classList.remove("hidden");
		});
	};

	const initConversationsPage = () => {
		const wrapper = qs("[data-conversations]");
		if (!wrapper) return;
		conversationState.selectedUserId = parseInt(wrapper.dataset.userId || "0", 10) || null;
		const searchInput = qs("[data-conversation-search]", wrapper);
		if (searchInput) {
			searchInput.addEventListener("input", () => {
				const nextSearch = searchInput.value.trim();
				clearTimeout(conversationSearchTimer);
				conversationSearchTimer = setTimeout(() => {
					conversationState.search = nextSearch;
					conversationState.page = 1;
					loadConversationContacts();
				}, 220);
			});
		}
		loadConversationContacts();
		if (conversationState.selectedUserId) {
			loadConversationThread(conversationState.selectedUserId, false);
		}
		if (conversationsPollTimer) {
			clearInterval(conversationsPollTimer);
		}
		conversationsPollTimer = setInterval(() => {
			if (conversationState.selectedUserId) {
				loadConversationLatest(conversationState.selectedUserId, false);
			}
		}, window.interval_time || 5000);
	};

	const allConversations = async (userId) => {
		if (!userId) return;
		const data = await fetchJson(`${baseUrl}chat/all_conversations/${userId}`);
		if (!data || !data.chats) return;
		data.chats.forEach((chat) => {
			const body = qs(`#conversation_chat_${chat.chatid}`);
			if (body && chat.messages_template) {
				body.innerHTML = chat.messages_template;
				scrollChatBody(body);
			}
		});
	};

	const loadConversationContacts = async (showLoading = true) => {
		const wrapper = qs("[data-conversations]");
		if (!wrapper) return;
		const contactsRoot = qs("[data-conversation-contacts]", wrapper);
		if (!contactsRoot) return;
		const params = new URLSearchParams({
			page: String(conversationState.page || 1),
			search: conversationState.search || "",
			selected_user_id: String(conversationState.selectedUserId || ""),
		});
		if (showLoading) {
			contactsRoot.innerHTML =
				'<div class="flex min-h-[620px] items-center justify-center px-6 py-12 text-sm text-muted-foreground">Loading...</div>';
		}
		const data = await fetchJson(`${wrapper.dataset.contactsUrl}?${params.toString()}`);
		if (!data || !data.success) return;
		contactsRoot.innerHTML = data.html || "";
		bindConversationContacts(wrapper);
		if (window.lucide && typeof window.lucide.createIcons === "function") {
			window.lucide.createIcons();
		}
	};

	const bindConversationContacts = (wrapper) => {
		qsa("[data-conversation-user]", wrapper).forEach((btn) => {
			btn.addEventListener("click", () => {
				const userId = parseInt(btn.dataset.userId || "0", 10) || null;
				if (!userId) return;
				loadConversationThread(userId, true);
			});
		});

		const prevBtn = qs("[data-conversation-prev]", wrapper);
		if (prevBtn) {
			prevBtn.addEventListener("click", () => {
				if (conversationState.page <= 1) return;
				conversationState.page -= 1;
				loadConversationContacts();
			});
		}

		const nextBtn = qs("[data-conversation-next]", wrapper);
		if (nextBtn) {
			nextBtn.addEventListener("click", () => {
				conversationState.page += 1;
				loadConversationContacts();
			});
		}
	};

	const loadConversationThread = async (userId, pushHistory = true) => {
		const wrapper = qs("[data-conversations]");
		if (!wrapper || !userId) return;
		const threadRoot = qs("[data-conversation-thread]", wrapper);
		if (!threadRoot) return;
		conversationState.selectedUserId = parseInt(userId, 10) || null;
		threadRoot.innerHTML =
			'<div class="overflow-hidden rounded-3xl border border-border bg-card shadow-sm"><div class="flex min-h-[620px] items-center justify-center px-8 py-12 text-sm text-muted-foreground">Loading conversation...</div></div>';
		const data = await fetchJson(`${wrapper.dataset.threadUrlBase}${userId}`);
		if (!data || !data.success) return;
		threadRoot.innerHTML = data.html || "";
		wrapper.dataset.userId = String(userId);
		bindConversationThread(threadRoot);
		scrollConversationThread(threadRoot);
		if (pushHistory) {
			window.history.replaceState({}, "", `${baseUrl}chat/conversations/${userId}`);
		}
		await loadConversationContacts(false);
		if (window.lucide && typeof window.lucide.createIcons === "function") {
			window.lucide.createIcons();
		}
	};

	const bindConversationThread = (root) => {
		qsa("[data-conversation-send]", root).forEach((btn) => {
			btn.addEventListener("click", () => {
				const chatId = btn.dataset.chatId;
				const input = qs(`#chat_input_message_${chatId}`, root) || qs(`#chat_input_message_${chatId}`);
				if (!input) return;
				const message = input.value.trim();
				if (!message.length) return;
				input.value = "";
				sendMessage(chatId, message);
			});
		});

		qsa("[data-chat-input]", root).forEach((input) => {
			input.addEventListener("keydown", (e) => {
				if (e.key === "Enter" && !e.shiftKey) {
					e.preventDefault();
					const chatId = input.dataset.chatInput;
					const message = input.value.trim();
					if (!message.length) return;
					input.value = "";
					sendMessage(chatId, message);
				}
			});
		});

		qsa("[data-chat-start]", root).forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.preventDefault();
				const userId = btn.dataset.userId;
				openChatForUser(userId);
			});
		});

		const body = qs("[data-conversation-messages]", root);
		if (body) {
			body.addEventListener("scroll", () => {
				if (body.scrollTop < 60) {
					loadConversationHistory(body);
				}
			});
		}
	};

	const scrollConversationThread = (root) => {
		const body = qs("[data-conversation-messages]", root);
		if (body) {
			scrollChatBody(body);
		}
	};

	const loadConversationHistory = async (body) => {
		if (!body || conversationHistoryLoading) return;
		if (body.dataset.hasMore !== "1") return;
		const userId = body.dataset.userId;
		const oldestId = body.dataset.oldestId;
		if (!userId || !oldestId) return;
		conversationHistoryLoading = true;
		const loader = qs("[data-conversation-history-loader]", body);
		if (loader) loader.classList.remove("hidden");
		const previousHeight = body.scrollHeight;
		const data = await fetchJson(`${baseUrl}chat/conversation_history/${userId}?before_id=${encodeURIComponent(oldestId)}`);
		if (data && data.success && data.html) {
			const list = qs("[data-conversation-message-list]", body);
			if (list) {
				list.insertAdjacentHTML("afterbegin", data.html);
				body.dataset.oldestId = String(data.oldest_id || oldestId);
				body.dataset.hasMore = data.has_more ? "1" : "0";
				const nextHeight = body.scrollHeight;
				body.scrollTop = nextHeight - previousHeight + body.scrollTop;
			}
		} else if (body) {
			body.dataset.hasMore = "0";
		}
		if (loader) loader.classList.add("hidden");
		if (window.lucide && typeof window.lucide.createIcons === "function") {
			window.lucide.createIcons();
		}
		conversationHistoryLoading = false;
	};

	const loadConversationLatest = async (userId, forceScrollToBottom = false) => {
		const wrapper = qs("[data-conversations]");
		if (!wrapper || !userId || conversationLatestLoading) return;
		const threadRoot = qs("[data-conversation-thread]", wrapper);
		const body = qs("[data-conversation-messages]", threadRoot);
		if (!body) return;
		const chatId = body.dataset.chatId;
		const newestId = body.dataset.newestId || "0";
		if (!chatId) return;
		conversationLatestLoading = true;
		const nearBottom = (body.scrollHeight - body.clientHeight - body.scrollTop) < 80;
		const data = await fetchJson(`${baseUrl}chat/conversation_latest/${userId}?after_id=${encodeURIComponent(newestId)}`);
		if (data && data.success && data.count > 0 && data.html) {
			const list = qs("[data-conversation-message-list]", body);
			const emptyState = qs("[data-conversation-empty-state]", body);
			if (emptyState) emptyState.classList.add("hidden");
			if (list) {
				list.classList.remove("hidden");
				list.insertAdjacentHTML("beforeend", data.html);
				body.dataset.newestId = String(data.newest_id || newestId);
				if (!body.dataset.oldestId || body.dataset.oldestId === "0") {
					const firstMessage = qs("[data-message-id]", list);
					if (firstMessage) {
						body.dataset.oldestId = firstMessage.dataset.messageId;
					}
				}
				if (nearBottom || forceScrollToBottom) {
					scrollChatBody(body);
				}
			}
			if (window.lucide && typeof window.lucide.createIcons === "function") {
				window.lucide.createIcons();
			}
		}
		conversationLatestLoading = false;
	};

	window.open_chat_box = activateChatBox;
	window.minimize_chat_box = minimizeChatBox;
	window.close_chat_box = closeChatBox;
	window.delete_chat_box = deleteChatBox;
	window.send_message = (e, chatId) => {
		if (e && e.key === "Enter") {
			e.preventDefault();
			const input = qs(`#chat_input_message_${chatId}`);
			if (input) {
				const message = input.value.trim();
				if (message) {
					input.value = "";
					sendMessage(chatId, message);
				}
			}
			return false;
		}
		return true;
	};
	window.all_conversations = allConversations;

	document.addEventListener("DOMContentLoaded", () => {
		initChatListToggle();
		initChatBoxes();
		initConversationsPage();
		refreshOpenChats();
		setInterval(updateMessages, window.interval_time || 5000);
	});
})();
