<script lang="ts">
	import { goto } from '$app/navigation';
	import { getSupabase } from '$lib/supabase';
	import { currentCollective, userCollectives } from '$lib/stores/collective';
	import * as m from '$lib/paraglide/messages';

	let { onClose }: { onClose: () => void } = $props();

	const EMOJI_OPTIONS = [
		'🏠', '🏡', '🏢', '🏣', '🏤', '🏥', '🏦', '🏨',
		'🏩', '🏪', '🏫', '🏬', '🏭', '🏯', '🏰', '🗼',
		'🌆', '🌇', '🌃', '🌉', '🏙️', '⛺', '🌴', '🌵'
	];

	let name = $state('');
	let emoji = $state('🏠');
	let creating = $state(false);
	let error = $state<string | null>(null);

	async function submit() {
		if (!name.trim() || creating) return;
		creating = true;
		error = null;
		const { data, error: rpcErr } = await getSupabase().rpc('create_collective', {
			p_name: name.trim(),
			p_emoji: emoji
		});
		if (rpcErr || !data) {
			creating = false;
			error = rpcErr?.message ?? 'Failed to create collective.';
			return;
		}
		const created = data as { id: string; name: string; emoji: string; created_at: string };
		userCollectives.update((list) => [...list, created]);
		currentCollective.set(created);
		localStorage.setItem('activeCollectiveId', created.id);
		creating = false;
		onClose();
		await goto('/lists');
	}
</script>

<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" data-testid="create-collective-modal">
	<div class="w-full max-w-md rounded-lg bg-surface p-5 shadow-[0px_20px_40px_rgba(15,23,42,0.2)] dark:bg-surface-raised">
		<h2 class="mb-4 text-base font-semibold text-slate-900 dark:text-slate-50">
			{m.create_collective_modal_title()}
		</h2>
		<form onsubmit={(e) => { e.preventDefault(); void submit(); }} class="space-y-4">
			<div>
				<label for="cc-modal-name" class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">
					{m.onboarding_collective_name()}
				</label>
				<input
					id="cc-modal-name"
					data-testid="create-collective-modal-name"
					type="text"
					bind:value={name}
					placeholder={m.onboarding_collective_name_placeholder()}
					maxlength="60"
					class="w-full rounded-lg border border-slate-300 bg-surface px-3 py-2 text-sm
						focus:border-slate-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800"
				/>
			</div>

			<div>
				<p class="mb-2 text-sm font-medium text-slate-700 dark:text-slate-300">
					{m.onboarding_collective_emoji()}
				</p>
				<div class="grid grid-cols-8 gap-1">
					{#each EMOJI_OPTIONS as e}
						<button
							type="button"
							class="flex h-9 w-9 items-center justify-center rounded-md text-xl transition-colors
								{emoji === e
								? 'bg-slate-900 dark:bg-slate-100'
								: 'hover:bg-slate-100 dark:hover:bg-slate-700'}"
							onclick={() => (emoji = e)}
							aria-label={e}
						>{e}</button>
					{/each}
				</div>
			</div>

			{#if error}
				<p class="text-sm text-red-600">{error}</p>
			{/if}

			<div class="flex justify-end gap-2">
				<button
					type="button"
					onclick={onClose}
					class="rounded-md px-3 py-1.5 text-sm font-medium text-slate-600 hover:bg-slate-100
						dark:text-slate-300 dark:hover:bg-slate-800"
				>
					{m.common_cancel()}
				</button>
				<button
					type="submit"
					data-testid="create-collective-modal-submit"
					disabled={!name.trim() || creating}
					class="rounded-lg bg-slate-900 px-4 py-1.5 text-sm font-semibold text-white
						transition-opacity hover:opacity-90 disabled:opacity-50
						dark:bg-slate-50 dark:text-slate-900"
				>
					{creating ? m.loading() : m.create_collective_modal_button()}
				</button>
			</div>
		</form>
	</div>
</div>
