<script lang="ts">
	import { models } from '$lib/stores';
	import WorkspaceFiles from './WorkspaceFiles.svelte';

	export let selectedModels = [''];
	export let disabled = false;
	export let showSetDefault = true;
	let showWorkspace = false;

	const modelOptions = [
		{ id: 'luna', label: 'Luna', thinking: '开启 · 不分档' },
		{ id: 'terra', label: 'Terra', thinking: '开启 · 不分档' },
		{ id: 'sol', label: 'Sol', thinking: '开启 · 不分档' },
		{ id: 'deepseek-v4-pro', label: 'DeepSeek', thinking: '极高' }
	];
	const allowed = new Set(modelOptions.map((item) => item.id));

	$: selected = allowed.has(selectedModels?.[0]) ? selectedModels[0] : 'terra';
	$: selectedOption = modelOptions.find((item) => item.id === selected) ?? modelOptions[1];
	$: availableIds = new Set($models.map((model) => model.id));

	$: if ($models.length > 0 && !availableIds.has(selectedModels?.[0])) {
		const fallback = availableIds.has('terra')
			? 'terra'
			: modelOptions.find((item) => availableIds.has(item.id))?.id;
		if (fallback) selectedModels = [fallback];
	}

	const chooseModel = (modelId: string) => {
		if (disabled || !availableIds.has(modelId)) return;
		selectedModels = [modelId];
	};
</script>

<div class="flex max-w-full items-center gap-2 select-none">
	<div
		class="flex items-center overflow-x-auto rounded-xl border border-gray-200/80 p-1 text-xs dark:border-gray-700/80"
		aria-label="模型"
	>
		{#each modelOptions as item}
			<button
				type="button"
				class="whitespace-nowrap rounded-lg px-2.5 py-1.5 font-medium transition {selected === item.id
					? 'bg-gray-900 text-white dark:bg-white dark:text-gray-900'
					: 'text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800'}"
				on:click={() => chooseModel(item.id)}
				disabled={disabled || ($models.length > 0 && !availableIds.has(item.id))}
				title={item.id === 'deepseek-v4-pro' ? 'DeepSeek V4 Pro' : item.label}
			>
				{item.label}
			</button>
		{/each}
	</div>

	<div
		class="whitespace-nowrap rounded-xl bg-gray-100/90 px-2.5 py-2 text-xs text-gray-500 dark:bg-gray-800/90 dark:text-gray-400"
		title="模型与思考能力是两个独立概念"
	>
		思考 <span class="font-medium text-gray-800 dark:text-gray-200">{selectedOption.thinking}</span>
	</div>

	<button
		type="button"
		class="rounded-xl border border-gray-200/80 p-2 text-gray-500 transition hover:bg-gray-100 hover:text-gray-900 dark:border-gray-700/80 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-white"
		on:click={() => (showWorkspace = true)}
		title="工作区文件"
		aria-label="工作区文件"
	>
		<svg viewBox="0 0 24 24" class="size-4" fill="none" stroke="currentColor" stroke-width="1.8">
			<path d="M3.5 6.5h6l2 2h9v10h-17z" stroke-linejoin="round" />
		</svg>
	</button>
</div>

<WorkspaceFiles bind:show={showWorkspace} />
