import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { ChevronDown, Folder } from "lucide-react";
import { Select } from "../../components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { ProjectPropertiesPanel } from "./ProjectPropertiesPanel";
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",
        ringColor: "#cbd5e1",
        swatchClassName: "bg-slate-300",
    },
    {
        key: "waiting",
        label: "Waiting",
        segmentClassName: "bg-amber-300",
        ringColor: "#fcd34d",
        swatchClassName: "bg-amber-300",
    },
    {
        key: "inProgress",
        label: "In progress",
        segmentClassName: "bg-blue-400",
        ringColor: "#60a5fa",
        swatchClassName: "bg-blue-400",
    },
    {
        key: "review",
        label: "Review",
        segmentClassName: "bg-violet-400",
        ringColor: "#a78bfa",
        swatchClassName: "bg-violet-400",
    },
    {
        key: "done",
        label: "Done",
        segmentClassName: "bg-emerald-400",
        ringColor: "#34d399",
        swatchClassName: "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 CostProgressRing(props) {
    const { used, limit, size = 44, strokeWidth = 4 } = props;
    const radius = (size - strokeWidth) / 2;
    const circumference = 2 * Math.PI * radius;
    const pct = limit > 0 ? Math.max(0, Math.min((used / limit) * 100, 100)) : 0;
    const dashOffset = circumference - (pct / 100) * circumference;
    const stroke = pct >= 100 ? "#ef4444" : pct >= 80 ? "#f59e0b" : "#10b981";
    const center = size / 2;
    const formatAmount = (value) => value >= 1000
        ? `${(value / 1000).toFixed(value >= 10000 ? 0 : 1)}k`
        : value.toFixed(value >= 100 ? 0 : 0);
    return (_jsxs("div", { className: "relative", style: { width: size, height: size }, children: [_jsxs("svg", { width: size, height: size, viewBox: `0 0 ${size} ${size}`, className: "-rotate-90", "aria-hidden": true, children: [_jsx("circle", { cx: center, cy: center, r: radius, stroke: "#e2e8f0", strokeWidth: strokeWidth, fill: "none" }), _jsx("circle", { cx: center, cy: center, r: radius, stroke: stroke, strokeWidth: strokeWidth, fill: "none", strokeLinecap: "round", strokeDasharray: circumference, strokeDashoffset: dashOffset, style: { transition: "stroke-dashoffset 200ms ease-out" } })] }), _jsxs("div", { className: "pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-[10px] leading-none font-semibold text-slate-700", children: [_jsxs("span", { children: ["$", formatAmount(used)] }), _jsxs("span", { className: "text-[8px] font-normal text-slate-500", children: ["of $", formatAmount(limit)] })] })] }));
}
export function TaskStateProgressRing(props) {
    const { counts, size = 44, strokeWidth = 4 } = props;
    const radius = (size - strokeWidth) / 2;
    const circumference = 2 * Math.PI * radius;
    const center = size / 2;
    const total = counts.total;
    let cumulative = 0;
    const segments = total
        ? STATE_STOPS.map((stop) => {
            const value = counts[stop.key];
            if (value <= 0)
                return null;
            const fraction = value / total;
            const dashLength = fraction * circumference;
            const dashGap = circumference - dashLength;
            const dashOffset = -cumulative * circumference;
            cumulative += fraction;
            return (_jsx("circle", { cx: center, cy: center, r: radius, stroke: stop.ringColor, strokeWidth: strokeWidth, fill: "none", strokeDasharray: `${dashLength} ${dashGap}`, strokeDashoffset: dashOffset }, stop.key));
        })
        : [];
    return (_jsxs("div", { className: "relative", style: { width: size, height: size }, children: [_jsxs("svg", { width: size, height: size, viewBox: `0 0 ${size} ${size}`, className: "-rotate-90", "aria-hidden": true, children: [_jsx("circle", { cx: center, cy: center, r: radius, stroke: "#e2e8f0", strokeWidth: strokeWidth, fill: "none" }), segments] }), _jsxs("div", { className: "pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-[11px] leading-none font-semibold text-slate-700", children: [_jsx("span", { children: total }), _jsx("span", { className: "text-[8px] font-normal text-slate-500", children: total === 1 ? "task" : "tasks" })] })] }));
}
export function ProjectDashboard(props) {
    const { 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 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 subprojectRows = hasSubprojects && showSubprojects
        ? subprojects.map((subproject) => ({
            projectId: subproject.project.projectId,
            title: subproject.project.title,
            counts: taskCountsByProjectId[subproject.project.projectId] || EMPTY_COUNTS,
        }))
        : [];
    return (_jsxs("div", { "data-testid": "taskboard-project-dashboard", children: [parentProjectId && parentProjectTitle && onSelectProject && (_jsx("div", { className: "mb-2", 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: "flex items-center gap-3 px-3 py-2", "data-testid": "taskboard-project-info-row", children: [_jsxs("div", { className: "flex shrink-0 flex-col gap-0.5", children: [_jsx("span", { className: "text-[10px] font-semibold tracking-wider text-slate-500 uppercase", id: "taskboard-project-status-label", children: "Project Status" }), _jsx(Select, { "data-testid": "taskboard-project-status-select", "aria-labelledby": "taskboard-project-status-label", 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 w-28 text-xs" })] }), _jsxs("div", { className: "flex flex-1 items-center justify-end gap-2", children: [_jsxs(Tooltip, { delayDuration: 250, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("div", { "data-testid": "taskboard-project-cost-ring", children: _jsx(CostProgressRing, { used: normalizedCostUsed, limit: effectiveCostLimit }) }) }), _jsxs(TooltipContent, { side: "bottom", children: ["Cumulative cost: $", normalizedCostUsed.toFixed(2), " / $", effectiveCostLimit.toFixed(2)] })] }), _jsxs(Tooltip, { delayDuration: 250, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("div", { "data-testid": "taskboard-project-progress-ring", children: _jsx(TaskStateProgressRing, { counts: aggregatedCounts }) }) }), _jsx(TooltipContent, { side: "bottom", className: "max-w-xs text-left", children: aggregatedCounts.total > 0 ? (_jsx("div", { className: "space-y-1", children: STATE_STOPS.map((stop) => (_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx("span", { className: `inline-block h-2 w-2 rounded-full ${stop.swatchClassName}` }), stop.label] }), _jsx("span", { children: aggregatedCounts[stop.key] })] }, stop.key))) })) : ("No tasks yet") })] })] })] }), hasSubprojects && (_jsxs("div", { className: "mt-3", children: [_jsxs("button", { type: "button", className: "mb-1.5 flex items-center gap-1 text-[11px] font-semibold tracking-wider text-slate-500 uppercase hover:text-slate-700", onClick: () => setShowSubprojects((prev) => !prev), "aria-label": showSubprojects ? "Hide subprojects" : "Show subprojects", "data-testid": "taskboard-subproject-toggle-label", children: [_jsx(ChevronDown, { className: `h-3 w-3 transition-transform ${showSubprojects ? "rotate-0" : "-rotate-90"}` }), "Subprojects (", subprojects.length, ")"] }), showSubprojects && (_jsx("div", { className: "space-y-2", "data-testid": "taskboard-project-progress-rows", children: subprojectRows.map((row) => (_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 pl-4 text-xs", children: [onSelectProject ? (_jsxs("button", { type: "button", className: "flex min-w-0 items-center gap-1.5 truncate text-left font-medium text-slate-700 hover:text-slate-900", 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 })] })) : (_jsxs("div", { className: "flex min-w-0 items-center gap-1.5 truncate font-medium text-slate-800", 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 })] })), _jsxs("div", { className: "shrink-0 text-[11px] text-slate-600", children: [row.counts.total, " tasks"] })] }), _jsx("div", { className: "pr-6 pl-4", children: _jsx(TaskStateProgressBar, { counts: row.counts, compact: true }) })] }, row.projectId))) }))] })), _jsx(ProjectPropertiesPanel, { projectId: projectId, canEdit: canEditProperties, className: "mt-4" })] }));
}
//# sourceMappingURL=ProjectDashboard.js.map