import { getKeybindings, truncateToWidth, visibleWidth } from "@sheason/pi-tui";
import { theme } from "../../components/index.js";
import { renderForkedPanelBorder } from "./selector-themes.js";
export class RemoteAgentSelectorComponent {
    agents;
    currentAgentId;
    onSelectAgent;
    onCancelSelection;
    onSelectError;
    constraint;
    selectedIndex = 0;
    focused = false;
    constructor(agents, currentAgentId, onSelectAgent, onCancelSelection, onSelectError, constraint = {}) {
        this.agents = agents;
        this.currentAgentId = currentAgentId;
        this.onSelectAgent = onSelectAgent;
        this.onCancelSelection = onCancelSelection;
        this.onSelectError = onSelectError;
        this.constraint = constraint;
    }
    getFocusTarget() {
        return this;
    }
    updateAgents(agents, currentAgentId) {
        const selectedAgentId = this.agents[this.selectedIndex]?.id;
        this.agents = agents;
        this.currentAgentId = currentAgentId;
        if (this.agents.length === 0) {
            this.selectedIndex = 0;
            return;
        }
        const nextIndex = selectedAgentId ? this.agents.findIndex((agent) => agent.id === selectedAgentId) : -1;
        this.selectedIndex = nextIndex >= 0 ? nextIndex : Math.min(this.selectedIndex, this.agents.length - 1);
    }
    isAgentBlocked(agent) {
        return agent.kind === this.constraint.blockedKind;
    }
    render(width) {
        const lines = [
            renderForkedPanelBorder(width),
            "",
            theme.bold(theme.fg("accent", "Agents")),
            theme.fg("muted", "Select an agent visible to the current token."),
            "",
        ];
        if (this.agents.length === 0) {
            lines.push(theme.fg("muted", "  No agents are visible yet."));
            lines.push("");
            lines.push(theme.fg("dim", "  Esc to close"));
            lines.push("");
            lines.push(renderForkedPanelBorder(width));
            return lines.map((line) => truncateToWidth(line, width, ""));
        }
        const nameColumnWidth = computeNameColumnWidth(this.agents, width);
        for (let i = 0; i < this.agents.length; i += 1) {
            const agent = this.agents[i];
            if (!agent) {
                continue;
            }
            lines.push(this.renderRow(agent, i === this.selectedIndex, nameColumnWidth, width));
        }
        lines.push("");
        lines.push(theme.fg("dim", "  Enter to switch · Esc to close"));
        lines.push("");
        lines.push(renderForkedPanelBorder(width));
        return lines.map((line) => truncateToWidth(line, width, ""));
    }
    handleInput(data) {
        const kb = getKeybindings();
        if (this.agents.length === 0) {
            if (kb.matches(data, "tui.select.cancel")) {
                this.onCancelSelection();
            }
            return;
        }
        if (kb.matches(data, "tui.select.up")) {
            this.selectedIndex = this.selectedIndex === 0 ? this.agents.length - 1 : this.selectedIndex - 1;
            return;
        }
        if (kb.matches(data, "tui.select.down")) {
            this.selectedIndex = this.selectedIndex === this.agents.length - 1 ? 0 : this.selectedIndex + 1;
            return;
        }
        if (kb.matches(data, "tui.select.confirm")) {
            const selected = this.agents[this.selectedIndex];
            if (selected) {
                if (this.isAgentBlocked(selected)) {
                    this.onSelectError?.(new Error(this.constraint.blockedReason ?? `Cannot switch to ${selected.kind} agent`));
                    return;
                }
                void Promise.resolve(this.onSelectAgent(selected)).catch((error) => {
                    this.onSelectError?.(error);
                });
            }
            return;
        }
        if (kb.matches(data, "tui.select.cancel")) {
            this.onCancelSelection();
        }
    }
    invalidate() { }
    renderRow(agent, isSelected, nameColumnWidth, rowWidth) {
        const blocked = this.isAgentBlocked(agent);
        const prefix = isSelected ? theme.fg("accent", "-> ") : "   ";
        const label = agent.name ? `${agent.id} (${agent.name})` : agent.id;
        const labelPadded = padEndVisible(label, nameColumnWidth);
        const name = blocked ? theme.fg("dim", labelPadded) : isSelected ? theme.fg("accent", labelPadded) : labelPadded;
        const active = agent.id === this.currentAgentId ? theme.fg("success", "[current]") : "";
        const status = agent.isRunning ? theme.fg("success", "working") : theme.fg("muted", "idle");
        const kind = agent.kind ? theme.fg("muted", `[${agent.kind}]`) : "";
        const model = theme.fg("muted", formatAgentModel(agent));
        const blockedTag = blocked ? theme.fg("dim", "[unavailable]") : "";
        const left = [prefix + name, active, kind, status, model, blockedTag].filter((part) => part.length > 0).join(" ");
        const summary = buildSummary(agent, rowWidth, left, blocked);
        return summary.length > 0 ? `${left} ${summary}` : left;
    }
}
function formatAgentModel(agent) {
    return agent.model ? `${agent.model.provider}/${agent.model.modelId}` : "no-model";
}
function buildSummary(agent, rowWidth, leftWithAnsi, blocked) {
    const maxSummary = Math.max(0, rowWidth - visibleWidth(leftWithAnsi) - 1);
    if (maxSummary === 0) {
        return "";
    }
    const suffix = agent.messageCount === 1 ? "message" : "messages";
    const summary = agent.summary
        ? `${agent.summary} · ${agent.messageCount} ${suffix}`
        : `${agent.messageCount} ${suffix}`;
    return theme.fg(blocked ? "dim" : "muted", truncateToWidth(summary, maxSummary, ""));
}
function computeNameColumnWidth(agents, width) {
    let max = 5;
    for (const agent of agents) {
        const label = agent.name ? `${agent.id} (${agent.name})` : agent.id;
        const w = visibleWidth(label);
        if (w > max) {
            max = w;
        }
    }
    const cap = Math.max(12, width - 42);
    return Math.min(max, 48, cap);
}
function padEndVisible(text, columnWidth) {
    const w = visibleWidth(text);
    if (w >= columnWidth) {
        return text;
    }
    return `${text}${" ".repeat(columnWidth - w)}`;
}
//# sourceMappingURL=agent-selector.js.map