<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { currentCollective } from '$lib/stores/collective';
	import { currentUser } from '$lib/stores/auth';
	import {
		lists,
		listsLoading,
		loadLists,
		loadTrashedLists,
		createList,
		softDeleteList,
		restoreList,
		permanentDeleteList,
		archiveList,
		resetList
	} from '$lib/stores/lists';
	import type { ShoppingList } from '@colectivo/types';
	import { ShoppingCart, Plus, MoreHorizontal, Trash2, Archive, RotateCcw } from 'lucide-svelte';
	import * as m from '$lib/paraglide/messages';
	import ScreenMasthead from '$lib/components/ScreenMasthead.svelte';

	// ── State ──────────────────────────────────────────────────────────────────

	let creating = $state(false);

	let showTrash = $state(false);
	let trashedLists = $state<ShoppingList[]>([]);
	let trashLoading = $state(false);

	let openMenuId = $state<string | null>(null);

	// ── Derived ────────────────────────────────────────────────────────────────

	const activeLists = $derived($lists.filter((l) => l.status === 'active'));
	const completedLists = $derived($lists.filter((l) => l.status === 'completed'));
	const featuredList = $derived(activeLists[0] ?? null);
	const gridLists = $derived(activeLists.slice(1));

	// ── Load ───────────────────────────────────────────────────────────────────

	$effect(() => {
		if ($currentCollective) {
			loadLists($currentCollective.id);
		}
	});

	async function toggleTrash() {
		showTrash = !showTrash;
		if (showTrash && $currentCollective) {
			trashLoading = true;
			trashedLists = await loadTrashedLists($currentCollective.id);
			trashLoading = false;
		}
	}

	// ── Create ─────────────────────────────────────────────────────────────────
	// Matches the /notes flow: click the masthead button → create with an empty
	// name → navigate to /lists/[id] where the user renames inline.

	async function handleCreate() {
		if (!$currentCollective || !$currentUser || creating) return;
		creating = true;
		const created = await createList($currentCollective.id, '', $currentUser.id);
		creating = false;
		if (created) await goto(`/lists/${created.id}`);
	}

	// ── Actions ────────────────────────────────────────────────────────────────

	function toggleMenu(id: string, e: MouseEvent) {
		e.stopPropagation();
		openMenuId = openMenuId === id ? null : id;
	}

	function closeMenu() {
		openMenuId = null;
	}

	async function handleArchive(id: string) {
		closeMenu();
		await archiveList(id);
	}

	async function handleReset(id: string) {
		closeMenu();
		await resetList(id);
	}

	async function handleDelete(id: string) {
		closeMenu();
		await softDeleteList(id);
	}

	async function handleRestore(id: string) {
		if (!$currentCollective) return;
		await restoreList(id, $currentCollective.id);
		trashedLists = trashedLists.filter((l) => l.id !== id);
	}

	async function handlePermanentDelete(id: string) {
		await permanentDeleteList(id);
		trashedLists = trashedLists.filter((l) => l.id !== id);
	}

	// Dismiss open menu on outside click
	function handleWindowClick() {
		openMenuId = null;
	}

	// ── Helpers ────────────────────────────────────────────────────────────────

	function trashDaysLeft(deletedAt: string): number {
		const expiry = new Date(deletedAt).getTime() + 7 * 24 * 60 * 60 * 1000;
		return Math.max(0, Math.ceil((expiry - Date.now()) / (24 * 60 * 60 * 1000)));
	}
</script>

<svelte:window onclick={handleWindowClick} />

