import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { Box, Text } from "ink";
import { truncateCells } from "./design/textLayout.js";
import { toneColor } from "./design/terminalTheme.js";
const FRAMES = ["-", "\\", "|", "/"];
export function Spinner(props) {
    const [tick, setTick] = useState(0);
    const active = props.mode !== "idle";
    useEffect(() => {
        if (!active || props.frameIndex !== undefined)
            return;
        const timer = setInterval(() => setTick((previous) => previous + 1), 120);
        return () => clearInterval(timer);
    }, [active, props.frameIndex]);
    const model = spinnerModel(props.mode, {
        label: props.label,
        detail: props.detail,
        frameIndex: props.frameIndex ?? tick,
        width: props.width,
    });
    const content = `${model.frame} ${model.label}`;
    if (props.inline) {
        return _jsx(Text, { color: toneColor(model.tone), children: content });
    }
    return (_jsx(Box, { flexDirection: "row", children: _jsx(Text, { color: toneColor(model.tone), children: content }) }));
}
export function spinnerModel(mode, options = {}) {
    const active = mode !== "idle";
    const tone = spinnerTone(mode);
    const frame = active ? spinnerFrame(options.frameIndex ?? 0) : " ";
    const label = spinnerLabel(mode, options.label, options.detail, options.width);
    return { active, frame, label, tone };
}
export function spinnerFrame(index) {
    const normalized = Math.abs(Math.floor(index)) % FRAMES.length;
    return FRAMES[normalized] ?? "-";
}
export function spinnerLabel(mode, label, detail, width = 48) {
    const base = (label?.trim() || defaultSpinnerLabel(mode)).trim();
    const suffix = detail?.trim() ? ` ${detail.trim()}` : "";
    return truncateCells(`${base}${suffix}`, Math.max(8, width));
}
function defaultSpinnerLabel(mode) {
    if (mode === "thinking")
        return "thinking";
    if (mode === "tool")
        return "running tool";
    if (mode === "queued")
        return "queued";
    if (mode === "idle")
        return "idle";
    return "working";
}
function spinnerTone(mode) {
    if (mode === "idle")
        return "muted";
    if (mode === "thinking")
        return "brand";
    if (mode === "tool")
        return "warning";
    if (mode === "queued")
        return "muted";
    return "success";
}
