import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, Text } from "ink";
import { toneColor } from "./design/terminalTheme.js";
export function SearchBox(props) {
    const model = searchBoxModel(props);
    return (_jsxs(Box, { flexShrink: 0, borderStyle: props.borderless ? undefined : "round", borderColor: props.isFocused ? toneColor("brand") : undefined, borderDimColor: !props.isFocused, paddingX: props.borderless ? 0 : 1, width: props.width, children: [_jsxs(Text, { dimColor: !model.focused, children: [model.prefix, " "] }), model.focused && model.terminalFocused ? (_jsxs(_Fragment, { children: [_jsx(Text, { dimColor: model.showingPlaceholder, children: model.beforeCursor }), _jsx(Text, { inverse: true, children: model.cursor }), _jsx(Text, { dimColor: model.showingPlaceholder, children: model.afterCursor })] })) : (_jsx(Text, { dimColor: model.showingPlaceholder && model.focused, children: model.query || model.placeholder }))] }));
}
export function searchBoxModel(props) {
    const placeholder = props.placeholder ?? "Search...";
    const prefix = props.prefix ?? "/";
    const query = props.query;
    const offset = clampCursorOffset(props.cursorOffset ?? query.length, query);
    const showingPlaceholder = query.length === 0;
    const text = showingPlaceholder ? placeholder : query;
    const cursorOffset = showingPlaceholder ? 0 : offset;
    return {
        prefix,
        query,
        placeholder,
        beforeCursor: text.slice(0, cursorOffset),
        cursor: text[cursorOffset] ?? " ",
        afterCursor: text.slice(cursorOffset + 1),
        focused: props.isFocused,
        terminalFocused: props.isTerminalFocused,
        showingPlaceholder,
    };
}
function clampCursorOffset(value, text) {
    if (!Number.isFinite(value))
        return text.length;
    return Math.max(0, Math.min(text.length, Math.trunc(value)));
}
