import gradientString from "gradient-string";
import { System24Renderer } from "./system24-renderer.js";
import { NEON_GRID_THEME, resolveTuiMotion, shouldUseAnsiColor } from "../../brand/theme.js";
import { renderOmkSparkleText } from "../../ui/omk-sigil.js";
const ESC = "\x1b[";
const RST = `${ESC}0m`;
function stripAnsi(value) {
    return value.replace(/\x1b\[[0-9;]*m/g, "");
}
function visibleLength(value) {
    return stripAnsi(value).length;
}
function line(stream, text, noColor) {
    stream.write(`${noColor ? stripAnsi(text) : text}\n`);
}
function truncate(value, max) {
    return value.length > max ? `${value.slice(0, Math.max(0, max - 1))}…` : value;
}
function center(text, width) {
    const pad = Math.max(0, Math.floor((width - visibleLength(text)) / 2));
    return `${" ".repeat(pad)}${text}`;
}
function signalScanline(seed, width) {
    const glyphs = ["◇", "◆", "●", "○", "▣", "⟁", "⟐", "⟡"];
    let hash = 0;
    for (const char of seed)
        hash = (hash * 33 + char.charCodeAt(0)) >>> 0;
    const chars = [];
    for (let i = 0; i < width; i += 1) {
        hash = (hash * 1664525 + 1013904223) >>> 0;
        chars.push(hash % 7 === 0 ? glyphs[hash % glyphs.length] : hash % 5 === 0 ? "─" : " ");
    }
    return chars.join("").trimEnd();
}
function gradientLine(text, colors, noColor) {
    return noColor ? text : gradientString(colors).multiline(text);
}
export class NeonGridRenderer {
    base;
    err;
    noColor;
    motion;
    started = false;
    constructor(streams = {}) {
        this.err = streams.stderr ?? process.stderr;
        this.noColor = !shouldUseAnsiColor();
        this.motion = resolveTuiMotion();
        this.base = new System24Renderer(streams, NEON_GRID_THEME, {
            sessionHeader: "compact",
            noColor: this.noColor,
            terminalControls: true,
        });
    }
    start() {
        this.started = true;
        this.base.start();
    }
    emit(event) {
        if (event.type === "session:start") {
            this.base.setStickyHeaderPrefixRows(this.neonGridHeaderRows());
            this.renderNeonGridHeader(event);
        }
        this.base.emit(event);
    }
    setThinkingSummary(summary) {
        this.base.setThinkingSummary(summary);
    }
    stop() {
        this.base.stop();
    }
    neonGridHeaderRows() {
        const shouldRenderScanline = this.motion !== "off" && this.started && this.err.isTTY !== false;
        return (shouldRenderScanline ? 1 : 0) + 5;
    }
    renderNeonGridHeader(event) {
        const width = Math.min(76, Math.max(40, this.err.columns ?? process.stderr.columns ?? 80) - 2);
        const dim = NEON_GRID_THEME.colors.muted;
        const run = event.runId ? `run#${event.runId.slice(0, 7)}` : "run#pending";
        const root = event.root ? truncate(event.root, Math.max(12, width - 16)) : "root:unknown";
        const shouldRenderScanline = this.motion !== "off" && this.started && this.err.isTTY !== false;
        const titleLine = center("◢█ OMK//CONTROL █◣", width);
        const mottoLine = center(truncate(NEON_GRID_THEME.motto, width), width);
        const routeLine = truncate(`${NEON_GRID_THEME.symbols.signal} ROUTE ${run} · provider:${event.provider} · model:${event.model ?? "auto"}`, width);
        const statusLine = truncate(`▣ NEON metrics live · VERIFY armed · SCOPE MCP/skills/hooks · LOOP controlled`, width);
        const rootLine = truncate(`${NEON_GRID_THEME.symbols.pending} PENDING root ${root}`, width);
        if (shouldRenderScanline) {
            line(this.err, `${dim}${signalScanline(event.runId ?? "omk-control", width)}${RST}`, this.noColor);
        }
        line(this.err, renderOmkSparkleText(titleLine, {
            frame: Math.floor(Date.now() / 80),
            noColor: this.noColor,
            colors: ["#00D6FF", "#f4ffff", "#ffd166", "#FF47B2", "#00FFC2"],
        }), this.noColor);
        line(this.err, gradientLine(mottoLine, ["#00FFC2", "#00D6FF", "#9D4EDD"], this.noColor), this.noColor);
        line(this.err, `${dim}${routeLine}${RST}`, this.noColor);
        line(this.err, gradientLine(statusLine, ["#00FFC2", "#00D6FF", "#FFB000"], this.noColor), this.noColor);
        line(this.err, `${dim}${rootLine}${RST}`, this.noColor);
    }
}
