"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { ApiResourceVisibility } from "@stigmer/protos/ai/stigmer/commons/apiresource/enum_pb";
import { useAgent } from "./useAgent";
import { useUpdateAgent } from "./useUpdateAgent";
import { agentToInput } from "./internal/agentToInput";
import { ErrorMessage } from "../error/ErrorMessage";
import { VisibilityToggle } from "../library/VisibilityToggle";
import { PermissionGate } from "../iam-policy/PermissionGate";
import { ResourceDetailShell } from "../resource-detail/ResourceDetailShell";
import { Section } from "../resource-detail/Section";
import { useDetailTabs } from "../resource-detail/useDetailTabs";
import { DependencyGraph } from "../dependency-graph/DependencyGraph";
import { useDependencyGraph } from "../dependency-graph/useDependencyGraph";
import { InlineEditTextarea } from "../inline-edit/InlineEditTextarea";
import { InlineEditImage } from "../inline-edit/InlineEditImage";
import { InlineEditKeyValue } from "../inline-edit/InlineEditKeyValue";
import { InlineEditResourceList } from "../inline-edit/InlineEditResourceList";
import { AgentInstanceList } from "../agent-instance/AgentInstanceList";
const INSTRUCTIONS_COLLAPSED_HEIGHT = "12rem";
const OVERVIEW_TAB = { id: "overview", label: "Overview" };
const INSTANCES_TAB = { id: "instances", label: "Instances" };
const DEPENDENCIES_TAB = { id: "dependencies", label: "Dependencies" };
/**
 * Operational detail hub for an Agent blueprint.
 *
 * Fetches the agent via {@link useAgent} internally and renders its
 * full configuration inside a {@link ResourceDetailShell}: a
 * standardized header with action bar, followed by structured content
 * sections (instructions, MCP server usages, skills, sub-agents, and
 * environment variables). Sections with no data are omitted entirely
 * — reducing visual noise per Nielsen heuristic #8.
 *
 * The action bar transforms this from a read-only view into an
 * operational hub. Actions are provided by the consumer via
 * `primaryAction` and `actions` props.
 *
 * Handles loading, error, and not-found states automatically.
 * Zero Console dependencies — safe for platform builder embedding.
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * // Minimal — self-contained, fetches its own data
 * <AgentDetailView org="acme" slug="pr-review-agent" />
 * ```
 *
 * @example
 * ```tsx
 * // Operational hub with actions in a Console page
 * <AgentDetailView
 *   org={org}
 *   slug={slug}
 *   primaryAction={{ id: "edit", label: "Edit", onAction: handleEdit }}
 *   actions={[
 *     { id: "copy-id", label: "Copy ID", onAction: () => copyId(id) },
 *     { id: "delete", label: "Delete", variant: "destructive", onAction: handleDelete },
 *   ]}
 *   onMcpServerClick={({ org, slug }) => navigateToDetail("mcp-servers", org, slug)}
 *   onSkillClick={({ org, slug }) => navigateToDetail("skills", org, slug)}
 * />
 * ```
 */
