'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * BedrockMemoryPanel — the bedrock visualization surface.
 *
 * Replaces the simple toggle on Application detail and is reused on
 * Repository and Feature detail pages. Goes beyond "enable / disable":
 * users can SEE the markdown memory bedrock has captured (files, sizes,
 * mtimes, preview snippets) and run lifecycle commands inline.
 *
 * The component is presentation-only — every server interaction goes
 * through injected action overrides so Storybook can render every
 * state (Default / Loading / Empty / Disabled / Error) without DI.
 */
import { useState, useTransition } from 'react';
import { AlertCircle, CheckCircle2, Database, FileText, RefreshCw, ShipIcon, XCircle, Zap, } from 'lucide-react';
import { toast } from 'sonner';
import { cn } from '../lib/utils.js';
import { Badge } from './ui/badge.js';
import { Button } from './ui/button.js';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card.js';
import { ScrollArea } from './ui/scroll-area.js';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip.js';
const PREVIEW_CLAMP = 160;
export function BedrockMemoryPanel({ targetKind, targetId, targetLabel, initialEnabled, initialSnapshot, initialHealth, actions, }) {
    const [enabled, setEnabled] = useState(initialEnabled);
    const [snapshot, setSnapshot] = useState(initialSnapshot);
    const health = initialHealth;
    const [failure, setFailure] = useState(null);
    const [isPending, startTransition] = useTransition();
    function handleEnable() {
        setFailure(null);
        startTransition(async () => {
            const result = await actions.enable(targetKind, targetId);
            if (!result.ok) {
                setFailure({ code: result.code, remediation: result.remediation });
                toast.error(result.remediation);
                return;
            }
            setEnabled(true);
            const fresh = await actions.refreshSnapshot(targetKind, targetId);
            if (fresh)
                setSnapshot(fresh);
            toast.success('Bedrock memory enabled');
        });
    }
    function handleSync() {
        setFailure(null);
        startTransition(async () => {
            const result = await actions.sync(targetKind, targetId);
            if (!result.ok) {
                setFailure({ code: result.code, remediation: result.remediation });
                toast.error(result.remediation);
                return;
            }
            const fresh = await actions.refreshSnapshot(targetKind, targetId);
            if (fresh)
                setSnapshot(fresh);
            toast.success('Bedrock memory synced');
        });
    }
    function handleShip() {
        setFailure(null);
        startTransition(async () => {
            const result = await actions.ship(targetKind, targetId);
            if (!result.ok) {
                setFailure({ code: result.code, remediation: result.remediation });
                toast.error(result.remediation);
                return;
            }
            const fresh = await actions.refreshSnapshot(targetKind, targetId);
            if (fresh)
                setSnapshot(fresh);
            toast.success('Bedrock memory shipped');
        });
    }
    return (_jsx(TooltipProvider, { delayDuration: 150, children: _jsxs(Card, { "data-testid": "bedrock-memory-panel", "data-target-kind": targetKind, "data-enabled": enabled ? 'true' : 'false', "data-pending": isPending ? 'true' : 'false', className: "overflow-hidden", children: [_jsxs(CardHeader, { className: "flex flex-row items-center justify-between gap-2 space-y-0 pb-3", children: [_jsxs(CardTitle, { className: "flex items-center gap-2 text-sm", children: [_jsx(Database, { className: "text-muted-foreground size-4" }), _jsx("span", { className: "font-medium", children: "Bedrock memory" }), _jsxs("span", { className: "text-muted-foreground text-xs font-normal", children: ["\u00B7 ", targetLabel] })] }), _jsx(StatusBadge, { enabled: enabled, snapshot: snapshot })] }), _jsxs(CardContent, { className: "space-y-4", children: [_jsxs("p", { className: "text-muted-foreground text-xs leading-relaxed", children: ["Persistent markdown project memory for AI coding agents. Bedrock writes its memory store inside this ", kindWord(targetKind), "'s worktree and syncs it through git."] }), _jsx(HealthRow, { health: health }), enabled ? (_jsx(MemoryFileList, { snapshot: snapshot })) : (_jsx(EmptyEnableState, { onEnable: handleEnable, disabled: isPending })), enabled ? (_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsxs(Button, { type: "button", size: "sm", variant: "secondary", "data-testid": "bedrock-sync-button", onClick: handleSync, disabled: isPending, className: "gap-1.5", children: [_jsx(RefreshCw, { className: cn('size-3.5', isPending && 'animate-spin') }), "Sync"] }), _jsxs(Button, { type: "button", size: "sm", variant: "outline", "data-testid": "bedrock-ship-button", onClick: handleShip, disabled: isPending, className: "gap-1.5", children: [_jsx(ShipIcon, { className: "size-3.5" }), "Ship"] }), _jsx("span", { className: "text-muted-foreground ml-auto text-[10px]", children: snapshot?.present
                                        ? `${snapshot.files.length} file${snapshot.files.length === 1 ? '' : 's'} · ${formatBytes(snapshot.totalBytes)}`
                                        : 'no .bedrock/ on disk yet' })] })) : null, failure ? (_jsxs("div", { "data-testid": "bedrock-panel-failure", role: "alert", className: "border-destructive/40 bg-destructive/5 text-destructive flex items-start gap-2 rounded-md border p-2 text-xs", children: [_jsx(AlertCircle, { className: "mt-0.5 size-3.5 shrink-0" }), _jsx("span", { children: failure.remediation })] })) : null] })] }) }));
}
function StatusBadge({ enabled, snapshot, }) {
    if (!enabled) {
        return (_jsxs(Badge, { variant: "outline", className: "gap-1 text-[10px]", children: [_jsx(XCircle, { className: "size-3" }), "Disabled"] }));
    }
    if (snapshot?.present) {
        return (_jsxs(Badge, { variant: "default", className: "gap-1 bg-emerald-600 text-[10px] hover:bg-emerald-700", children: [_jsx(CheckCircle2, { className: "size-3" }), "Active"] }));
    }
    return (_jsxs(Badge, { variant: "secondary", className: "gap-1 text-[10px]", children: [_jsx(Zap, { className: "size-3" }), "Pending init"] }));
}
function HealthRow({ health }) {
    if (!health)
        return null;
    return (_jsxs("div", { className: "grid grid-cols-3 gap-2", "data-testid": "bedrock-health-row", children: [_jsx(HealthTile, { label: "Python", status: health.python.status, detail: health.python.detail }), _jsx(HealthTile, { label: "pipx", status: health.pipx.status, detail: health.pipx.detail }), _jsx(HealthTile, { label: "bedrock", status: health.bedrock.status, detail: health.bedrock.detail })] }));
}
function HealthTile({ label, status, detail, }) {
    const color = status === 'ok'
        ? 'border-emerald-500/40 bg-emerald-500/5 text-emerald-700 dark:text-emerald-300'
        : status === 'missing'
            ? 'border-amber-500/40 bg-amber-500/5 text-amber-700 dark:text-amber-300'
            : 'border-destructive/40 bg-destructive/5 text-destructive';
    return (_jsxs("div", { "data-testid": `bedrock-health-${label.toLowerCase()}`, "data-status": status, className: cn('rounded-md border px-2 py-1', color), children: [_jsx("div", { className: "text-[10px] font-medium tracking-wide uppercase opacity-80", children: label }), _jsx("div", { className: "truncate font-mono text-xs", title: detail ?? status, children: detail ?? status })] }));
}
function EmptyEnableState({ onEnable, disabled }) {
    return (_jsxs("div", { "data-testid": "bedrock-empty-state", className: "bg-muted/30 flex flex-col items-start gap-2 rounded-md border border-dashed p-3", children: [_jsxs("p", { className: "text-muted-foreground text-xs", children: ["No memory store yet. Enabling bedrock will run ", _jsx("code", { children: "bedrock init" }), " in this worktree and start capturing markdown memory."] }), _jsx(Button, { type: "button", size: "sm", onClick: onEnable, disabled: disabled, "data-testid": "bedrock-enable-button", children: "Enable bedrock memory" })] }));
}
function MemoryFileList({ snapshot }) {
    if (!snapshot) {
        return (_jsx("div", { "data-testid": "bedrock-loading-state", className: "text-muted-foreground rounded-md border border-dashed p-3 text-xs", children: "Loading memory snapshot\u2026" }));
    }
    if (!snapshot.present || snapshot.files.length === 0) {
        return (_jsxs("div", { "data-testid": "bedrock-empty-snapshot", className: "bg-muted/20 text-muted-foreground rounded-md border border-dashed p-3 text-xs", children: ["Bedrock is enabled but ", _jsx("code", { children: ".bedrock/" }), " is empty on disk. Try ", _jsx("strong", { children: "Sync" }), " to bootstrap the memory store."] }));
    }
    return (_jsx("div", { "data-testid": "bedrock-file-list", className: "rounded-md border", children: _jsx(ScrollArea, { className: "max-h-64", children: _jsx("ul", { className: "divide-y", children: snapshot.files.map((file) => (_jsxs("li", { "data-testid": `bedrock-file-${file.path}`, className: "hover:bg-muted/40 flex items-start gap-2 px-3 py-2 text-xs", children: [_jsx(FileText, { className: "text-muted-foreground mt-0.5 size-3.5 shrink-0" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex items-baseline gap-2", children: [_jsx("span", { className: "truncate font-mono text-xs font-medium", children: file.path }), _jsxs("span", { className: "text-muted-foreground ml-auto shrink-0 text-[10px]", children: [formatBytes(file.sizeBytes), " \u00B7 ", relativeTime(file.modifiedAt)] })] }), file.preview ? (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("p", { className: "text-muted-foreground mt-0.5 line-clamp-2 cursor-help text-[11px] leading-snug", children: clamp(file.preview, PREVIEW_CLAMP) }) }), _jsx(TooltipContent, { className: "max-w-md whitespace-pre-wrap", children: _jsx("pre", { className: "text-[11px] leading-snug", children: file.preview }) })] })) : null] })] }, file.path))) }) }) }));
}
function kindWord(kind) {
    switch (kind) {
        case 'application':
            return 'application';
        case 'repository':
            return 'repository';
        case 'feature':
            return 'feature';
        default:
            return 'target';
    }
}
function formatBytes(value) {
    const n = typeof value === 'bigint' ? Number(value) : value;
    if (n < 1024)
        return `${n} B`;
    if (n < 1024 * 1024)
        return `${(n / 1024).toFixed(1)} KB`;
    return `${(n / (1024 * 1024)).toFixed(2)} MB`;
}
function relativeTime(value) {
    const t = value instanceof Date ? value.getTime() : new Date(value).getTime();
    if (Number.isNaN(t))
        return '—';
    const diff = Date.now() - t;
    const minutes = Math.floor(diff / 60_000);
    if (minutes < 1)
        return 'just now';
    if (minutes < 60)
        return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24)
        return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days < 30)
        return `${days}d ago`;
    const months = Math.floor(days / 30);
    if (months < 12)
        return `${months}mo ago`;
    return `${Math.floor(days / 365)}y ago`;
}
function clamp(text, max) {
    if (text.length <= max)
        return text;
    return `${text.slice(0, max)}…`;
}
