import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
import { createContext, useEffect, useMemo } from "react";
import { Box, Text, render, useApp, useInput, useStdin, useStdout, } from "ink";
import { cellWidth } from "../prompt/promptViewport.js";
export { Box, Text, render, useApp, useInput, useStdin, useStdout };
export const ESC = "\x1b";
export const CSI = `${ESC}[`;
export const cursorHide = `${CSI}?25l`;
export const cursorShow = `${CSI}?25h`;
export const clearScreen = `${CSI}2J${CSI}H`;
export const instances = new Set();
export const styles = {};
export const lineWidthCache = new Map();
export const AppContext = createContext({ exit: () => undefined });
export const StdinContext = createContext(undefined);
export const TerminalFocusContext = createContext(true);
export const TerminalSizeContext = createContext({ width: 80, height: 24 });
export const CursorDeclarationContext = createContext({ visible: true });
export const ClockContext = createContext(Date.now());
export default function InkCompat(props) {
    return _jsx(_Fragment, { children: props.children });
}
export function App(props) {
    return _jsx(_Fragment, { children: props.children });
}
export function AlternateScreen(props) {
    return _jsx(_Fragment, { children: props.children });
}
export function Button(props) {
    return _jsx(Text, { children: props.children ?? props.label ?? "" });
}
export function Link(props) {
    return _jsx(Text, { children: props.children ?? props.url ?? "" });
}
export function Newline(props = {}) {
    return _jsx(Text, { children: Array.from({ length: Math.max(1, props.count ?? 1) }, () => "\n").join("") });
}
export function Spacer() {
    return _jsx(Text, { children: " " });
}
export function RawAnsi(props) {
    return _jsx(Text, { children: String(props.children ?? "") });
}
export function NoSelect(props) {
    return _jsx(_Fragment, { children: props.children });
}
export function ScrollBox(props) {
    return _jsx(Box, { flexDirection: "column", children: props.children });
}
export function ErrorOverview(props) {
    return _jsx(Text, { color: "red", children: props.error instanceof Error ? props.error.message : String(props.error ?? "") });
}
export function useInterval(callback, delay) {
    useEffect(() => {
        if (delay === null)
            return;
        const timer = setInterval(callback, delay);
        return () => clearInterval(timer);
    }, [callback, delay]);
}
export function useAnimationFrame(callback, enabled = true) {
    useEffect(() => {
        if (!enabled)
            return;
        const timer = setInterval(callback, 16);
        return () => clearInterval(timer);
    }, [callback, enabled]);
}
export function useDeclaredCursor(visible = true) {
    return useMemo(() => ({ visible }), [visible]);
}
export function useSelection() {
    return null;
}
export function useSearchHighlight(query = "") {
    return { query };
}
export function useTabStatus() {
    return { active: true };
}
export function useTerminalFocus() {
    return true;
}
export function useTerminalTitle(title) {
    useEffect(() => {
        if (!title || !process.stdout.isTTY)
            return;
        process.stdout.write(`\x1b]0;${title}\x07`);
    }, [title]);
}
export function useTerminalViewport() {
    const { stdout } = useStdout();
    return {
        width: stdout.columns ?? 80,
        height: stdout.rows ?? 24,
    };
}
export function useTerminalNotification(message) {
    useEffect(() => {
        if (message && process.stdout.isTTY)
            process.stdout.write("\x07");
    }, [message]);
}
export function stringWidth(value) {
    return cellWidth(stripAnsi(value));
}
export function widestLine(value) {
    return value.split(/\r?\n/).reduce((max, line) => Math.max(max, stringWidth(line)), 0);
}
export function measureText(value) {
    const lines = value.split(/\r?\n/);
    return { width: widestLine(value), height: Math.max(1, lines.length) };
}
export function measureElement(value) {
    return measureText(typeof value === "string" ? value : "");
}
export function getMaxWidth(values) {
    return values.reduce((max, value) => Math.max(max, stringWidth(value)), 0);
}
export function wrapText(value, width) {
    return value.split(/\r?\n/).map((line) => wrapLine(line, width)).join("\n");
}
export function wrapAnsi(value, width = 80) {
    return wrapText(value, width);
}
export function stripAnsi(value) {
    return value.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "");
}
export function colorize(value) {
    return value;
}
export function clearTerminal() {
    return clearScreen;
}
export function warn(message) {
    process.emitWarning(message);
}
export function supportsHyperlinks() {
    return process.env.DEEPSEEKCODE_OSC8_LINKS === "1";
}
export function parseKeypress(input) {
    return {
        input,
        key: {
            sequence: input,
            name: keyName(input),
            ctrl: input.length === 1 && input.charCodeAt(0) > 0 && input.charCodeAt(0) < 27,
            backspace: input === "\b" || input === "\x7f",
            delete: input === "\x1b[3~",
        },
    };
}
export class TerminalEvent {
    type;
    constructor(type) {
        this.type = type;
    }
}
export class InputEvent extends TerminalEvent {
    input;
    key;
    constructor(input, key = {}) {
        super("input");
        this.input = input;
        this.key = key;
    }
}
export class KeyboardEvent extends InputEvent {
}
export class ClickEvent extends TerminalEvent {
}
export class FocusEvent extends TerminalEvent {
}
export class ResizeEvent extends TerminalEvent {
}
export class PasteEvent extends InputEvent {
}
export class TerminalFocusEvent extends TerminalEvent {
}
export class EventEmitter {
    listeners = new Set();
    emit(event) {
        for (const listener of this.listeners)
            listener(event);
    }
    on(listener) {
        this.listeners.add(listener);
        return () => this.listeners.delete(listener);
    }
}
export class EventDispatcher extends EventEmitter {
}
export function createEventHandlers(emit) {
    return { emit };
}
export class Output {
    frames = [];
    write(value) {
        this.frames.push(value);
    }
    lastFrame() {
        return this.frames.at(-1) ?? "";
    }
}
export class Screen {
    output = new Output();
    render(value) {
        this.output.write(value);
    }
}
export class Terminal {
    size() {
        return {
            width: process.stdout.columns ?? 80,
            height: process.stdout.rows ?? 24,
        };
    }
}
export class TerminalQuerier {
    query() {
        return Promise.resolve(null);
    }
}
export class TerminalFocusState {
    focused = true;
}
export function renderBorder(width) {
    return "-".repeat(Math.max(0, width));
}
export function renderNodeToOutput(node) {
    return typeof node === "string" ? node : "";
}
export function renderToScreen(value) {
    return value;
}
export function createRenderer() {
    return render;
}
export const reconciler = {};
export const root = render;
export const renderer = createRenderer;
export function squashTextNodes(value) {
    return value;
}
export function optimize(value) {
    return value;
}
export function frame(value) {
    return value;
}
export function bidi(value) {
    return value;
}
export function searchHighlight(value, query) {
    if (!query)
        return value;
    return value.replaceAll(query, `[${query}]`);
}
export function getTabStops(width, tabWidth = 8) {
    const stops = [];
    for (let cell = tabWidth; cell <= width; cell += tabWidth)
        stops.push(cell);
    return stops;
}
export function hitTest() {
    return null;
}
export function focus() { }
export function dom() {
    return null;
}
export function createLayoutNode(node = {}) {
    return {
        x: node.x ?? 0,
        y: node.y ?? 0,
        width: node.width ?? 0,
        height: node.height ?? 0,
    };
}
export const yoga = { createNode: createLayoutNode };
export const layoutEngine = { createNode: createLayoutNode };
export const ansi = { ESC, CSI };
export const csi = { CSI };
export const dec = {};
export const esc = { ESC };
export const osc = {};
export const sgr = {};
export function tokenize(value) {
    return [{ type: "text", value }];
}
export function parseTermio(value) {
    return tokenize(value);
}
export function terminal() {
    return new Terminal();
}
export function termio(value) {
    return tokenize(value);
}
function keyName(input) {
    if (input === "\r" || input === "\n")
        return "return";
    if (input === "\b" || input === "\x7f")
        return "backspace";
    if (input === "\x1b[3~")
        return "delete";
    if (input === "\x1b[A")
        return "up";
    if (input === "\x1b[B")
        return "down";
    if (input === "\x1b[C")
        return "right";
    if (input === "\x1b[D")
        return "left";
    return undefined;
}
function wrapLine(line, width) {
    const max = Math.max(1, width);
    let current = "";
    const output = [];
    for (const char of line) {
        if (stringWidth(current + char) > max) {
            output.push(current);
            current = char;
        }
        else {
            current += char;
        }
    }
    output.push(current);
    return output.join("\n");
}
