<script lang="ts">
	import { page } from '$app/state';
	import { getContext } from 'svelte';
	import { useQuery, useConvexClient } from 'convex-svelte';
	import { usePollingQuery, usePollingMutation } from '$lib/convex-polling.svelte';
	import { api } from '$lib/convex/_generated/api';
	import ChatMessage from '$lib/components/ChatMessage.svelte';
	import ChatInput from '$lib/components/ChatInput.svelte';
	import FollowUpButtons from '$lib/components/FollowUpButtons.svelte';
	import StealthOverlay from '$lib/components/StealthOverlay.svelte';

	const usePolling = getContext<boolean>('convex-use-polling') ?? false;
	let mnemonic = $derived(page.params.mnemonic);

	let lastMessageElement: HTMLDivElement | null = $state(null);
	let showScrollButton = $state(false);

	$effect(() => {
		if (!lastMessageElement) return;

		const observer = new IntersectionObserver(
			([entry]) => {
				showScrollButton = !entry.isIntersecting;
			},
			{ threshold: 0, rootMargin: '0px 0px -90% 0px' }
		);

		observer.observe(lastMessageElement);
		return () => observer.disconnect();
	});

	function scrollToLastMessage() {
		lastMessageElement?.scrollIntoView({ behavior: 'smooth', block: 'start' });
	}

	const chatDataWs = usePolling
		? null
		: useQuery(api.chats.getWithUser, () => (mnemonic ? { mnemonic } : 'skip'));
	const chatDataPoll = usePolling
		? usePollingQuery(api.chats.getWithUser, () => (mnemonic ? { mnemonic } : 'skip'))
		: null;
	const chatData = $derived(usePolling ? chatDataPoll! : chatDataWs!);

	const messagesQueryWs = usePolling
		? null
		: useQuery(api.messages.listByChat, () =>
				chatData.data?.chat?._id ? { chatId: chatData.data.chat._id } : 'skip'
			);
	const messagesQueryPoll = usePolling
		? usePollingQuery(api.messages.listByChat, () =>
				chatData.data?.chat?._id ? { chatId: chatData.data.chat._id } : 'skip'
			)
		: null;
	const messagesQuery = $derived(usePolling ? messagesQueryPoll! : messagesQueryWs!);

	let messages = $derived(messagesQuery.data ?? []);
	let lastMessage = $derived(messages[messages.length - 1]);
	let followUpOptions = $derived(
		lastMessage?.role === 'assistant' && lastMessage.followUpOptions
			? lastMessage.followUpOptions
			: []
	);

	let prevMessageCount = 0;
	let prevLastMessageId: string | undefined;

	$effect(() => {
		const count = messages.length;
		const lastId = lastMessage?._id;
		if (count > prevMessageCount || (lastId && lastId !== prevLastMessageId)) {
			prevMessageCount = count;
			prevLastMessageId = lastId;
			window.scrollTo(0, document.body.scrollHeight);
		}
	});

	const clientWs = usePolling ? null : useConvexClient();
	const createMessagePoll = usePolling ? usePollingMutation(api.messages.create) : null;

	async function sendMessage(content: string) {
		const chat = chatData.data?.chat;
		if (!chat) return;

		if (usePolling && createMessagePoll) {
			await createMessagePoll({
				chatId: chat._id,
				role: 'user',
				content,
				source: 'web'
			});
		} else if (clientWs) {
			await clientWs.mutation(api.messages.create, {
				chatId: chat._id,
				role: 'user',
				content,
				source: 'web'
			});
		}
	}

	async function summarize() {
		const chat = chatData.data?.chat;
		if (!chat) return;

		if (usePolling && createMessagePoll) {
			await createMessagePoll({
				chatId: chat._id,
				role: 'user',
				content: '/summarize',
				source: 'web'
			});
		} else if (clientWs) {
			await clientWs.mutation(api.messages.create, {
				chatId: chat._id,
				role: 'user',
				content: '/summarize',
				source: 'web'
			});
		}
	}
</script>

<svelte:head>
	<title>Chat</title>
	<meta
		name="viewport"
		content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover"
	/>
</svelte:head>

<div class="min-h-dvh bg-black p-1.5 text-white">
	{#if chatData.isLoading}
		<div class="py-4 text-center text-xs text-neutral-500">Loading...</div>
	{:else if chatData.error}
		<div class="py-4 text-center text-red-500">
			<div class="text-xs">Error</div>
			<div class="text-[8px] break-all">{chatData.error.message}</div>
		</div>
	{:else if !chatData.data}
		<div class="py-4 text-center text-xs text-neutral-500">Not found</div>
	{:else}
		<div class="space-y-1">
			{#each messages as message, i (message._id)}
				{#if i === messages.length - 1}
					<div bind:this={lastMessageElement}>
						<ChatMessage
							role={message.role}
							content={message.content}
							isStreaming={message.isStreaming}
						/>
					</div>
				{:else}
					<ChatMessage
						role={message.role}
						content={message.content}
						isStreaming={message.isStreaming}
					/>
				{/if}
			{/each}
		</div>

		{#if followUpOptions.length > 0}
			<div class="mt-2">
				<FollowUpButtons options={followUpOptions} onselect={sendMessage} />
			</div>
		{/if}

		<div class="mt-2 flex gap-1">
			<button
				onclick={summarize}
				class="shrink-0 rounded bg-neutral-800 px-1.5 py-0.5 text-[8px] text-neutral-400"
			>
				/sum
			</button>
			<div class="flex-1">
				<ChatInput onsubmit={sendMessage} />
			</div>
		</div>
	{/if}

	{#if showScrollButton}
		<button
			onclick={scrollToLastMessage}
			class="fixed right-3 bottom-12 z-50 flex h-8 w-8 animate-pulse items-center justify-center rounded-full bg-blue-600 text-white shadow-lg"
		>
			↓
		</button>
	{/if}

	<StealthOverlay />
</div>
