<script lang="ts">
	import { onMount } from 'svelte';

	interface ImmichAsset {
		id: string;
		type: string;
		fileCreatedAt: string;
	}

	let {
		open = $bindable(false),
		multiple = true,
		onselect
	}: {
		open: boolean;
		multiple?: boolean;
		onselect: (assetIds: string[]) => void;
	} = $props();

	let assets = $state<ImmichAsset[]>([]);
	let loading = $state(true);
	let currentPage = $state(1);
	let hasMore = $state(true);
	let selected = $state<Set<string>>(new Set());
	let searchQuery = $state('');
	let searchTimer: ReturnType<typeof setTimeout>;
	let errorMsg = $state('');

	async function loadAssets(reset = false) {
		if (reset) { currentPage = 1; hasMore = true; assets = []; }
		loading = true;
		errorMsg = '';
		try {
			const body: Record<string, unknown> = {
				type: 'IMAGE',
				size: 20,
				page: reset ? 1 : currentPage,
				order: 'desc'
			};
			if (searchQuery.trim()) {
				body.originalFileName = searchQuery.trim();
			}
			const res = await fetch('/api/immich/search/metadata', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				credentials: 'include',
				body: JSON.stringify(body)
			});
			if (res.ok) {
				const data = await res.json();
				const items = data.assets?.items || [];
				assets = reset ? items : [...assets, ...items];
				hasMore = items.length === 20;
				currentPage = (reset ? 1 : currentPage) + 1;
			} else {
				errorMsg = 'Failed to load photos (' + res.status + ')';
			}
		} catch {
			errorMsg = 'Could not connect to photo library';
		}
		finally { loading = false; }
	}

	function toggleSelect(id: string) {
		const next = new Set(selected);
		if (next.has(id)) next.delete(id);
		else { if (!multiple) next.clear(); next.add(id); }
		selected = next;
	}

	function confirmSelection() {
		onselect(Array.from(selected));
		selected = new Set();
		open = false;
	}

	function close() {
		selected = new Set();
		open = false;
	}

	function onSearch() {
		clearTimeout(searchTimer);
		searchTimer = setTimeout(() => loadAssets(true), 400);
	}

	// Load photos as soon as this component mounts
	onMount(() => { loadAssets(true); });
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="immich-overlay" onclick={close}>
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="immich-modal" onclick={(e) => e.stopPropagation()}>
		<div class="immich-header">
			<div class="immich-title">Choose from Photos</div>
			<button class="immich-close" onclick={close} aria-label="Close">
				<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
			</button>
		</div>

		<div class="immich-search">
			<input type="text" class="immich-search-input" placeholder="Search photos..." bind:value={searchQuery} oninput={onSearch} />
		</div>

		<div class="immich-grid">
			{#each assets as asset (asset.id)}
				<!-- svelte-ignore a11y_no_static_element_interactions -->
				<div class="immich-thumb" class:selected={selected.has(asset.id)} onclick={() => toggleSelect(asset.id)}>
					<img src="/api/immich/assets/{asset.id}/thumbnail" alt="" loading="lazy" />
					{#if selected.has(asset.id)}
						<div class="immich-check">
							<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>
						</div>
					{/if}
				</div>
			{/each}

			{#if loading}
				{#each Array(8) as _}
					<div class="immich-thumb skeleton"></div>
				{/each}
			{/if}

			{#if !loading && assets.length === 0 && !errorMsg}
				<div class="immich-empty">No photos found</div>
			{/if}

			{#if errorMsg}
				<div class="immich-empty">{errorMsg}</div>
			{/if}
		</div>

		{#if hasMore && !loading && assets.length > 0}
			<button class="immich-load-more" onclick={() => loadAssets()}>Load more</button>
		{/if}

		<div class="immich-footer">
			<span class="immich-count">{selected.size} selected</span>
			<div class="immich-actions">
				<button class="immich-btn-cancel" onclick={close}>Cancel</button>
				<button class="immich-btn-confirm" onclick={confirmSelection} disabled={selected.size === 0}>
					Use {selected.size} photo{selected.size !== 1 ? 's' : ''}
				</button>
			</div>
		</div>
	</div>
</div>

<style>
	.immich-overlay {
		position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 70;
		display: flex; align-items: center; justify-content: center;
		animation: imFadeIn 150ms ease;
	}
	@keyframes imFadeIn { from { opacity: 0; } to { opacity: 1; } }

	.immich-modal {
		background: var(--surface); border-radius: 16px;
		width: 560px; max-width: 95vw; max-height: 85vh;
		display: flex; flex-direction: column;
		box-shadow: 0 20px 60px rgba(0,0,0,0.2);
		animation: imSlideUp 200ms ease;
	}
	@keyframes imSlideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

	.immich-header {
		display: flex; align-items: center; justify-content: space-between;
		padding: 18px 20px; border-bottom: 1px solid var(--border);
	}
	.immich-title { font-size: var(--text-md); font-weight: 600; color: var(--text-1); }
	.immich-close { background: none; border: none; cursor: pointer; color: var(--text-3); padding: 4px; border-radius: 6px; transition: all 0.15s; }
	.immich-close:hover { color: var(--text-1); background: var(--card-hover); }
	.immich-close svg { width: 18px; height: 18px; }

	.immich-search { padding: 12px 20px 0; }
	.immich-search-input {
		width: 100%; padding: 10px 14px; border-radius: 8px;
		border: 1px solid var(--border); background: var(--surface-secondary);
		color: var(--text-1); font-size: var(--text-md); font-family: var(--font);
	}
	.immich-search-input:focus { outline: none; border-color: var(--accent); }
	.immich-search-input::placeholder { color: var(--text-4); }

	.immich-grid {
		display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px;
		padding: 12px 20px; overflow-y: auto; flex: 1; min-height: 200px;
	}

	.immich-thumb {
		aspect-ratio: 1; border-radius: 8px; overflow: hidden;
		cursor: pointer; position: relative; background: var(--card-hover);
		transition: transform 0.1s;
	}
	.immich-thumb:hover { transform: scale(0.97); }
	.immich-thumb.selected { outline: 3px solid var(--accent); outline-offset: -3px; }
	.immich-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }

	.immich-check {
		position: absolute; top: 6px; right: 6px;
		width: 24px; height: 24px; border-radius: 50%;
		background: var(--accent); color: white;
		display: flex; align-items: center; justify-content: center;
	}
	.immich-check svg { width: 14px; height: 14px; }

	.immich-thumb.skeleton {
		background: linear-gradient(90deg, var(--card) 25%, var(--card-hover) 50%, var(--card) 75%);
		background-size: 200% 100%; animation: shimmer 1.5s infinite;
	}
	@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }

	.immich-empty {
		grid-column: 1 / -1; text-align: center; padding: 40px;
		color: var(--text-3); font-size: var(--text-base);
	}

	.immich-load-more {
		display: block; margin: 0 auto 8px; padding: 8px 20px;
		border-radius: 8px; background: none; border: 1px solid var(--border);
		font-size: var(--text-sm); font-weight: 500; color: var(--text-2);
		cursor: pointer; font-family: var(--font); transition: all 0.15s;
	}
	.immich-load-more:hover { background: var(--card-hover); }

	.immich-footer {
		display: flex; align-items: center; justify-content: space-between;
		padding: 14px 20px; border-top: 1px solid var(--border);
	}
	.immich-count { font-size: var(--text-sm); color: var(--text-3); }
	.immich-actions { display: flex; gap: 8px; }
	.immich-btn-cancel {
		padding: 8px 16px; border-radius: 8px; background: var(--card-secondary);
		color: var(--text-2); border: 1px solid var(--border); font-size: var(--text-sm);
		font-weight: 500; cursor: pointer; font-family: var(--font); transition: all 0.15s;
	}
	.immich-btn-cancel:hover { background: var(--card-hover); }
	.immich-btn-confirm {
		padding: 8px 16px; border-radius: 8px; background: var(--accent);
		color: white; border: none; font-size: var(--text-sm); font-weight: 600;
		cursor: pointer; font-family: var(--font); transition: opacity 0.15s;
	}
	.immich-btn-confirm:hover { opacity: 0.9; }
	.immich-btn-confirm:disabled { opacity: 0.4; cursor: default; }

	@media (max-width: 768px) {
		.immich-modal { max-height: 90vh; border-radius: 16px 16px 0 0; align-self: flex-end; width: 100%; max-width: 100%; }
		.immich-grid { grid-template-columns: repeat(3, 1fr); }
	}
</style>
