<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { createChat } from '$lib/chat/create.svelte';
	import type { MessageData } from '$lib/types/message';
	import type { ChatConnection } from '$lib/chat/types';
	import MessageBox from '$lib/components/MessageBox.svelte';
	import Editor from '$lib/components/Editor.svelte';

	let { props = {} }: { props?: Record<string, unknown> } = $props();

	const channelId = props.channelId as string | undefined;

	let chat = $state<ChatConnection | null>(null);
	let sending = $state(false);
	let messagesEl: HTMLDivElement | undefined;

	const chatCallbacks = {
		onMentionClick: (entityId: string) => goto(`/entities/${entityId}`),
		onReaction: async (messageId: string, reaction: string) => {
			try {
				const msg = chat?.messages.find(m => m.id === messageId);
				const existing = msg?.reactions?.find(r => r.reaction === reaction);
				const res = await fetch(`/api/messages/${messageId}/reactions`, {
					method: existing?.user_reacted ? 'DELETE' : 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ reaction })
				});
				if (res.ok) await chat?.refresh();
			} catch { /* stille feil */ }
		},
		onTogglePin: async (messageId: string, pinned: boolean) => {
			try {
				const res = await fetch(`/api/messages/${messageId}`, {
					method: 'PATCH',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ pinned })
				});
				if (res.ok) await chat?.refresh();
			} catch { /* stille feil */ }
		}
	};

	async function handleSubmit(html: string, json: Record<string, unknown>, mentions: Array<{ id: string; name: string; type: string; aliases: string[] }>) {
		if (!chat || sending) return;
		sending = true;
		try {
			await chat.send(html, mentions.length > 0 ? mentions : undefined);
			scrollToBottom();
		} finally {
			sending = false;
		}
	}

	function scrollToBottom() {
		requestAnimationFrame(() => {
			messagesEl?.scrollTo(0, messagesEl.scrollHeight);
		});
	}

	function formatDate(iso: string): string {
		const d = new Date(iso);
		const today = new Date();
		if (d.toDateString() === today.toDateString()) return 'I dag';
		const yesterday = new Date(today);
		yesterday.setDate(today.getDate() - 1);
		if (d.toDateString() === yesterday.toDateString()) return 'I går';
		return d.toLocaleDateString('nb-NO', { day: 'numeric', month: 'short' });
	}

	let messages = $derived(chat?.messages ?? []);
	let prevCount = 0;

	$effect(() => {
		const count = messages.length;
		if (count > prevCount) {
			scrollToBottom();
		}
		prevCount = count;
	});

	let grouped = $derived.by(() => {
		const groups: { date: string; messages: MessageData[] }[] = [];
		let currentDate = '';
		for (const msg of messages) {
			const date = formatDate(msg.created_at);
			if (date !== currentDate) {
				currentDate = date;
				groups.push({ date, messages: [] });
			}
			groups[groups.length - 1].messages.push(msg);
		}
		return groups;
	});

	onMount(() => {
		if (channelId) {
			const user = $page.data.user;
			chat = createChat(channelId, {
				id: user?.id ?? 'anonymous',
				name: user?.name ?? 'Ukjent'
			});
		}
		return () => chat?.destroy();
	});
</script>

{#if !channelId}
	<div class="no-channel">
		<p>Ingen kanal konfigurert for denne blokken.</p>
	</div>
{:else}
	<div class="chat">
		<div class="messages" bind:this={messagesEl}>
			{#each grouped as group}
				<div class="date-divider">
					<span>{group.date}</span>
				</div>
				{#each group.messages as msg (msg.id)}
					<MessageBox message={msg} mode="expanded" callbacks={chatCallbacks} />
				{/each}
			{/each}

			{#if messages.length === 0 && !chat?.error}
				<div class="empty">Ingen meldinger ennå. Skriv noe!</div>
			{/if}
		</div>

		{#if chat?.error}
			<div class="error">{chat.error}</div>
		{/if}

		<div class="input-row">
			<Editor
				mode="compact"
				placeholder="Skriv en melding..."
				onSubmit={handleSubmit}
				autofocus
			/>
		</div>
	</div>
{/if}

<style>
	.chat {
		display: flex;
		flex-direction: column;
		height: 100%;
		min-height: 0;
	}

	.messages {
		flex: 1;
		overflow-y: auto;
		display: flex;
		flex-direction: column;
		gap: 0.15rem;
		padding-bottom: 0.5rem;
	}

	.date-divider {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0.75rem 0 0.25rem;
	}

	.date-divider span {
		font-size: 0.7rem;
		color: #8b92a5;
		background: #0f1117;
		padding: 0.15rem 0.6rem;
		border-radius: 10px;
	}

	.empty {
		display: flex;
		align-items: center;
		justify-content: center;
		flex: 1;
		color: #8b92a5;
		font-size: 0.85rem;
	}

	.error {
		font-size: 0.75rem;
		color: #f87171;
		padding: 0.25rem 0.5rem;
	}

	.input-row {
		padding-top: 0.5rem;
		border-top: 1px solid #2d3148;
	}

	.no-channel {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
		color: #8b92a5;
		font-size: 0.85rem;
	}
</style>
