<script lang="ts">
	import { XCircle } from 'lucide-svelte';
	import { m } from '$lib/paraglide/messages.js';

	interface Props {
		error: string;
	}

	let { error }: Props = $props();

	// Parse semicolon-separated errors from backend validation failures
	const errors = $derived(
		error.includes(';')
			? error
					.split(';')
					.map((e) => e.trim())
					.filter((e) => e.length > 0)
			: [error]
	);

	// Extract prefix if present (e.g., "Generated routine failed safety validation: ")
	const hasPrefix = $derived(errors.length === 1 && errors[0].includes(': '));
	const prefix = $derived(
		hasPrefix ? errors[0].substring(0, errors[0].indexOf(': ') + 1) : ''
	);
	const cleanedErrors = $derived(
		hasPrefix && prefix ? [errors[0].substring(prefix.length)] : errors
	);

	// Translate known error prefixes
	const translatedPrefix = $derived(() => {
		if (!prefix) return '';
		const prefixText = prefix.replace(':', '').trim();
		// Check for common validation failure prefix
		if (
			prefixText.includes('safety validation') ||
			prefixText.includes('validation')
		) {
			return m.observability_validationFailed();
		}
		return prefixText;
	});
</script>

<div class="editorial-alert editorial-alert--error">
	<div class="flex items-start gap-2">
		<XCircle class="size-5 shrink-0 mt-0.5" />
		<div class="flex-1">
			{#if prefix}
				<p class="font-medium mb-2">{translatedPrefix()}</p>
			{/if}
			{#if cleanedErrors.length === 1}
				<p>{cleanedErrors[0]}</p>
			{:else}
				<ul class="list-disc list-inside space-y-1">
					{#each cleanedErrors as err}
						<li>{err}</li>
					{/each}
				</ul>
			{/if}
		</div>
	</div>
</div>
