<script lang="ts">
	import type { MessageData, MessageBoxMode, MessageBoxCallbacks } from '$lib/types/message';
	import Editor from '$lib/components/Editor.svelte';
	import { marked } from 'marked';

	let {
		message,
		mode = 'expanded',
		showAuthor = true,
		showTimestamp = true,
		callbacks = {},
		isReply = false
	}: {
		message: MessageData;
		mode?: MessageBoxMode;
		showAuthor?: boolean;
		showTimestamp?: boolean;
		callbacks?: MessageBoxCallbacks;
		isReply?: boolean;
	} = $props();

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

	function stripHtml(html: string): string {
		if (typeof document !== 'undefined') {
			const div = document.createElement('div');
			div.innerHTML = html;
			return div.textContent ?? '';
		}
		return html.replace(/<[^>]*>/g, '');
	}

	function truncate(text: string, max: number): string {
		if (text.length <= max) return text;
		return text.slice(0, max) + '…';
	}

	function handleClick(e: MouseEvent) {
		const target = e.target as HTMLElement;
		if (target.classList.contains('mention') && target.dataset.id) {
			e.preventDefault();
			e.stopPropagation();
			callbacks.onMentionClick?.(target.dataset.id);
			return;
		}
		callbacks.onClick?.(message.id);
	}

	const ALL_REACTIONS = ['👍', '❤️', '🔥', '👀', '💯'];

	let userReaction = $derived(
		message.reactions?.find(r => r.user_reacted)?.reaction ?? null
	);

	let availableReactions = $derived(
		userReaction ? [] : ALL_REACTIONS.filter(
			emoji => !message.reactions?.some(r => r.reaction === emoji && r.user_reacted)
		)
	);

	let hasBadges = $derived(
		(mode === 'expanded' && (message.kanban_view || message.calendar_view))
	);

	let hasReactions = $derived(
		mode === 'expanded' && message.reactions && message.reactions.length > 0
	);

	let bodyPreview = $derived(truncate(stripHtml(message.body), 80));

	let editing = $state(false);
	let editBody = $state('');
	let expanded = $state(false);
	let bodyEl: HTMLDivElement | undefined = $state();
	let isClamped = $state(false);

	function checkClamped() {
		if (bodyEl) {
			isClamped = bodyEl.scrollHeight > bodyEl.clientHeight + 2;
		}
	}

	$effect(() => {
		if (bodyEl && !editing && !expanded) {
			// Check after render
			checkClamped();
		}
	});

	let isOwnMessage = $derived(
		callbacks.currentUserId != null && message.author_id === callbacks.currentUserId
	);

	function handleReaction(e: MouseEvent, reaction: string) {
		e.stopPropagation();
		callbacks.onReaction?.(message.id, reaction);
	}

	function handleTogglePin(e: MouseEvent) {
		e.stopPropagation();
		callbacks.onTogglePin?.(message.id, !message.pinned);
	}

	function startEdit(e: MouseEvent) {
		e.stopPropagation();
		editBody = message.body;
		editing = true;
	}

	function cancelEdit() {
		editing = false;
		editBody = '';
	}

	function submitEdit(html: string) {
		const body = html || editBody;
		if (!body.trim()) return;
		callbacks.onEdit?.(message.id, body);
		editing = false;
		editBody = '';
	}

	let confirmingDelete = $state(false);

	function handleDelete(e: MouseEvent) {
		e.stopPropagation();
		confirmingDelete = true;
	}

	function confirmDelete(e: MouseEvent) {
		e.stopPropagation();
		confirmingDelete = false;
		callbacks.onDelete?.(message.id);
	}

	function cancelDelete(e: MouseEvent) {
		e.stopPropagation();
		confirmingDelete = false;
	}

	function handleReply(e: MouseEvent) {
		e.stopPropagation();
		callbacks.onReply?.(message.id);
	}

	function handleConvertToKanban(e: MouseEvent) {
		e.stopPropagation();
		callbacks.onConvertToKanban?.(message.id);
	}

	function handleConvertToCalendar(e: MouseEvent) {
		e.stopPropagation();
		callbacks.onConvertToCalendar?.(message.id);
	}

	// --- AI-prompt-meny ---
	interface AiPrompt {
		action: string;
		label: string;
		icon: string | null;
		description: string | null;
	}

	let showAiMenu = $state(false);
	let aiPrompts = $state<AiPrompt[]>([]);
	let aiPromptsLoaded = $state(false);

	async function loadAiPrompts() {
		if (aiPromptsLoaded) return;
		try {
			const res = await fetch('/api/ai/prompts');
			if (res.ok) {
				aiPrompts = await res.json();
				aiPromptsLoaded = true;
			}
		} catch { /* stille */ }
	}

	function handleMagic(e: MouseEvent) {
		e.stopPropagation();
		if (aiPrompts.length <= 1) {
			// Bare én prompt — kjør direkte
			callbacks.onMagic?.(message.id, aiPrompts[0]?.action);
			return;
		}
		showAiMenu = !showAiMenu;
	}

	function selectAiAction(action: string) {
		showAiMenu = false;
		callbacks.onMagic?.(message.id, action);
	}

	// Last prompts ved mount
	loadAiPrompts();

	// Lukk AI-meny ved klikk utenfor
	function handleWindowClick() {
		if (showAiMenu) showAiMenu = false;
	}

	let isAiProcessing = $derived(message.metadata?.ai_processing === true);

	// --- Revisjonshistorikk (generell — gjelder alle redigerte meldinger) ---

	interface Revision {
		id: string;
		body: string;
		edited_at: string;
	}

	let revisions = $state<Revision[]>([]);
	let revisionIndex = $state(-1); // -1 = nåværende versjon
	let loadingRevisions = $state(false);
	let revisionsLoaded = $state(false);

	async function loadRevisions() {
		if (revisionsLoaded) return;
		loadingRevisions = true;
		try {
			const res = await fetch(`/api/messages/${message.id}/revisions`);
			if (res.ok) {
				const data = await res.json();
				revisions = data.revisions ?? [];
			}
		} finally {
			loadingRevisions = false;
			revisionsLoaded = true;
		}
	}

	async function toggleRevisions(e: MouseEvent) {
		e.stopPropagation();
		if (revisionIndex >= 0) {
			// Tilbake til nåværende
			revisionIndex = -1;
			return;
		}
		await loadRevisions();
		if (revisions.length > 0) {
			revisionIndex = 0; // Vis nyeste revisjon (original)
		}
	}

	function prevRevision(e: MouseEvent) {
		e.stopPropagation();
		if (revisionIndex < revisions.length - 1) revisionIndex++;
	}

	function nextRevision(e: MouseEvent) {
		e.stopPropagation();
		if (revisionIndex > 0) revisionIndex--;
		else revisionIndex = -1; // Tilbake til nåværende
	}

	let showingRevision = $derived(revisionIndex >= 0);
	let totalVersions = $derived(revisions.length + 1); // revisjoner + nåværende
	let currentVersionNumber = $derived(
		revisionIndex < 0
			? totalVersions
			: totalVersions - revisionIndex - 1
	);

	// --- Body-rendering med markdown-deteksjon ---

	function renderBody(body: string): string {
		// Sjekk om body allerede er HTML (fra Tiptap-editor)
		const isHtml = /<(?:p|div|br|span|h[1-6]|ul|ol|li|a|strong|em|code)\b/i.test(body);
		if (isHtml) return body;
		// Ellers: behandle som markdown
		return marked.parse(body, { async: false }) as string;
	}

	let activeBody = $derived(
		showingRevision ? revisions[revisionIndex]?.body ?? message.body : message.body
	);
	let displayBody = $derived(renderBody(activeBody));

	let isEdited = $derived(
		!!(message.edited_at || message.metadata?.ai_processed)
	);
