'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { ExternalLink, AlertTriangle, FileDiff, GitCommitHorizontal, GitBranch, ArrowRight, Camera, FileText, MonitorPlay, Terminal, Download, ChevronDown, ChevronRight, } from 'lucide-react';
import { Badge } from '../../ui/badge.js';
import { CiStatusBadge } from '../../common/ci-status-badge/index.js';
import { DrawerActionBar } from '../../common/drawer-action-bar/index.js';
import { DiffView } from './diff-view.js';
const EVIDENCE_ICONS = {
    Screenshot: Camera,
    Video: MonitorPlay,
    TestOutput: FileText,
    TerminalRecording: Terminal,
};
const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp']);
const VIDEO_EXTENSIONS = new Set(['.mp4', '.webm', '.mov']);
function getExtension(path) {
    const dot = path.lastIndexOf('.');
    return dot >= 0 ? path.slice(dot).toLowerCase() : '';
}
/** Build the API URL for serving an evidence file (paths are pre-normalized to absolute). */
function buildEvidenceUrl(absolutePath) {
    return `/api/evidence?path=${encodeURIComponent(absolutePath)}`;
}
function EvidenceItem({ evidence }) {
    const [expanded, setExpanded] = useState(true);
    const Icon = EVIDENCE_ICONS[evidence.type] ?? Camera;
    const ext = getExtension(evidence.relativePath);
    const url = buildEvidenceUrl(evidence.relativePath);
    const isImage = evidence.type === 'Screenshot' || IMAGE_EXTENSIONS.has(ext);
    const isVideo = evidence.type === 'Video' || VIDEO_EXTENSIONS.has(ext);
    const isText = evidence.type === 'TestOutput' || evidence.type === 'TerminalRecording';
    return (_jsxs("li", { className: "border-border rounded-md border", children: [_jsxs("button", { type: "button", onClick: () => setExpanded(!expanded), className: "flex w-full cursor-pointer items-center gap-2.5 px-3 py-2.5 text-start", children: [expanded ? (_jsx(ChevronDown, { className: "text-muted-foreground h-3 w-3 shrink-0" })) : (_jsx(ChevronRight, { className: "text-muted-foreground h-3 w-3 shrink-0" })), _jsx(Icon, { className: "text-muted-foreground h-3.5 w-3.5 shrink-0" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "text-foreground text-xs font-medium", children: evidence.description }), evidence.taskRef ? (_jsxs("span", { className: "text-muted-foreground ms-1.5 text-[10px]", children: ["(", evidence.taskRef, ")"] })) : null] }), url ? (_jsx("a", { href: url, download: true, onClick: (e) => e.stopPropagation(), className: "text-muted-foreground hover:text-foreground shrink-0 rounded p-1 transition-colors", "aria-label": "Download", children: _jsx(Download, { className: "h-3 w-3" }) })) : null] }), expanded && url ? (_jsx("div", { className: "border-border border-t px-3 py-2.5", children: isImage ? (
                /* eslint-disable-next-line @next/next/no-img-element */
                _jsx("img", { src: url, alt: evidence.description, className: "max-h-80 w-full rounded-md border object-contain", loading: "lazy" })) : isVideo ? (_jsx("video", { src: url, controls: true, className: "max-h-80 w-full rounded-md border", preload: "metadata", children: _jsx("track", { kind: "captions" }) })) : isText ? (_jsx(EvidenceTextPreview, { url: url })) : (_jsx("p", { className: "text-muted-foreground truncate font-mono text-[10px]", children: evidence.relativePath })) })) : null, expanded && !url ? (_jsx("div", { className: "border-border border-t px-3 py-2.5", children: _jsx("p", { className: "text-muted-foreground truncate font-mono text-[10px]", children: evidence.relativePath }) })) : null] }));
}
function EvidenceTextPreview({ url }) {
    const [content, setContent] = useState(null);
    const [loaded, setLoaded] = useState(false);
    if (!loaded) {
        fetch(url)
            .then((r) => (r.ok ? r.text() : Promise.reject(new Error('Failed'))))
            .then((text) => {
            // Limit to first 100 lines for preview
            const lines = text.split('\n');
            setContent(lines.length > 100 ? `${lines.slice(0, 100).join('\n')}\n...` : text);
        })
            .catch(() => setContent(null))
            .finally(() => setLoaded(true));
        return _jsx("div", { className: "bg-muted/50 h-16 animate-pulse rounded-md" });
    }
    if (!content) {
        return _jsx("p", { className: "text-muted-foreground text-[10px]", children: "Unable to load preview" });
    }
    return (_jsx("pre", { className: "bg-muted/50 max-h-60 overflow-auto rounded-md p-3 font-mono text-[11px] leading-relaxed", children: content }));
}
function EvidenceList({ evidence }) {
    return (_jsx("div", { className: "border-border rounded-lg border", children: _jsxs("div", { className: "px-4 py-3", children: [_jsxs("div", { className: "mb-3 flex items-center gap-2", children: [_jsx(Camera, { className: "text-muted-foreground h-4 w-4" }), _jsx("span", { className: "text-foreground text-xs font-semibold", children: "Evidence" }), _jsx(Badge, { variant: "secondary", className: "text-[10px]", children: evidence.length })] }), _jsx("ul", { className: "space-y-2", children: evidence.map((e) => (_jsx(EvidenceItem, { evidence: e }, `${e.type}-${e.relativePath}`))) })] }) }));
}
export function MergeReview({ data, readOnly = false, onApprove, onReject, isProcessing = false, isRejecting = false, chatInput, onChatInputChange, }) {
    const { pr, diffSummary, fileDiffs, branch, warning, evidence, hideCiStatus } = data;
    const hasConflicts = pr?.mergeable === false;
    const handleApproveOrResolve = hasConflicts && onReject ? () => onReject('Resolve merge conflicts', []) : onApprove;
    return (_jsxs("div", { className: "flex min-h-0 flex-1 flex-col", children: [_jsxs("div", { className: "flex-1 space-y-4 overflow-y-auto p-4", children: [_jsxs("div", { className: "flex items-start gap-3", children: [_jsx("div", { className: "mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full bg-emerald-500" }), _jsxs("div", { className: "flex-1", children: [_jsx("h2", { className: "text-foreground text-sm font-bold", children: readOnly ? 'Merge History' : 'Merge Review' }), _jsx("p", { className: "text-muted-foreground mt-1 text-xs leading-relaxed", children: readOnly
                                            ? 'This feature was merged. Review the pull request details and evidence below.'
                                            : pr
                                                ? 'Review the pull request details and approve to merge.'
                                                : 'Review the changes and approve to merge.' })] })] }), branch ? (_jsx("div", { className: "border-border rounded-lg border", children: _jsxs("div", { className: "flex items-center gap-2 px-4 py-3", children: [_jsx(GitBranch, { className: "text-muted-foreground h-4 w-4 shrink-0" }), _jsx(Badge, { variant: "secondary", className: "font-mono text-[11px]", children: branch.source }), _jsx(ArrowRight, { className: "text-muted-foreground h-3.5 w-3.5 shrink-0" }), _jsx(Badge, { variant: "outline", className: "font-mono text-[11px]", children: branch.target })] }) })) : null, pr ? (_jsx("div", { className: "border-border rounded-lg border", children: _jsxs("div", { className: "space-y-3 px-4 py-3", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("a", { href: pr.url, target: "_blank", rel: "noopener noreferrer", className: "text-primary flex items-center gap-1.5 text-sm font-semibold underline underline-offset-2", children: ["PR #", pr.number, _jsx(ExternalLink, { className: "h-3.5 w-3.5" })] }), _jsx(Badge, { variant: "outline", className: "text-xs", children: pr.status })] }), pr.mergeable === false ? (_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-muted-foreground text-xs font-medium", children: "Merge Status" }), _jsxs(Badge, { className: "border-transparent bg-orange-50 text-orange-700 hover:bg-orange-50", children: [_jsx(AlertTriangle, { className: "me-1 h-3.5 w-3.5" }), "Conflicts"] })] })) : null, pr.ciStatus && hideCiStatus !== true ? (_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-muted-foreground text-xs font-medium", children: "CI Status" }), _jsx(CiStatusBadge, { status: pr.ciStatus })] })) : null, pr.commitHash ? (_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "text-muted-foreground text-xs font-medium", children: "Commit" }), _jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(GitCommitHorizontal, { className: "text-muted-foreground h-3.5 w-3.5" }), _jsx("code", { className: "bg-muted text-foreground rounded-md px-1.5 py-0.5 font-mono text-[11px]", children: pr.commitHash.slice(0, 7) })] })] })) : null] }) })) : null, diffSummary ? (_jsx("div", { className: "border-border rounded-lg border", children: _jsxs("div", { className: "px-4 py-3", children: [_jsxs("div", { className: "mb-3 flex items-center gap-2", children: [_jsx(FileDiff, { className: "text-muted-foreground h-4 w-4" }), _jsx("span", { className: "text-foreground text-xs font-semibold", children: "Changes" })] }), _jsxs("div", { className: "grid grid-cols-4 gap-3", children: [_jsxs("div", { className: "text-center", children: [_jsx("div", { className: "text-foreground text-sm font-bold", children: diffSummary.filesChanged }), _jsx("div", { className: "text-muted-foreground text-[10px]", children: "files" })] }), _jsxs("div", { className: "text-center", children: [_jsxs("div", { className: "text-sm font-bold text-green-600", children: ["+", diffSummary.additions] }), _jsx("div", { className: "text-muted-foreground text-[10px]", children: "additions" })] }), _jsxs("div", { className: "text-center", children: [_jsxs("div", { className: "text-sm font-bold text-red-600", children: ["-", diffSummary.deletions] }), _jsx("div", { className: "text-muted-foreground text-[10px]", children: "deletions" })] }), _jsxs("div", { className: "text-center", children: [_jsx("div", { className: "text-foreground text-sm font-bold", children: diffSummary.commitCount }), _jsx("div", { className: "text-muted-foreground text-[10px]", children: "commits" })] })] })] }) })) : warning ? (_jsx("div", { className: "border-border rounded-lg border", children: _jsxs("div", { className: "flex items-center gap-2 px-4 py-3", children: [_jsx(AlertTriangle, { className: "text-muted-foreground h-4 w-4 shrink-0" }), _jsx("span", { className: "text-muted-foreground text-xs", children: warning })] }) })) : null, evidence && evidence.length > 0 ? _jsx(EvidenceList, { evidence: evidence }) : null, fileDiffs && fileDiffs.length > 0 ? _jsx(DiffView, { fileDiffs: fileDiffs }) : null] }), !readOnly && (_jsx(DrawerActionBar, { onReject: onReject, onApprove: handleApproveOrResolve, approveLabel: hasConflicts ? 'Resolve Conflicts' : 'Approve Merge', approveVariant: hasConflicts ? 'warning' : 'default', revisionPlaceholder: "Ask AI to revise before merging...", isProcessing: isProcessing, isRejecting: isRejecting, chatInput: chatInput, onChatInputChange: onChatInputChange }))] }));
}
