import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from "react";
import { ChevronDown, Folder } from "lucide-react";
import { Select } from "../../components/ui/select";
import { ProjectPropertiesPanel } from "./ProjectPropertiesPanel";
import { TaskboardPersistentLogPanel } from "./TaskboardPersistentLogPanel";
const EMPTY_COUNTS = {
    total: 0,
    todo: 0,
    waiting: 0,
    inProgress: 0,
    review: 0,
    done: 0,
};
const DEFAULT_COST_LIMIT = 25;
const STATE_STOPS = [
    { key: "todo", label: "Todo", segmentClassName: "bg-slate-300" },
    { key: "waiting", label: "Waiting", segmentClassName: "bg-amber-300" },
    { key: "inProgress", label: "In progress", segmentClassName: "bg-blue-400" },
    { key: "review", label: "Review", segmentClassName: "bg-violet-400" },
    { key: "done", label: "Done", segmentClassName: "bg-emerald-400" },
];
export function TaskStateProgressBar(props) {
    const { counts, compact = false } = props;
    const total = counts.total;
    return (_jsx("div", { className: `${compact ? "h-1.5" : "h-2"} w-full overflow-hidden rounded-full bg-slate-100`, children: total > 0 ? (_jsx("div", { className: "flex h-full w-full", children: STATE_STOPS.map((stop) => {
                const value = counts[stop.key];
                const widthPct = (value / total) * 100;
                return (_jsx("div", { className: stop.segmentClassName, style: { width: `${widthPct}%` }, title: `${stop.label}: ${value}` }, stop.key));
            }) })) : null }));
}
export function ProjectDashboard(props) {
    const { selectedProjectDescription, selectedProjectStatus, selectedProjectCostUsed = 0, selectedProjectCostLimit = null, canEditProjectStatus = false, savingProjectStatus = false, onStatusChange, selectedProjectTaskCounts, subprojects, taskCountsByProjectId, parentProjectId, parentProjectTitle, onSelectProject, projectId, canEditProperties = false, } = props;
    const hasSubprojects = subprojects.length > 0;
    const [showSubprojects, setShowSubprojects] = useState(hasSubprojects);
    const previousSubprojectCountRef = useRef(subprojects.length);
    useEffect(() => {
        const previousCount = previousSubprojectCountRef.current;
        const nextCount = subprojects.length;
        if (nextCount > previousCount) {
            setShowSubprojects(true);
        }
        previousSubprojectCountRef.current = nextCount;
    }, [subprojects.length]);
    const normalizedCostUsed = Number.isFinite(selectedProjectCostUsed)
        ? Math.max(0, selectedProjectCostUsed)
        : 0;
    const effectiveCostLimit = typeof selectedProjectCostLimit === "number" && selectedProjectCostLimit > 0
        ? selectedProjectCostLimit
        : DEFAULT_COST_LIMIT;
    const costProgressPct = useMemo(() => {
        const pct = (normalizedCostUsed / effectiveCostLimit) * 100;
        return Math.max(0, Math.min(pct, 100));
    }, [effectiveCostLimit, normalizedCostUsed]);
    const costProgressClassName = costProgressPct >= 100
        ? "bg-red-500"
        : costProgressPct >= 80
            ? "bg-amber-500"
            : "bg-emerald-500";
    const statusValue = selectedProjectStatus ?? "Active";
    const aggregatedCounts = hasSubprojects
        ? subprojects.reduce((acc, subproject) => {
            const counts = taskCountsByProjectId[subproject.project.projectId] || EMPTY_COUNTS;
            return {
                total: acc.total + counts.total,
                todo: acc.todo + counts.todo,
                waiting: acc.waiting + counts.waiting,
                inProgress: acc.inProgress + counts.inProgress,
                review: acc.review + counts.review,
                done: acc.done + counts.done,
            };
        }, {
            total: selectedProjectTaskCounts.total,
            todo: selectedProjectTaskCounts.todo,
            waiting: selectedProjectTaskCounts.waiting,
            inProgress: selectedProjectTaskCounts.inProgress,
            review: selectedProjectTaskCounts.review,
            done: selectedProjectTaskCounts.done,
        })
        : selectedProjectTaskCounts;
    const rows = [
        {
            projectId: "selected-project",
            title: "Progress",
            counts: aggregatedCounts,
            compact: false,
            indented: false,
            isLink: false,
        },
        ...(hasSubprojects && showSubprojects
            ? subprojects.map((subproject) => ({
                projectId: subproject.project.projectId,
                title: subproject.project.title,
                counts: taskCountsByProjectId[subproject.project.projectId] || EMPTY_COUNTS,
                compact: true,
                indented: true,
                isLink: true,
            }))
            : []),
    ];
    return (_jsxs("div", { className: "mb-4", "data-testid": "taskboard-project-dashboard", children: [parentProjectId && parentProjectTitle && onSelectProject && (_jsx("div", { className: "mb-3", children: _jsxs("button", { type: "button", className: "text-xs text-slate-600 hover:text-slate-800", onClick: () => onSelectProject(parentProjectId), "data-testid": "taskboard-parent-project-button", children: ["\u2190 Back to ", parentProjectTitle] }) })), _jsxs("div", { className: "mb-4", children: [_jsxs("div", { className: "grid gap-3 md:grid-cols-[minmax(0,1fr)_220px]", children: [_jsxs("div", { children: [_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("div", { className: "text-[11px] font-semibold tracking-wider text-slate-500 uppercase", children: "Description" }), _jsx(TaskboardPersistentLogPanel, { scope: "project", projectId: projectId, title: "Project Activity Log", emptyMessage: "No project-level orchestration entries yet.", refreshKey: `${projectId}:${statusValue}:${normalizedCostUsed}:${selectedProjectTaskCounts.total}:${selectedProjectTaskCounts.waiting}:${selectedProjectTaskCounts.inProgress}:${selectedProjectTaskCounts.review}:${selectedProjectTaskCounts.done}`, testId: "taskboard-project-dashboard-log-panel" })] }), _jsx("div", { className: "mt-1 text-xs text-slate-700", children: selectedProjectDescription?.trim() || "No description" })] }), _jsxs("div", { children: [_jsx("div", { className: "text-[11px] font-semibold tracking-wider text-slate-500 uppercase", children: "Status" }), _jsx("div", { className: "mt-1", children: _jsx(Select, { "data-testid": "taskboard-project-status-select", value: statusValue, onValueChange: (value) => onStatusChange?.(value), disabled: !canEditProjectStatus ||
                                                savingProjectStatus ||
                                                !onStatusChange, options: [
                                                { value: "Planning", label: "Planning" },
                                                { value: "Active", label: "Active" },
                                                { value: "Finished", label: "Finished" },
                                                { value: "Archived", label: "Archived" },
                                            ], className: "h-7 text-xs" }) })] })] }), _jsxs("div", { className: "mt-3", children: [_jsxs("div", { className: "mb-1.5 flex items-center justify-between text-[11px] font-semibold tracking-wider text-slate-500 uppercase", children: [_jsx("span", { children: "Cumulative cost" }), _jsxs("span", { className: "tracking-normal text-slate-600 normal-case", children: ["$", normalizedCostUsed.toFixed(2), ` / $${effectiveCostLimit.toFixed(2)}`] })] }), _jsx("div", { className: "h-2 w-full overflow-hidden rounded-full bg-slate-100", "data-testid": "taskboard-project-cost-bar", children: _jsx("div", { className: `h-full ${costProgressClassName}`, style: { width: `${costProgressPct}%` } }) })] })] }), _jsxs(_Fragment, { children: [_jsx("div", { className: hasSubprojects ? "space-y-2" : "space-y-3", "data-testid": "taskboard-project-progress-rows", children: rows.map((row) => {
                            const isRootRow = row.projectId === "selected-project";
                            const rootLabelClass = "text-[11px] font-semibold uppercase tracking-wider text-slate-500";
                            return (_jsxs("div", { className: "space-y-1", "data-testid": `taskboard-project-progress-row-${row.projectId}`, children: [_jsxs("div", { className: `flex items-center justify-between gap-4 ${row.compact ? "text-xs" : "text-sm"} ${row.indented ? "pl-4" : ""}`, children: [isRootRow && hasSubprojects ? (_jsx("button", { type: "button", className: `truncate text-left hover:text-slate-600 ${rootLabelClass}`, onClick: () => setShowSubprojects((prev) => !prev), "aria-label": showSubprojects
                                                    ? "Hide subprojects"
                                                    : "Show subprojects", title: showSubprojects
                                                    ? "Hide subprojects"
                                                    : "Show subprojects", "data-testid": "taskboard-subproject-toggle-label", children: row.title })) : row.isLink && onSelectProject ? (_jsxs("button", { type: "button", className: `flex min-w-0 items-center gap-1.5 truncate text-left text-slate-700 hover:text-slate-900 ${row.compact ? "font-medium" : "font-medium"}`, onClick: () => onSelectProject(row.projectId), "data-testid": `taskboard-subproject-link-${row.projectId}`, children: [_jsx(Folder, { className: "h-3.5 w-3.5 shrink-0 text-slate-500", "aria-hidden": true }), _jsx("span", { className: "truncate", children: row.title })] })) : (_jsx("div", { className: `truncate ${isRootRow
                                                    ? rootLabelClass
                                                    : `text-slate-800 ${row.compact ? "font-medium" : "font-medium"}`}`, children: row.title })), _jsxs("div", { className: `shrink-0 text-slate-600 ${row.compact ? "text-[11px]" : "text-xs"}`, children: [row.counts.total, " tasks"] })] }), _jsxs("div", { className: `flex items-center gap-2 ${row.indented ? "pr-6 pl-4" : ""}`, children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(TaskStateProgressBar, { counts: row.counts, compact: row.compact }) }), hasSubprojects && isRootRow && (_jsx("button", { type: "button", className: "flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-slate-500 hover:bg-slate-100 hover:text-slate-700", onClick: () => setShowSubprojects((prev) => !prev), "aria-label": showSubprojects
                                                    ? "Hide subprojects"
                                                    : "Show subprojects", title: showSubprojects
                                                    ? "Hide subprojects"
                                                    : "Show subprojects", "data-testid": "taskboard-subproject-toggle-button", children: _jsx(ChevronDown, { className: `h-3.5 w-3.5 transition-transform ${showSubprojects ? "rotate-180" : "rotate-0"}` }) }))] })] }, row.projectId));
                        }) }), _jsx("div", { className: "mt-4 grid grid-cols-2 gap-1 text-[11px] sm:grid-cols-5", children: STATE_STOPS.map((stop) => (_jsxs("div", { className: "flex items-center gap-1.5 text-slate-600", children: [_jsx("span", { className: `inline-block h-2 w-2 rounded-full ${stop.segmentClassName}` }), _jsx("span", { children: stop.label })] }, stop.key))) })] }), _jsx(ProjectPropertiesPanel, { projectId: projectId, canEdit: canEditProperties, className: "mt-4" })] }));
}
//# sourceMappingURL=ProjectDashboard.js.map