import { color } from "../../components/color.js";
import { GLYPHS, symbol, symbolBar } from "./glyphs.js";
import { Prompt } from "./core.js";
class TextPrompt extends Prompt {
    constructor(opts) {
        const initialUserInput = opts.initialValue ?? "";
        super({
            ...opts,
            initialValue: initialUserInput,
            initialUserInput,
            render: (prompt) => renderTextPrompt(prompt, opts),
            validate: opts.validate
        });
        this.on("userInput", (value) => this.setValue(value));
        this.on("finalize", () => {
            if (this.state === "submit") {
                this.setValue(this.value || opts.defaultValue || "");
            }
        });
    }
    get userInputWithCursor() {
        if (this.state === "submit") {
            return this.userInput;
        }
        const before = this.userInput.slice(0, this.cursor);
        const current = this.userInput[this.cursor];
        const after = this.userInput.slice(this.cursor + 1);
        if (current) {
            return `${before}${color.inverse(current)}${after}`;
        }
        return `${before}${color.inverse("█")}`;
    }
    promptNonTty() {
        return this.readNonTtyLine();
    }
}
function renderHeader(prompt, message) {
    return `${color.gray(GLYPHS.barStart)} ${symbol(prompt.state)} ${message}`;
}
function renderTextPrompt(prompt, opts) {
    const value = prompt.value ?? "";
    if (prompt.state === "submit") {
        return `${renderHeader(prompt, opts.message)}\n${color.gray(GLYPHS.bar)}  ${color.dim(value)}\n${color.green(GLYPHS.barEnd)}`;
    }
    if (prompt.state === "cancel") {
        return `${renderHeader(prompt, opts.message)}\n${color.gray(GLYPHS.bar)}  ${color.dim.strikethrough(value)}\n${color.red(GLYPHS.barEnd)}`;
    }
    const input = prompt.userInput.length > 0
        ? prompt.userInputWithCursor
        : opts.placeholder
            ? `${color.inverse(opts.placeholder[0] ?? " ")}${color.dim(opts.placeholder.slice(1))}`
            : color.inverse("_");
    if (prompt.state === "error") {
        return `${renderHeader(prompt, opts.message)}\n${symbolBar(prompt.state)}  ${input}\n${color.yellow(GLYPHS.barEnd)}  ${color.yellow(prompt.error)}`;
    }
    return `${renderHeader(prompt, opts.message)}\n${symbolBar(prompt.state)}  ${input}\n${color.cyan(GLYPHS.barEnd)}`;
}
export function textPrompt(opts) {
    return new TextPrompt(opts).prompt();
}
