<script lang="ts">
	interface Template {
		id: string;
		name: string;
	}

	interface Props {
		templates: Template[];
		isOpen: boolean;
		onToggle: () => void;
		onCreateBlank: () => void;
		onCreateFromTemplate: (templateId: string) => void;
	}

	let { templates, isOpen, onToggle, onCreateBlank, onCreateFromTemplate }: Props = $props();
</script>

<div class="relative">
	{#if templates.length > 0}
		<button
			type="button"
			onclick={onToggle}
			class="inline-flex items-center gap-2 rounded-lg bg-accent-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-accent-600"
		>
			<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
			</svg>
			<span>Create Scope</span>
			<svg class="h-3 w-3" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
			</svg>
		</button>
		{#if isOpen}
			<!-- Backdrop to close dropdown -->
			<button
				type="button"
				class="fixed inset-0 z-10"
				onclick={onToggle}
				aria-label="Close dropdown"
			></button>
			<!-- Dropdown menu -->
			<div
				class="absolute right-0 z-20 mt-1 w-56 rounded-lg border border-theme bg-theme-card py-1 shadow-theme-lg"
			>
				<button
					type="button"
					onclick={() => {
						onToggle();
						onCreateBlank();
					}}
					class="block w-full interactive px-3 py-2 text-left text-sm text-theme"
				>
					Blank Scope
				</button>
				<div class="my-1 border-t border-theme"></div>
				<p class="px-3 py-1 text-[10px] font-medium text-theme-muted uppercase">From Template</p>
				{#each templates as template (template.id)}
					<button
						type="button"
						onclick={() => {
							onToggle();
							onCreateFromTemplate(template.id);
						}}
						class="block w-full interactive px-3 py-2 text-left text-sm text-theme"
					>
						{template.name}
					</button>
				{/each}
			</div>
		{/if}
	{:else}
		<button
			type="button"
			onclick={onCreateBlank}
			class="inline-flex items-center gap-2 rounded-lg bg-accent-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-accent-600"
		>
			<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
			</svg>
			<span>Create Scope</span>
		</button>
	{/if}
</div>