</script>

<svelte:window onclick={handleWindowClick} />

{#if mode === 'expanded'}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="messagebox messagebox--expanded" class:messagebox--ai-processing={isAiProcessing} id="msg-{message.id}" onclick={handleClick}>
		{#if message.reply_to && message.parent_author_name && !isReply}
			<!-- svelte-ignore a11y_click_events_have_key_events -->
			<!-- svelte-ignore a11y_no_static_element_interactions -->
			<div class="messagebox__reply-context" onclick={(e) => { e.stopPropagation(); const el = document.getElementById(`msg-${message.reply_to}`); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' }); }}>
				↩ {message.parent_author_name}: {truncate(stripHtml(message.parent_body ?? ''), 50)}
			</div>
		{/if}
		{#if showAuthor || showTimestamp}
			<div class="messagebox__header">
				{#if showAuthor}
					<span class="messagebox__author">{message.author_name ?? 'Ukjent'}</span>
				{/if}
				{#if showTimestamp}
					<span class="messagebox__time">{formatTime(message.created_at)}</span>
				{/if}
				{#if message.pinned}
					<span class="messagebox__pinned" title="Festet">📌</span>
				{/if}
			</div>
		{/if}
		<!-- Øvre toolbar: opprett/transformer-handlinger -->
		<div class="messagebox__toolbar messagebox__toolbar--top">
			{#if isOwnMessage && !editing && callbacks.onEdit}
				<button class="messagebox__toolbar-btn" title="Rediger" onclick={startEdit}>✏️</button>
			{/if}
			{#if callbacks.onConvertToKanban}
				<button class="messagebox__toolbar-btn" title="Opprett kanban-kort" onclick={handleConvertToKanban}>📋</button>
			{/if}
			{#if callbacks.onConvertToCalendar}
				<button class="messagebox__toolbar-btn" title="Opprett kalenderhendelse" onclick={handleConvertToCalendar}>📅</button>
			{/if}
			{#if callbacks.onMagic}
				<span class="messagebox__ai-wrapper">
					<button class="messagebox__toolbar-btn" title="AI-behandling" onclick={handleMagic} disabled={isAiProcessing}>✨</button>
					{#if showAiMenu && aiPrompts.length > 1}
						<div class="messagebox__ai-menu">
							{#each aiPrompts as prompt}
								<button
									class="messagebox__ai-menu-item"
									onclick={(e) => { e.stopPropagation(); selectAiAction(prompt.action); }}
								>
									<span class="ai-menu-icon">{prompt.icon ?? '✨'}</span>
									<span class="ai-menu-label">{prompt.label ?? prompt.action}</span>
								</button>
							{/each}
						</div>
					{/if}
				</span>
			{/if}
		</div>
		<!-- Nedre toolbar: samtale-handlinger -->
		<div class="messagebox__toolbar messagebox__toolbar--bottom">
			{#if isOwnMessage && !editing && callbacks.onDelete}
				<button class="messagebox__toolbar-btn messagebox__toolbar-btn--danger" title="Slett" onclick={handleDelete}><svg class="messagebox__icon-delete" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke-linecap="round"><path d="M2.5 4h11M5.5 4V2.5h5V4M4 4l.7 9.5h6.6L12 4" stroke="#8b92a5" stroke-width="1.3"/><line x1="1" y1="15" x2="15" y2="1" stroke="#ef4444" stroke-width="2.5"/><line x1="1" y1="1" x2="15" y2="15" stroke="#ef4444" stroke-width="2.5"/></svg></button>
			{/if}
			{#if callbacks.onTogglePin}
				<button class="messagebox__toolbar-btn" title={message.pinned ? 'Løsne' : 'Fest'} onclick={handleTogglePin}>📌</button>
			{/if}
			{#if callbacks.onReply}
				<button class="messagebox__toolbar-btn" title="Svar" onclick={handleReply}>💬</button>
			{/if}
		</div>
		{#if confirmingDelete}
			<div class="messagebox__confirm-delete">
				<span>Slette melding?</span>
				<button class="messagebox__confirm-btn messagebox__confirm-btn--yes" onclick={confirmDelete}>Slett</button>
				<button class="messagebox__confirm-btn messagebox__confirm-btn--no" onclick={cancelDelete}>Avbryt</button>
			</div>
		{/if}
		{#if editing}
			<!-- svelte-ignore a11y_no_static_element_interactions -->
			<div class="messagebox__edit" onkeydown={(e) => { if (e.key === 'Escape') cancelEdit(); }}>
				<Editor
					mode="compact"
					content={editBody}
					autofocus
					onSubmit={(html) => submitEdit(html)}
				/>
				<div class="messagebox__edit-actions">
					<span class="messagebox__edit-hint">Enter = lagre · Esc = avbryt</span>
					<button class="messagebox__edit-btn messagebox__edit-btn--cancel" onclick={cancelEdit}>Avbryt</button>
				</div>
			</div>
		{:else}
			{#if expanded}
				<button class="messagebox__expand-btn" onclick={(e) => { e.stopPropagation(); expanded = false; checkClamped(); }}>
					Vis mindre
				</button>
			{/if}
			<div class="messagebox__body" class:messagebox__body--clamped={!expanded} bind:this={bodyEl}>{@html displayBody}</div>
			{#if isClamped && !expanded}
				<button class="messagebox__expand-btn" onclick={(e) => { e.stopPropagation(); expanded = true; }}>
					Vis mer
				</button>
			{:else if expanded}
				<button class="messagebox__expand-btn" onclick={(e) => { e.stopPropagation(); expanded = false; checkClamped(); }}>
					Vis mindre
				</button>
			{/if}
			{#if isAiProcessing}
				<div class="messagebox__ai-status">✨ AI behandler…</div>
			{/if}
			{#if isEdited && !editing}
				<div class="messagebox__revision-footer">
					<button class="messagebox__revision-toggle" onclick={toggleRevisions} disabled={loadingRevisions}>
						{#if loadingRevisions}
							…
						{:else if showingRevision}
							versjon {currentVersionNumber}/{totalVersions}
						{:else}
							redigert
						{/if}
					</button>
					{#if showingRevision}
						<button class="messagebox__revision-nav" onclick={prevRevision} disabled={revisionIndex >= revisions.length - 1}>&#9664;</button>
						<button class="messagebox__revision-nav" onclick={nextRevision}>&#9654;</button>
						{#if revisionIndex >= 0}
							<button class="messagebox__revision-toggle" onclick={(e) => { e.stopPropagation(); revisionIndex = -1; }}>
								nåværende
							</button>
						{/if}
					{/if}
					{#if message.metadata?.ai_action}
						{@const promptInfo = aiPrompts.find(p => p.action === message.metadata?.ai_action)}
						<span class="messagebox__ai-badge">{promptInfo?.icon ?? '✨'} {promptInfo?.label ?? message.metadata.ai_action}</span>
					{/if}
				</div>
			{/if}
		{/if}
		{#if hasReactions || callbacks.onReaction}
			<div class="messagebox__reactions">
				{#each message.reactions ?? [] as r}
					<button
						class="messagebox__reaction-pill"
						class:messagebox__reaction-pill--active={r.user_reacted}
						onclick={(e) => handleReaction(e, r.reaction)}
					>{r.reaction} {r.count}</button>
				{/each}
				{#if callbacks.onReaction && availableReactions.length > 0}
					<span class="messagebox__reaction-add">
						{#each availableReactions as emoji}
							<button
								class="messagebox__reaction-quick"
								onclick={(e) => handleReaction(e, emoji)}
							>{emoji}</button>
						{/each}
					</span>
				{/if}
			</div>
		{/if}
		{#if hasBadges}
			<div class="messagebox__badges">
				{#if message.kanban_view}
					<span class="messagebox__badge messagebox__badge--kanban">Kort</span>
				{/if}
				{#if message.calendar_view}
					<span class="messagebox__badge messagebox__badge--calendar">Hendelse</span>
				{/if}
			</div>
		{/if}
	</div>
{:else if mode === 'compact'}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div
		class="messagebox messagebox--compact"
		onclick={handleClick}
		style:border-left-color={message.kanban_view?.color ?? 'transparent'}
	>
		<div class="messagebox__title">{message.title ?? bodyPreview}</div>
		{#if message.body && message.title}
			<div class="messagebox__preview">{bodyPreview}</div>
		{/if}
	</div>
{:else if mode === 'calendar'}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div
		class="messagebox messagebox--calendar"
		onclick={handleClick}
		style:background={message.calendar_view?.color ?? '#3b82f6'}
	>
		{#if message.calendar_view && !message.calendar_view.all_day}
			<span class="messagebox__event-time">{formatTime(message.calendar_view.starts_at)}</span>
		{/if}
		{message.title ?? stripHtml(message.body)}
	</div>
{/if}

<style>
	/* === Expanded mode (chat) === */
	.messagebox--expanded {
		position: relative;
		padding: 0.3rem 0.5rem;
		border-radius: 4px;
	}

	.messagebox--expanded:hover {
		background: rgba(255, 255, 255, 0.03);
	}

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

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

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

	.messagebox__pinned {
		font-size: 0.65rem;
	}

	/* === Flytende toolbars (absolutt-posisjonert, ingen layout-shift) === */
	.messagebox__toolbar {
		position: absolute;
		right: 0.4rem;
		display: flex;
		gap: 0.1rem;
		background: #1a1d2e;
		border: 1px solid #2d3148;
		border-radius: 6px;
		padding: 0.15rem 0.2rem;
		opacity: 0;
		pointer-events: none;
		transition: opacity 0.12s;
		z-index: 5;
	}

	.messagebox__toolbar--top {
		top: -0.6rem;
	}

	.messagebox__toolbar--bottom {
		bottom: -0.6rem;
	}

	.messagebox--expanded:hover .messagebox__toolbar {
		opacity: 1;
		pointer-events: auto;
	}

	/* Skjul tomme toolbars (kun har betingede barn) */
	.messagebox__toolbar:empty {
		display: none;
	}

	.messagebox__toolbar-btn {
		font-size: 0.7rem;
		background: none;
		border: none;
		cursor: pointer;
		padding: 0.15rem 0.25rem;
		border-radius: 4px;
		line-height: 1;
		transition: background 0.12s;
	}

	.messagebox__toolbar-btn:hover {
		background: rgba(255, 255, 255, 0.1);
	}

	.messagebox__toolbar-btn--danger {
		color: #f87171;
	}

	.messagebox__toolbar-btn--danger:hover {
		background: rgba(220, 38, 38, 0.25);
	}

	.messagebox__icon-delete {
		display: block;
	}

	.messagebox__confirm-delete {
		display: flex;
		align-items: center;
		gap: 0.4rem;
		font-size: 0.7rem;
		color: #f87171;
		padding: 0.2rem 0;
	}

	.messagebox__confirm-btn {
		font-size: 0.65rem;
		padding: 0.15rem 0.4rem;
		border-radius: 4px;
		border: none;
		cursor: pointer;
		font-family: inherit;
	}

	.messagebox__confirm-btn--yes {
		background: rgba(220, 38, 38, 0.3);
		color: #f87171;
	}

	.messagebox__confirm-btn--yes:hover {
		background: rgba(220, 38, 38, 0.5);
	}

	.messagebox__confirm-btn--no {
		background: none;
		color: #8b92a5;
	}

	.messagebox__confirm-btn--no:hover {
		color: #e1e4e8;
	}

	/* === Inline edit === */
	.messagebox__edit {
		margin-top: 0.2rem;
	}

	.messagebox__edit-actions {
		display: flex;
		align-items: center;
		gap: 0.35rem;
		margin-top: 0.25rem;
		justify-content: flex-end;
	}

	.messagebox__edit-hint {
		font-size: 0.6rem;
		color: #8b92a5;
		margin-right: auto;
	}

	.messagebox__edit-btn {
		font-size: 0.7rem;
		padding: 0.2rem 0.5rem;
		border-radius: 4px;
		border: none;
		cursor: pointer;
		font-family: inherit;
	}

	.messagebox__edit-btn--cancel {
		background: none;
		color: #8b92a5;
	}

	.messagebox__edit-btn--cancel:hover {
		color: #e1e4e8;
	}

	/* === Reactions === */
	.messagebox__reactions {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: 0.25rem;
		margin-top: 0.2rem;
	}

	.messagebox__reaction-pill {
		font-size: 0.7rem;
		padding: 0.1rem 0.4rem;
		border-radius: 10px;
		border: 1px solid #2d3148;
		background: rgba(255, 255, 255, 0.04);
		color: #e1e4e8;
		cursor: pointer;
		transition: background 0.15s;
	}

	.messagebox__reaction-pill:hover {
		background: rgba(255, 255, 255, 0.1);
	}

	.messagebox__reaction-pill--active {
		border-color: #7dd3fc;
		background: rgba(125, 211, 252, 0.12);
	}

	.messagebox__reaction-add {
		display: flex;
		gap: 0.1rem;
		opacity: 0;
		transition: opacity 0.12s;
	}

	.messagebox--expanded:hover .messagebox__reaction-add {
		opacity: 1;
	}

	.messagebox__reaction-quick {
		font-size: 0.65rem;
		background: none;
		border: none;
		cursor: pointer;
		padding: 0.05rem 0.15rem;
		border-radius: 4px;
		opacity: 0.4;
		transition: opacity 0.15s;
	}

	.messagebox__reaction-quick:hover {
		opacity: 1;
		background: rgba(255, 255, 255, 0.08);
	}

	/* === Reply context === */
	.messagebox__reply-context {
		font-size: 0.7rem;
		color: #8b92a5;
		padding: 0.1rem 0.4rem;
		margin-bottom: 0.1rem;
		border-left: 2px solid #3b82f6;
		cursor: pointer;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.messagebox__reply-context:hover {
		color: #c0c6d4;
	}

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

	.messagebox__body--clamped {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.messagebox__expand-btn {
		font-size: 0.7rem;
		color: #7dd3fc;
		background: none;
		border: none;
		cursor: pointer;
		padding: 0;
		margin-top: 0.1rem;
		font-family: inherit;
	}

	.messagebox__expand-btn:hover {
		color: #bae6fd;
		text-decoration: underline;
	}

	/* === Revisjonshistorikk === */
	.messagebox__revision-footer {
		display: flex;
		align-items: center;
		gap: 0.4rem;
		margin-top: 0.2rem;
	}

	.messagebox__revision-toggle {
		font-size: 0.65rem;
		color: #8b92a5;
		background: none;
		border: none;
		cursor: pointer;
		padding: 0;
		font-family: inherit;
	}

	.messagebox__revision-toggle:hover {
		color: #7dd3fc;
	}

	.messagebox__revision-toggle:disabled {
		cursor: wait;
	}

	.messagebox__revision-nav {
		font-size: 0.65rem;
		color: #8b92a5;
		background: none;
		border: 1px solid #2d3148;
		border-radius: 3px;
		cursor: pointer;
		padding: 0 0.3rem;
		font-family: inherit;
		line-height: 1.4;
	}

	.messagebox__revision-nav:hover:not(:disabled) {
		color: #7dd3fc;
		border-color: #7dd3fc;
	}

	.messagebox__revision-nav:disabled {
		opacity: 0.3;
		cursor: default;
	}

	.messagebox__ai-badge {
		font-size: 0.65rem;
		color: #facc15;
		opacity: 0.7;
	}

	.messagebox__ai-wrapper {
		position: relative;
	}

	.messagebox__ai-menu {
		position: absolute;
		bottom: 100%;
		right: 0;
		background: #1e1e2e;
		border: 1px solid #2d3148;
		border-radius: 6px;
		padding: 0.25rem;
		display: flex;
		flex-direction: column;
		gap: 1px;
		min-width: 140px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
		z-index: 100;
	}

	.messagebox__ai-menu-item {
		display: flex;
		align-items: center;
		gap: 0.4rem;
		padding: 0.35rem 0.5rem;
		border: none;
		background: none;
		color: #cdd6f4;
		font-size: 0.8rem;
		cursor: pointer;
		border-radius: 4px;
		white-space: nowrap;
	}

	.messagebox__ai-menu-item:hover {
		background: #2d3148;
	}

	.ai-menu-icon {
		font-size: 0.9rem;
	}

	.ai-menu-label {
		flex: 1;
	}

	/* Tiptap HTML rendering */
	.messagebox__body :global(p) {
		margin: 0;
	}

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

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

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

	.messagebox__body :global(h1),
	.messagebox__body :global(h2),
	.messagebox__body :global(h3) {
		margin: 0.6em 0 0.3em;
		color: #f1f3f5;
		line-height: 1.3;
	}

	.messagebox__body :global(h1) { font-size: 1.1rem; }
	.messagebox__body :global(h2) { font-size: 1rem; }
	.messagebox__body :global(h3) { font-size: 0.9rem; }

	.messagebox__body :global(ul),
	.messagebox__body :global(ol) {
		margin: 0.3em 0;
		padding-left: 1.5em;
	}

	.messagebox__body :global(li) {
		margin-bottom: 0.15em;
	}

	.messagebox__body :global(blockquote) {
		border-left: 3px solid #3b82f6;
		margin: 0.4em 0;
		padding: 0.2em 0.6em;
		color: #8b92a5;
	}

	.messagebox__body :global(pre) {
		background: #1e2235;
		padding: 0.5em;
		border-radius: 4px;
		overflow-x: auto;
		font-size: 0.8rem;
		margin: 0.4em 0;
	}

	.messagebox__body :global(hr) {
		border: none;
		border-top: 1px solid #2d3148;
		margin: 0.5em 0;
	}

	.messagebox__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;
	}

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

	.messagebox__body :global(.mention::before) {
		content: '#';
	}

	.messagebox__badges {
		display: flex;
		gap: 0.35rem;
		margin-top: 0.25rem;
	}

	.messagebox__badge {
		font-size: 0.6rem;
		padding: 0.1rem 0.35rem;
		border-radius: 3px;
		color: #e1e4e8;
	}

	.messagebox__badge--kanban {
		background: rgba(59, 130, 246, 0.2);
	}

	.messagebox__badge--calendar {
		background: rgba(16, 185, 129, 0.2);
	}

	/* === AI-prosessering === */
	.messagebox--ai-processing {
		animation: ai-pulse 2s ease-in-out infinite;
	}

	@keyframes ai-pulse {
		0%, 100% { background: transparent; }
		50% { background: rgba(250, 204, 21, 0.06); }
	}

	.messagebox__ai-status {
		font-size: 0.7rem;
		color: #facc15;
		margin-top: 0.2rem;
		animation: ai-pulse-text 1.5s ease-in-out infinite;
	}

	@keyframes ai-pulse-text {
		0%, 100% { opacity: 0.5; }
		50% { opacity: 1; }
	}

	/* === Compact mode (kanban) === */
	.messagebox--compact {
		border-left: 3px solid transparent;
		padding-left: 0.4rem;
	}

	.messagebox__title {
		font-size: 0.8rem;
		color: #e1e4e8;
		line-height: 1.3;
	}

	.messagebox__preview {
		font-size: 0.7rem;
		color: #8b92a5;
		margin-top: 0.25rem;
		line-height: 1.3;
	}

	/* === Calendar mode (pill) === */
	.messagebox--calendar {
		font-size: 0.6rem;
		color: white;
		padding: 0.1rem 0.25rem;
		border-radius: 3px;
		margin-top: 1px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		cursor: pointer;
		border: none;
		text-align: left;
		font-family: inherit;
		line-height: 1.3;
	}

	.messagebox--calendar:hover {
		filter: brightness(1.2);
	}

	.messagebox__event-time {
		font-weight: 600;
		margin-right: 0.2rem;
		opacity: 0.85;
	}
</style>
