<script lang="ts">
	import { messages as WSMsg } from '$lib/core/handlers/messageHandler';
	import * as Card from './ui/card/index';
	import { ScrollArea } from './ui/scroll-area/index';
	import { Separator } from './ui/separator/index';
	import { permission as currentPermissions } from '$lib/core/stores/permissions';
	import { get } from 'svelte/store';
	import { needPermission, requirePermission } from '$lib/core/handlers/permissionHandler';
	import DashboardQuickAdb from './dashboard-quick-adb.svelte';
	import MachineInfo from './machine-info.svelte';
	import { departmentStore } from '$lib/core/stores/departments.ts';
	import { onDestroy } from 'svelte';

	let activities: string[] = $state([]);
	let activitiesLogElement: HTMLElement | undefined = $state();

	function scrollToLatest(node: HTMLElement) {
		node.scroll({
			top: node.scrollHeight,
			behavior: 'smooth'
		});
	}

	let unsubWebSocketMsg = WSMsg.subscribe((history) => {
		activities = history;
	});

	let perms = get(currentPermissions);

	$effect.pre(() => {
		if (activitiesLogElement && activities) {
		}
	});

	$effect(() => {
		if (activitiesLogElement && activities) {
			scrollToLatest(activitiesLogElement);
		}
	});

	onDestroy(() => {
		unsubWebSocketMsg();
	});

	console.log('current department: ', get(departmentStore));
</script>

<div class="grid grid-flow-row-dense grid-cols-3 grid-rows-3">
	<div class="col-span-2 p-4">
		<Card.Root class=" h-full w-full bg-muted/50">
			<Card.Header>
				<Card.Title>Latest Activity</Card.Title>
				<Card.Description>Real time activities. Click to view full activities.</Card.Description>
				<!-- add view full activity popup -->
			</Card.Header>
			<Card.Content>
				<ScrollArea class="h-full max-h-50 w-full rounded-md border" ref={activitiesLogElement}>
					<div class="h-max p-4">
						{#if activities.length > 0}
							{#each activities as activity}
								<div class="text-sm">
									{activity}
								</div>
								<Separator class="my-2" />
							{/each}
						{:else}
							<div class="text-sm">No ongoing activity right now!</div>
							<Separator class="my-2" />
						{/if}
					</div>
				</ScrollArea>
			</Card.Content>
		</Card.Root>
	</div>

	<!-- needPermission('tools.core.*') -->
	<DashboardQuickAdb enableComponent={true} />

	<!-- needPermission('tools.core.*') -->
	<MachineInfo enableComponent={true} />
</div>
