<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { onMount } from 'svelte';
	import AddUrlScreen from '../components/AddUrlScreen.svelte';

	let status = $state<'idle' | 'enqueuing' | 'success' | 'error'>('idle');

	// URL param parsing for Share Target
	let sharedText = $derived($page.url.searchParams.get('text') || '');
	let sharedUrl = $derived($page.url.searchParams.get('url') || '');

	function extractUrl(text: string) {
		const match = text.match(/(https?:\/\/[^\s]+)/);
		return match ? match[0] : null;
	}

	let targetUrl = $derived(sharedUrl || extractUrl(sharedText) || '');

	// Track if we've already auto-processed to prevent duplicate processing
	let hasAutoProcessed = $state(false);

	// Auto-process URL if provided via share target
	onMount(() => {
		if (targetUrl && status === 'idle' && !hasAutoProcessed) {
			hasAutoProcessed = true;
			process(targetUrl);
		}
	});

	async function process(url: string) {
		if (!url) return;
		status = 'enqueuing';

		try {
			const response = await fetch('/api/queue', {
				method: 'POST',
				body: JSON.stringify({ url }),
				headers: { 'Content-Type': 'application/json' }
			});

			if (!response.ok) {
				const error = await response.json();
				throw new Error(error.message || 'Failed to enqueue URL');
			}

			const queueItem = await response.json();
			status = 'success';

			setTimeout(() => {
				goto(`/?highlight=${queueItem.id}`);
			}, 800);
		} catch (e) {
			status = 'error';
			console.error('Failed to enqueue:', e);
		}
	}
</script>

<svelte:head>
	<title>Add Recipe — InstaChef</title>
	<meta name="description" content="Share Instagram recipes to InstaChef" />
</svelte:head>

{#if status === 'enqueuing' || status === 'success'}
	<!-- Transitional feedback while enqueuing -->
	<div class="enqueue-screen">
		<div class="enqueue-card">
			{#if status === 'enqueuing'}
				<div class="spinner"></div>
				<div class="enqueue-title">Adding to queue…</div>
			{:else}
				<div class="enqueue-check">✓</div>
				<div class="enqueue-title">Added! Redirecting…</div>
			{/if}
			<div class="enqueue-url">{targetUrl}</div>
		</div>
	</div>
{:else}
	<AddUrlScreen
		initialUrl={targetUrl}
		onBack={() => goto('/')}
		onSubmit={process}
	/>
{/if}

<style>
	.enqueue-screen {
		min-height: 100vh;
		min-height: 100dvh;
		background: var(--bg);
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 24px;
	}
	.enqueue-card {
		background: var(--surface);
		border: 1px solid var(--border);
		border-radius: 28px;
		padding: 40px 32px;
		text-align: center;
		width: 100%;
		max-width: 360px;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 14px;
	}
	.spinner {
		width: 44px;
		height: 44px;
		border-radius: 50%;
		border: 4px solid var(--border);
		border-top-color: var(--pink);
		animation: spin 0.75s linear infinite;
	}
	@keyframes spin {
		to { transform: rotate(360deg); }
	}
	.enqueue-check {
		width: 44px;
		height: 44px;
		border-radius: 50%;
		background: var(--status-success);
		color: #fff;
		font-size: 22px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.enqueue-title {
		font-family: 'Lilita One', system-ui, sans-serif;
		font-size: 22px;
		color: var(--ink);
	}
	.enqueue-url {
		font-size: 12px;
		font-family: var(--font-mono);
		color: var(--muted);
		word-break: break-all;
		max-width: 300px;
	}
</style>