import { displayWidth, graphemes } from "../../dashboard/terminal-width.js";
const ELLIPSIS = "…";
export function cellWidth(value, startColumn = 0) {
    return displayWidth(value, startColumn);
}
export function fitToWidth(text, width, startColumn = 0) {
    if (width <= 0) {
        return "";
    }
    if (cellWidth(text, startColumn) <= width) {
        return text;
    }
    const ellipsisWidth = cellWidth(ELLIPSIS, startColumn);
    if (ellipsisWidth > width) {
        return takeCells(text, width, startColumn);
    }
    const prefix = takeCells(text, width - ellipsisWidth, startColumn);
    return `${prefix}${ELLIPSIS}`;
}
export function centerCells(text, width, startColumn = 0) {
    const fitted = fitToWidth(text, width, startColumn);
    const padding = Math.max(0, Math.floor((width - cellWidth(fitted, startColumn)) / 2));
    return `${" ".repeat(padding)}${fitted}`;
}
export function padEndCells(text, width, fill = " ", startColumn = 0) {
    let output = takeCells(text, width, startColumn);
    let used = cellWidth(output, startColumn);
    let column = startColumn + used;
    while (used < width) {
        const fillWidth = cellWidth(fill, column);
        if (fill.length === 0 || fillWidth <= 0 || used + fillWidth > width) {
            const spaces = width - used;
            output += " ".repeat(spaces);
            used += spaces;
            column += spaces;
            continue;
        }
        output += fill;
        used += fillWidth;
        column += fillWidth;
    }
    return output;
}
export function splitGraphemeCells(value, startColumn = 0) {
    const cells = [];
    let offset = 0;
    let column = startColumn;
    for (const segment of graphemes(value)) {
        const width = cellWidth(segment, column);
        cells.push({
            value: segment,
            start: offset,
            end: offset + segment.length,
            width
        });
        offset += segment.length;
        column += width;
    }
    return cells;
}
export function stripAnsi(value) {
    return value.replace(/\u001b\[[0-9;]*m/g, "");
}
function takeCells(text, width, startColumn) {
    if (width <= 0) {
        return "";
    }
    let output = "";
    let used = 0;
    let column = startColumn;
    for (const segment of graphemes(text)) {
        const segmentWidth = cellWidth(segment, column);
        if (used + segmentWidth > width) {
            break;
        }
        output += segment;
        used += segmentWidth;
        column += segmentWidth;
    }
    return output;
}
