<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 { Message, ChatConnection } from '$lib/chat/types';
	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;

	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 handleMessageClick(e: MouseEvent) {
		const target = e.target as HTMLElement;
		if (target.classList.contains('mention') && target.dataset.id) {
			e.preventDefault();
			goto(`/entities/${target.dataset.id}`);
		}
	}

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

	function formatTime(iso: string): string {
		return new Date(iso).toLocaleTimeString('nb-NO', { hour: '2-digit', minute: '2-digit' });
	}

	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: Message[] }[] = [];
		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)}
					<div class="message">
						<div class="message-header">
							<span class="author">{msg.author_name ?? 'Ukjent'}</span>
							<span class="time">{formatTime(msg.created_at)}</span>
						</div>
						<!-- svelte-ignore a11y_click_events_have_key_events -->
						<!-- svelte-ignore a11y_no_static_element_interactions -->
						<div class="message-body" onclick={handleMessageClick}>{@html msg.body}</div>
					</div>
				{/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;
	}

	.message {
		padding: 0.3rem 0.5rem;
		border-radius: 4px;
	}

	.message:hover {
		background: rgba(255, 255, 255, 0.03);
	}

	.message-header {
		display: flex;
		align-items: baseline;
		gap: 0.5rem;
	}

	.author {
		font-size: 0.8rem;
		font-weight: 600;
		color: #7dd3fc;
	}

	.time {
		font-size: 0.65rem;
		color: #8b92a5;
	}

	.message-body {
		font-size: 0.85rem;
		color: #e1e4e8;
		line-height: 1.4;
		word-break: break-word;
	}

	/* Render HTML from Tiptap */
	.message-body :global(p) {
		margin: 0;
	}

	.message-body :global(p + p) {
		margin-top: 0.3em;
	}

	.message-body :global(strong) {
		font-weight: 700;
		color: #f1f3f5;
	}

	.message-body :global(code) {
		background: #1e2235;
		padding: 0.1em 0.25em;
		border-radius: 3px;
		font-size: 0.8rem;
	}

	.message-body :global(.mention) {
		color: #8b5cf6;
		background: rgba(139, 92, 246, 0.12);
		padding: 0.05em 0.25em;
		border-radius: 3px;
		font-weight: 500;
		cursor: pointer;
		text-decoration: none;
	}

	.message-body :global(.mention:hover) {
		background: rgba(139, 92, 246, 0.25);
	}

	.message-body :global(.mention::before) {
		content: '#';
	}

	.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>
