<script lang="ts">
	import { currentCollective } from '$lib/stores/collective';
	import { currentUser } from '$lib/stores/auth';
	import { loadArchivedNotes, unarchiveNote, trashNote } 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 archived = $state<Note[]>([]);
	let loading = $state(true);

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

	async function handleUnarchive(id: string) {
		if (!$currentUser) return;
		await unarchiveNote(id, $currentUser.id);
		archived = archived.filter((n) => n.id !== id);
	}

	async function handleTrash(id: string) {
		if (!$currentUser) return;
		await trashNote(id, $currentUser.id);
		archived = archived.filter((n) => n.id !== id);
	}
</script>

<svelte:head><title>{m.notes_archive_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_archive_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 archived.length === 0}
			<p class="text-sm text-text-secondary">{m.notes_archived_empty()}</p>
		{:else}
			<div class="space-y-2">
				{#each archived as note (note.id)}
					<div role="listitem" data-testid="note-card" class="flex items-center gap-3 rounded-md bg-surface-raised p-3">
						<a href={`/notes/${note.id}`} 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>
						</a>
						<button
							type="button"
							onclick={() => handleUnarchive(note.id)}
							aria-label={m.notes_unarchive()}
							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={() => handleTrash(note.id)}
							aria-label={m.notes_send_to_trash()}
							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>
