import { getExplorerStyles } from "../theme.js";
import { cellWidth, fitToWidth } from "./text.js";
export function renderFooter(state, screen, layout) {
    const rect = layout.footer;
    const styles = getExplorerStyles();
    screen.clearRect(rect);
    if (rect.width <= 0 || rect.height <= 0) {
        return;
    }
    const hints = footerHints(state);
    let x = rect.x + 2;
    const y = rect.y;
    const endX = rect.x + rect.width;
    for (const hint of hints) {
        if (x >= endX) {
            break;
        }
        if (hint.bracketed === false) {
            const text = `${hint.key} ${hint.label}`;
            x += putFooterText(screen, x, y, endX, text, hint.running ? styles.muted : {}) + 2;
            continue;
        }
        const keyText = `[${hint.key}]`;
        const keyWidth = putFooterText(screen, x, y, endX, keyText, hint.running ? styles.muted : styles.accent);
        x += keyWidth;
        if (keyWidth < cellWidth(keyText) || x >= endX) {
            break;
        }
        x += putFooterText(screen, x, y, endX, ` ${hint.label}`, hint.running ? styles.muted : {}) + 2;
    }
}
function putFooterText(screen, x, y, endX, text, style = {}) {
    const remaining = Math.max(0, endX - x);
    const fitted = fitToWidth(text, remaining, x);
    screen.put(x, y, fitted, style);
    return cellWidth(fitted, x);
}
function footerHints(state) {
    const hints = [];
    if (state.focused === "detail") {
        hints.push({ key: "Tab", label: "focus", running: false });
        hints.push({ key: "Enter", label: "sub", running: false });
    }
    for (const [id, entry] of state.actionState) {
        if (!entry.available || entry.action?.showInFooter === false) {
            continue;
        }
        const key = actionKey(entry, id);
        const label = state.multiSelect && state.selected.size > 0 && entry.source === "row"
            ? `${entry.label} ${state.selected.size}`
            : entry.label;
        hints.push({ key, label, running: entry.running === true });
    }
    hints.push({ key: "?", label: "help", running: false });
    hints.push({ key: "Ctrl+P", label: "palette", running: false });
    if (hasShiftReorderBindings(state)) {
        hints.push({ key: "⇧↑↓", label: "reorder (within state)", running: false, bracketed: false });
    }
    hints.push({ key: "q", label: "quit", running: false });
    return hints;
}
function hasShiftReorderBindings(state) {
    const up = state.bindings.keysByTarget.get("builtin:reorderUp") ?? [];
    const down = state.bindings.keysByTarget.get("builtin:reorderDown") ?? [];
    return up.includes("Shift+up") && down.includes("Shift+down");
}
function actionKey(entry, fallback) {
    const key = entry.action?.key;
    if (Array.isArray(key)) {
        return key[0] ?? fallback;
    }
    return key ?? (entry.action?.primary === true ? "Enter" : fallback);
}