export function AgentDetailView({ org, slug, onMcpServerClick, onSkillClick, onResourceLoad, onVisibilityChange, isVisibilityPending, primaryAction, actions, additionalTabs, activeTab, onTabChange, defaultTab, editable = false, onResourceUpdated, onCreateInstanceClick, onInstanceClick, onInstanceStartSessionClick, onInstanceDeleteClick, instancesRefreshKey, className, }) {
    const { agent, isLoading, error, refetch } = useAgent(org, slug);
    const { update, isUpdating } = useUpdateAgent();
    const saveField = useCallback(async (field, value) => {
        if (!agent)
            return false;
        const input = agentToInput(agent);
        input[field] = value;
        try {
            const updated = await update(input);
            onResourceUpdated?.(updated);
            refetch();
            return true;
        }
        catch {
            return false;
        }
    }, [agent, update, onResourceUpdated, refetch]);
    const { tree, isEmpty: noDeps } = useDependencyGraph({
        agentName: agent?.metadata?.name || agent?.metadata?.slug || slug,
        agentOrg: agent?.metadata?.org || org,
        spec: agent?.spec,
    });
    const builtInTabs = useMemo(() => noDeps
        ? [OVERVIEW_TAB, INSTANCES_TAB]
        : [OVERVIEW_TAB, INSTANCES_TAB, DEPENDENCIES_TAB], [noDeps]);
    const { effectiveTabs, effectiveActiveTab, effectiveOnTabChange, activeAdditionalTab, } = useDetailTabs({
        builtInTabs,
        additionalTabs,
        activeTab,
        onTabChange,
        defaultTab,
    });
    const handleNodeClick = useCallback((node) => {
        if (!node.ref)
            return;
        if (node.kind === "mcp-server") {
            onMcpServerClick?.(node.ref);
        }
        else if (node.kind === "skill") {
            onSkillClick?.(node.ref);
        }
    }, [onMcpServerClick, onSkillClick]);
    const onResourceLoadRef = useRef(onResourceLoad);
    onResourceLoadRef.current = onResourceLoad;
    useEffect(() => {
        if (agent?.metadata?.name) {
            onResourceLoadRef.current?.({ name: agent.metadata.name, id: agent.metadata.id });
        }
    }, [agent]);
    if (isLoading)
        return _jsx(LoadingSkeleton, { className: className });
    if (error)
        return _jsx(ErrorMessage, { error: error, retry: refetch, className: className });
    if (!agent)
        return _jsx(NotFoundState, { className: className });
    const meta = agent.metadata;
    const spec = agent.spec;
    const specAudit = agent.status?.audit?.specAudit;
    const agentOrg = meta?.org || org;
    const headerMeta = {
        name: meta?.name || meta?.slug || "Untitled",
        id: meta?.id || "",
        org: meta?.org,
        slug: meta?.slug,
        description: undefined,
        iconUrl: editable ? undefined : spec?.iconUrl,
        icon: editable
            ? (_jsx(InlineEditImage, { value: spec?.iconUrl ?? "", onSave: (v) => saveField("iconUrl", v || undefined), isSaving: isUpdating, fallback: _jsx(AgentIcon, { className: "size-6 text-muted-foreground" }), disabled: !editable }))
            : spec?.iconUrl ? undefined : _jsx(AgentIcon, { className: "size-6 text-muted-foreground" }),
        createdAt: specAudit?.createdAt ? timestampDate(specAudit.createdAt) : null,
        updatedAt: specAudit?.updatedAt ? timestampDate(specAudit.updatedAt) : null,
    };
    const visibilityBadge = meta?.visibility === ApiResourceVisibility.visibility_public ? (_jsx("span", { className: "shrink-0 rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground", children: "Public" })) : undefined;
    const visibilityControl = onVisibilityChange && meta ? (_jsx(PermissionGate, { resource: { kind: "agent", id: meta.id }, relation: "can_edit", fallback: visibilityBadge, children: _jsx(VisibilityToggle, { visibility: meta.visibility, onVisibilityChange: onVisibilityChange, isPending: isVisibilityPending }) })) : visibilityBadge;
    let tabContent;
    if (activeAdditionalTab) {
        tabContent = activeAdditionalTab.content;
    }
    else if (effectiveActiveTab === "instances") {
        tabContent = (_jsx(AgentInstanceList, { agentId: meta?.id ?? "", defaultInstanceId: agent.status?.defaultInstanceId, org: org, onCreateClick: onCreateInstanceClick, onInstanceClick: onInstanceClick, onStartSessionClick: onInstanceStartSessionClick, onDeleteClick: onInstanceDeleteClick, refreshKey: instancesRefreshKey }));
    }
    else if (effectiveActiveTab === "dependencies" && tree) {
        tabContent = (_jsx(DependencyGraph, { tree: tree, onNodeClick: handleNodeClick }));
    }
    else {
        tabContent = (_jsx(AgentOverview, { spec: spec, agentOrg: agentOrg, description: spec?.description, onMcpServerClick: onMcpServerClick, onSkillClick: onSkillClick, editable: editable, isSaving: isUpdating, saveField: saveField }));
    }
    return (_jsx(ResourceDetailShell, { header: headerMeta, visibilityControl: visibilityControl, primaryAction: primaryAction, actions: actions, tabs: effectiveTabs, activeTab: effectiveTabs ? effectiveActiveTab : undefined, onTabChange: effectiveTabs ? effectiveOnTabChange : undefined, tabsAriaLabel: "Agent detail sections", className: className, children: tabContent }));
}
// ---------------------------------------------------------------------------
// Overview content — the agent's configuration sections
// ---------------------------------------------------------------------------
function AgentOverview({ spec, agentOrg, description, onMcpServerClick, onSkillClick, editable, isSaving, saveField, }) {
    const handleInstructionsSave = useCallback(async (v) => saveField?.("instructions", v || undefined) ?? false, [saveField]);
    const handleMcpServersSave = useCallback(async (refs) => saveField?.("mcpServerUsages", refs.map((r) => ({
        mcpServerRef: { org: r.org, slug: r.slug },
    }))) ?? false, [saveField]);
    const handleSkillsSave = useCallback(async (refs) => saveField?.("skillRefs", refs.map((r) => ({ org: r.org, slug: r.slug }))) ?? false, [saveField]);
    const handleEnvSave = useCallback(async (rows) => {
        const env = {};
        for (const row of rows) {
            if (row.key.trim()) {
                env[row.key.trim()] = {
                    isSecret: row.isSecret || undefined,
                    description: row.description || undefined,
                    optional: row.optional || undefined,
                };
            }
        }
        return saveField?.("env", Object.keys(env).length > 0 ? env : undefined) ?? false;
    }, [saveField]);
    const mcpRefRows = useMemo(() => (spec?.mcpServerUsages ?? []).map((u) => ({
        org: u.mcpServerRef?.org || agentOrg,
        slug: u.mcpServerRef?.slug ?? "",
        label: u.mcpServerRef?.org && u.mcpServerRef.org !== agentOrg
            ? `${u.mcpServerRef.org}/${u.mcpServerRef.slug}`
            : u.mcpServerRef?.slug ?? "",
    })), [spec?.mcpServerUsages, agentOrg]);
    const skillRefRows = useMemo(() => (spec?.skillRefs ?? []).map((ref) => ({
        org: ref.org || agentOrg,
        slug: ref.slug,
        label: ref.org && ref.org !== agentOrg
            ? `${ref.org}/${ref.slug}`
            : ref.slug,
    })), [spec?.skillRefs, agentOrg]);
    const envRows = useMemo(() => Object.entries(spec?.env ?? {})
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([key, decl]) => ({
        key,
        value: "",
        isSecret: decl.isSecret,
        description: decl.description,
        optional: decl.optional,
    })), [spec?.env]);
    const showDescription = editable || !!description;
    const showInstructions = editable || !!spec?.instructions;
    const showMcpServers = editable || (spec && spec.mcpServerUsages.length > 0);
    const showSkills = editable || (spec && spec.skillRefs.length > 0);
    const showSubAgents = editable || (spec && spec.subAgents.length > 0);
    const showEnv = editable || (spec?.env && Object.keys(spec.env).length > 0);
    const [mcpEditing, setMcpEditing] = useState(false);
    const [skillsEditing, setSkillsEditing] = useState(false);
    const [envEditing, setEnvEditing] = useState(false);
    return (_jsxs("div", { className: "flex flex-col gap-6", children: [showDescription && (_jsx(Section, { title: "Description", children: editable ? (_jsx("div", { className: "max-h-20 overflow-y-auto p-3", children: _jsx(InlineEditTextarea, { value: spec?.description || "", onSave: (v) => saveField?.("description", v || undefined) ?? Promise.resolve(false), isSaving: isSaving, placeholder: "Add a description", minRows: 2 }) })) : (_jsx("div", { className: "p-3", children: _jsx("pre", { className: "whitespace-pre-wrap break-words text-sm text-foreground font-sans", children: description }) })) })), showInstructions && (_jsx(Section, { title: "Instructions", children: editable ? (_jsx("div", { className: "max-h-72 overflow-y-auto p-3", children: _jsx(InlineEditTextarea, { value: spec?.instructions ?? "", onSave: handleInstructionsSave, isSaving: isSaving, placeholder: "Add instructions for the agent", minRows: 4 }) })) : (_jsx(InstructionsContent, { text: spec?.instructions ?? "" })) })), showMcpServers && (_jsx(Section, { title: "MCP Servers", count: spec?.mcpServerUsages.length, onEdit: editable ? () => setMcpEditing((v) => !v) : undefined, children: editable ? (_jsx(InlineEditResourceList, { value: mcpRefRows, onSave: handleMcpServersSave, isSaving: isSaving, editing: mcpEditing, onEditingChange: setMcpEditing, onItemClick: onMcpServerClick ? (ref) => onMcpServerClick({ org: ref.org, slug: ref.slug }) : undefined, itemIcon: _jsx(McpServerIcon, { className: "size-4" }), resourceLabel: "MCP server", defaultOrg: agentOrg })) : (_jsx(McpUsagesContent, { usages: spec?.mcpServerUsages ?? [], defaultOrg: agentOrg, onMcpServerClick: onMcpServerClick })) })), showSkills && (_jsx(Section, { title: "Skills", count: spec?.skillRefs.length, onEdit: editable ? () => setSkillsEditing((v) => !v) : undefined, children: editable ? (_jsx(InlineEditResourceList, { value: skillRefRows, onSave: handleSkillsSave, isSaving: isSaving, editing: skillsEditing, onEditingChange: setSkillsEditing, onItemClick: onSkillClick ? (ref) => onSkillClick({ org: ref.org, slug: ref.slug }) : undefined, itemIcon: _jsx(SkillIcon, { className: "size-4" }), resourceLabel: "skill", defaultOrg: agentOrg })) : (_jsx(SkillsContent, { refs: spec?.skillRefs ?? [], defaultOrg: agentOrg, onSkillClick: onSkillClick })) })), showSubAgents && (_jsx(SubAgentsSection, { subAgents: spec?.subAgents ?? [], editable: editable, isSaving: isSaving, onSave: (subs) => saveField?.("subAgents", subs.length > 0 ? subs : undefined) ?? Promise.resolve(false) })), showEnv && (_jsx(Section, { title: "Environment Variables", count: Object.keys(spec?.env ?? {}).length, onEdit: editable ? () => setEnvEditing((v) => !v) : undefined, children: editable ? (_jsx(InlineEditKeyValue, { value: envRows, onSave: handleEnvSave, isSaving: isSaving, editing: envEditing, onEditingChange: setEnvEditing, showSecretToggle: true, showOptionalToggle: true, showDescription: true, keyLabel: "Variable name" })) : (_jsx(EnvContent, { data: spec?.env ?? {} })) }))] }));
}
// ---------------------------------------------------------------------------
// Internal section components
// ---------------------------------------------------------------------------
function InstructionsContent({ text }) {
    const [expanded, setExpanded] = useState(false);
    const contentRef = useRef(null);
    const [overflows, setOverflows] = useState(false);
    useEffect(() => {
        const el = contentRef.current;
        if (!el)
            return;
        setOverflows(el.scrollHeight > el.clientHeight);
    }, [text]);
    return (_jsxs("div", { className: "relative p-3", children: [_jsx("pre", { ref: contentRef, className: cn("whitespace-pre-wrap break-words font-mono text-sm text-foreground overflow-y-auto transition-[max-height] duration-200", !expanded && "overflow-hidden"), style: { maxHeight: expanded ? "none" : INSTRUCTIONS_COLLAPSED_HEIGHT }, children: text }), !expanded && overflows && (_jsx("div", { className: "pointer-events-none absolute inset-x-3 bottom-10 h-8 bg-gradient-to-t from-background to-transparent" })), overflows && (_jsx("button", { type: "button", onClick: () => setExpanded((v) => !v), className: "mt-2 text-xs font-medium text-primary transition-colors hover:text-primary-muted", children: expanded ? "Show less" : "Show more" }))] }));
}
function McpUsagesContent({ usages, defaultOrg, onMcpServerClick, }) {
    return (_jsx("div", { className: "flex flex-col", children: usages.map((usage, index) => {
            const ref = usage.mcpServerRef;
            if (!ref)
                return null;
            const refOrg = ref.org || defaultOrg;
            const label = ref.org && ref.org !== defaultOrg
                ? `${ref.org}/${ref.slug}`
                : ref.slug;
            const toolCount = usage.enabledTools.length;
            const approvalCount = usage.toolApprovalOverrides.length;
            const summary = [
                toolCount > 0
                    ? `${toolCount} ${toolCount === 1 ? "tool" : "tools"}`
                    : "all tools",
                approvalCount > 0
                    ? `${approvalCount} approval ${approvalCount === 1 ? "override" : "overrides"}`
                    : "",
            ]
                .filter(Boolean)
                .join(" \u00B7 ");
            const row = (_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(McpServerIcon, { className: "size-4 shrink-0 text-muted-foreground" }), _jsx("span", { className: "text-sm font-medium text-foreground", children: label }), _jsx("span", { className: "text-xs text-muted-foreground", children: summary })] }));
            return onMcpServerClick ? (_jsx("button", { type: "button", onClick: () => onMcpServerClick({ org: refOrg, slug: ref.slug }), className: cn("w-full rounded-md px-3 py-2 text-left transition-colors", "hover:bg-accent-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"), children: row }, ref.slug || index)) : (_jsx("div", { className: "px-3 py-2", children: row }, ref.slug || index));
        }) }));
}
function SkillsContent({ refs, defaultOrg, onSkillClick, }) {
    return (_jsx("div", { className: "flex flex-col", children: refs.map((ref, index) => {
            const refOrg = ref.org || defaultOrg;
            const label = ref.org && ref.org !== defaultOrg
                ? `${ref.org}/${ref.slug}`
                : ref.slug;
            const row = (_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(SkillIcon, { className: "size-4 shrink-0 text-muted-foreground" }), _jsx("span", { className: "text-sm font-medium text-foreground", children: label })] }));
            return onSkillClick ? (_jsx("button", { type: "button", onClick: () => onSkillClick({ org: refOrg, slug: ref.slug }), className: cn("w-full rounded-md px-3 py-2 text-left transition-colors", "hover:bg-accent-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"), children: row }, ref.slug || index)) : (_jsx("div", { className: "px-3 py-2", children: row }, ref.slug || index));
        }) }));
}
function SubAgentsSection({ subAgents, editable, isSaving, onSave, }) {
    const [expanded, setExpanded] = useState(new Set());
    const [isEditing, setIsEditing] = useState(false);
    const [showAddForm, setShowAddForm] = useState(false);
    const [addDraft, setAddDraft] = useState({ name: "", description: "", instructions: "" });
    const toggle = (index) => {
        setExpanded((prev) => {
            const next = new Set(prev);
            if (next.has(index))
                next.delete(index);
            else
                next.add(index);
            return next;
        });
    };
    const handleRemove = useCallback(async (index) => {
        if (!onSave)
            return;
        const updated = subAgents
            .filter((_, i) => i !== index)
            .map((sa) => ({
            name: sa.name,
            description: sa.description || undefined,
            instructions: sa.instructions || undefined,
            mcpAccess: sa.mcpAccess.length > 0
                ? sa.mcpAccess.map((a) => ({ mcpServer: a.mcpServer, enabledTools: a.enabledTools.length > 0 ? [...a.enabledTools] : undefined }))
                : undefined,
            skillRefs: sa.skillRefs.length > 0
                ? sa.skillRefs.map((r) => ({ org: r.org || "", slug: r.slug }))
                : undefined,
            modelOverride: sa.modelOverride || undefined,
        }));
        await onSave(updated);
    }, [subAgents, onSave]);
    const handleAdd = useCallback(async () => {
        if (!onSave || !addDraft.name.trim())
            return;
        const existing = subAgents.map((sa) => ({
            name: sa.name,
            description: sa.description || undefined,
            instructions: sa.instructions || undefined,
            mcpAccess: sa.mcpAccess.length > 0
                ? sa.mcpAccess.map((a) => ({ mcpServer: a.mcpServer, enabledTools: a.enabledTools.length > 0 ? [...a.enabledTools] : undefined }))
                : undefined,
            skillRefs: sa.skillRefs.length > 0
                ? sa.skillRefs.map((r) => ({ org: r.org || "", slug: r.slug }))
                : undefined,
            modelOverride: sa.modelOverride || undefined,
        }));
        const newSub = {
            name: addDraft.name.trim(),
            description: addDraft.description.trim() || undefined,
            instructions: addDraft.instructions.trim() || undefined,
        };
        const ok = await onSave([...existing, newSub]);
        if (ok) {
            setAddDraft({ name: "", description: "", instructions: "" });
            setShowAddForm(false);
        }
    }, [subAgents, addDraft, onSave]);
    return (_jsx(Section, { title: "Sub-Agents", count: subAgents.length, onEdit: editable ? () => setIsEditing((v) => !v) : undefined, children: _jsxs("div", { className: "flex flex-col", children: [subAgents.length > 0 ? (_jsx("div", { className: "flex flex-col divide-y divide-border", children: subAgents.map((sa, index) => {
                        const isOpen = expanded.has(index);
                        return (_jsxs("div", { children: [_jsxs("div", { className: "flex items-start gap-3 px-3 py-2.5", children: [_jsxs("button", { type: "button", onClick: () => toggle(index), "aria-expanded": isOpen, className: cn("flex flex-1 items-start gap-3 text-left", "focus-visible:outline-none"), children: [_jsx(ChevronRightIcon, { className: cn("mt-0.5 size-4 shrink-0 text-muted-foreground transition-transform", isOpen && "rotate-90") }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "text-sm font-medium text-foreground", children: sa.name }), sa.description && (_jsx("p", { className: "mt-0.5 text-xs text-muted-foreground", children: sa.description }))] })] }), isEditing && (_jsx("button", { type: "button", onClick: () => handleRemove(index), disabled: isSaving, "aria-label": `Remove ${sa.name}`, className: cn("mt-0.5 inline-flex size-6 items-center justify-center rounded-md text-muted-foreground", "hover:bg-destructive-subtle hover:text-destructive", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: _jsx(XRemoveIcon, { className: "size-3.5" }) }))] }), isOpen && (_jsx(SubAgentDetails, { subAgent: sa }))] }, sa.name || index));
                    }) })) : (_jsx("p", { className: "px-3 py-3 text-xs text-muted-foreground italic", children: "No sub-agents configured" })), editable && isEditing && !showAddForm && (_jsx("div", { className: "border-t border-border px-3 py-2", children: _jsxs("button", { type: "button", onClick: () => setShowAddForm(true), className: cn("inline-flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium", "border border-dashed border-border text-muted-foreground", "hover:border-muted-foreground hover:text-foreground hover:bg-muted-subtle", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "transition-colors"), children: [_jsx(PlusAddIcon, { className: "size-3" }), "Add sub-agent"] }) })), editable && showAddForm && (_jsxs("div", { className: "border-t border-border p-3 space-y-2", children: [_jsx("input", { type: "text", value: addDraft.name, onChange: (e) => setAddDraft((d) => ({ ...d, name: e.target.value })), placeholder: "Sub-agent name (required)", className: cn("w-full rounded-md border border-border bg-input-bg px-2 py-1.5 text-sm text-foreground", "focus:outline-none focus:ring-2 focus:ring-ring") }), _jsx("input", { type: "text", value: addDraft.description, onChange: (e) => setAddDraft((d) => ({ ...d, description: e.target.value })), placeholder: "Description (optional)", className: cn("w-full rounded-md border border-border bg-input-bg px-2 py-1.5 text-xs text-foreground", "focus:outline-none focus:ring-2 focus:ring-ring") }), _jsx("textarea", { value: addDraft.instructions, onChange: (e) => setAddDraft((d) => ({ ...d, instructions: e.target.value })), placeholder: "Instructions (optional)", rows: 2, className: cn("w-full resize-y rounded-md border border-border bg-input-bg px-2 py-1.5 font-mono text-xs text-foreground", "focus:outline-none focus:ring-2 focus:ring-ring") }), _jsxs("div", { className: "flex items-center justify-end gap-1.5", children: [_jsx("button", { type: "button", onClick: () => { setShowAddForm(false); setAddDraft({ name: "", description: "", instructions: "" }); }, className: cn("rounded-md px-2.5 py-1 text-xs font-medium", "border border-border bg-background text-foreground hover:bg-accent", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Cancel" }), _jsx("button", { type: "button", onClick: handleAdd, disabled: !addDraft.name.trim() || isSaving, className: cn("rounded-md px-2.5 py-1 text-xs font-medium", "bg-primary text-primary-foreground hover:bg-primary-hover", "disabled:opacity-50", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Add" })] })] }))] }) }));
}
function SubAgentDetails({ subAgent: sa, }) {
    return (_jsxs("div", { className: "mb-1 ml-7 space-y-3 border-l border-border pl-4 pt-1", children: [sa.instructions && (_jsxs("div", { children: [_jsx("h4", { className: "mb-1 text-xs font-medium text-muted-foreground", children: "Instructions" }), _jsx("pre", { className: "whitespace-pre-wrap break-words rounded-md bg-muted-subtle p-2 font-mono text-xs text-foreground", children: sa.instructions })] })), sa.mcpAccess.length > 0 && (_jsxs("div", { children: [_jsx("h4", { className: "mb-1 text-xs font-medium text-muted-foreground", children: "MCP Access" }), _jsx("div", { className: "space-y-1", children: sa.mcpAccess.map((access) => (_jsxs("div", { className: "flex items-center gap-2 text-xs text-foreground", children: [_jsx(McpServerIcon, { className: "size-3 shrink-0 text-muted-foreground" }), _jsx("span", { className: "font-medium", children: access.mcpServer }), _jsx("span", { className: "text-muted-foreground", children: access.enabledTools.length > 0
                                        ? `${access.enabledTools.length} ${access.enabledTools.length === 1 ? "tool" : "tools"}`
                                        : "all tools" })] }, access.mcpServer))) })] })), sa.skillRefs.length > 0 && (_jsxs("div", { children: [_jsx("h4", { className: "mb-1 text-xs font-medium text-muted-foreground", children: "Skills" }), _jsx("div", { className: "space-y-1", children: sa.skillRefs.map((ref) => (_jsxs("div", { className: "flex items-center gap-2 text-xs text-foreground", children: [_jsx(SkillIcon, { className: "size-3 shrink-0 text-muted-foreground" }), _jsx("span", { children: ref.org ? `${ref.org}/${ref.slug}` : ref.slug })] }, ref.slug))) })] })), sa.modelOverride && (_jsxs("div", { children: [_jsx("h4", { className: "mb-1 text-xs font-medium text-muted-foreground", children: "Model Override" }), _jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 font-mono text-xs text-foreground", children: sa.modelOverride })] }))] }));
}
function EnvContent({ data, }) {
    const entries = Object.entries(data).sort(([a], [b]) => a.localeCompare(b));
    return (_jsx("div", { className: "flex flex-col divide-y divide-border", children: entries.map(([name, env]) => (_jsxs("div", { className: "flex items-start gap-3 px-3 py-2", children: [_jsx("code", { className: "shrink-0 font-mono text-sm font-medium text-foreground", children: name }), _jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: env.isSecret ? "secret" : "config" }), env.description && (_jsx("span", { className: "text-xs text-muted-foreground", children: env.description }))] }, name))) }));
}
// ---------------------------------------------------------------------------
// Shared layout primitives
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Non-happy states
// ---------------------------------------------------------------------------
function LoadingSkeleton({ className }) {
    return (_jsxs("div", { className: cn("flex flex-col gap-6", className), "aria-busy": "true", "aria-label": "Loading agent details", children: [_jsxs("div", { className: "flex items-start gap-3", children: [_jsx("div", { className: "mt-1 size-6 shrink-0 animate-pulse rounded bg-muted" }), _jsxs("div", { className: "flex-1 space-y-2", children: [_jsx("div", { className: "h-5 w-48 animate-pulse rounded bg-muted" }), _jsx("div", { className: "h-3 w-64 animate-pulse rounded bg-muted" }), _jsx("div", { className: "h-4 w-full max-w-md animate-pulse rounded bg-muted" })] })] }), [40, 24, 16].map((h) => (_jsxs("div", { className: "space-y-2", children: [_jsx("div", { className: "h-3 w-24 animate-pulse rounded bg-muted" }), _jsx("div", { className: "animate-pulse rounded-lg border border-border bg-muted-faint", style: { height: `${h * 4}px` } })] }, h)))] }));
}
function NotFoundState({ className }) {
    return (_jsxs("div", { role: "status", className: cn("flex flex-col items-center gap-2 py-12 text-center", className), children: [_jsx(AgentIcon, { className: "size-10 text-muted-foreground-faint" }), _jsx("p", { className: "text-sm font-medium text-muted-foreground", children: "Agent not found" }), _jsx("p", { className: "text-xs text-muted-foreground-subtle", children: "This agent doesn't exist or you don't have access to it." })] }));
}
// ---------------------------------------------------------------------------
// Icons — inline SVGs following the SDK pattern (no icon library dependency)
// ---------------------------------------------------------------------------
function AgentIcon({ className }) {
    return (_jsxs("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("rect", { x: "3", y: "5", width: "10", height: "8", rx: "1.5" }), _jsx("path", { d: "M6 9h.01M10 9h.01", strokeWidth: "2" }), _jsx("path", { d: "M8 2v3" })] }));
}
function McpServerIcon({ className }) {
    return (_jsxs("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("rect", { x: "2", y: "2", width: "12", height: "5", rx: "1" }), _jsx("rect", { x: "2", y: "9", width: "12", height: "5", rx: "1" }), _jsx("circle", { cx: "5", cy: "4.5", r: "0.75", fill: "currentColor", stroke: "none" }), _jsx("circle", { cx: "5", cy: "11.5", r: "0.75", fill: "currentColor", stroke: "none" })] }));
}
function SkillIcon({ className }) {
    return (_jsx("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M9 1.5 4 9h4l-1 5.5L12 7H8l1-5.5Z" }) }));
}
function ChevronRightIcon({ className }) {
    return (_jsx("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m6 3 5 5-5 5" }) }));
}
function XRemoveIcon({ className }) {
    return (_jsx("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m4 4 8 8M12 4l-8 8" }) }));
}
function PlusAddIcon({ className }) {
    return (_jsx("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M8 3v10M3 8h10" }) }));
}
//# sourceMappingURL=AgentDetailView.js.map