<script lang="ts">
	import ImageLightbox from './ImageLightbox.svelte';

	interface ImageData {
		id: string;
		ext: string;
		filename: string;
	}

	interface Props {
		images: ImageData[];
		entryId: string;
		editMode?: boolean;
		onDelete?: (imageId: string) => void;
	}

	let { images, entryId, editMode = false, onDelete }: Props = $props();

	// Lightbox state
	let lightboxOpen = $state(false);
	let lightboxIndex = $state(0);

	function openLightbox(index: number) {
		lightboxIndex = index;
		lightboxOpen = true;
	}

	function closeLightbox() {
		lightboxOpen = false;
	}

	function handleDelete(imageId: string) {
		onDelete?.(imageId);
	}
</script>

<div class="flex gap-2 overflow-x-auto py-2 -mx-2 px-2 scrollbar-thin">
	{#each images as image, i}
		<div class="relative flex-shrink-0">
			<button
				type="button"
				onclick={() => openLightbox(i)}
				class="block rounded-lg overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-500"
			>
				<img
					src="/api/images/{image.id}/thumbnail"
					alt={image.filename}
					class="w-20 h-20 object-cover"
					loading="lazy"
				/>
			</button>

			{#if editMode}
				<button
					type="button"
					onclick={() => handleDelete(image.id)}
					class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center shadow-md hover:bg-red-600 transition-colors"
					aria-label="Delete image"
				>
					<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M6 18L18 6M6 6l12 12"
						/>
					</svg>
				</button>
			{/if}
		</div>
	{/each}
</div>

{#if lightboxOpen}
	<ImageLightbox {images} startIndex={lightboxIndex} onClose={closeLightbox} />
{/if}

<style>
	.scrollbar-thin::-webkit-scrollbar {
		height: 4px;
	}
	.scrollbar-thin::-webkit-scrollbar-track {
		background: transparent;
	}
	.scrollbar-thin::-webkit-scrollbar-thumb {
		background: #d1d5db;
		border-radius: 2px;
	}
</style>
