"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback } from "react";
import { GitHubRepoPicker } from "../github/GitHubRepoPicker";
import { RunnerFileBrowser } from "../runner/RunnerFileBrowser";
import { useScrollShadows } from "../internal/useScrollShadows";
import { ScrollFade } from "../internal/ScrollFade";
const TYPE_LABELS = {
    git: "GitHub",
};
/**
 * Styled component for managing workspace entries with a flat-list
 * layout and drill-in sub-views.
 *
 * The default view shows:
 * 1. Current workspace entries (with remove buttons)
 * 2. Action items: "Browse Folder" and "Connect GitHub"
 *
 * Each action drills into a sub-view (file browser or GitHub picker)
 * with a back button to return to the list. This follows the same
 * progressive-disclosure pattern as the Configure menu.
 *
 * All visual properties flow through `--stgm-*` tokens.
 *
 * @example
 * ```tsx
 * function SessionSetup({ org }: { org: string }) {
 *   const workspace = useWorkspaceEntries();
 *   const gh = useGitHubConnection(org);
 *
 *   return (
 *     <WorkspaceEditor
 *       workspace={workspace}
 *       gitHubConnection={gh}
 *       enableGitHub
 *       enableLocal
 *       runnerId={browseRunnerId}
 *     />
 *   );
 * }
 * ```
 */
