<script lang="ts">
	import { getTodoCollection } from '$lib/todocollectionscontext';
	import { useLiveQuery } from '@tanstack/svelte-db';
	import Todo from './Todo.svelte';

	const todoCollection = getTodoCollection();
	const data = useLiveQuery((q) => q.from({ todos: todoCollection }));
	const todos = $derived.by(() => {
		return data.data.toSorted((a, b) => {
			if (a.done != b.done) {
				return a.done ? -1 : 1;
			}
			if (!a.done && !b.done) {
				const adate = a.createdAt ? new Date(a.createdAt) : new Date();
				const bdate = b.createdAt ? new Date(b.createdAt) : new Date();
				return bdate.getTime() - adate.getTime();
			}
			return 0;
		});
	});
</script>

{#if data.isLoading}
	<div>Loading...</div>
{:else}
	{#each todos as todo (todo.id)}
		<Todo {todo} />
	{/each}
{/if}
