'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback, useEffect } from 'react';
import { Handle, Position } from '@xyflow/react';
import { useRouter } from 'next/navigation';
import { Github, Plus, Code2, Terminal, FolderOpen, Trash2, Play, Square, GitBranch, GitCommitHorizontal, ArrowDown, User, RotateCcw, MessageSquare, } from 'lucide-react';
import { Trans, useTranslation } from 'react-i18next';
import { cn } from '../../../lib/utils.js';
import { buildCreateUrl } from '../../../lib/url-params.js';
import { ActionButton } from '../../common/action-button/index.js';
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '../../ui/dialog.js';
import { Button } from '../../ui/button.js';
import { Checkbox } from '../../ui/checkbox.js';
import { Label } from '../../ui/label.js';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../../ui/tooltip.js';
import { useDeployAction } from '../../../hooks/use-deploy-action.js';
import { useFeatureFlags } from '../../../hooks/feature-flags-context.js';
import { useRepositoryActions } from './use-repository-actions.js';
import { ChatDotIndicator } from '../../features/chat/ChatDotIndicator.js';
import { useTurnStatus } from '../../../hooks/turn-statuses-provider.js';
import { FeatureSessionsDropdown, } from '../../common/feature-node/feature-sessions-dropdown.js';
export function RepositoryNode({ data, selected, }) {
    const { t, i18n } = useTranslation('web');
    const router = useRouter();
    const isRtl = i18n.dir() === 'rtl';
    const targetHandlePos = isRtl ? Position.Right : Position.Left;
    const sourceHandlePos = isRtl ? Position.Left : Position.Right;
    const featureFlags = useFeatureFlags();
    const [confirmOpen, setConfirmOpen] = useState(false);
    const [deleteFromDisk, setDeleteFromDisk] = useState(false);
    useEffect(() => {
        if (confirmOpen)
            setDeleteFromDisk(false);
    }, [confirmOpen]);
    const repoScopeId = data.id ? `repo-${data.id}` : `repo-${data.name}`;
    const chatTurnStatus = useTurnStatus(repoScopeId);
    const actions = useRepositoryActions(data.repositoryPath ? { repositoryId: data.id, repositoryPath: data.repositoryPath } : null);
    const deployAction = useDeployAction(data.repositoryPath
        ? {
            targetId: data.repositoryPath,
            targetType: 'repository',
            repositoryPath: data.repositoryPath,
        }
        : null);
    const isDeploymentActive = deployAction.status === 'Booting' || deployAction.status === 'Ready';
    const handleCreateFromSession = useCallback((session, sessionFilePath) => {
        if (!data.repositoryPath)
            return;
        const preview = session.preview ? session.preview.slice(0, 200) : 'Unknown conversation';
        const prompt = [
            `Continue work from a previous agent session.`,
            ``,
            `## Session Context`,
            `- Session ID: ${session.id}`,
            `- Messages: ${session.messageCount}`,
            session.lastMessageAt ? `- Last active: ${session.lastMessageAt}` : '',
            `- Conversation file: ${sessionFilePath}`,
            ``,
            `## Session Preview`,
            `> ${preview}`,
            ``,
            `## Instructions`,
            `1. Read the full conversation history from the file above`,
            `2. Analyze the current state of the repository — what was done, what remains`,
            `3. Create or update spec files to accurately reflect the current state and remaining work`,
            `4. Continue implementing any unfinished work from the conversation`,
        ]
            .filter(Boolean)
            .join('\n');
        router.push(buildCreateUrl({ repo: data.repositoryPath, prompt }));
    }, [data.repositoryPath, router]);
    return (_jsxs("div", { className: cn('group relative', data.onDelete && data.id && 'ps-10'), style: { direction: isRtl ? 'rtl' : 'ltr' }, children: [data.showHandles ? (_jsx(Handle, { type: "target", position: targetHandlePos, isConnectable: false, className: "opacity-0!", style: { top: 70 } })) : null, data.onDelete && data.id ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "absolute -start-3 top-1/2 -translate-y-1/2 opacity-0 transition-opacity group-hover:opacity-100", children: _jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { "aria-label": t('repositoryNode.removeRepository'), "data-testid": "repository-node-delete-button", onClick: (e) => {
                                                e.stopPropagation();
                                                setConfirmOpen(true);
                                            }, className: "bg-card text-muted-foreground hover:border-destructive hover:text-destructive flex h-7 w-7 cursor-pointer items-center justify-center rounded-full border shadow-sm transition-colors", children: _jsx(Trash2, { className: "h-3.5 w-3.5" }) }) }), _jsx(TooltipContent, { children: t('repositoryNode.removeRepository') })] }) }) }), _jsx(Dialog, { open: confirmOpen, onOpenChange: setConfirmOpen, children: _jsxs(DialogContent, { className: "max-w-sm", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: t('repositoryNode.removeConfirmTitle') }), _jsxs(DialogDescription, { children: [_jsx(Trans, { t: t, i18nKey: "repositoryNode.removeConfirmDescription", values: { name: data.name }, components: { strong: _jsx("strong", {}) } }), ' ', deleteFromDisk
                                                    ? t('repositoryNode.removeConfirmDescriptionDeleteFiles')
                                                    : t('repositoryNode.removeConfirmDescriptionKeepFiles')] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Checkbox, { id: "repository-delete-from-disk", checked: deleteFromDisk, onCheckedChange: (checked) => setDeleteFromDisk(checked === true), "data-testid": "repository-node-delete-from-disk-checkbox", "aria-label": t('repositoryNode.deleteFromDiskLabel') }), _jsx(Label, { htmlFor: "repository-delete-from-disk", className: "cursor-pointer text-sm font-normal", children: t('repositoryNode.deleteFromDiskLabel') })] }), _jsxs(DialogFooter, { className: "grid grid-cols-2 gap-2 sm:flex-none", children: [_jsx(DialogClose, { asChild: true, children: _jsx(Button, { variant: "outline", children: t('repositoryNode.cancel') }) }), _jsx(Button, { variant: "destructive", "data-testid": "repository-node-delete-confirm-button", onClick: () => {
                                                setConfirmOpen(false);
                                                data.onDelete?.(data.id, { deleteFromDisk });
                                            }, children: t('repositoryNode.remove') })] })] }) })] })) : null, _jsxs("div", { role: "button", tabIndex: 0, "data-testid": "repository-node-card", "data-repo-name": data.name, onClick: (e) => {
                    e.stopPropagation();
                    data.onClick?.();
                }, onKeyDown: (e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        e.stopPropagation();
                        data.onClick?.();
                    }
                }, className: cn('nodrag bg-card flex w-[26rem] cursor-pointer flex-col overflow-hidden rounded-xl border shadow-sm transition-[border-color,box-shadow] duration-200 dark:bg-neutral-800/80', selected && 'border-blue-400 dark:border-amber-500/60'), children: [_jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [_jsx(Github, { className: "text-muted-foreground h-5 w-5 shrink-0" }), _jsx("span", { "data-testid": "repository-node-name", className: "min-w-0 truncate text-sm font-medium", children: data.name }), _jsxs("div", { className: cn('flex shrink-0 items-center gap-2', (data.repositoryPath ?? data.onAdd) && 'ms-auto'), onClick: (e) => e.stopPropagation(), children: [data.repositoryPath ? (_jsxs(_Fragment, { children: [_jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: "flex items-center", children: _jsx(ActionButton, { label: t('repositoryNode.openInIde'), onClick: actions.openInIde, loading: actions.ideLoading, error: !!actions.ideError, icon: Code2, iconOnly: true, variant: "ghost", size: "icon-xs" }) }) }), _jsx(TooltipContent, { children: t('repositoryNode.openInIde') })] }) }), _jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: "flex items-center", children: _jsx(ActionButton, { label: t('repositoryNode.openInShell'), onClick: actions.openInShell, loading: actions.shellLoading, error: !!actions.shellError, icon: Terminal, iconOnly: true, variant: "ghost", size: "icon-xs" }) }) }), _jsx(TooltipContent, { children: t('repositoryNode.openInShell') })] }) }), _jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: "flex items-center", children: _jsx(ActionButton, { label: t('repositoryNode.openFolder'), onClick: actions.openFolder, loading: actions.folderLoading, error: !!actions.folderError, icon: FolderOpen, iconOnly: true, variant: "ghost", size: "icon-xs" }) }) }), _jsx(TooltipContent, { children: t('repositoryNode.openFolder') })] }) }), _jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsxs(Button, { variant: "ghost", size: "icon-xs", "aria-label": t('repositoryNode.chatWithAgent'), onClick: (e) => {
                                                                    e.stopPropagation();
                                                                    if (data.id)
                                                                        router.push(`/repository/${data.id}/chat`);
                                                                }, className: "nodrag relative cursor-pointer text-violet-500 hover:text-violet-600 dark:text-violet-400 dark:hover:text-violet-300", children: [_jsx(MessageSquare, { className: "h-3 w-3" }), _jsx(ChatDotIndicator, { status: chatTurnStatus })] }) }), _jsx(TooltipContent, { children: t('repositoryNode.chatWithAgent') })] }) }), _jsx(FeatureSessionsDropdown, { repositoryPath: data.repositoryPath, includeWorktrees: true, onCreateFromSession: handleCreateFromSession })] })) : null, data.onAdd ? _jsx("div", { className: "ms-1.5" }) : null, data.onAdd ? (_jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsxs("button", { "aria-label": t('repositoryNode.newFeature'), "data-testid": "repository-node-add-button", onClick: (e) => {
                                                            e.stopPropagation();
                                                            data.onAdd?.();
                                                        }, className: cn('flex h-6 shrink-0 cursor-pointer items-center gap-0.5 rounded bg-blue-500 px-1.5 text-[11px] font-bold text-white transition-colors hover:bg-blue-600 dark:bg-amber-500 dark:hover:bg-amber-400', data.pulseAdd && 'animate-pulse-cta'), children: [_jsx(Plus, { className: "h-3 w-3" }), _jsx("span", { className: "translate-y-px", children: t('repositoryNode.new') })] }) }), _jsx(TooltipContent, { side: "top", children: t('repositoryNode.newFeature') })] }) })) : null] })] }), data.branch ? (_jsxs(_Fragment, { children: [_jsx("div", { "data-testid": "repository-node-git-info", className: "text-muted-foreground border-border/50 border-t px-4 py-2", children: _jsxs("div", { className: "flex items-center gap-3 text-xs", children: [_jsxs("span", { className: "flex items-center gap-1 truncate", "data-testid": "repository-node-branch", children: [_jsx(GitBranch, { className: "h-3 w-3 shrink-0" }), _jsx("span", { className: "truncate", children: data.branch })] }), data.behindCount != null && data.behindCount > 0 ? (_jsxs("span", { className: "flex shrink-0 items-center gap-1 whitespace-nowrap text-amber-500", "data-testid": "repository-node-behind", children: [_jsx(ArrowDown, { className: "h-3 w-3 shrink-0" }), t('repositoryNode.behind', { count: data.behindCount })] })) : null] }) }), data.commitMessage ? (_jsx("div", { "data-testid": "repository-node-commit-info", className: "text-muted-foreground border-border/50 border-t px-4 py-2", children: _jsxs("div", { className: "flex items-center gap-2 text-xs", children: [_jsx(GitCommitHorizontal, { className: "h-3 w-3 shrink-0" }), _jsx("span", { className: "min-w-0 truncate", "data-testid": "repository-node-commit-message", children: data.commitMessage }), data.committer ? (_jsxs("span", { className: "text-muted-foreground/70 ms-auto flex shrink-0 items-center gap-1", "data-testid": "repository-node-committer", children: [_jsx(User, { className: "h-3 w-3 shrink-0" }), _jsx("span", { children: data.committer })] })) : null] }) })) : null] })) : data.gitInfoStatus === 'not-a-repo' ? (
                    /* Not a git repo — two rows for consistency with loading/ready states */
                    _jsxs(_Fragment, { children: [_jsx("div", { "data-testid": "repository-node-not-repo", className: "text-muted-foreground border-border/50 border-t px-4 py-2", children: _jsxs("div", { className: "flex items-center gap-2 text-xs", children: [_jsx(FolderOpen, { className: "h-3 w-3 shrink-0" }), _jsx("span", { className: "min-w-0 truncate opacity-60", children: data.repositoryPath ?? 'Unknown path' })] }) }), _jsx("div", { className: "text-muted-foreground border-border/50 border-t px-4 py-2", children: _jsxs("div", { className: "flex items-center gap-2 text-xs opacity-40", children: [_jsx(GitBranch, { className: "h-3 w-3 shrink-0" }), _jsx("span", { children: t('repositoryNode.notAGitRepository') })] }) })] })) : data.gitInfoStatus !== 'ready' ? (
                    /* Loading — show skeleton placeholders for both rows */
                    _jsxs(_Fragment, { children: [_jsx("div", { "data-testid": "repository-node-git-loading", className: "border-border/50 border-t px-4 py-2", children: _jsxs("div", { className: "flex h-4 items-center gap-2 text-xs", children: [_jsx(GitBranch, { className: "text-muted-foreground h-3 w-3 shrink-0" }), _jsx("span", { className: "bg-muted h-3 w-20 animate-pulse rounded" })] }) }), _jsx("div", { className: "border-border/50 border-t px-4 py-2", children: _jsxs("div", { className: "flex h-4 items-center gap-2 text-xs", children: [_jsx(GitCommitHorizontal, { className: "text-muted-foreground h-3 w-3 shrink-0" }), _jsx("span", { className: "bg-muted h-3 w-36 animate-pulse rounded" })] }) })] })) : null, featureFlags.envDeploy && data.repositoryPath ? (_jsx("div", { "data-testid": "repository-node-dev-preview", className: "border-border/50 border-t px-4 py-2", onClick: (e) => e.stopPropagation(), children: _jsxs("div", { className: "flex items-center gap-2 text-xs", children: [deployAction.deployError ? (_jsx("span", { className: "truncate text-xs text-red-500", children: deployAction.deployError })) : isDeploymentActive ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "me-0.5 inline-block h-2 w-2 shrink-0 rounded-full bg-green-500" }), deployAction.url ? (_jsx("a", { href: deployAction.url, target: "_blank", rel: "noopener noreferrer", className: "truncate text-green-700 hover:underline dark:text-green-400", children: deployAction.url })) : (_jsx("span", { className: "text-muted-foreground", children: t('repositoryNode.starting') }))] })) : (_jsxs("span", { className: "text-muted-foreground inline-flex items-baseline gap-2", children: [_jsx("span", { children: t('repositoryNode.run') }), _jsx("span", { className: "text-muted-foreground/50 text-[10px]", children: t('repositoryNode.startLocalEnvironment') })] })), _jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: cn('ms-auto flex items-center', !isDeploymentActive &&
                                                        !deployAction.deployError &&
                                                        '[&_button]:text-green-600 [&_button]:hover:text-green-700 dark:[&_button]:text-green-400 dark:[&_button]:hover:text-green-300'), children: _jsx(ActionButton, { label: deployAction.deployError
                                                            ? t('repositoryNode.retry')
                                                            : isDeploymentActive
                                                                ? t('repositoryNode.stopDevServer')
                                                                : t('repositoryNode.startDevServer'), onClick: isDeploymentActive ? deployAction.stop : deployAction.deploy, loading: deployAction.deployLoading || deployAction.stopLoading, error: false, icon: deployAction.deployError ? RotateCcw : isDeploymentActive ? Square : Play, iconOnly: true, variant: "ghost", size: "icon-xs" }) }) }), _jsx(TooltipContent, { children: isDeploymentActive
                                                    ? t('repositoryNode.stopDevServer')
                                                    : t('repositoryNode.startDevServer') })] }) })] }) })) : null] }), data.onAdd || data.showHandles ? (_jsx(Handle, { type: "source", position: sourceHandlePos, isConnectable: !data.showHandles, className: "opacity-0!", style: { top: 70 } })) : null] }));
}
