"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useRef } from "react";
import Markdown from "react-markdown";
import { cn } from "@stigmer/theme";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { SkillState } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/status_pb";
import { ApiResourceVisibility } from "@stigmer/protos/ai/stigmer/commons/apiresource/enum_pb";
import { useSkill } from "./useSkill";
import { ErrorMessage } from "../error/ErrorMessage";
import { VisibilityToggle } from "../library/VisibilityToggle";
import { MARKDOWN_COMPONENTS, REMARK_PLUGINS, stripFrontmatter } from "../internal/markdown-components";
/**
 * Read-only detail view for a Skill knowledge package.
 *
 * Fetches the skill via {@link useSkill} internally and renders its
 * full content in structured sections: header, SKILL.md content
 * (rendered as formatted markdown), and version/provenance info.
 * Sections with no data are omitted entirely.
 *
 * The SKILL.md content is the primary value of this view — it IS the
 * skill. The markdown is rendered using the same styled component
 * overrides used across all SDK markdown surfaces.
 *
 * 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
 * <SkillDetailView org="acme" slug="code-style-guide" />
 * ```
 *
 * @example
 * ```tsx
 * // Pinned to a specific version tag
 * <SkillDetailView org="acme" slug="code-style-guide" version="stable" />
 * ```
 */
