"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useMemo, useState, useRef } from "react";
import { getUserMessage } from "@stigmer/sdk";
import { useRunnerFileBrowser } from "./useRunnerFileBrowser";
import { useRecentWorkspaces } from "../workspace/useRecentWorkspaces";
/**
 * Styled component for browsing a runner's filesystem and selecting
 * a project directory as a workspace entry.
 *
 * Uses the runner's `ListDirectory` command (via `sendCommand`) to
 * fetch directory listings over the bidi stream. The user navigates
 * with breadcrumbs, shortcut buttons (Home, CWD), and click-to-enter
 * for directories.
 *
 * All visual properties flow through `--stgm-*` tokens.
 *
 * @example
 * ```tsx
 * <RunnerFileBrowser
 *   runnerId="runner-abc123"
 *   onSelect={(path) => workspace.addLocalPath(path)}
 *   onCancel={() => setShowBrowser(false)}
 * />
 * ```
 */
export function RunnerFileBrowser({ runnerId, onSelect, onCancel, className, runnerName, runnerHostname, }) {
    const browser = useRunnerFileBrowser(runnerId);
    const recents = useRecentWorkspaces(runnerId);
    const handleSelect = useCallback((path) => {
        recents.recordSelection(path);
        onSelect(path);
    }, [recents, onSelect]);
    const [isEditingPath, setIsEditingPath] = useState(false);
    const [editPathValue, setEditPathValue] = useState("");
    const pathInputRef = useRef(null);
    const startEditingPath = useCallback(() => {
        setEditPathValue(browser.currentPath);
        setIsEditingPath(true);
        requestAnimationFrame(() => pathInputRef.current?.select());
    }, [browser.currentPath]);
    const commitPath = useCallback(() => {
        const trimmed = editPathValue.trim();
        if (trimmed && trimmed !== browser.currentPath) {
            browser.navigateToPath(trimmed);
        }
        setIsEditingPath(false);
    }, [editPathValue, browser]);
    const cancelEditing = useCallback(() => {
        setIsEditingPath(false);
    }, []);
    const handlePathKeyDown = useCallback((e) => {
        if (e.key === "Enter") {
            e.preventDefault();
            commitPath();
        }
        else if (e.key === "Escape") {
            e.preventDefault();
            cancelEditing();
        }
    }, [commitPath, cancelEditing]);
    const visibleEntries = useMemo(() => browser.showHidden
        ? browser.entries
        : browser.entries.filter((e) => !e.isHidden), [browser.entries, browser.showHidden]);
    const directories = useMemo(() => visibleEntries.filter((e) => e.isDirectory), [visibleEntries]);
    const files = useMemo(() => visibleEntries.filter((e) => !e.isDirectory), [visibleEntries]);
    // --- Error state ---
    if (browser.error && !browser.currentPath) {
        return (_jsx("div", { className: ["space-y-3", className].filter(Boolean).join(" "), children: _jsx(ErrorDisplay, { error: browser.error, onRetry: browser.retry, onCancel: onCancel }) }));
    }
    return (_jsxs("div", { className: ["space-y-2", className].filter(Boolean).join(" "), children: [(runnerName || runnerHostname) && (_jsxs("div", { className: "flex items-center gap-1.5 text-[0.65rem] text-muted-foreground", children: [_jsx(ServerIcon, {}), _jsxs("span", { className: "truncate", children: [runnerName ?? runnerHostname, runnerName && runnerHostname && (_jsxs("span", { className: "text-border", children: [" \u00B7 ", runnerHostname] }))] })] })), recents.entries.length > 0 && (_jsx(RecentPathsList, { entries: recents.entries, onSelect: (path) => {
                    recents.recordSelection(path);
                    onSelect(path);
                }, onTogglePin: recents.togglePin, onRemove: recents.remove, onNavigate: browser.navigateToPath })), _jsxs("div", { className: "space-y-1.5", children: [_jsxs("div", { className: "flex items-center gap-1", children: [_jsx(ShortcutButton, { label: "Home", icon: _jsx(HomeIcon, {}), onClick: browser.navigateHome, disabled: browser.isLoading }), browser.currentDirectory && (_jsx(ShortcutButton, { label: "CWD", icon: _jsx(TerminalIcon, {}), onClick: browser.navigateCwd, disabled: browser.isLoading })), !browser.isAtRoot && (_jsx(ShortcutButton, { label: "Up", icon: _jsx(ChevronUpIcon, {}), onClick: browser.navigateUp, disabled: browser.isLoading })), _jsx("div", { className: "ml-auto flex items-center gap-1", children: _jsx("button", { type: "button", onClick: browser.toggleHidden, className: [
                                        "rounded px-1.5 py-0.5 text-[0.6rem] transition-colors",
                                        browser.showHidden
                                            ? "bg-accent text-foreground"
                                            : "text-muted-foreground hover:text-foreground hover:bg-accent-hover",
                                    ].join(" "), title: browser.showHidden ? "Hide hidden files" : "Show hidden files", children: browser.showHidden ? "Hide dotfiles" : "Show dotfiles" }) })] }), isEditingPath ? (_jsx("input", { ref: pathInputRef, type: "text", value: editPathValue, onChange: (e) => setEditPathValue(e.target.value), onKeyDown: handlePathKeyDown, onBlur: commitPath, className: "w-full rounded-md border border-input bg-background px-2 py-1 text-[0.65rem] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", placeholder: "/path/to/directory or ~/relative", autoFocus: true })) : browser.segments.length > 0 ? (_jsxs("div", { className: "flex items-center gap-0.5 overflow-x-auto text-[0.65rem] scrollbar-none", children: [browser.segments.map((seg, i) => {
                                const isLast = i === browser.segments.length - 1;
                                return (_jsxs("span", { className: "flex shrink-0 items-center gap-0.5", children: [i > 0 && _jsx(ChevronRightIcon, {}), isLast ? (_jsx("span", { className: "rounded px-1 py-0.5 font-medium text-foreground", children: seg.name })) : (_jsx("button", { type: "button", onClick: () => browser.navigateToPath(seg.path), disabled: browser.isLoading, className: "rounded px-1 py-0.5 text-muted-foreground hover:text-foreground hover:bg-accent-hover transition-colors disabled:pointer-events-none", children: seg.name }))] }, seg.path));
                            }), _jsx("button", { type: "button", onClick: startEditingPath, className: "ml-1 shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground hover:bg-accent-hover transition-colors", title: "Type a path directly", "aria-label": "Edit path", children: _jsx(EditIcon, {}) })] })) : null] }), browser.error && browser.currentPath && (_jsxs("div", { className: "flex items-center gap-2 rounded-md bg-destructive-subtle px-2.5 py-1.5 text-xs text-destructive", children: [_jsx("span", { className: "min-w-0 flex-1 truncate", children: getUserMessage(browser.error) }), _jsx("button", { type: "button", onClick: browser.retry, className: "shrink-0 text-[0.6rem] font-medium hover:underline", children: "Retry" })] })), _jsx("div", { className: "max-h-56 overflow-y-auto rounded-md border border-border", role: "listbox", "aria-label": "Directory contents", children: browser.isLoading ? (_jsx(LoadingSkeleton, {})) : visibleEntries.length === 0 ? (_jsx("div", { className: "py-6 text-center text-xs text-muted-foreground", children: "This directory is empty" })) : (_jsxs(_Fragment, { children: [directories.map((entry) => (_jsxs("button", { type: "button", onClick: () => browser.navigateTo(entry.name), className: "flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-foreground transition-colors hover:bg-accent-hover", role: "option", "aria-selected": false, children: [_jsx(FolderIcon, {}), _jsx("span", { className: "min-w-0 flex-1 truncate", children: entry.name })] }, entry.name))), files.map((entry) => (_jsxs("div", { className: "flex items-center gap-2 px-2.5 py-1.5 text-xs text-muted-foreground", children: [_jsx(FileIcon, {}), _jsx("span", { className: "min-w-0 flex-1 truncate", children: entry.name })] }, entry.name)))] })) }), _jsxs("div", { className: "flex items-center justify-between", children: [_jsx("span", { className: "min-w-0 flex-1 truncate text-[0.6rem] text-muted-foreground [direction:rtl] text-left", title: browser.currentPath, children: _jsx("bdi", { children: browser.currentPath }) }), _jsxs("div", { className: "flex shrink-0 gap-2", children: [_jsx("button", { type: "button", onClick: onCancel, className: "rounded-md px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground transition-colors", children: "Cancel" }), _jsx("button", { type: "button", onClick: () => handleSelect(browser.currentPath), disabled: !browser.currentPath || browser.isLoading, className: "rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground hover:bg-primary-hover transition-colors disabled:opacity-40", children: "Select" })] })] })] }));
}
// ---------------------------------------------------------------------------
// Error display (initial load failure)
// ---------------------------------------------------------------------------
function ErrorDisplay({ error, onRetry, onCancel, }) {
    return (_jsxs("div", { className: "space-y-3 py-2 text-center", children: [_jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-xs font-medium text-destructive", children: "Could not browse runner filesystem" }), _jsx("p", { className: "text-[0.65rem] text-muted-foreground", children: getUserMessage(error) })] }), _jsxs("div", { className: "flex justify-center gap-2", children: [_jsx("button", { type: "button", onClick: onCancel, className: "rounded-md px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground transition-colors", children: "Cancel" }), _jsx("button", { type: "button", onClick: onRetry, className: "rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground hover:bg-primary-hover transition-colors", children: "Retry" })] })] }));
}
// ---------------------------------------------------------------------------
// Recent paths list
// ---------------------------------------------------------------------------
function RecentPathsList({ entries, onSelect, onTogglePin, onRemove, onNavigate, }) {
    return (_jsxs("div", { className: "space-y-1", children: [_jsx("span", { className: "text-[0.6rem] font-medium text-muted-foreground", children: "Recent" }), _jsx("div", { className: "max-h-24 overflow-y-auto rounded-md border border-border", children: entries.map((entry) => {
                    const dirName = entry.path.split("/").filter(Boolean).pop() ?? entry.path;
                    return (_jsxs("div", { className: "group flex items-center gap-1.5 px-2 py-1 text-xs transition-colors hover:bg-accent-hover", children: [_jsx("button", { type: "button", onClick: () => onTogglePin(entry.path), className: [
                                    "shrink-0 transition-colors",
                                    entry.pinned
                                        ? "text-foreground"
                                        : "text-transparent group-hover:text-muted-foreground",
                                ].join(" "), title: entry.pinned ? "Unpin" : "Pin", "aria-label": entry.pinned ? `Unpin ${dirName}` : `Pin ${dirName}`, children: _jsx(PinIcon, {}) }), _jsxs("button", { type: "button", onClick: () => onSelect(entry.path), className: "flex min-w-0 flex-1 items-center gap-1.5 text-left text-foreground", title: `Select ${entry.path}`, children: [_jsx(FolderIcon, {}), _jsx("span", { className: "truncate [direction:rtl] text-left", children: _jsx("bdi", { children: entry.path }) })] }), _jsx("button", { type: "button", onClick: () => onNavigate(entry.path), className: "shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground", title: "Browse this directory", "aria-label": `Browse ${dirName}`, children: _jsx(ChevronRightIcon, {}) }), _jsx("button", { type: "button", onClick: () => onRemove(entry.path), className: "shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive", title: "Remove from recent", "aria-label": `Remove ${dirName} from recent`, children: _jsx(XSmallIcon, {}) })] }, entry.path));
                }) })] }));
}
// ---------------------------------------------------------------------------
// Shortcut button
// ---------------------------------------------------------------------------
function ShortcutButton({ label, icon, onClick, disabled, }) {
    return (_jsxs("button", { type: "button", onClick: onClick, disabled: disabled, className: "inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-[0.65rem] text-muted-foreground hover:text-foreground hover:bg-accent-hover transition-colors disabled:pointer-events-none disabled:opacity-50", title: label, children: [icon, _jsx("span", { className: "max-sm:hidden", children: label })] }));
}
// ---------------------------------------------------------------------------
// Loading skeleton
// ---------------------------------------------------------------------------
function LoadingSkeleton() {
    return (_jsx("div", { className: "space-y-0.5 p-1", children: [60, 45, 72, 38, 55, 50].map((w, i) => (_jsxs("div", { className: "flex items-center gap-2 px-2 py-1.5", children: [_jsx("div", { className: "h-3.5 w-3.5 shrink-0 rounded bg-muted animate-pulse" }), _jsx("div", { className: "h-3 rounded bg-muted animate-pulse", style: { width: `${w}%` } })] }, i))) }));
}
// ---------------------------------------------------------------------------
// Icons (inline SVG, consistent with existing SDK icon patterns)
// ---------------------------------------------------------------------------
function EditIcon() {
    return (_jsx("svg", { width: "10", height: "10", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M8.5 1.5L10.5 3.5L4 10H2V8L8.5 1.5Z" }) }));
}
function PinIcon() {
    return (_jsx("svg", { width: "10", height: "10", viewBox: "0 0 12 12", fill: "currentColor", stroke: "none", children: _jsx("path", { d: "M7.5 1.5L10.5 4.5L8 7L9 10L6 7L2 11L5 3L4.5 1.5L7.5 1.5Z" }) }));
}
function XSmallIcon() {
    return (_jsx("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M2.5 2.5L7.5 7.5M7.5 2.5L2.5 7.5" }) }));
}
function ServerIcon() {
    return (_jsxs("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "shrink-0", children: [_jsx("rect", { x: "1.5", y: "1.5", width: "9", height: "3.5", rx: "0.5" }), _jsx("rect", { x: "1.5", y: "7", width: "9", height: "3.5", rx: "0.5" }), _jsx("circle", { cx: "3.5", cy: "3.25", r: "0.5", fill: "currentColor", stroke: "none" }), _jsx("circle", { cx: "3.5", cy: "8.75", r: "0.5", fill: "currentColor", stroke: "none" })] }));
}
function HomeIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M2 5.5L6 2L10 5.5V10a.5.5 0 01-.5.5h-2V8a.5.5 0 00-.5-.5H5a.5.5 0 00-.5.5v2.5h-2A.5.5 0 012 10V5.5z" }) }));
}
function TerminalIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M2.5 3.5L5 6L2.5 8.5M6.5 8.5H9.5" }) }));
}
function ChevronUpIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M3 7.5L6 4.5L9 7.5" }) }));
}
function ChevronRightIcon() {
    return (_jsx("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "text-border", children: _jsx("path", { d: "M3 1.5L5.5 4L3 6.5" }) }));
}
function FolderIcon() {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "shrink-0", children: _jsx("path", { d: "M1.5 3.5V11a1 1 0 001 1h9a1 1 0 001-1V5.5a1 1 0 00-1-1H7L5.5 3H2.5a1 1 0 00-1 .5z" }) }));
}
function FileIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "shrink-0", children: [_jsx("path", { d: "M8 1.5H4a1 1 0 00-1 1v9a1 1 0 001 1h6a1 1 0 001-1V4.5L8 1.5z" }), _jsx("path", { d: "M8 1.5V4.5H11" })] }));
}
//# sourceMappingURL=RunnerFileBrowser.js.map