'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState, useTransition } from 'react';
import { Button } from '../ui/button.js';
import { Textarea } from '../ui/textarea.js';
import { Badge } from '../ui/badge.js';
import { Alert, AlertDescription } from '../ui/alert.js';
import { saveAgentPrompt, resetAgentPrompt } from '../../app/actions/agent-prompts.js';
export function PromptEditor({ entries, onSaveOverride, onResetOverride }) {
    if (entries.length === 0) {
        return (_jsx("p", { className: "text-muted-foreground rounded-lg border border-dashed p-4 text-sm", children: "No editable prompt slots are registered for this agent yet." }));
    }
    return (_jsx("div", { className: "flex flex-col gap-4", "data-testid": "prompt-editor", children: entries.map((entry) => (_jsx(PromptSlotCard, { entry: entry, ...(onSaveOverride && { onSaveOverride }), ...(onResetOverride && { onResetOverride }) }, `${entry.agentType}-${entry.promptId}`))) }));
}
function PromptSlotCard({ entry, onSaveOverride, onResetOverride, }) {
    const [body, setBody] = useState(entry.effectiveBody);
    const [isPending, startTransition] = useTransition();
    const [error, setError] = useState(null);
    const [savedAt, setSavedAt] = useState(null);
    // Re-sync when server data refreshes (revalidatePath after save).
    useEffect(() => {
        setBody(entry.effectiveBody);
    }, [entry.effectiveBody]);
    const dirty = body !== entry.effectiveBody;
    const overridden = entry.hasOverride || dirty;
    function handleSave() {
        setError(null);
        startTransition(async () => {
            const fn = onSaveOverride ?? saveAgentPrompt;
            const result = await fn({ agentType: entry.agentType, promptId: entry.promptId, body });
            if (!result.ok)
                setError(result.error ?? 'Failed to save');
            else
                setSavedAt(new Date());
        });
    }
    function handleReset() {
        setError(null);
        startTransition(async () => {
            const fn = onResetOverride ?? resetAgentPrompt;
            const result = await fn({ agentType: entry.agentType, promptId: entry.promptId });
            if (!result.ok)
                setError(result.error ?? 'Failed to reset');
            else {
                setBody(entry.bundledBody);
                setSavedAt(new Date());
            }
        });
    }
    return (_jsxs("article", { className: "bg-card flex flex-col gap-3 rounded-lg border p-4", "data-testid": `prompt-slot-${entry.promptId}`, children: [_jsxs("header", { className: "flex items-start justify-between gap-3", children: [_jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("h3", { className: "text-sm font-semibold", children: entry.name }), _jsx("p", { className: "text-muted-foreground text-xs", children: entry.description }), _jsxs("p", { className: "text-muted-foreground mt-1 font-mono text-[10px]", children: [entry.agentType, "/", entry.promptId] })] }), overridden ? (_jsx(Badge, { variant: "default", className: "shrink-0", "data-testid": `badge-overridden-${entry.promptId}`, children: "Overridden" })) : (_jsx(Badge, { variant: "secondary", className: "shrink-0", children: "Bundled" }))] }), _jsx(Textarea, { value: body, onChange: (e) => setBody(e.target.value), rows: Math.min(20, Math.max(6, body.split('\n').length)), className: "font-mono text-xs", "data-testid": `prompt-textarea-${entry.promptId}`, disabled: isPending, spellCheck: false }), error ? (_jsx(Alert, { variant: "destructive", "data-testid": `prompt-error-${entry.promptId}`, children: _jsx(AlertDescription, { children: error }) })) : null, savedAt ? (_jsxs("p", { className: "text-muted-foreground text-xs", "data-testid": `prompt-saved-${entry.promptId}`, children: ["Saved at ", savedAt.toLocaleTimeString()] })) : null, _jsxs("div", { className: "flex items-center justify-end gap-2", children: [entry.hasOverride ? (_jsx(Button, { type: "button", variant: "ghost", size: "sm", disabled: isPending, onClick: handleReset, "data-testid": `prompt-reset-${entry.promptId}`, children: "Reset to bundled" })) : null, _jsx(Button, { type: "button", size: "sm", disabled: !dirty || isPending, onClick: handleSave, "data-testid": `prompt-save-${entry.promptId}`, children: isPending ? 'Saving…' : entry.hasOverride ? 'Update override' : 'Save override' })] })] }));
}
