<script lang="ts">
	import { ExternalLink, ChevronDown, Link } from 'lucide-svelte';
	import { slide } from 'svelte/transition';
	import type { LinkGroupWidgetConfig } from '$lib/types/widget.js';

	interface Props {
		config: LinkGroupWidgetConfig;
	}

	let { config }: Props = $props();

	let collapsed = $state(false);

	const isCollapsible = $derived(config.collapsible ?? false);
	const links = $derived(config.links ?? []);
</script>

<div class="flex h-full flex-col rounded-xl border border-border bg-card p-4">
	<!-- Header -->
	{#if isCollapsible}
		<button
			type="button"
			onclick={() => (collapsed = !collapsed)}
			class="mb-2 flex w-full items-center justify-between text-left"
		>
			<div class="flex items-center gap-2">
				<Link class="h-4 w-4 text-muted-foreground" />
				<span class="text-sm font-medium text-foreground">Links</span>
				<span class="text-xs text-muted-foreground">({links.length})</span>
			</div>
			<ChevronDown
				class="h-4 w-4 text-muted-foreground transition-transform {collapsed ? '-rotate-90' : ''}"
			/>
		</button>
	{:else}
		<div class="mb-2 flex items-center gap-2">
			<Link class="h-4 w-4 text-muted-foreground" />
			<span class="text-sm font-medium text-foreground">Links</span>
		</div>
	{/if}

	<!-- Links list -->
	{#if !collapsed}
		<div transition:slide={{ duration: 200 }}>
			{#if links.length === 0}
				<p class="text-xs text-muted-foreground">No links configured</p>
			{:else}
				<div class="space-y-0.5">
					{#each links as link (link.url + link.label)}
						<a
							href={link.url}
							target="_blank"
							rel="noopener noreferrer"
							class="flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-foreground transition-colors hover:bg-muted/50 hover:text-primary"
						>
							{#if link.icon}
								<span class="flex-shrink-0 text-base">{link.icon}</span>
							{:else}
								<ExternalLink class="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
							{/if}
							<span class="min-w-0 flex-1 truncate">{link.label}</span>
						</a>
					{/each}
				</div>
			{/if}
		</div>
	{/if}
</div>
