'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { Code2, Terminal, FolderOpen, RefreshCw, Play, Square, Copy, Check, Loader2, LayoutDashboard, MessageSquare, GitBranch, GitCommitHorizontal, AlertTriangle, Globe, Tag, Archive, FileEdit, FilePlus, FileCheck2, Database, } from 'lucide-react';
import { BedrockTargetKind } from '../../../../../../packages/core/src/domain/generated/output.js';
import { BedrockMemorySection } from '../../bedrock-memory-section.js';
import { cn } from '../../../lib/utils.js';
import { BaseDrawer } from '../../common/base-drawer/index.js';
import { DeploymentStatusBadge } from '../../common/deployment-status-badge/index.js';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../../ui/tooltip.js';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../../ui/tabs.js';
import { useRepositoryActions } from '../../common/repository-node/use-repository-actions.js';
import { useDeployAction } from '../../../hooks/use-deploy-action.js';
import { useFeatureFlags } from '../../../hooks/feature-flags-context.js';
import { ChatTab } from '../../features/chat/ChatTab.js';
import { getGitRepoInfo } from '../../../app/actions/get-git-log.js';
const COPY_FEEDBACK_DELAY = 2000;
const tbBtn = 'text-muted-foreground hover:bg-foreground/8 hover:text-foreground inline-flex size-8 items-center justify-center rounded-[3px] disabled:opacity-40';
const tbSep = 'bg-border/60 mx-1.5 h-5 w-px shrink-0';
export function RepositoryDrawerClient({ data, initialTab }) {
    const featureFlags = useFeatureFlags();
    const router = useRouter();
    const pathname = usePathname();
    const isOpen = pathname.startsWith('/repository/');
    const [activeTab, setActiveTab] = useState(initialTab ?? 'overview');
    const [pathCopied, setPathCopied] = useState(false);
    const repoActions = useRepositoryActions(data.repositoryPath ? { repositoryId: data.id, repositoryPath: data.repositoryPath } : null);
    const onClose = useCallback(() => {
        router.push('/control-center');
    }, [router]);
    const deployAction = useDeployAction(data.repositoryPath
        ? {
            targetId: data.repositoryPath,
            targetType: 'repository',
            repositoryPath: data.repositoryPath,
        }
        : null);
    const isDeployActive = deployAction.status === 'Booting' || deployAction.status === 'Ready';
    const handleCopyPath = useCallback(() => {
        if (!data.repositoryPath)
            return;
        void navigator.clipboard.writeText(data.repositoryPath);
        setPathCopied(true);
        setTimeout(() => setPathCopied(false), COPY_FEEDBACK_DELAY);
    }, [data.repositoryPath]);
    // Session ID for repo chat — deterministic per repo
    const repoSessionId = data.id ? `repo-${data.id}` : `repo-${data.name}`;
    return (_jsx(BaseDrawer, { open: isOpen, onClose: onClose, size: "lg", modal: false, "data-testid": "repository-drawer", children: _jsxs(Tabs, { value: activeTab, onValueChange: setActiveTab, className: "flex min-h-0 flex-1 flex-col", children: [_jsxs(TabsList, { className: "bg-muted/50 h-auto w-full shrink-0 justify-start gap-0 rounded-none border-b p-0", children: [_jsxs(TabsTrigger, { value: "overview", className: "text-muted-foreground hover:bg-muted hover:text-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:border-t-primary [&:not([data-state=active])]:border-r-border relative h-auto rounded-none border-t-2 border-r border-t-transparent border-r-transparent bg-transparent px-3.5 py-2.5 text-[13px] font-normal shadow-none transition-none last:border-r-transparent data-[state=active]:shadow-none", children: [_jsx(LayoutDashboard, { className: "mr-1.5 size-4" }), "Overview"] }), _jsxs(TabsTrigger, { value: "chat", className: "text-muted-foreground hover:bg-muted hover:text-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:border-t-primary [&:not([data-state=active])]:border-r-border relative h-auto rounded-none border-t-2 border-r border-t-transparent border-r-transparent bg-transparent px-3.5 py-2.5 text-[13px] font-normal shadow-none transition-none last:border-r-transparent data-[state=active]:shadow-none", children: [_jsx(MessageSquare, { className: "mr-1.5 size-4" }), "Chat"] }), featureFlags.bedrockIntegration ? (_jsxs(TabsTrigger, { value: "bedrock", "data-testid": "repository-drawer-bedrock-tab", className: "text-muted-foreground hover:bg-muted hover:text-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:border-t-primary [&:not([data-state=active])]:border-r-border relative h-auto rounded-none border-t-2 border-r border-t-transparent border-r-transparent bg-transparent px-3.5 py-2.5 text-[13px] font-normal shadow-none transition-none last:border-r-transparent data-[state=active]:shadow-none", children: [_jsx(Database, { className: "mr-1.5 size-4" }), "Bedrock"] })) : null] }), _jsxs("div", { className: "bg-muted/40 shrink-0 border-b", children: [_jsxs("div", { className: "flex items-center gap-2 px-4 pe-10 pt-2.5 pb-2", "data-testid": "repository-drawer-header", children: [_jsx("h2", { className: "text-foreground min-w-0 truncate text-base font-semibold tracking-tight", children: data.name }), data.repositoryPath ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-muted-foreground/40 text-xs", children: "/" }), _jsx("span", { className: "text-muted-foreground min-w-0 truncate font-mono text-[11px]", children: data.repositoryPath })] })) : null] }), data.repositoryPath ? (_jsx("div", { "data-testid": "repository-drawer-toolbar", children: _jsxs("div", { className: "flex h-9 items-center px-1.5", children: [_jsxs(TooltipProvider, { delayDuration: 300, children: [_jsxs("div", { className: "flex items-center", children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", className: tbBtn, onClick: repoActions.openInIde, disabled: repoActions.ideLoading, "aria-label": "Open in IDE", children: repoActions.ideLoading ? (_jsx(Loader2, { className: "size-3.5 animate-spin" })) : (_jsx(Code2, { className: "size-4" })) }) }), _jsx(TooltipContent, { side: "bottom", className: "text-xs", children: "Open in IDE" })] }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", className: tbBtn, onClick: repoActions.openInShell, disabled: repoActions.shellLoading, "aria-label": "Open terminal", children: repoActions.shellLoading ? (_jsx(Loader2, { className: "size-3.5 animate-spin" })) : (_jsx(Terminal, { className: "size-4" })) }) }), _jsx(TooltipContent, { side: "bottom", className: "text-xs", children: "Open terminal" })] }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", className: tbBtn, onClick: repoActions.openFolder, disabled: repoActions.folderLoading, "aria-label": "Open folder", children: repoActions.folderLoading ? (_jsx(Loader2, { className: "size-3.5 animate-spin" })) : (_jsx(FolderOpen, { className: "size-4" })) }) }), _jsx(TooltipContent, { side: "bottom", className: "text-xs", children: "Open folder" })] }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", className: tbBtn, onClick: handleCopyPath, "aria-label": "Copy path", children: pathCopied ? (_jsx(Check, { className: "size-3.5 text-green-500" })) : (_jsx(Copy, { className: "size-4" })) }) }), _jsx(TooltipContent, { side: "bottom", className: "text-xs", children: pathCopied ? 'Copied!' : 'Copy path' })] })] }), data.id ? (_jsxs(_Fragment, { children: [_jsx("div", { className: tbSep }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", className: tbBtn, onClick: repoActions.syncMain, disabled: repoActions.syncLoading, "aria-label": "Sync main", children: repoActions.syncLoading ? (_jsx(Loader2, { className: "size-3.5 animate-spin" })) : (_jsx(RefreshCw, { className: "size-4" })) }) }), _jsx(TooltipContent, { side: "bottom", className: "text-xs", children: "Sync main" })] })] })) : null, featureFlags.envDeploy ? (_jsxs(_Fragment, { children: [_jsx("div", { className: tbSep }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", disabled: deployAction.deployLoading || deployAction.stopLoading, onClick: isDeployActive ? deployAction.stop : deployAction.deploy, className: cn('inline-flex size-7 items-center justify-center rounded-[3px] disabled:opacity-40', isDeployActive
                                                                        ? 'text-red-500 hover:bg-red-500/10 hover:text-red-400'
                                                                        : 'text-green-500 hover:bg-green-500/10 hover:text-green-400'), "aria-label": isDeployActive ? 'Stop dev server' : 'Start dev server', children: deployAction.deployLoading || deployAction.stopLoading ? (_jsx(Loader2, { className: "size-3.5 animate-spin" })) : isDeployActive ? (_jsx(Square, { className: "size-4" })) : (_jsx(Play, { className: "size-4" })) }) }), _jsx(TooltipContent, { side: "bottom", className: "text-xs", children: isDeployActive ? 'Stop dev server' : 'Start dev server' })] }), isDeployActive ? (_jsx(DeploymentStatusBadge, { status: deployAction.status, url: deployAction.url, targetId: data.repositoryPath })) : null] })) : null] }), _jsx("div", { className: "flex-1" })] }) })) : null] }), _jsx(TabsContent, { value: "overview", className: "mt-0 flex-1 overflow-y-auto", children: _jsx(RepoOverview, { data: data, syncError: repoActions.syncError }) }), _jsx(TabsContent, { value: "chat", className: "mt-0 flex min-h-0 flex-1 flex-col overflow-hidden", children: _jsx(ChatTab, { featureId: repoSessionId, worktreePath: data.repositoryPath }) }), featureFlags.bedrockIntegration ? (_jsx(TabsContent, { value: "bedrock", className: "mt-0 flex min-h-0 flex-1 flex-col overflow-y-auto p-4", children: data.id ? (_jsx(BedrockMemorySection, { targetKind: BedrockTargetKind.Repository, targetId: data.id, targetLabel: data.name, initialEnabled: false })) : (_jsx("p", { className: "text-muted-foreground text-xs", children: "Bedrock memory is unavailable for repositories not yet tracked by Shep." })) })) : null] }) }));
}
// ── Repo Overview ───────────────────────────────────────────────────
function Section({ icon: Icon, title, children, }) {
    return (_jsxs("div", { className: "px-3 pt-4 pb-1", children: [_jsxs("div", { className: "text-foreground mb-2 flex items-center gap-1.5 text-sm font-semibold tracking-wider uppercase", children: [_jsx(Icon, { className: "size-4 opacity-50" }), title] }), children] }));
}
function Card({ children, className }) {
    return (_jsx("div", { className: cn('bg-muted/60 rounded-md border border-transparent p-3', className), children: children }));
}
function KV({ label, children }) {
    return (_jsxs("div", { className: "flex flex-col gap-0.5", children: [_jsx("span", { className: "text-foreground/40 text-[11px] font-medium tracking-wider uppercase", children: label }), _jsx("span", { className: "text-sm leading-snug", children: children })] }));
}
function RepoOverview({ data, syncError, }) {
    const [repoInfo, setRepoInfo] = useState(null);
    const [loading, setLoading] = useState(false);
    useEffect(() => {
        if (!data.repositoryPath)
            return;
        let cancelled = false;
        setLoading(true);
        getGitRepoInfo(data.repositoryPath, 8)
            .then((result) => {
            if (!cancelled)
                setRepoInfo(result);
        })
            .catch(() => {
            // Silently handle — repo info is non-critical
        })
            .finally(() => {
            if (!cancelled)
                setLoading(false);
        });
        return () => {
            cancelled = true;
        };
    }, [data.repositoryPath]);
    if (!data.repositoryPath)
        return null;
    const wt = repoInfo?.workingTree;
    const isDirty = wt && (wt.staged > 0 || wt.modified > 0 || wt.untracked > 0);
    const ds = repoInfo?.diffStats;
    return (_jsxs("div", { className: "pb-4", children: [loading ? (_jsxs("div", { className: "text-foreground/40 flex items-center gap-2 px-4 py-8 text-sm", children: [_jsx(Loader2, { className: "size-4 animate-spin" }), " Loading repository info..."] })) : null, repoInfo ? (_jsxs("div", { className: "grid grid-cols-2 gap-2 px-3 pt-3", children: [_jsx(Card, { children: _jsxs(KV, { label: "Branch", children: [_jsxs("span", { className: "inline-flex items-center gap-1.5", children: [_jsx(GitBranch, { className: "text-foreground/30 size-3.5 shrink-0" }), _jsx("code", { className: "font-mono text-sm", children: repoInfo.currentBranch ?? data.branch ?? '—' })] }), data.behindCount != null && data.behindCount > 0 ? (_jsxs("span", { className: "mt-0.5 block text-xs text-orange-600 dark:text-orange-400", children: [data.behindCount, " behind default"] })) : null] }) }), _jsx(Card, { children: _jsx(KV, { label: "Working Tree", children: isDirty ? (_jsxs("div", { className: "flex flex-wrap gap-x-3 gap-y-0.5", children: [wt.staged > 0 ? (_jsxs("span", { className: "inline-flex items-center gap-1 text-sm text-green-600 dark:text-green-400", children: [_jsx(FileCheck2, { className: "size-3.5" }), " ", wt.staged, " staged"] })) : null, wt.modified > 0 ? (_jsxs("span", { className: "inline-flex items-center gap-1 text-sm text-amber-600 dark:text-amber-400", children: [_jsx(FileEdit, { className: "size-3.5" }), " ", wt.modified, " modified"] })) : null, wt.untracked > 0 ? (_jsxs("span", { className: "text-foreground/50 inline-flex items-center gap-1 text-sm", children: [_jsx(FilePlus, { className: "size-3.5" }), " ", wt.untracked, " untracked"] })) : null] })) : (_jsxs("span", { className: "inline-flex items-center gap-1.5 text-sm text-green-600 dark:text-green-400", children: [_jsx(Check, { className: "size-3.5" }), " Clean"] })) }) }), ds ? (_jsx(Card, { children: _jsx(KV, { label: "Uncommitted Changes", children: _jsxs("div", { className: "flex items-center gap-3 text-sm", children: [_jsxs("span", { children: [ds.filesChanged, " file", ds.filesChanged !== 1 ? 's' : ''] }), _jsxs("span", { className: "text-green-600 dark:text-green-400", children: ["+", ds.insertions] }), _jsxs("span", { className: "text-red-500 dark:text-red-400", children: ["-", ds.deletions] })] }) }) })) : null, repoInfo.remotes.length > 0 ? (_jsx(Card, { children: _jsx(KV, { label: "Remote", children: repoInfo.remotes.map((r) => (_jsxs("span", { className: "inline-flex items-center gap-1.5 text-sm", children: [_jsx(Globe, { className: "text-foreground/30 size-3.5 shrink-0" }), _jsx("span", { className: "truncate", children: r.url
                                            .replace(/\.git$/, '')
                                            .replace(/^https?:\/\/([^@]+@)?/, '')
                                            .replace(/x-access-token:[^@]+@/, '') })] }, r.name))) }) })) : null, repoInfo.stashCount > 0 ? (_jsx(Card, { children: _jsx(KV, { label: "Stashes", children: _jsxs("span", { className: "inline-flex items-center gap-1.5 text-sm", children: [_jsx(Archive, { className: "text-foreground/30 size-3.5 shrink-0" }), repoInfo.stashCount, " stash", repoInfo.stashCount !== 1 ? 'es' : ''] }) }) })) : null, repoInfo.tags.length > 0 ? (_jsx(Card, { children: _jsx(KV, { label: "Tags", children: _jsx("div", { className: "flex flex-wrap gap-1.5", children: repoInfo.tags.map((t) => (_jsxs("span", { className: "bg-foreground/[0.04] inline-flex items-center gap-0.5 rounded px-1.5 py-0.5 text-xs", children: [_jsx(Tag, { className: "text-foreground/30 size-2.5" }), t] }, t))) }) }) })) : null] })) : null, repoInfo && repoInfo.commits.length > 0 ? (_jsx(Section, { icon: GitCommitHorizontal, title: "Recent Commits", children: _jsxs("div", { className: "relative ml-3", children: [_jsx("div", { className: "bg-border absolute top-2 bottom-2 left-[5px] w-px" }), repoInfo.commits.map((c, i) => (_jsxs("div", { className: "group relative flex gap-3 py-1.5", children: [_jsx("div", { className: cn('relative z-10 mt-1.5 size-[11px] shrink-0 rounded-full border-2', i === 0
                                        ? 'border-primary bg-primary'
                                        : 'border-border bg-background group-hover:border-foreground/30') }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex items-baseline gap-2", children: [_jsx("p", { className: "min-w-0 truncate text-sm leading-snug", children: c.subject }), _jsx("code", { className: "text-foreground/30 shrink-0 font-mono text-[11px]", children: c.shortHash })] }), _jsxs("div", { className: "text-foreground/40 mt-0.5 flex items-center gap-2 text-xs", children: [_jsx("span", { children: c.author }), _jsx("span", { children: "\u00B7" }), _jsx("span", { children: c.relativeDate }), c.branch ? (_jsxs(_Fragment, { children: [_jsx("span", { children: "\u00B7" }), _jsxs("span", { className: "inline-flex items-center gap-0.5", children: [_jsx(GitBranch, { className: "size-3" }), c.branch] })] })) : null] })] })] }, c.hash)))] }) })) : null, repoInfo && repoInfo.branches.length > 1 ? (_jsx(Section, { icon: GitBranch, title: "Branches", children: _jsx("div", { className: "flex flex-col", children: [...repoInfo.branches]
                        .sort((a, b) => {
                        const isDefault = (n) => /^(main|master)$/.test(n);
                        if (a.isCurrent && !b.isCurrent)
                            return -1;
                        if (!a.isCurrent && b.isCurrent)
                            return 1;
                        if (isDefault(a.name) && !isDefault(b.name))
                            return -1;
                        if (!isDefault(a.name) && isDefault(b.name))
                            return 1;
                        return 0;
                    })
                        .map((b) => (_jsxs("div", { className: cn('flex items-center justify-between rounded px-2 py-1.5', b.isCurrent && 'bg-muted/60'), children: [_jsxs("span", { className: "inline-flex items-center gap-1.5 text-sm", children: [b.isCurrent ? (_jsx("span", { className: "size-2 shrink-0 rounded-full bg-green-500" })) : /^(main|master)$/.test(b.name) ? (_jsx("span", { className: "size-2 shrink-0 rounded-full bg-blue-500" })) : (_jsx("span", { className: "bg-foreground/10 size-2 shrink-0 rounded-full" })), _jsx("code", { className: "font-mono text-[13px]", children: b.name }), b.isCurrent ? (_jsx("span", { className: "text-foreground/40 text-[10px]", children: "current" })) : null] }), _jsx("span", { className: "text-foreground/40 text-xs", children: b.lastCommitDate })] }, b.name))) }) })) : null, syncError ? (_jsx(Section, { icon: AlertTriangle, title: "Issues", children: _jsx(Card, { className: "bg-destructive/5 border-transparent", children: _jsx("p", { className: "text-destructive text-sm", children: syncError }) }) })) : null] }));
}
