<!-- TerminalComponent.svelte -->

<script lang="ts">
	import { createMessage } from '$lib/services/messages/messages';
	import { drawerStore } from '@skeletonlabs/skeleton';
	import type { DrawerSettings } from '@skeletonlabs/skeleton';
	import { Avatar } from '@skeletonlabs/skeleton';

	const drawerSettings: DrawerSettings = {
		position: 'bottom',
		id: 'drawer',
		meta: { id: 'navigation', component: 'Navigation' },
		height: 'auto'
	};

	const openDrawer = () => {
		drawerStore.open(drawerSettings);
	};

	let newMessageText = '';

	function handleKeyDown(event) {
		if (event.key === 'Enter') {
			sendMessage(newMessageText);
			newMessageText = '';
			event.preventDefault();
		}
	}

	function sendMessage(text) {
		if (text && text.trim() !== '') {
			const message = {
				text: text,
				sender: 'user',
				type: 'chat'
			};

			const appCommandPattern = /@(\w+)/;
			const match = text.match(appCommandPattern);
			if (match && match[1]) {
				message.composite = {
					id: match[1],
					component: match[1]
				};
			}
			createMessage(message);
		}
	}
</script>

<div class="input-group input-group-divider grid-cols-[auto_1fr_auto] rounded-container-token h-14">
	<button class="input-group-shim" on:drawer{closeDrawer} on:click={openDrawer}>
		<Avatar src="/logo.png" width="w-10" rounded="rounded-full" />
	</button>

	<input
		class="p-4 bg-transparent border-0 ring-0"
		name="prompt"
		id="prompt"
		placeholder="Write a message..."
		rows="1"
		bind:value={newMessageText}
		on:keydown={handleKeyDown}
	/>
	<button class="variant-filled-primary" on:click={() => sendMessage(newMessageText)}>Send</button>
</div>
