import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import fs from "node:fs";
import path from "node:path";
import { Box, Text } from "ink";
import { getQuickOpenItems, } from "../prompt/quickOpen.js";
import { FuzzyPicker } from "./design/FuzzyPicker.js";
import { flattenCellText, padRightCells, truncateCells } from "./design/textLayout.js";
export function QuickOpenPanel(props) {
    const items = getQuickOpenItems(props.files, props.query, 9);
    return (_jsx(FuzzyPicker, { title: "Quick Open", query: props.query, placeholder: "Search project files", items: items, selectedIndex: props.selectedIndex, width: props.width, emptyMessage: props.files.length === 0 ? "No project files found" : "No matching files", footer: "Enter mention  Tab insert path  Esc close  Up/Down select", tone: "brand", getKey: (item) => item.id, renderItem: renderFileRow, renderPreview: (item) => renderFilePreview(props.projectPath, item) }));
}
function renderFileRow(item, selected) {
    return (_jsxs(Text, { color: selected ? "white" : "gray", children: [_jsx(Text, { color: selected ? "cyan" : "gray", children: padRightCells(item.name, 30) }), truncateCells(item.folder, 44), _jsx(Text, { color: "gray", children: `  ${item.sizeLabel}` })] }));
}
function renderFilePreview(projectPath, item) {
    const preview = readPreview(projectPath, item.path);
    return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: "gray", children: ["path ", _jsx(Text, { color: "white", children: truncateCells(item.path, 94) })] }), _jsxs(Text, { color: "gray", children: ["match ", _jsx(Text, { color: "white", children: item.match }), "  ", "size ", _jsx(Text, { color: "white", children: item.sizeLabel })] }), preview.map((line, index) => (_jsx(Text, { color: "gray", children: truncateCells(flattenCellText(line), 96) }, `${index}:${line}`)))] }));
}
function readPreview(projectPath, relativePath) {
    try {
        const root = path.resolve(projectPath);
        const target = path.resolve(root, relativePath);
        if (!target.startsWith(root + path.sep) && target !== root)
            return ["(preview unavailable)"];
        const stat = fs.statSync(target);
        if (!stat.isFile() || stat.size > 256 * 1024)
            return ["(preview skipped)"];
        const buffer = fs.readFileSync(target);
        if (buffer.includes(0))
            return ["(binary preview skipped)"];
        const text = buffer.toString("utf8");
        return text.split(/\r?\n/).slice(0, 8).filter((line) => line.trim() !== "");
    }
    catch {
        return ["(preview unavailable)"];
    }
}
