"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useCallback, useMemo, useState } from "react";
import { cn } from "@stigmer/theme";
/**
 * Branches tab for switch_case and fork nodes.
 *
 * - switch_case: shows case listing with conditions, default marking, reorder, remove
 * - fork: shows branch listing, join policy toggle, reorder, remove
 *
 * @since T09 (Branch Management UX)
 */
export const BranchesTab = memo(function BranchesTab({ node, graph, mutations, kindString, }) {
    if (kindString === "switch_case") {
        return (_jsx(SwitchCaseBranches, { node: node, graph: graph, mutations: mutations }));
    }
    if (kindString === "fork") {
        return _jsx(ForkBranches, { node: node, mutations: mutations });
    }
    return null;
});
// ---------------------------------------------------------------------------
// Switch Case branches
// ---------------------------------------------------------------------------
function SwitchCaseBranches({ node, graph, mutations, }) {
    const config = node.config;
    const cases = useMemo(() => {
        const raw = config.cases;
        if (!Array.isArray(raw))
            return [];
        return raw
            .filter((c) => c != null && typeof c === "object")
            .map((c) => ({
            name: c.name || "",
            when: c.when || "",
            then: c.then || "",
        }));
    }, [config.cases]);
    const edges = graph.edges.filter((e) => e.source === node.id && e.sourceHandle?.startsWith("case_"));
    const handleRemove = useCallback((caseName) => {
        mutations.onRemoveSwitchCase?.(node.id, caseName);
    }, [mutations, node.id]);
    const handleMoveUp = useCallback((index) => {
        if (index <= 0 || !mutations.onReorderSwitchCases)
            return;
        const newOrder = cases.map((c) => c.name);
        [newOrder[index - 1], newOrder[index]] = [newOrder[index], newOrder[index - 1]];
        mutations.onReorderSwitchCases(node.id, newOrder);
    }, [cases, mutations, node.id]);
    const handleMoveDown = useCallback((index) => {
        if (index >= cases.length - 1 || !mutations.onReorderSwitchCases)
            return;
        const newOrder = cases.map((c) => c.name);
        [newOrder[index], newOrder[index + 1]] = [newOrder[index + 1], newOrder[index]];
        mutations.onReorderSwitchCases(node.id, newOrder);
    }, [cases, mutations, node.id]);
    return (_jsxs("div", { className: "flex flex-col gap-3 px-3 py-3", children: [_jsx("div", { className: "flex items-center justify-between", children: _jsxs("h3", { className: "text-xs font-semibold text-[var(--stgm-foreground,#1a1a2e)]", children: ["Cases (", cases.length, ")"] }) }), cases.length === 0 ? (_jsx("p", { className: "text-[11px] text-[var(--stgm-muted-foreground,#737373)]", children: "No cases defined. Add a case to create conditional branches." })) : (_jsx("div", { className: "flex flex-col gap-1.5", children: cases.map((caseEntry, idx) => {
                    const isDefault = !caseEntry.when;
                    const targetEdge = edges.find((e) => e.sourceHandle === `case_${caseEntry.name}`);
                    return (_jsxs("div", { className: cn("group/case flex items-center gap-2 rounded-md border px-2 py-1.5", isDefault
                            ? "border-dashed border-[var(--stgm-border,#e5e5e5)] bg-[var(--stgm-muted,#f5f5f5)]"
                            : "border-[var(--stgm-border,#e5e5e5)]"), children: [_jsxs("div", { className: "flex flex-col gap-0.5 opacity-0 group-hover/case:opacity-100 transition-opacity", children: [_jsx("button", { type: "button", onClick: () => handleMoveUp(idx), disabled: idx === 0, className: "text-[var(--stgm-muted-foreground,#737373)] disabled:opacity-30 hover:text-[var(--stgm-foreground,#1a1a2e)]", "aria-label": `Move ${caseEntry.name} up`, children: _jsx("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "currentColor", "aria-hidden": "true", children: _jsx("path", { d: "M4 1L1 5h6L4 1z" }) }) }), _jsx("button", { type: "button", onClick: () => handleMoveDown(idx), disabled: idx === cases.length - 1, className: "text-[var(--stgm-muted-foreground,#737373)] disabled:opacity-30 hover:text-[var(--stgm-foreground,#1a1a2e)]", "aria-label": `Move ${caseEntry.name} down`, children: _jsx("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "currentColor", "aria-hidden": "true", children: _jsx("path", { d: "M4 7L1 3h6L4 7z" }) }) })] }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx("span", { className: "text-[11px] font-medium text-[var(--stgm-foreground,#1a1a2e)] truncate", children: caseEntry.name }), isDefault && (_jsx("span", { className: "shrink-0 rounded-sm bg-[var(--stgm-muted,#f5f5f5)] border border-[var(--stgm-border,#e5e5e5)] px-1 py-px text-[9px] font-medium text-[var(--stgm-muted-foreground,#737373)]", children: "default" }))] }), caseEntry.when && (_jsx("p", { className: "mt-0.5 text-[10px] font-mono text-[var(--stgm-muted-foreground,#737373)] truncate", children: caseEntry.when })), targetEdge && (_jsxs("p", { className: "mt-0.5 text-[10px] text-[var(--stgm-muted-foreground,#737373)]", children: ["\u2192 ", targetEdge.target] }))] }), _jsx("button", { type: "button", onClick: () => handleRemove(caseEntry.name), className: "shrink-0 opacity-0 group-hover/case:opacity-100 transition-opacity text-[var(--stgm-muted-foreground,#737373)] hover:text-[var(--stgm-destructive,#ef4444)]", "aria-label": `Remove case ${caseEntry.name}`, title: "Remove case", children: _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M3 3l6 6M9 3l-6 6" }) }) })] }, caseEntry.name));
                }) }))] }));
}
// ---------------------------------------------------------------------------
// Fork branches
// ---------------------------------------------------------------------------
function ForkBranches({ node, mutations, }) {
    const config = node.config;
    const branches = useMemo(() => {
        const raw = config.branches;
        if (!Array.isArray(raw))
            return [];
        return raw
            .filter((b) => b != null && typeof b === "object")
            .map((b) => ({
            name: b.name || "",
            taskCount: Array.isArray(b.do) ? b.do.length : 0,
        }));
    }, [config.branches]);
    const compete = config.compete === true;
    const handleSetCompete = useCallback((value) => {
        mutations.onSetForkCompete?.(node.id, value);
    }, [mutations, node.id]);
    const handleRemove = useCallback((branchName) => {
        mutations.onRemoveForkBranch?.(node.id, branchName);
    }, [mutations, node.id]);
    const handleMoveUp = useCallback((index) => {
        if (index <= 0 || !mutations.onReorderForkBranches)
            return;
        const newOrder = branches.map((b) => b.name);
        [newOrder[index - 1], newOrder[index]] = [newOrder[index], newOrder[index - 1]];
        mutations.onReorderForkBranches(node.id, newOrder);
    }, [branches, mutations, node.id]);
    const handleMoveDown = useCallback((index) => {
        if (index >= branches.length - 1 || !mutations.onReorderForkBranches)
            return;
        const newOrder = branches.map((b) => b.name);
        [newOrder[index], newOrder[index + 1]] = [newOrder[index + 1], newOrder[index]];
        mutations.onReorderForkBranches(node.id, newOrder);
    }, [branches, mutations, node.id]);
    const [renamingIdx, setRenamingIdx] = useState(null);
    const [renameValue, setRenameValue] = useState("");
    const startRename = useCallback((idx, currentName) => {
        setRenamingIdx(idx);
        setRenameValue(currentName);
    }, []);
    const commitRename = useCallback(() => {
        if (renamingIdx === null)
            return;
        const oldName = branches[renamingIdx]?.name;
        const trimmed = renameValue.trim();
        if (oldName && trimmed && trimmed !== oldName && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(trimmed)) {
            mutations.onRenameForkBranch?.(node.id, oldName, trimmed);
        }
        setRenamingIdx(null);
    }, [renamingIdx, renameValue, branches, mutations, node.id]);
    return (_jsxs("div", { className: "flex flex-col gap-3 px-3 py-3", children: [_jsxs("fieldset", { children: [_jsx("legend", { className: "text-xs font-semibold text-[var(--stgm-foreground,#1a1a2e)] mb-1.5", children: "Join policy" }), _jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsxs("label", { className: "flex items-center gap-2 text-[11px] text-[var(--stgm-foreground,#1a1a2e)] cursor-pointer", children: [_jsx("input", { type: "radio", name: `join-policy-${node.id}`, checked: !compete, onChange: () => handleSetCompete(false), className: "h-3 w-3 accent-[var(--stgm-primary,#6366f1)]" }), "Wait for all branches"] }), _jsxs("label", { className: "flex items-center gap-2 text-[11px] text-[var(--stgm-foreground,#1a1a2e)] cursor-pointer", children: [_jsx("input", { type: "radio", name: `join-policy-${node.id}`, checked: compete, onChange: () => handleSetCompete(true), className: "h-3 w-3 accent-[var(--stgm-primary,#6366f1)]" }), "Race mode (first branch wins)"] })] })] }), _jsxs("div", { children: [_jsxs("h3", { className: "text-xs font-semibold text-[var(--stgm-foreground,#1a1a2e)] mb-1.5", children: ["Parallel branches (", branches.length, ")"] }), _jsx("div", { className: "flex flex-col gap-1.5", children: branches.map((branch, idx) => (_jsxs("div", { className: "group/branch flex items-center gap-2 rounded-md border border-[var(--stgm-border,#e5e5e5)] px-2 py-1.5", children: [_jsxs("div", { className: "flex flex-col gap-0.5 opacity-0 group-hover/branch:opacity-100 transition-opacity", children: [_jsx("button", { type: "button", onClick: () => handleMoveUp(idx), disabled: idx === 0, className: "text-[var(--stgm-muted-foreground,#737373)] disabled:opacity-30 hover:text-[var(--stgm-foreground,#1a1a2e)]", "aria-label": `Move ${branch.name} up`, children: _jsx("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "currentColor", "aria-hidden": "true", children: _jsx("path", { d: "M4 1L1 5h6L4 1z" }) }) }), _jsx("button", { type: "button", onClick: () => handleMoveDown(idx), disabled: idx === branches.length - 1, className: "text-[var(--stgm-muted-foreground,#737373)] disabled:opacity-30 hover:text-[var(--stgm-foreground,#1a1a2e)]", "aria-label": `Move ${branch.name} down`, children: _jsx("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "currentColor", "aria-hidden": "true", children: _jsx("path", { d: "M4 7L1 3h6L4 7z" }) }) })] }), _jsxs("div", { className: "min-w-0 flex-1", children: [renamingIdx === idx ? (_jsx("input", { type: "text", value: renameValue, onChange: (e) => setRenameValue(e.target.value), onBlur: commitRename, onKeyDown: (e) => {
                                                if (e.key === "Enter")
                                                    commitRename();
                                                if (e.key === "Escape")
                                                    setRenamingIdx(null);
                                            }, autoFocus: true, className: "w-full rounded border border-[var(--stgm-ring,#3b82f6)] bg-[var(--stgm-background,#fff)] px-1 py-0.5 text-[11px] text-[var(--stgm-foreground,#1a1a2e)] outline-none" })) : (_jsx("span", { className: "text-[11px] font-medium text-[var(--stgm-foreground,#1a1a2e)] truncate block cursor-text", onDoubleClick: () => startRename(idx, branch.name), title: "Double-click to rename", children: branch.name })), _jsxs("span", { className: "text-[10px] text-[var(--stgm-muted-foreground,#737373)]", children: [branch.taskCount, " ", branch.taskCount === 1 ? "task" : "tasks"] })] }), _jsx("button", { type: "button", onClick: () => handleRemove(branch.name), disabled: branches.length <= 2, className: "shrink-0 opacity-0 group-hover/branch:opacity-100 transition-opacity text-[var(--stgm-muted-foreground,#737373)] hover:text-[var(--stgm-destructive,#ef4444)] disabled:opacity-30 disabled:cursor-not-allowed", "aria-label": `Remove branch ${branch.name}`, title: branches.length <= 2 ? "Fork requires at least 2 branches" : "Remove branch", children: _jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M3 3l6 6M9 3l-6 6" }) }) })] }, branch.name))) })] })] }));
}
//# sourceMappingURL=BranchesTab.js.map