<div class="flex flex-1 flex-col overflow-hidden">
	<ScreenMasthead label={m.masthead_lists_label()} title={m.lists_title()}>
		{#snippet actions()}
			<button
				onclick={toggleTrash}
				aria-label={m.lists_trash()}
				class="rounded p-1.5 {showTrash
					? 'bg-slate-900 text-white dark:bg-white dark:text-slate-900'
					: 'text-text-secondary hover:bg-black/5 dark:hover:bg-white/5'}"
			>
				<Trash2 size={16} strokeWidth={1.5} />
			</button>
			<button
				type="button"
				onclick={handleCreate}
				disabled={creating || !$currentCollective}
				class="ml-1 inline-flex items-center gap-1 rounded-md bg-slate-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-60 dark:bg-slate-100 dark:text-slate-900"
			>
				<Plus size={14} strokeWidth={2} />
				{m.lists_new_list()}
			</button>
		{/snippet}
	</ScreenMasthead>

	<!-- Content -->
	<div class="flex-1 overflow-y-auto px-4 pb-6 md:px-6">
		{#if showTrash}
			<!-- Trash view -->
			<div class="mb-6">
				<p class="mb-3 text-[13px] font-semibold uppercase tracking-[0.05em] text-text-secondary">
					{m.lists_trash()}
				</p>
				{#if trashLoading}
					<p class="text-sm text-text-muted">{m.loading()}</p>
				{:else if trashedLists.length === 0}
					<p class="text-sm text-text-muted">{m.trash_empty()}</p>
				{:else}
					<div class="space-y-1">
						{#each trashedLists as list (list.id)}
							<div
								class="flex items-center gap-3 rounded-lg bg-surface px-4 py-3"
							>
								<ShoppingCart size={16} strokeWidth={1.5} class="shrink-0 text-text-muted" />
								<span class="min-w-0 flex-1 truncate text-sm text-text-primary">{list.name}</span>
								<span class="shrink-0 text-[12px] text-text-muted">
									{m.trash_expires_in({ days: trashDaysLeft(list.deleted_at!) })}
								</span>
								<button
									onclick={() => handleRestore(list.id)}
									class="shrink-0 rounded px-2 py-1 text-[12px] font-medium text-slate-600
										hover:bg-black/5 dark:text-slate-400 dark:hover:bg-white/5"
								>
									{m.trash_restore()}
								</button>
								<button
									onclick={() => handlePermanentDelete(list.id)}
									class="shrink-0 rounded px-2 py-1 text-[12px] font-medium text-destructive
										hover:bg-destructive/10"
								>
									{m.trash_delete_permanent()}
								</button>
							</div>
						{/each}
					</div>
				{/if}
			</div>
		{:else if $listsLoading}
			<!-- Loading state -->
			<div class="space-y-3">
				{#each [1, 2, 3] as i}
					<div class="h-24 animate-pulse rounded-lg bg-surface-container-low" aria-hidden="true"></div>
				{/each}
			</div>
		{:else if activeLists.length === 0 && completedLists.length === 0}
			<!-- Empty state -->
			<div class="flex flex-col items-center justify-center py-16 text-center">
				<div class="mb-4 rounded-full bg-surface-container-low p-4">
					<ShoppingCart size={24} strokeWidth={1.5} class="text-text-muted" />
				</div>
				<p class="mb-1 text-sm font-medium text-text-primary">{m.lists_no_lists()}</p>
				<p class="text-sm text-text-muted">{m.lists_create_first()}</p>
			</div>
		{:else}
			<!-- Featured list (first active list) -->
			{#if featuredList}
				<div class="relative mb-4">
					<a
						href="/lists/{featuredList.id}"
						class="block rounded-lg bg-surface p-5 shadow-[0px_2px_8px_rgba(15,23,42,0.04)]
							hover:shadow-[0px_4px_16px_rgba(15,23,42,0.08)] transition-shadow"
					>
						<div class="mb-3 flex items-start justify-between">
							<div class="flex items-center gap-2">
								<ShoppingCart size={16} strokeWidth={1.5} class="text-text-muted" />
								<span class="text-[13px] font-semibold uppercase tracking-[0.05em] text-text-secondary">
									{m.list_status_active()}
								</span>
							</div>
						</div>
						<h2 class="text-[18px] font-semibold tracking-[-0.01em] text-slate-900 dark:text-slate-50">
							{featuredList.name}
						</h2>
					</a>
					<!-- Action menu -->
					<div class="absolute right-3 top-3">
						<button
							onclick={(e) => toggleMenu(featuredList.id, e)}
							class="rounded-md p-1.5 text-text-muted hover:bg-black/5 dark:hover:bg-white/5"
							aria-label={m.list_actions()}
						>
							<MoreHorizontal size={16} strokeWidth={1.5} />
						</button>
						{#if openMenuId === featuredList.id}
							<div
								class="absolute right-0 top-full z-10 mt-1 w-44 rounded-lg bg-surface
									shadow-[0px_20px_40px_rgba(15,23,42,0.1)] dark:shadow-[0px_20px_40px_rgba(0,0,0,0.3)]"
							>
								<button
									onclick={() => handleReset(featuredList.id)}
									class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-slate-700
										hover:bg-black/5 dark:text-slate-300 dark:hover:bg-white/5 rounded-t-lg"
								>
									<RotateCcw size={14} strokeWidth={1.5} />
									{m.list_reset()}
								</button>
								<button
									onclick={() => handleArchive(featuredList.id)}
									class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-slate-700
										hover:bg-black/5 dark:text-slate-300 dark:hover:bg-white/5"
								>
									<Archive size={14} strokeWidth={1.5} />
									{m.list_archive()}
								</button>
								<button
									onclick={() => handleDelete(featuredList.id)}
									class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-destructive
										hover:bg-destructive/10 rounded-b-lg"
								>
									<Trash2 size={14} strokeWidth={1.5} />
									{m.list_delete()}
								</button>
							</div>
						{/if}
					</div>
				</div>
			{/if}

			<!-- Grid of remaining active lists (2 col mobile, 3 col md+) -->
			{#if gridLists.length > 0}
				<div class="mb-4 grid grid-cols-2 gap-3 md:grid-cols-3">
					{#each gridLists as list (list.id)}
						<div class="relative">
							<a
								href="/lists/{list.id}"
								class="block rounded-lg bg-surface p-4 shadow-[0px_2px_8px_rgba(15,23,42,0.04)]
									hover:shadow-[0px_4px_16px_rgba(15,23,42,0.08)] transition-shadow"
							>
								<div class="mb-1 flex items-center gap-1.5">
									<ShoppingCart size={14} strokeWidth={1.5} class="text-text-muted" />
								</div>
								<h3 class="text-[15px] font-semibold tracking-[-0.01em] text-slate-900
									dark:text-slate-50 truncate">
									{list.name}
								</h3>
							</a>
							<div class="absolute right-2 top-2">
								<button
									onclick={(e) => toggleMenu(list.id, e)}
									class="rounded-md p-1 text-text-muted hover:bg-black/5 dark:hover:bg-white/5"
									aria-label={m.list_actions()}
								>
									<MoreHorizontal size={14} strokeWidth={1.5} />
								</button>
								{#if openMenuId === list.id}
									<div
										class="absolute right-0 top-full z-10 mt-1 w-44 rounded-lg bg-surface
											shadow-[0px_20px_40px_rgba(15,23,42,0.1)] dark:shadow-[0px_20px_40px_rgba(0,0,0,0.3)]"
									>
										<button
											onclick={() => handleReset(list.id)}
											class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-slate-700
												hover:bg-black/5 dark:text-slate-300 dark:hover:bg-white/5 rounded-t-lg"
										>
											<RotateCcw size={14} strokeWidth={1.5} />
											{m.list_reset()}
										</button>
										<button
											onclick={() => handleArchive(list.id)}
											class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-slate-700
												hover:bg-black/5 dark:text-slate-300 dark:hover:bg-white/5"
										>
											<Archive size={14} strokeWidth={1.5} />
											{m.list_archive()}
										</button>
										<button
											onclick={() => handleDelete(list.id)}
											class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-destructive
												hover:bg-destructive/10 rounded-b-lg"
										>
											<Trash2 size={14} strokeWidth={1.5} />
											{m.list_delete()}
										</button>
									</div>
								{/if}
							</div>
						</div>
					{/each}
				</div>
			{/if}

			<!-- Completed lists -->
			{#if completedLists.length > 0}
				<div class="mt-6">
					<p class="mb-3 text-[13px] font-semibold uppercase tracking-[0.05em] text-text-secondary">
						{m.list_status_completed()}
					</p>
					<div class="space-y-1">
						{#each completedLists as list (list.id)}
							<div class="relative flex items-center gap-3 rounded-lg bg-surface px-4 py-3">
								<ShoppingCart size={15} strokeWidth={1.5} class="shrink-0 text-text-muted" />
								<a
									href="/lists/{list.id}"
									class="min-w-0 flex-1 truncate text-sm text-slate-600 hover:text-slate-900
										dark:text-slate-400 dark:hover:text-slate-50"
								>
									{list.name}
								</a>
								<button
									onclick={(e) => toggleMenu(list.id, e)}
									class="shrink-0 rounded-md p-1 text-text-muted hover:bg-black/5 dark:hover:bg-white/5"
									aria-label={m.list_actions()}
								>
									<MoreHorizontal size={14} strokeWidth={1.5} />
								</button>
								{#if openMenuId === list.id}
									<div
										class="absolute right-8 top-1 z-10 w-44 rounded-lg bg-surface
											shadow-[0px_20px_40px_rgba(15,23,42,0.1)] dark:shadow-[0px_20px_40px_rgba(0,0,0,0.3)]"
									>
										<button
											onclick={() => handleReset(list.id)}
											class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-slate-700
												hover:bg-black/5 dark:text-slate-300 dark:hover:bg-white/5 rounded-t-lg"
										>
											<RotateCcw size={14} strokeWidth={1.5} />
											{m.list_reset()}
										</button>
										<button
											onclick={() => handleArchive(list.id)}
											class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-slate-700
												hover:bg-black/5 dark:text-slate-300 dark:hover:bg-white/5"
										>
											<Archive size={14} strokeWidth={1.5} />
											{m.list_archive()}
										</button>
										<button
											onclick={() => handleDelete(list.id)}
											class="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-destructive
												hover:bg-destructive/10 rounded-b-lg"
										>
											<Trash2 size={14} strokeWidth={1.5} />
											{m.list_delete()}
										</button>
									</div>
								{/if}
							</div>
						{/each}
					</div>
				</div>
			{/if}
		{/if}
	</div>

</div>
