import { truncateToWidth } from "@sheason/pi-tui";
import { theme } from "../../components/index.js";
function getConnectionIndicator(state) {
    switch (state) {
        case "connected":
        case "reconnecting":
            return "●";
        case "error":
            return "✕";
        default:
            return "○";
    }
}
function getDPiRowColor(state) {
    switch (state) {
        case "connected":
            return "success";
        case "reconnecting":
        case "disconnected":
            return "warning";
        case "error":
            return "error";
        default:
            return "dim";
    }
}
function getDPiRowSignature(view) {
    return [
        view.connection.state,
        view.welcome?.hubVersion,
        view.welcome?.protocolVersion,
        view.footer.boundAgentId,
        view.footer.sessionId,
        view.peers.length,
    ].join("\u0002");
}
export class DPiRowComponent {
    view = null;
    cachedSignature = "";
    cachedWidth = 0;
    cachedLines;
    setView(view) {
        this.view = view;
        const signature = getDPiRowSignature(view);
        if (this.cachedSignature !== signature) {
            this.cachedSignature = signature;
            this.cachedLines = undefined;
        }
    }
    invalidate() {
        this.cachedLines = undefined;
    }
    render(width) {
        if (this.cachedLines && this.cachedWidth === width) {
            return this.cachedLines;
        }
        if (!this.view) {
            this.cachedWidth = width;
            this.cachedLines = [theme.fg("dim", "○ idle")];
            return this.cachedLines;
        }
        const view = this.view;
        const parts = [];
        // 1. Connection indicator + state
        const indicator = getConnectionIndicator(view.connection.state);
        parts.push(`${indicator} ${view.connection.state}`);
        // 2. Bound agent
        if (view.footer.boundAgentId) {
            parts.push(`agent ${view.footer.boundAgentId}`);
        }
        // 3. Peer count
        parts.push(`${view.peers.length} peers`);
        // 4. Hub version
        if (view.welcome?.hubVersion) {
            parts.push(`hub v${view.welcome.hubVersion}`);
        }
        // 5. Protocol version
        if (view.welcome?.protocolVersion !== undefined) {
            parts.push(`protocol v${view.welcome.protocolVersion}`);
        }
        // 6. Session ID (truncated to 8 chars)
        if (view.footer.sessionId) {
            parts.push(`session ${view.footer.sessionId.slice(0, 8)}`);
        }
        const line = parts.join(" • ");
        const color = getDPiRowColor(view.connection.state);
        const truncated = truncateToWidth(line, width, "…");
        this.cachedWidth = width;
        this.cachedLines = [theme.fg(color, truncated)];
        return this.cachedLines;
    }
}
//# sourceMappingURL=d-pi-row.js.map