"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, 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 { ErrorMessage } from "../error/ErrorMessage";
import { VisibilityToggle } from "../library/VisibilityToggle";
const INSTRUCTIONS_COLLAPSED_LINES = 8;
/**
 * Read-only detail view for an Agent blueprint.
 *
 * Fetches the agent via {@link useAgent} internally and renders its
 * full configuration in structured sections: header, instructions,
 * MCP server usages, skills, sub-agents, and environment variables.
 * Sections with no data are omitted entirely — reducing visual noise
 * per the aesthetic-minimalist design heuristic (Nielsen #8).
 *
 * 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
 * // With cross-resource linking in a Console page
 * <AgentDetailView
 *   org={org}
 *   slug={slug}
 *   onMcpServerClick={({ org, slug }) => router.push(`/library/mcp-servers/${org}/${slug}`)}
 *   onSkillClick={({ org, slug }) => router.push(`/library/skills/${org}/${slug}`)}
 * />
 * ```
 */
export function AgentDetailView({ org, slug, onMcpServerClick, onSkillClick, onResourceLoad, onVisibilityChange, isVisibilityPending, className, }) {
    const { agent, isLoading, error, refetch } = useAgent(org, slug);
    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 spec = agent.spec;
    const specAudit = agent.status?.audit?.specAudit;
    const agentOrg = agent.metadata?.org || org;
    return (_jsxs("div", { className: cn("flex flex-col gap-6", className), children: [_jsx(Header, { agent: agent, createdAt: specAudit?.createdAt ? timestampDate(specAudit.createdAt) : null, updatedAt: specAudit?.updatedAt ? timestampDate(specAudit.updatedAt) : null, onVisibilityChange: onVisibilityChange, isVisibilityPending: isVisibilityPending }), spec?.instructions && (_jsx(InstructionsSection, { text: spec.instructions })), spec && spec.mcpServerUsages.length > 0 && (_jsx(McpUsagesSection, { usages: spec.mcpServerUsages, defaultOrg: agentOrg, onMcpServerClick: onMcpServerClick })), spec && spec.skillRefs.length > 0 && (_jsx(SkillsSection, { refs: spec.skillRefs, defaultOrg: agentOrg, onSkillClick: onSkillClick })), spec && spec.subAgents.length > 0 && (_jsx(SubAgentsSection, { subAgents: spec.subAgents })), spec?.env && Object.keys(spec.env).length > 0 && (_jsx(EnvSection, { data: spec.env }))] }));
}
// ---------------------------------------------------------------------------
// Internal section components
// ---------------------------------------------------------------------------
function Header({ agent, createdAt, updatedAt, onVisibilityChange, isVisibilityPending, }) {
    const meta = agent.metadata;
    const spec = agent.spec;
    const displayName = meta?.name || meta?.slug || "Untitled";
    const isPublic = meta?.visibility === ApiResourceVisibility.visibility_public;
    return (_jsxs("div", { className: "flex items-start gap-3", children: [spec?.iconUrl ? (_jsx("img", { src: spec.iconUrl, alt: "", className: "mt-0.5 size-8 shrink-0 rounded object-cover" })) : (_jsx(AgentIcon, { className: "mt-1 size-6 shrink-0 text-muted-foreground" })), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("h2", { className: "truncate text-lg font-semibold text-foreground", children: displayName }), onVisibilityChange && meta ? (_jsx(VisibilityToggle, { visibility: meta.visibility, onVisibilityChange: onVisibilityChange, isPending: isVisibilityPending })) : (isPublic && (_jsx("span", { className: "shrink-0 rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground", children: "Public" })))] }), _jsxs("div", { className: "mt-0.5 flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground", children: [meta?.org && _jsx("span", { children: meta.org }), createdAt && (_jsxs(_Fragment, { children: [_jsx(Dot, {}), _jsxs("span", { children: ["Created ", formatDate(createdAt)] })] })), updatedAt && (_jsxs(_Fragment, { children: [_jsx(Dot, {}), _jsxs("span", { children: ["Updated ", formatDate(updatedAt)] })] }))] }), spec?.description && (_jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: spec.description }))] })] }));
}
function InstructionsSection({ text }) {
    const lines = text.split("\n");
    const needsCollapse = lines.length > INSTRUCTIONS_COLLAPSED_LINES;
    const [expanded, setExpanded] = useState(false);
    const displayText = needsCollapse && !expanded
        ? lines.slice(0, INSTRUCTIONS_COLLAPSED_LINES).join("\n")
        : text;
    return (_jsx(Section, { title: "Instructions", children: _jsxs("div", { className: "p-3", children: [_jsxs("pre", { className: "whitespace-pre-wrap break-words font-mono text-sm text-foreground", children: [displayText, needsCollapse && !expanded && "\u2026"] }), needsCollapse && (_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 McpUsagesSection({ usages, defaultOrg, onMcpServerClick, }) {
    return (_jsx(Section, { title: `MCP Servers (${usages.length})`, children: _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 SkillsSection({ refs, defaultOrg, onSkillClick, }) {
    return (_jsx(Section, { title: `Skills (${refs.length})`, children: _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, }) {
    const [expanded, setExpanded] = useState(new Set());
    const toggle = (index) => {
        setExpanded((prev) => {
            const next = new Set(prev);
            if (next.has(index))
                next.delete(index);
            else
                next.add(index);
            return next;
        });
    };
    return (_jsx(Section, { title: `Sub-Agents (${subAgents.length})`, children: _jsx("div", { className: "flex flex-col", children: subAgents.map((sa, index) => {
                const isOpen = expanded.has(index);
                return (_jsxs("div", { children: [_jsxs("button", { type: "button", onClick: () => toggle(index), "aria-expanded": isOpen, className: cn("flex w-full items-start gap-3 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: [_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 }))] })] }), isOpen && (_jsx(SubAgentDetails, { subAgent: sa }))] }, sa.name || index));
            }) }) }));
}
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 EnvSection({ data, }) {
    const entries = Object.entries(data).sort(([a], [b]) => a.localeCompare(b));
    return (_jsx(Section, { title: `Environment Variables (${entries.length})`, children: _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
// ---------------------------------------------------------------------------
function Section({ title, children, }) {
    return (_jsxs("section", { children: [_jsx("h3", { className: "mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground", children: title }), _jsx("div", { className: "overflow-hidden rounded-lg border border-border", children: children })] }));
}
function Dot() {
    return (_jsx("span", { className: "shrink-0", "aria-hidden": "true", children: "\u00B7" }));
}
// ---------------------------------------------------------------------------
// 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." })] }));
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
function formatDate(date) {
    return date.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
    });
}
// ---------------------------------------------------------------------------
// 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" }) }));
}
//# sourceMappingURL=AgentDetailView.js.map