<script lang="ts">
	import { MessageCirclePlus } from '@lucide/svelte';
	import { useNodes, useSvelteFlow, type Node } from '@xyflow/svelte';

	import * as ContextMenu from '$lib/components/ui/context-menu/index.js';
	import { MAX_DEFAULT_MODELS } from '$lib';
	import type { ChatModel } from '$lib/helpers/types';
	import { modelsState } from '$lib/state/models.svelte';

	let triggerRef: HTMLDivElement | null = null;
	const { update: updateNodes } = useNodes();

	export function openAt(e: MouseEvent) {
		const syntheticEvent = new MouseEvent('contextmenu', {
			clientX: e.clientX,
			clientY: e.clientY,
			bubbles: true
		});
		(syntheticEvent as MouseEvent & { __contextMenuSynthetic?: true }).__contextMenuSynthetic =
			true;
		triggerRef?.dispatchEvent(syntheticEvent);
	}

	function handleNewChat() {
		const newNodeId = `user-${crypto.randomUUID()}`;
		const newNode: Node = {
			id: newNodeId,
			type: 'user',
			position: {
				x: 0,
				y: 0
			},
			data: {
				role: 'user',
				isParentNode: true,
				selectedModels: modelsState.models.slice(0, MAX_DEFAULT_MODELS).map((m) => m.id) as string[]
			}
		};
		updateNodes((currentNodes) => {
			const firstNode = currentNodes.find((node) => node.data.isFirstNode);
			const updatedNodes = currentNodes.map((node) => {
				if (node.id === firstNode?.id) {
					return { ...node, data: { ...node.data, showWelcome: false } };
				}
				return node;
			});
			return [...updatedNodes, newNode];
		});
	}
</script>

<ContextMenu.Root>
	<ContextMenu.Trigger bind:ref={triggerRef}>
		<div class="absolute inset-0" aria-hidden="true"></div>
	</ContextMenu.Trigger>
	<ContextMenu.Content>
		<ContextMenu.Item onclick={handleNewChat}>
			<MessageCirclePlus />
			New chat
		</ContextMenu.Item>
	</ContextMenu.Content>
</ContextMenu.Root>
