import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from "react";
import { Box, Text } from "ink";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
import { useTheme } from "../theme/theme.js";
import { useAnimationTick, useAnimationActive } from "./AnimationContext.js";
const SHIMMER_WIDTH = 3;
const PHASE_LABELS = {
    worker: "working",
    verifier: "verifying",
    reviewing: "reviewing",
    orchestrating: "orchestrating",
    failed: "failed",
};
export function formatGoalElapsed(ms) {
    const total = Math.max(0, Math.floor(ms / 1000));
    const minutes = Math.floor(total / 60);
    const seconds = total % 60;
    return `${minutes}:${seconds.toString().padStart(2, "0")}`;
}
function truncateLabel(label, maxLength) {
    if (label.length <= maxLength)
        return label;
    if (maxLength <= 1)
        return "…";
    return `${label.slice(0, maxLength - 1)}…`;
}
function GoalAnimationSentinel() {
    useAnimationActive();
    return null;
}
function ShimmerText({ text, color, tick }) {
    const cycle = text.length + SHIMMER_WIDTH * 2;
    const shimmerPos = (tick % cycle) - SHIMMER_WIDTH;
    return (_jsx(Text, { children: text.split("").map((character, index) => {
            const isBright = Math.abs(index - shimmerPos) <= SHIMMER_WIDTH;
            return (_jsx(Text, { color: color, bold: isBright, dimColor: !isBright, children: character }, index));
        }) }));
}
function getPhaseColor(phase, theme) {
    switch (phase) {
        case "worker":
            return theme.primary;
        case "verifier":
            return theme.accent;
        case "reviewing":
        case "orchestrating":
            return theme.secondary;
        case "failed":
            return theme.warning;
    }
}
export function formatGoalStatusActiveText(entry) {
    return `Goal ${PHASE_LABELS[entry.phase]} · ${truncateLabel(entry.label, 42)}`;
}
export function syncGoalStatusEntries(previous, entry) {
    const withoutRun = previous.filter((item) => item.runId !== entry.runId);
    const existingGoalNumber = previous.findIndex((item) => item.runId === entry.runId) + 1;
    const goalNumber = entry.goalNumber ?? (existingGoalNumber || withoutRun.length + 1);
    return [...withoutRun, { ...entry, goalNumber }];
}
export function removeGoalStatusEntry(previous, runId) {
    return previous.filter((entry) => entry.runId !== runId);
}
function hasActiveGoalProcess(entry, run, options) {
    if (entry.phase === "worker") {
        if (entry.workerId && options.isWorkerActive?.(entry.workerId, run))
            return true;
        if (run.activeWorkerId && options.isWorkerActive?.(run.activeWorkerId, run))
            return true;
        return run.tasks.some((task) => (task.status === "running" || task.status === "verifying") &&
            task.workerId !== undefined &&
            options.isWorkerActive?.(task.workerId, run) === true);
    }
    if (entry.phase === "verifier")
        return options.isVerifierActive?.(run) === true;
    return false;
}
export function reconcileGoalStatusEntriesWithRuns(previous, runs, options = {}) {
    const runsById = new Map(runs.map((run) => [run.id, run]));
    const next = previous.filter((entry) => {
        const run = runsById.get(entry.runId);
        if (!run)
            return false;
        if (hasActiveGoalProcess(entry, run, options))
            return true;
        return run.status === "running" || run.status === "verifying";
    });
    return next.length === previous.length ? previous : next;
}
function GoalStatusSlot({ entry, tick }) {
    const theme = useTheme();
    const phaseColor = getPhaseColor(entry.phase, theme);
    const phaseLabel = PHASE_LABELS[entry.phase];
    const elapsed = formatGoalElapsed(Date.now() - entry.startedAt);
    const label = truncateLabel(entry.label, 42);
    if (entry.phase === "failed") {
        return (_jsxs(Text, { children: [_jsxs(Text, { color: phaseColor, children: ["\u2717 Goal ", phaseLabel] }), _jsxs(Text, { color: theme.textDim, children: [" \u00B7 ", label] }), _jsxs(Text, { color: theme.textDim, children: [" ", elapsed] })] }));
    }
    return (_jsxs(Text, { children: [_jsx(ShimmerText, { text: `Goal ${phaseLabel}`, color: phaseColor, tick: tick }), _jsx(Text, { color: theme.textDim, children: " \u00B7 " }), _jsx(Text, { color: theme.text, children: label }), _jsxs(Text, { color: theme.textDim, children: [" ", elapsed] })] }));
}
export function GoalStatusBar({ entries }) {
    const theme = useTheme();
    const { columns } = useTerminalSize();
    const tick = useAnimationTick(entries.some((entry) => entry.phase !== "failed"));
    if (entries.length === 0)
        return null;
    const activeEntries = entries.filter((entry) => entry.phase !== "failed");
    const failedEntries = entries.filter((entry) => entry.phase === "failed");
    const visibleEntries = [...activeEntries, ...failedEntries].slice(0, 3);
    const hiddenCount = entries.length - visibleEntries.length;
    return (_jsxs(Box, { paddingX: 1, width: columns, flexShrink: 1, children: [activeEntries.length > 0 && _jsx(GoalAnimationSentinel, {}), _jsxs(Text, { wrap: "truncate", children: [visibleEntries.map((entry, index) => (_jsxs(React.Fragment, { children: [index > 0 ? _jsx(Text, { color: theme.border, children: " │ " }) : null, _jsx(GoalStatusSlot, { entry: entry, tick: tick })] }, entry.runId))), hiddenCount > 0 ? _jsxs(Text, { color: theme.textDim, children: [" \u2502 +", hiddenCount, " more"] }) : null] })] }));
}
//# sourceMappingURL=GoalStatusBar.js.map