<script lang="ts">
	import { currentCollective } from '$lib/stores/collective';
	import { currentUser } from '$lib/stores/auth';
	import { loadTrashedNotes, restoreNote, permanentDeleteNote } from '$lib/stores/notes';
	import type { Note } from '@colectivo/types';
	import { ArrowLeft, ArchiveRestore, Trash2 } from 'lucide-svelte';
	import * as m from '$lib/paraglide/messages';

	let trashed = $state<Note[]>([]);
	let loading = $state(true);

	$effect(() => {
		if ($currentCollective) {
			(async () => {
				loading = true;
				trashed = await loadTrashedNotes($currentCollective.id);
				loading = false;
			})();
		}
	});

	async function handleRestore(id: string) {
		if (!$currentUser) return;
		await restoreNote(id, $currentUser.id);
		trashed = trashed.filter((n) => n.id !== id);
	}

	async function handlePurge(id: string) {
		if (!confirm(m.confirm_delete())) return;
		await permanentDeleteNote(id);
		trashed = trashed.filter((n) => n.id !== id);
	}
</script>

<svelte:head><title>{m.notes_trash_view()} — Colectivo</title></svelte:head>

<div class="flex h-full flex-col overflow-hidden">
	<header class="flex h-14 items-center gap-2 border-b border-black/5 px-6 dark:border-white/5">
		<a href="/notes" class="rounded p-1 text-text-secondary hover:bg-black/5 dark:hover:bg-white/5" aria-label={m.notes_back_to_board()}>
			<ArrowLeft size={18} strokeWidth={1.5} />
		</a>
		<h1 class="text-base font-semibold text-text-primary">{m.notes_trash_view()}</h1>
	</header>

	<div class="flex-1 overflow-y-auto px-6 py-6">
		{#if loading}
			<p class="text-sm text-text-secondary">{m.loading()}</p>
		{:else if trashed.length === 0}
			<p class="text-sm text-text-secondary">{m.notes_trash_empty()}</p>
		{:else}
			<div class="space-y-2">
				{#each trashed as note (note.id)}
					<div role="listitem" data-testid="note-card" class="flex items-center gap-3 rounded-md bg-surface-raised p-3">
						<div class="min-w-0 flex-1">
							{#if note.title}
								<h3 class="truncate text-sm font-semibold text-text-primary">{note.title}</h3>
							{/if}
							<p class="truncate text-xs text-text-secondary">{note.content}</p>
						</div>
						<button
							type="button"
							onclick={() => handleRestore(note.id)}
							aria-label={m.notes_restore()}
							class="rounded p-1.5 text-text-secondary hover:bg-black/5 dark:hover:bg-white/5"
						>
							<ArchiveRestore size={16} strokeWidth={1.5} />
						</button>
						<button
							type="button"
							onclick={() => handlePurge(note.id)}
							aria-label={m.trash_delete_permanent()}
							class="rounded p-1.5 text-text-secondary hover:bg-black/5 dark:hover:bg-white/5"
						>
							<Trash2 size={16} strokeWidth={1.5} />
						</button>
					</div>
				{/each}
			</div>
		{/if}
	</div>
</div>