export function WorkspaceEditor({ workspace, className, disabled, gitHubConnection, enableGitHub = true, enableLocal = false, runnerId, onBrowseLocalFolder, runnerName, runnerHostname, }) {
    const [activePanel, setActivePanel] = useState(null);
    const [manualUrl, setManualUrl] = useState("");
    const [manualBranch, setManualBranch] = useState("");
    const entryList = useScrollShadows();
    const canBrowse = enableLocal && !!runnerId;
    const handleGitHubSelect = useCallback((repoUrl, branch) => {
        workspace.addGitRepo(repoUrl, branch);
    }, [workspace]);
    const handleManualAdd = useCallback(() => {
        if (manualUrl.trim()) {
            workspace.addGitRepo(manualUrl.trim(), manualBranch.trim() || undefined);
            setManualUrl("");
            setManualBranch("");
        }
    }, [manualUrl, manualBranch, workspace]);
    const handleKeyDown = useCallback((handler) => (e) => {
        if (e.key === "Enter") {
            e.preventDefault();
            handler();
        }
    }, []);
    const goBack = useCallback(() => setActivePanel(null), []);
    // ---------------------------------------------------------------------------
    // Drill-in: Browse Folder
    // ---------------------------------------------------------------------------
    if (activePanel === "browse" && canBrowse) {
        return (_jsxs("div", { className: ["space-y-2", className].filter(Boolean).join(" "), children: [_jsxs("button", { type: "button", onClick: goBack, className: "inline-flex items-center gap-1 text-[0.65rem] text-muted-foreground hover:text-foreground transition-colors", children: [_jsx(ChevronLeftIcon, {}), "Back"] }), _jsx("div", { className: "space-y-2", children: _jsx(RunnerFileBrowser, { runnerId: runnerId, onSelect: (path) => {
                            workspace.addLocalPath(path);
                            setActivePanel(null);
                        }, onCancel: goBack, runnerName: runnerName, runnerHostname: runnerHostname }) })] }));
    }
    // ---------------------------------------------------------------------------
    // Drill-in: Connect GitHub
    // ---------------------------------------------------------------------------
    if (activePanel === "github" && enableGitHub) {
        return (_jsxs("div", { className: ["space-y-2", className].filter(Boolean).join(" "), children: [_jsxs("button", { type: "button", onClick: goBack, className: "inline-flex items-center gap-1 text-[0.65rem] text-muted-foreground hover:text-foreground transition-colors", children: [_jsx(ChevronLeftIcon, {}), "Back"] }), gitHubConnection ? (_jsx(GitHubPanel, { connection: gitHubConnection, onSelect: (url, branch) => {
                        handleGitHubSelect(url, branch);
                        setActivePanel(null);
                    }, onClose: goBack })) : (_jsx(ManualGitPanel, { url: manualUrl, branch: manualBranch, onUrlChange: setManualUrl, onBranchChange: setManualBranch, onAdd: () => {
                        handleManualAdd();
                        setActivePanel(null);
                    }, onCancel: goBack, onKeyDown: handleKeyDown(() => {
                        handleManualAdd();
                        setActivePanel(null);
                    }) }))] }));
    }
    // ---------------------------------------------------------------------------
    // Default view: flat list (entries + actions)
    // ---------------------------------------------------------------------------
    return (_jsxs("div", { className: ["space-y-2", className].filter(Boolean).join(" "), children: [workspace.entries.length > 0 && (_jsxs("div", { className: "relative", children: [entryList.canScrollUp && _jsx(ScrollFade, { position: "top" }), _jsx("div", { ref: entryList.scrollRef, className: "max-h-28 space-y-1 overflow-y-auto", children: workspace.entries.map((entry) => (_jsxs("div", { className: "flex items-center gap-2 rounded-md border border-border bg-muted-faint px-2.5 py-1.5 text-xs", children: [TYPE_LABELS[entry.type] ? (_jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-[0.65rem] text-muted-foreground", children: TYPE_LABELS[entry.type] })) : (_jsx("span", { className: "shrink-0 text-muted-foreground", children: _jsx(FolderIcon, {}) })), _jsx("span", { className: [
                                        "min-w-0 flex-1 truncate text-foreground",
                                        entry.type === "local" ? "[direction:rtl] text-left" : "",
                                    ].join(" "), title: entry.name, children: _jsx("bdi", { children: entry.name }) }), _jsx("button", { type: "button", onClick: () => workspace.remove(entry.id), disabled: disabled, className: "shrink-0 text-muted-foreground hover:text-destructive disabled:pointer-events-none", "aria-label": `Remove ${entry.name}`, children: _jsx(XIcon, {}) })] }, entry.id))) }), entryList.canScrollDown && _jsx(ScrollFade, { position: "bottom" })] })), _jsxs("div", { className: "space-y-0.5", children: [enableLocal && (_jsxs("button", { type: "button", onClick: onBrowseLocalFolder
                            ? async () => {
                                const path = await onBrowseLocalFolder();
                                if (path)
                                    workspace.addLocalPath(path);
                            }
                            : () => setActivePanel("browse"), disabled: disabled || !runnerId, className: "flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-xs text-foreground transition-colors hover:bg-accent-hover disabled:pointer-events-none disabled:opacity-40", children: [_jsx(FolderIcon, {}), _jsx("span", { className: "flex-1 text-left", children: "Browse Folder" }), !onBrowseLocalFolder && _jsx(ChevronRightIcon, {})] })), enableGitHub && (_jsxs("button", { type: "button", onClick: () => setActivePanel("github"), disabled: disabled, className: "flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-xs text-foreground transition-colors hover:bg-accent-hover disabled:pointer-events-none disabled:opacity-40", children: [_jsx(GitHubIcon, {}), _jsx("span", { className: "flex-1 text-left", children: "Connect GitHub" }), _jsx(ChevronRightIcon, {})] }))] })] }));
}
// ---------------------------------------------------------------------------
// GitHub panel (progressive disclosure: connect prompt or repo picker)
// ---------------------------------------------------------------------------
function GitHubPanel({ connection, onSelect, onClose, }) {
    if (connection.isLoading) {
        return (_jsx("div", { className: "py-4 text-center text-xs text-muted-foreground", children: "Checking GitHub connection..." }));
    }
    if (!connection.isConnected) {
        if (connection.isConnecting) {
            return (_jsxs("div", { className: "space-y-3 py-4 text-center", children: [_jsx("div", { className: "mx-auto h-5 w-5 animate-spin rounded-full border-2 border-muted-foreground border-t-foreground" }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Connecting to GitHub..." })] }));
        }
        const redirectUri = `${window.location.origin}/auth/github/callback`;
        return (_jsxs("div", { className: "space-y-3 text-center", children: [_jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-xs font-medium text-foreground", children: "Choose a GitHub repo to add to workspace" }), _jsx("p", { className: "text-[0.65rem] text-muted-foreground", children: "Connect your GitHub account so the agent can access your repos" })] }), connection.popupBlocked ? (_jsxs("div", { className: "space-y-2", children: [_jsx("p", { className: "text-[0.65rem] text-destructive", children: "Popup was blocked by your browser." }), _jsxs("div", { className: "flex items-center justify-center gap-2", children: [_jsx("button", { type: "button", onClick: () => connection.connect(redirectUri, { popup: true }), className: "rounded-md px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground transition-colors", children: "Try again" }), _jsxs("button", { type: "button", onClick: () => connection.connect(redirectUri), className: "inline-flex items-center gap-2 rounded-md bg-foreground px-3 py-1.5 text-xs text-background hover:bg-foreground-hover transition-colors", children: [_jsx(GitHubIcon, {}), _jsx("span", { children: "Continue with redirect" })] })] })] })) : (_jsxs("button", { type: "button", onClick: () => connection.connect(redirectUri, { popup: true }), className: "inline-flex items-center gap-2 rounded-md bg-foreground px-3 py-1.5 text-xs text-background hover:bg-foreground-hover transition-colors", children: [_jsx(GitHubIcon, {}), _jsx("span", { children: "Connect GitHub" })] }))] }));
    }
    return (_jsxs("div", { className: "space-y-2", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2 text-xs", children: [connection.user?.avatarUrl && (_jsx("img", { src: connection.user.avatarUrl, alt: "", className: "h-4 w-4 rounded-full" })), _jsx("span", { className: "text-muted-foreground", children: connection.user?.login ?? "Connected" })] }), _jsx("button", { type: "button", onClick: connection.disconnect, className: "text-[0.6rem] text-muted-foreground hover:text-destructive transition-colors", children: "Disconnect" })] }), _jsx(GitHubRepoPicker, { token: connection.token, onSelect: onSelect, onCancel: onClose })] }));
}
// ---------------------------------------------------------------------------
// Manual git URL input (fallback for platform builders without GitHub OAuth)
// ---------------------------------------------------------------------------
function ManualGitPanel({ url, branch, onUrlChange, onBranchChange, onAdd, onCancel, onKeyDown, }) {
    return (_jsxs("div", { className: "space-y-2", children: [_jsx("input", { type: "url", placeholder: "https://github.com/org/repo.git", value: url, onChange: (e) => onUrlChange(e.target.value), onKeyDown: onKeyDown, className: "w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", autoFocus: true }), _jsx("input", { type: "text", placeholder: "Branch (optional)", value: branch, onChange: (e) => onBranchChange(e.target.value), onKeyDown: onKeyDown, className: "w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" }), _jsxs("div", { className: "flex justify-end 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: onAdd, disabled: !url.trim(), 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: "Add" })] })] }));
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function ChevronLeftIcon() {
    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: "M7.5 2.5L4 6L7.5 9.5" }) }));
}
function ChevronRightIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", className: "text-muted-foreground", children: _jsx("path", { d: "M4.5 2.5L8 6L4.5 9.5" }) }));
}
function XIcon() {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "M4 4L10 10M10 4L4 10" }) }));
}
function GitHubIcon() {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "currentColor", children: _jsx("path", { d: "M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" }) }));
}
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", 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" }) }));
}
//# sourceMappingURL=WorkspaceEditor.js.map