<script lang="ts">
	// Spezialisierung Edit/Write/MultiEdit/NotebookEdit
	// Zeigt Diff-Vorschau (rot/gruen). Wenn ein passender Eintrag in
	// pendingChanges existiert, wird die existierende DiffView mit
	// Accept/Reject-Buttons gerendert.

	import ToolCallCard from './ToolCallCard.svelte';
	import DiffView from './DiffView.svelte';
	import { invoke } from '@tauri-apps/api/core';
	import { pendingChanges, type InlineToolCall, type FileChange } from '$lib/stores';

	interface Props {
		call: InlineToolCall;
	}
	let { call }: Props = $props();

	const filePath = $derived((call.input.file_path || call.input.path || '') as string);

	// Versuche, einen passenden Eintrag aus dem pendingChanges-Store zu finden
	const pending = $derived<FileChange | undefined>(
		$pendingChanges.find(c => c.toolId === call.id || c.filePath === filePath)
	);

	// Fallback fuer Edit-Tool ohne pendingChanges-Eintrag (z.B. wenn der
	// Snapshot bereits akzeptiert wurde): einfache Vorher/Nachher-Anzeige
	// aus den Tool-Inputs.
	const oldStr = $derived((call.input.old_string as string) || (pending?.contentBefore ?? ''));
	const newStr = $derived((call.input.new_string as string) || (call.input.content as string) || (pending?.contentAfter ?? ''));

	async function handleAccept() {
		if (pending) {
			try {
				await invoke('accept_change', { toolId: pending.toolId });
				pendingChanges.update(list => list.filter(c => c.toolId !== pending.toolId));
			} catch (e) {
				console.error('Accept failed:', e);
			}
		}
	}

	async function handleReject() {
		if (pending) {
			try {
				await invoke('reject_change', { toolId: pending.toolId });
				pendingChanges.update(list => list.filter(c => c.toolId !== pending.toolId));
			} catch (e) {
				console.error('Reject failed:', e);
			}
		}
	}
</script>

<ToolCallCard {call} defaultOpen={true}>
	{#snippet children()}
		{#if call.status === 'running'}
			<div class="placeholder">… Datei wird geschrieben …</div>
		{:else if call.status === 'error'}
			<div class="error-msg">{call.result || 'Fehler beim Schreiben'}</div>
		{:else if pending}
			<DiffView
				oldText={pending.contentBefore}
				newText={pending.contentAfter}
				filename={pending.filePath}
				interactive={true}
				toolId={pending.toolId}
				onAccept={handleAccept}
				onReject={handleReject}
			/>
		{:else if oldStr || newStr}
			<DiffView
				oldText={oldStr}
				newText={newStr}
				filename={filePath}
				interactive={false}
			/>
		{:else}
			<div class="placeholder">{filePath || 'Edit'}</div>
		{/if}
	{/snippet}
</ToolCallCard>

<style>
	.placeholder {
		color: var(--vscode-descriptionForeground);
		font-size: 11.5px;
		font-family: var(--font-mono);
	}
	.error-msg {
		color: var(--vscode-errorForeground);
		font-family: var(--font-mono);
		font-size: 11.5px;
		white-space: pre-wrap;
	}
</style>
