'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import Link from 'next/link';
import { Globe2, Layers, GitBranch, Sparkles, ArrowRight, ShieldCheck } from 'lucide-react';
import { Badge } from '../ui/badge.js';
import { SupervisorDecisionWhyDrawer } from './supervisor-decision-why-drawer.js';
import { SupervisorVerdict } from '../../../../../packages/core/src/domain/generated/output.js';
const VERDICT_VARIANT = {
    [SupervisorVerdict.approve]: 'default',
    [SupervisorVerdict.reject]: 'destructive',
    [SupervisorVerdict.escalate]: 'secondary',
    [SupervisorVerdict.advise]: 'secondary',
};
const AUTONOMY_LABEL = {
    advisory: 'Advisory',
    cosign: 'Co-sign',
    autonomous: 'Autonomous',
};
export function SupervisorDashboard({ policies, recentDecisions, names = {}, }) {
    const grouped = groupByScope(policies);
    return (_jsxs("div", { className: "flex flex-col gap-8", "data-testid": "supervisor-dashboard", children: [_jsxs("header", { className: "flex flex-col gap-1", children: [_jsxs("h1", { className: "flex items-center gap-2 text-2xl font-semibold", children: [_jsx(ShieldCheck, { className: "size-6" }), "Supervisor"] }), _jsx("p", { className: "text-muted-foreground text-sm", children: "Every configured supervisor policy and the most recent decisions across all scopes." })] }), _jsxs("section", { className: "flex flex-col gap-3", "data-testid": "supervisor-policies", children: [_jsxs("h2", { className: "text-sm font-semibold tracking-wide uppercase", children: ["Policies ", _jsxs("span", { className: "text-muted-foreground font-normal", children: ["(", policies.length, ")"] })] }), policies.length === 0 ? (_jsx(EmptyPoliciesState, {})) : (_jsxs("div", { className: "flex flex-col gap-4", children: [_jsx(ScopeGroup, { kind: "global", policies: grouped.global, names: names, "data-testid": "scope-group-global" }), _jsx(ScopeGroup, { kind: "app", policies: grouped.app, names: names, "data-testid": "scope-group-app" }), _jsx(ScopeGroup, { kind: "repo", policies: grouped.repo, names: names, "data-testid": "scope-group-repo" }), _jsx(ScopeGroup, { kind: "feature", policies: grouped.feature, names: names, "data-testid": "scope-group-feature" })] }))] }), _jsxs("section", { className: "flex flex-col gap-3", "data-testid": "supervisor-recent-decisions", children: [_jsxs("h2", { className: "text-sm font-semibold tracking-wide uppercase", children: ["Recent decisions", ' ', _jsxs("span", { className: "text-muted-foreground font-normal", children: ["(", recentDecisions.length, ")"] })] }), recentDecisions.length === 0 ? (_jsx("p", { className: "text-muted-foreground rounded-lg border border-dashed p-4 text-sm", children: "No decisions yet \u2014 the supervisor hasn't been invoked or no policies are configured." })) : (_jsx("ul", { className: "flex flex-col divide-y rounded-lg border", children: recentDecisions.map((decision) => (_jsxs("li", { className: "flex items-start gap-3 px-3 py-2", "data-testid": `recent-decision-${decision.decisionId}`, children: [_jsx(Badge, { variant: VERDICT_VARIANT[decision.verdict] ?? 'secondary', className: "mt-0.5 capitalize", children: decision.verdict }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("p", { className: "line-clamp-1 text-sm", children: decision.rationale }), _jsxs("p", { className: "text-muted-foreground text-xs", children: [describeScope(decision.scopeType, decision.scopeId, decision.featureId), " \u00B7", ' ', decision.sourceEventKind, " \u00B7 ", formatRelative(decision.createdAt)] })] }), _jsx(SupervisorDecisionWhyDrawer, { decisions: [decision], triggerLabel: "Why?" })] }, decision.decisionId))) }))] })] }));
}
function groupByScope(policies) {
    const grouped = { global: [], app: [], repo: [], feature: [] };
    for (const p of policies) {
        if (p.featureId)
            grouped.feature.push(p);
        else if (p.scopeType === 'global')
            grouped.global.push(p);
        else if (p.scopeType === 'app')
            grouped.app.push(p);
        else if (p.scopeType === 'repo')
            grouped.repo.push(p);
    }
    return grouped;
}
const SCOPE_LABEL = {
    global: 'Global',
    app: 'Applications',
    repo: 'Repositories',
    feature: 'Per-feature overrides',
};
function ScopeGroup({ kind, policies, names, ...rest }) {
    if (policies.length === 0)
        return null;
    return (_jsxs("div", { className: "flex flex-col gap-2", ...rest, children: [_jsxs("p", { className: "text-muted-foreground flex items-center gap-1.5 text-xs font-medium", children: [_jsx(KindIcon, { kind: kind, className: "size-3" }), SCOPE_LABEL[kind], " (", policies.length, ")"] }), _jsx("ul", { className: "flex flex-col divide-y rounded-lg border", children: policies.map((policy) => (_jsxs("li", { className: "flex items-center gap-3 px-3 py-2", "data-testid": `policy-row-${policy.id}`, children: [_jsx(KindIcon, { kind: kind, className: "text-muted-foreground size-4 shrink-0", "aria-hidden": true }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("p", { className: "truncate text-sm font-medium", children: describePolicyName(policy, names) }), _jsxs("p", { className: "text-muted-foreground text-xs", children: [AUTONOMY_LABEL[policy.autonomyLevel] ?? policy.autonomyLevel, policy.modelId ? ` · ${policy.modelId}` : ''] })] }), _jsx(Badge, { variant: policy.enabled ? 'default' : 'secondary', className: "shrink-0", children: policy.enabled ? 'Enabled' : 'Disabled' }), _jsxs(Link, { href: hrefForPolicy(policy), className: "text-primary inline-flex shrink-0 items-center gap-1 text-xs hover:underline", "data-testid": `policy-link-${policy.id}`, children: ["Configure", _jsx(ArrowRight, { className: "size-3" })] })] }, policy.id))) })] }));
}
function EmptyPoliciesState() {
    return (_jsxs("div", { className: "bg-muted/30 flex flex-col items-start gap-3 rounded-lg border border-dashed p-6", children: [_jsx("p", { className: "text-sm font-medium", children: "No supervisor policies configured" }), _jsx("p", { className: "text-muted-foreground text-sm", children: "Configure a supervisor at the global, application, repository, or feature level. The cascade picks the most specific match (feature > repo > app > global) at run time." }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsxs(Link, { href: '/', className: "border-border hover:bg-muted inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium", "data-testid": "empty-policies-cta-app", children: [_jsx(Layers, { className: "size-3" }), "Pick an application"] }), _jsxs(Link, { href: '/agents', className: "border-border hover:bg-muted inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium", "data-testid": "empty-policies-cta-agents", children: [_jsx(ArrowRight, { className: "size-3" }), "Edit agent prompts instead"] })] })] }));
}
function KindIcon({ kind, className, ...rest }) {
    const Icon = kind === 'global' ? Globe2 : kind === 'app' ? Layers : kind === 'repo' ? GitBranch : Sparkles;
    return _jsx(Icon, { className: className, ...rest });
}
function describePolicyName(policy, names) {
    if (policy.featureId) {
        const featureName = names.feature?.[policy.featureId] ?? policy.featureId;
        const parent = policy.scopeId
            ? (names[policy.scopeType === 'app' ? 'app' : 'repo']?.[policy.scopeId] ?? policy.scopeId)
            : 'global';
        return `${featureName} (under ${parent})`;
    }
    if (policy.scopeType === 'global')
        return 'Global default';
    const lookup = policy.scopeType === 'app' ? names.app : names.repo;
    return policy.scopeId ? (lookup?.[policy.scopeId] ?? policy.scopeId) : policy.scopeType;
}
function hrefForPolicy(policy) {
    if (policy.featureId)
        return `/supervisor/feature/${policy.featureId}`;
    if (policy.scopeType === 'app' && policy.scopeId) {
        return `/application/${policy.scopeId}/supervisor`;
    }
    if (policy.scopeType === 'repo' && policy.scopeId) {
        return `/supervisor/repo/${policy.scopeId}`;
    }
    return `/supervisor`;
}
function describeScope(scopeType, scopeId, featureId) {
    if (featureId)
        return `feature:${featureId.slice(0, 8)}`;
    if (scopeType === 'global')
        return 'global';
    return scopeId ? `${scopeType}:${scopeId.slice(0, 8)}` : scopeType;
}
const RELATIVE_THRESHOLDS = [
    { ms: 60_000, label: (n) => `${n}s ago` },
    { ms: 3_600_000, label: (n) => `${n}m ago` },
    { ms: 86_400_000, label: (n) => `${n}h ago` },
];
function formatRelative(iso) {
    const elapsed = Date.now() - new Date(iso).getTime();
    if (Number.isNaN(elapsed))
        return iso;
    for (const { ms, label } of RELATIVE_THRESHOLDS) {
        if (elapsed < ms) {
            const divisor = ms === 60_000 ? 1_000 : ms === 3_600_000 ? 60_000 : 3_600_000;
            return label(Math.max(1, Math.floor(elapsed / divisor)));
        }
    }
    return new Date(iso).toLocaleDateString();
}
