import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { AlertTriangle, Clock, FileStack, FolderPlus, LayoutGrid, Loader2, Search, Settings, Shield, Trash2, } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { cn } from "../../lib/utils";
import { TaskStateProgressBar } from "./ProjectDashboard";
function formatAttentionSummaryLine(project) {
    const attention = project.overview?.attention;
    if (!attention || attention.total <= 0)
        return "No attention needed";
    const cap = attention.capacity ?? 0;
    const parts = [];
    if (attention.failed > 0)
        parts.push(`${attention.failed} failed`);
    if (attention.budget > 0)
        parts.push(`${attention.budget} budget`);
    if (attention.blocked > 0)
        parts.push(`${attention.blocked} blocked`);
    if (cap > 0)
        parts.push(`${cap} capacity`);
    if (attention.approval > 0) {
        parts.push(`${attention.approval} ${attention.approval === 1 ? "approval" : "approvals"}`);
    }
    if (attention.input > 0) {
        parts.push(`${attention.input} ${attention.input === 1 ? "input" : "inputs"}`);
    }
    if (parts.length > 0)
        return parts.join(", ");
    return `${attention.total} need attention`;
}
function buildAttentionTooltipText(project) {
    const attention = project.overview?.attention;
    if (!attention || attention.total <= 0) {
        return "No tasks in this project currently need execution attention.";
    }
    const cap = attention.capacity ?? 0;
    const lines = [
        "Tasks counted here are waiting on execution: errors, limits, dependencies, approvals, input, or agent capacity.",
    ];
    if (attention.failed > 0) {
        lines.push(`Failed (${attention.failed}): agent or tool reported an error.`);
    }
    if (attention.budget > 0) {
        lines.push(`Budget (${attention.budget}): project cost limit reached.`);
    }
    if (attention.blocked > 0) {
        lines.push(`Blocked (${attention.blocked}): unfinished task dependencies.`);
    }
    if (cap > 0) {
        lines.push(`Capacity (${cap}): waiting for a free agent slot on this project.`);
    }
    if (attention.approval > 0) {
        lines.push(`Approval (${attention.approval}): review or tool approval required.`);
    }
    if (attention.input > 0) {
        lines.push(`Input (${attention.input}): user or agent input required.`);
    }
    if (lines.length === 1) {
        return `${lines[0]}\n\nTotal attention count may include categories not listed if data is from an older API.`;
    }
    return lines.join("\n\n");
}
function getAttentionClasses(project) {
    const attention = project.overview?.attention;
    if (!attention || attention.total <= 0) {
        return "border-slate-200 bg-slate-50 text-slate-500";
    }
    if (attention.failed > 0 || attention.budget > 0) {
        return "border-red-200 bg-red-50 text-red-700";
    }
    return "border-amber-200 bg-amber-50 text-amber-700";
}
export function ProjectOverviewContent({ nav }) {
    const [projectSearch, setProjectSearch] = useState("");
    const [hideArchivedProjects, setHideArchivedProjects] = useState(true);
    const filteredProjectOptions = useMemo(() => {
        const query = projectSearch.trim().toLowerCase();
        return nav.projectOptions.filter((project) => {
            if (hideArchivedProjects &&
                project.status?.toLowerCase() === "archived") {
                return false;
            }
            if (!query)
                return true;
            const title = project.title?.toLowerCase() ?? "";
            const description = project.description?.toLowerCase() ?? "";
            const permission = project.permission?.toLowerCase() ?? "";
            const status = project.status?.toLowerCase() ?? "";
            const attentionLabel = formatAttentionSummaryLine(project).toLowerCase();
            return (title.includes(query) ||
                description.includes(query) ||
                permission.includes(query) ||
                status.includes(query) ||
                attentionLabel.includes(query));
        });
    }, [hideArchivedProjects, nav.projectOptions, projectSearch]);
    return (_jsxs("div", { className: "flex min-h-full w-full flex-col rounded-2xl border bg-white shadow-sm", "data-testid": "taskboard-project-overview", children: [_jsxs("div", { className: "flex flex-col gap-3 border-b px-4 py-4 md:flex-row md:items-start md:justify-between", children: [_jsxs("div", { className: "space-y-1", children: [_jsx("div", { className: "text-xs font-semibold tracking-wider text-slate-500 uppercase", children: "Taskboard" }), _jsx("h2", { className: "text-xl font-semibold text-slate-900", children: "Projects Overview" }), _jsx("p", { className: "max-w-2xl text-sm text-slate-500", children: "Pick a project to open the board. Progress and attention are shown here so you can see what needs help first." })] }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsxs(Button, { variant: "outline", size: "sm", className: "h-9 px-3", "data-testid": "taskboard-project-overview-edit-templates-button", onClick: () => nav.onOpenProjectTemplates?.(), children: [_jsx(FileStack, { className: "mr-1.5 h-3.5 w-3.5" }), "Edit Templates"] }), _jsxs(Button, { variant: "default", size: "sm", className: "h-9 px-3", "data-testid": "taskboard-project-overview-create-button", onClick: () => nav.onCreateProject?.(), children: [_jsx(FolderPlus, { className: "mr-1.5 h-3.5 w-3.5" }), "New project"] })] })] }), _jsx("div", { className: "border-b px-4 py-3", children: _jsxs("div", { className: "grid gap-3 lg:grid-cols-[minmax(0,1fr)_auto_auto] lg:items-center", children: [_jsxs("div", { className: "relative", children: [_jsx(Search, { className: "pointer-events-none absolute top-1/2 left-2.5 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" }), _jsx(Input, { value: projectSearch, onChange: (e) => setProjectSearch(e.target.value), placeholder: "Search projects...", className: "h-9 pl-8 text-sm", "data-testid": "taskboard-project-overview-search-input" })] }), _jsxs("label", { className: "flex items-center gap-2 text-xs text-slate-600", children: [_jsx("input", { type: "checkbox", checked: hideArchivedProjects, onChange: (e) => setHideArchivedProjects(e.target.checked), "data-testid": "taskboard-project-overview-hide-archived" }), "Hide archived projects"] }), nav.isAdministrator ? (_jsxs("label", { className: "flex items-center gap-2 text-xs text-slate-600", children: [_jsx("input", { type: "checkbox", checked: nav.showAllProjects, onChange: (e) => nav.onToggleShowAllProjects?.(e.target.checked), "data-testid": "taskboard-project-overview-show-all-projects" }), "Show all projects"] })) : null] }) }), _jsx("div", { className: "min-h-0 flex-1 overflow-y-auto p-4", children: nav.isProjectsLoading && nav.projectOptions.length === 0 ? (_jsxs("div", { className: "flex min-h-[240px] items-center justify-center gap-2 rounded-xl border border-dashed text-sm text-slate-400", "data-testid": "taskboard-project-overview-loading", children: [_jsx(Loader2, { className: "h-4 w-4 animate-spin" }), "Loading projects..."] })) : nav.projectOptions.length === 0 ? (_jsx("div", { className: "rounded-xl border border-dashed px-4 py-12 text-center text-sm text-slate-400", children: "No projects yet" })) : filteredProjectOptions.length === 0 ? (_jsx("div", { className: "rounded-xl border border-dashed px-4 py-12 text-center text-sm text-slate-400", children: "No matching projects" })) : (_jsx("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3", children: filteredProjectOptions.map((project) => {
                        const counts = project.overview?.taskCounts ?? {
                            total: 0,
                            todo: 0,
                            waiting: 0,
                            inProgress: 0,
                            review: 0,
                            done: 0,
                        };
                        const attentionTotal = project.overview?.attention?.total ?? 0;
                        const attentionLine = formatAttentionSummaryLine(project);
                        const attentionTooltip = buildAttentionTooltipText(project);
                        const completionLabel = counts.total > 0
                            ? `${counts.done}/${counts.total} done`
                            : "No tasks yet";
                        const canManage = project.permission === "Owner";
                        const isSelected = project.projectId === nav.selectedProjectId;
                        const depth = Math.max(0, Math.min(project.depth ?? 0, 6));
                        const subprojectCount = project.overview?.directSubprojectCount ?? 0;
                        return (_jsxs("div", { className: cn("group flex flex-col rounded-xl border bg-white transition-colors", isSelected
                                ? "border-slate-300 shadow-sm"
                                : "border-slate-200 hover:border-slate-300"), "data-testid": `taskboard-project-overview-card-${project.projectId}`, children: [_jsxs("div", { className: "flex items-start justify-between gap-2 px-4 pt-4", children: [_jsxs("button", { type: "button", className: "min-w-0 flex-1 text-left", onClick: () => nav.onSelectProject?.(project.projectId), children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(LayoutGrid, { className: "h-4 w-4 flex-none text-slate-400" }), depth > 0 ? (_jsx("span", { className: "text-[10px] text-slate-400", children: "↳".repeat(Math.min(depth, 2)) })) : null, _jsx("span", { className: "truncate text-base font-semibold text-slate-900", children: project.title })] }), project.description?.trim() ? (_jsx("p", { className: "mt-2 line-clamp-3 text-xs text-slate-500", children: project.description.trim() })) : (_jsx("p", { className: "mt-2 text-xs text-slate-400", children: "No description" }))] }), canManage ? (_jsxs("div", { className: "flex items-center gap-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100", children: [_jsx(Button, { variant: "ghost", size: "icon", className: "h-8 w-8", onClick: (e) => {
                                                        e.stopPropagation();
                                                        nav.onOpenProjectSettings?.(project.projectId);
                                                    }, title: "Project settings", "data-testid": `taskboard-project-overview-settings-${project.projectId}`, children: _jsx(Settings, { className: "h-3.5 w-3.5" }) }), _jsx(Button, { variant: "ghost", size: "icon", className: "text-destructive hover:bg-destructive/10 hover:text-destructive h-8 w-8", onClick: (e) => {
                                                        e.stopPropagation();
                                                        nav.onDeleteProject?.(project.projectId, project.title);
                                                    }, title: "Delete project", "data-testid": `taskboard-project-overview-delete-${project.projectId}`, children: _jsx(Trash2, { className: "h-3.5 w-3.5" }) })] })) : null] }), _jsxs("button", { type: "button", className: "flex flex-1 flex-col px-4 pb-4 text-left", onClick: () => nav.onSelectProject?.(project.projectId), children: [_jsxs("div", { className: "mt-4 flex flex-wrap items-center gap-2", children: [_jsx("span", { className: "rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600", children: project.status ?? "Active" }), _jsxs(Tooltip, { delayDuration: 250, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: cn("inline-flex cursor-default rounded-full border px-2.5 py-1 text-[11px] font-medium", getAttentionClasses(project)), "data-testid": `taskboard-project-overview-attention-${project.projectId}`, children: _jsxs("span", { className: "inline-flex items-center gap-1", children: [_jsx(AlertTriangle, { className: "h-3 w-3" }), attentionTotal > 0
                                                                            ? attentionLine
                                                                            : "No attention needed"] }) }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, className: "max-w-xs text-left whitespace-pre-line", children: attentionTooltip })] })] }), _jsxs("div", { className: "mt-auto pt-4", children: [_jsxs("div", { className: "space-y-2", children: [_jsxs("div", { className: "flex items-center justify-between gap-3 text-xs text-slate-500", children: [_jsx("span", { children: "Progress" }), _jsx("span", { children: completionLabel })] }), _jsx(TaskStateProgressBar, { counts: counts }), _jsxs("div", { className: "flex flex-wrap gap-2 text-[11px] text-slate-500", children: [_jsxs("span", { children: [counts.todo, " todo"] }), _jsxs("span", { children: [counts.inProgress, " in progress"] }), _jsxs("span", { children: [counts.review, " review"] }), _jsxs("span", { children: [counts.waiting, " waiting"] })] })] }), _jsxs("div", { className: "mt-4 flex flex-wrap items-center gap-3 border-t pt-3 text-[11px] text-slate-500", children: [_jsxs("span", { className: "inline-flex items-center gap-1.5", children: [_jsx(Shield, { className: "h-3 w-3 text-slate-400" }), project.permission] }), subprojectCount > 0 ? (_jsxs("span", { children: [subprojectCount, " subproject", subprojectCount === 1 ? "" : "s"] })) : null, project.updatedAt ? (_jsxs("span", { className: "inline-flex items-center gap-1.5", title: `Last updated: ${new Date(project.updatedAt).toLocaleString()}`, children: [_jsx(Clock, { className: "h-3 w-3 text-slate-400" }), formatDistanceToNow(new Date(project.updatedAt), {
                                                                    addSuffix: true,
                                                                })] })) : null] })] })] })] }, project.projectId));
                    }) })) })] }));
}
//# sourceMappingURL=ProjectOverviewContent.js.map