<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import WishlistSection from '$lib/components/dashboard/WishlistSection.svelte';
	import { getLocalWishlists, forgetLocalWishlist, toggleLocalFavorite, type LocalWishlist } from '$lib/utils/localWishlists';
	import { languageStore } from '$lib/stores/language.svelte';
	import { Star } from 'lucide-svelte';
	import { onMount } from 'svelte';

	let {
		isAuthenticated = false
	}: {
		isAuthenticated?: boolean;
	} = $props();

	const t = $derived(languageStore.t);

	let localWishlists = $state<LocalWishlist[]>([]);

	// Load local wishlists on mount (client-side only)
	onMount(() => {
		localWishlists = getLocalWishlists();
	});

	function handleForget(ownerToken: string) {
		forgetLocalWishlist(ownerToken);
		localWishlists = getLocalWishlists();
	}

	function handleToggleFavorite(ownerToken: string) {
		toggleLocalFavorite(ownerToken);
		localWishlists = getLocalWishlists();
	}

	// Transform LocalWishlist to match the format expected by WishlistSection
	const transformedWishlists = $derived(() => {
		return localWishlists.map(w => ({
			id: w.ownerToken,
			title: w.title,
			ownerToken: w.ownerToken,
			publicToken: w.publicToken,
			createdAt: w.createdAt,
			isFavorite: w.isFavorite || false,
			items: [] // We don't have item data in localStorage
		}));
	});
</script>

{#if localWishlists.length > 0}
	<WishlistSection
		title={t.dashboard.localWishlists || "Local Wishlists"}
		description={t.dashboard.localWishlistsDescription || "Wishlists stored in your browser. Sign in to save them permanently."}
		items={transformedWishlists()}
		emptyMessage=""
	>
		{#snippet actions(wishlist, unlocked)}
			<div class="flex gap-2 flex-wrap">
				<Button
					size="sm"
					variant="outline"
					onclick={() => handleToggleFavorite(wishlist.ownerToken)}
				>
					<Star class={wishlist.isFavorite ? "fill-yellow-500 text-yellow-500" : ""} />
				</Button>
				<Button
					size="sm"
					onclick={() => (window.location.href = `/wishlist/${wishlist.ownerToken}/edit`)}
				>
					{t.dashboard.manage}
				</Button>
				<Button
					size="sm"
					variant="outline"
					onclick={() => {
						navigator.clipboard.writeText(
							`${window.location.origin}/wishlist/${wishlist.publicToken}`
						);
					}}
				>
					{t.dashboard.copyLink}
				</Button>
				{#if unlocked}
					<Button
						size="sm"
						variant="destructive"
						onclick={() => handleForget(wishlist.ownerToken)}
					>
						{t.dashboard.forget || "Forget"}
					</Button>
				{/if}
			</div>
		{/snippet}
	</WishlistSection>
{/if}
