<script lang="ts">
	import type { Snippet } from 'svelte';
	import { getSelectionContext } from './Selection.svelte';

	interface SnippetProps {
		onclick: (event: MouseEvent) => void;
		onauxclick: (event: MouseEvent) => void;
		selected: boolean;
	}

	interface Props {
		id: number;
		index: number;
		onclick?: (id: number) => void;
		onauxclick?: (id: number) => void;
		children?: Snippet<[SnippetProps]>;
	}

	let {
		id,
		index,
		onclick: onclick = undefined,
		onauxclick = undefined,
		children
	}: Props = $props();

	let selection = getSelectionContext();

	const click = (event: MouseEvent) => {
		if (selection.active) {
			selection.update(index, event.shiftKey);
			event.preventDefault();
		} else if (event.ctrlKey && onauxclick) {
			onauxclick(id);
		} else if (onclick) {
			onclick(id);
			event.preventDefault();
		}
	};

	const auxclick = (event: MouseEvent) => {
		if (event.button === 1 && onauxclick) {
			onauxclick(id);
		}
	};
</script>

{@render children?.({ onclick: click, onauxclick: auxclick, selected: selection.contains(id) })}