export function SkillDetailView({ org, slug, version, onResourceLoad, onVisibilityChange, isVisibilityPending, className, }) {
    const { skill, isLoading, error, refetch } = useSkill(org, slug, version);
    const onResourceLoadRef = useRef(onResourceLoad);
    onResourceLoadRef.current = onResourceLoad;
    useEffect(() => {
        if (skill?.metadata?.name) {
            onResourceLoadRef.current?.({ name: skill.metadata.name, id: skill.metadata.id });
        }
    }, [skill]);
    if (isLoading)
        return _jsx(LoadingSkeleton, { className: className });
    if (error)
        return _jsx(ErrorMessage, { error: error, retry: refetch, className: className });
    if (!skill)
        return _jsx(NotFoundState, { className: className });
    const spec = skill.spec;
    const status = skill.status;
    const specAudit = status?.audit?.specAudit;
    return (_jsxs("div", { className: cn("flex flex-col gap-6", className), children: [_jsx(Header, { skill: skill, createdAt: specAudit?.createdAt ? timestampDate(specAudit.createdAt) : null, updatedAt: specAudit?.updatedAt ? timestampDate(specAudit.updatedAt) : null, onVisibilityChange: onVisibilityChange, isVisibilityPending: isVisibilityPending }), spec?.skillMd && (_jsx(SkillContentSection, { content: spec.skillMd })), status && (status.versionHash || status.gitProvenance) && (_jsx(VersionSection, { versionHash: status.versionHash, gitProvenance: status.gitProvenance }))] }));
}
// ---------------------------------------------------------------------------
// Internal section components
// ---------------------------------------------------------------------------
function Header({ skill, createdAt, updatedAt, onVisibilityChange, isVisibilityPending, }) {
    const meta = skill.metadata;
    const spec = skill.spec;
    const status = skill.status;
    const displayName = meta?.name || meta?.slug || "Untitled";
    const isPublic = meta?.visibility === ApiResourceVisibility.visibility_public;
    return (_jsxs("div", { className: "flex items-start gap-3", children: [_jsx(SkillIcon, { 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 }), spec?.tag && (_jsxs(_Fragment, { children: [_jsx(Dot, {}), _jsx("span", { className: "rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium", children: spec.tag })] })), status && _jsx(SkillStateBadge, { state: status.state }), 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 SkillStateBadge({ state }) {
    switch (state) {
        case SkillState.READY:
            return (_jsxs(_Fragment, { children: [_jsx(Dot, {}), _jsxs("span", { className: "inline-flex items-center gap-1 text-emerald-600 dark:text-emerald-400", children: [_jsx(CheckIcon, { className: "size-3" }), "Ready"] })] }));
        case SkillState.FAILED:
            return (_jsxs(_Fragment, { children: [_jsx(Dot, {}), _jsx("span", { className: "text-destructive", children: "Failed" })] }));
        case SkillState.UPLOADING:
            return (_jsxs(_Fragment, { children: [_jsx(Dot, {}), _jsx("span", { className: "text-amber-600 dark:text-amber-400", children: "Uploading" })] }));
        default:
            return null;
    }
}
function SkillContentSection({ content }) {
    return (_jsx(Section, { title: "Skill Content", children: _jsx("div", { className: "p-4", children: _jsx(Markdown, { remarkPlugins: REMARK_PLUGINS, components: MARKDOWN_COMPONENTS, children: stripFrontmatter(content) }) }) }));
}
function VersionSection({ versionHash, gitProvenance, }) {
    const truncatedHash = versionHash ? versionHash.slice(0, 12) : null;
    return (_jsx(Section, { title: "Version", children: _jsxs("div", { className: "flex flex-col gap-3 p-3", children: [truncatedHash && (_jsxs("div", { className: "flex items-baseline gap-2", children: [_jsx("span", { className: "text-xs font-medium text-muted-foreground", children: "Hash" }), _jsx("code", { className: "font-mono text-xs text-foreground", title: versionHash, children: truncatedHash })] })), gitProvenance && _jsx(GitProvenanceDisplay, { provenance: gitProvenance })] }) }));
}
function GitProvenanceDisplay({ provenance, }) {
    const repoUrl = normalizeGitUrl(provenance.remoteUrl);
    const truncatedCommit = provenance.commit
        ? provenance.commit.slice(0, 7)
        : null;
    return (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsxs("div", { className: "flex items-baseline gap-2", children: [_jsx("span", { className: "text-xs font-medium text-muted-foreground", children: "Git" }), _jsxs("div", { className: "flex flex-wrap items-baseline gap-x-1.5 text-xs text-foreground", children: [repoUrl ? (_jsx("a", { href: repoUrl, className: "text-primary underline underline-offset-2 hover:text-primary-muted", target: "_blank", rel: "noopener noreferrer", children: formatRepoName(repoUrl) })) : (_jsx("span", { className: "font-mono", children: provenance.remoteUrl })), provenance.ref && (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-muted-foreground", children: "@" }), _jsx("span", { children: provenance.ref })] })), truncatedCommit && (_jsx("code", { className: "rounded bg-muted px-1 py-0.5 font-mono text-[10px]", title: provenance.commit, children: truncatedCommit }))] })] }), provenance.subdir && (_jsxs("div", { className: "flex items-baseline gap-2", children: [_jsx("span", { className: "text-xs font-medium text-muted-foreground", children: "Path" }), _jsx("code", { className: "font-mono text-xs text-foreground", children: provenance.subdir })] }))] }));
}
// ---------------------------------------------------------------------------
// 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 skill 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" })] })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("div", { className: "h-3 w-28 animate-pulse rounded bg-muted" }), _jsx("div", { className: "animate-pulse rounded-lg border border-border bg-muted-faint", style: { height: "240px" } })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("div", { className: "h-3 w-20 animate-pulse rounded bg-muted" }), _jsx("div", { className: "animate-pulse rounded-lg border border-border bg-muted-faint", style: { height: "64px" } })] })] }));
}
function NotFoundState({ className }) {
    return (_jsxs("div", { role: "status", className: cn("flex flex-col items-center gap-2 py-12 text-center", className), children: [_jsx(SkillIcon, { className: "size-10 text-muted-foreground-faint" }), _jsx("p", { className: "text-sm font-medium text-muted-foreground", children: "Skill not found" }), _jsx("p", { className: "text-xs text-muted-foreground-subtle", children: "This skill 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",
    });
}
function normalizeGitUrl(url) {
    if (!url)
        return null;
    const cleaned = url.replace(/\.git$/, "");
    if (cleaned.startsWith("https://") || cleaned.startsWith("http://")) {
        return cleaned;
    }
    const sshMatch = cleaned.match(/^(?:git@|ssh:\/\/)([^:/]+)[:/](.+)$/);
    if (sshMatch) {
        return `https://${sshMatch[1]}/${sshMatch[2]}`;
    }
    return null;
}
function formatRepoName(url) {
    try {
        const parsed = new URL(url);
        return parsed.pathname.replace(/^\//, "").replace(/\.git$/, "");
    }
    catch {
        return url;
    }
}
// ---------------------------------------------------------------------------
// Icons — inline SVGs following the SDK pattern (no icon library dependency)
// ---------------------------------------------------------------------------
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 CheckIcon({ 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: "m3 8.5 3.5 3.5 6.5-8" }) }));
}
//# sourceMappingURL=SkillDetailView.js.map