'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useEffect } from 'react';
import { FolderOpen, FolderPlus, Copy, Check, Loader2, CheckCircle2, AlertCircle, Terminal, ChevronDown, ExternalLink, Github, } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '../../../lib/utils.js';
import { pickFolder } from '../../common/add-repository-button/pick-folder.js';
import { ReactFileManagerDialog } from '../../common/react-file-manager-dialog/index.js';
import { useFeatureFlags } from '../../../hooks/feature-flags-context.js';
import { isAgentSetupComplete } from '../../../app/actions/agent-setup-flag.js';
import { checkAgentAuth } from '../../../app/actions/check-agent-auth.js';
import { checkToolStatus } from '../../../app/actions/check-tool-status.js';
import { WelcomeAgentSetup } from './welcome-agent-setup.js';
import { NewProjectDialog } from './new-project-dialog.js';
const commands = ['cd ~/my-repo', 'shep feat new "sleek dashboard"'];
export function ControlCenterOnboarding({ onRepositorySelect, className, }) {
    const { t } = useTranslation('web');
    const [copied, setCopied] = useState(false);
    const [loading, setLoading] = useState(false);
    const [showReactPicker, setShowReactPicker] = useState(false);
    const [agentReady, setAgentReady] = useState(null);
    const [authStatus, setAuthStatus] = useState(null);
    const [cliExpanded, setCliExpanded] = useState(false);
    const [toolStatus, setToolStatus] = useState(null);
    const [newProjectOpen, setNewProjectOpen] = useState(false);
    const { reactFileManager: useReactFileManager } = useFeatureFlags();
    useEffect(() => {
        isAgentSetupComplete()
            .then((done) => setAgentReady(done))
            .catch(() => setAgentReady(false));
    }, []);
    useEffect(() => {
        if (!agentReady)
            return;
        checkAgentAuth()
            .then(setAuthStatus)
            .catch(() => setAuthStatus({
            agentType: 'unknown',
            installed: false,
            authenticated: false,
            label: 'Agent',
            binaryName: null,
            installCommand: null,
            authCommand: null,
        }));
        checkToolStatus()
            .then(setToolStatus)
            .catch(() => setToolStatus({
            git: { installed: false, version: null, installCommand: null, installUrl: null },
            gh: { installed: false, version: null, installCommand: null, installUrl: null },
        }));
    }, [agentReady]);
    async function handlePickerClick() {
        if (loading)
            return;
        if (useReactFileManager) {
            setShowReactPicker(true);
            return;
        }
        setLoading(true);
        try {
            const path = await pickFolder();
            if (path) {
                onRepositorySelect?.(path);
            }
        }
        catch {
            setShowReactPicker(true);
        }
        finally {
            setLoading(false);
        }
    }
    function handleReactPickerSelect(path) {
        if (path) {
            onRepositorySelect?.(path);
        }
        setShowReactPicker(false);
    }
    const handleCopy = useCallback(async () => {
        await navigator.clipboard.writeText(commands.join('\n'));
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    }, []);
    const handleAgentSetupComplete = useCallback(() => {
        setAgentReady(true);
    }, []);
    const handleRetryAuth = useCallback(() => {
        setAuthStatus(null);
        checkAgentAuth().then(setAuthStatus);
    }, []);
    if (agentReady === null)
        return null;
    return (_jsxs("div", { "data-testid": "control-center-onboarding", className: cn('relative flex h-full w-full flex-col items-center justify-center px-8', className), children: [!agentReady ? (_jsx(WelcomeAgentSetup, { onComplete: handleAgentSetupComplete })) : (_jsxs("div", { className: "animate-in fade-in flex w-full max-w-md flex-col items-center duration-300", children: [_jsx("h1", { className: "text-foreground/90 text-center text-5xl font-extralight tracking-tight", children: t('emptyState.addProject') }), _jsxs("p", { className: "text-muted-foreground mt-3 text-center text-lg leading-relaxed font-light", children: [t('emptyState.addProjectDescription'), _jsx("br", {}), t('emptyState.addProjectDescriptionLine2')] }), _jsxs("div", { className: "mt-8 flex w-full flex-col gap-3", children: [_jsx(AgentAuthBanner, { status: authStatus, onRetry: handleRetryAuth }), _jsx(ToolStatusRow, { label: t('emptyState.git'), status: toolStatus?.git ?? null, missingHint: t('emptyState.gitRequired') }), _jsx(ToolStatusRow, { label: t('emptyState.githubCli'), status: toolStatus?.gh ?? null, missingHint: t('emptyState.githubCliRequired') })] }), _jsxs("button", { type: "button", "data-testid": "empty-state-add-repository", onClick: handlePickerClick, disabled: loading, className: "bg-foreground text-background hover:bg-foreground/90 mt-10 flex w-full cursor-pointer items-center justify-center gap-2.5 rounded-xl px-6 py-4 text-base font-medium shadow-lg transition-all duration-200 hover:shadow-xl active:scale-[0.98] disabled:cursor-wait disabled:opacity-50", children: [loading ? (_jsx(Loader2, { className: "h-5 w-5 animate-spin" })) : (_jsx(FolderOpen, { className: "h-5 w-5" })), loading ? t('emptyState.opening') : t('emptyState.chooseFolder')] }), _jsxs("button", { type: "button", "data-testid": "empty-state-new-project", onClick: () => setNewProjectOpen(true), disabled: loading, className: "border-foreground/15 text-foreground/80 hover:bg-foreground/5 hover:border-foreground/25 mt-3 flex w-full cursor-pointer items-center justify-center gap-2.5 rounded-xl border px-6 py-3.5 text-sm font-medium transition-all duration-200 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50", children: [_jsx(FolderPlus, { className: "h-4 w-4" }), "New Project"] }), _jsxs("button", { type: "button", "data-testid": "empty-state-import-github", onClick: () => window.dispatchEvent(new CustomEvent('shep:open-github-import')), disabled: loading, className: "border-foreground/15 text-foreground/80 hover:bg-foreground/5 hover:border-foreground/25 mt-3 flex w-full cursor-pointer items-center justify-center gap-2.5 rounded-xl border px-6 py-3.5 text-sm font-medium transition-all duration-200 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50", children: [_jsx(Github, { className: "h-4 w-4" }), "Import from GitHub"] }), _jsx("p", { className: "text-muted-foreground/60 mt-3 text-center text-sm", children: t('emptyState.folderHint') })] })), agentReady ? (_jsxs("div", { className: "absolute bottom-8 flex flex-col items-center", style: {
                    animationDelay: '400ms',
                    animationDuration: '600ms',
                    animationFillMode: 'both',
                }, children: [_jsxs("button", { type: "button", onClick: () => setCliExpanded(!cliExpanded), className: "text-muted-foreground hover:text-foreground flex cursor-pointer items-center gap-1.5 transition-colors duration-200", children: [_jsx(Terminal, { className: "h-3.5 w-3.5" }), _jsx("span", { className: "text-sm", children: t('emptyState.orUseCli') }), _jsx(ChevronDown, { className: cn('h-3.5 w-3.5 transition-transform duration-200', cliExpanded ? '' : 'rotate-180') })] }), cliExpanded ? (_jsx("div", { className: "animate-in fade-in slide-in-from-top-1 mt-3 w-80 duration-200", children: _jsxs("div", { "data-testid": "cli-code-block", className: "relative rounded-xl bg-zinc-900 px-5 py-4 font-mono text-[13px] leading-relaxed text-zinc-400", children: [_jsx("button", { type: "button", "data-testid": "cli-code-block-copy", onClick: handleCopy, className: "absolute top-3 right-3 cursor-pointer rounded-md p-1.5 text-zinc-600 transition-colors hover:bg-zinc-800 hover:text-zinc-300", "aria-label": t('emptyState.copyCommands'), children: copied ? (_jsx(Check, { className: "h-3.5 w-3.5 text-emerald-400" })) : (_jsx(Copy, { className: "h-3.5 w-3.5" })) }), _jsx("div", { className: "space-y-1", children: commands.map((cmd) => (_jsxs("div", { className: "whitespace-nowrap", children: [_jsx("span", { className: "text-zinc-600 select-none", children: "$ " }), _jsx("span", { className: "text-zinc-300", children: cmd })] }, cmd))) })] }) })) : null] })) : null, _jsx(ReactFileManagerDialog, { open: showReactPicker, onOpenChange: (open) => {
                    if (!open)
                        setShowReactPicker(false);
                }, onSelect: handleReactPickerSelect }), _jsx(NewProjectDialog, { open: newProjectOpen, onOpenChange: setNewProjectOpen, onCreated: (path) => onRepositorySelect?.(path) })] }));
}
function AgentAuthBanner({ status, onRetry, }) {
    const { t } = useTranslation('web');
    if (!status) {
        return (_jsx(ChecklistRow, { icon: _jsx(Loader2, { className: "text-muted-foreground/50 h-4 w-4 animate-spin" }), children: _jsx("span", { className: "text-muted-foreground/50 text-sm", children: t('emptyState.checkingSetup') }) }));
    }
    if (status.installed && status.authenticated) {
        return (_jsx(ChecklistRow, { icon: _jsx(CheckCircle2, { className: "h-4 w-4 text-emerald-500" }), children: _jsx("span", { className: "text-sm text-emerald-600 dark:text-emerald-400", children: t('emptyState.ready', { label: status.label }) }) }));
    }
    if (!status.installed) {
        return (_jsxs(ChecklistRow, { icon: _jsx(AlertCircle, { className: "h-4 w-4 text-amber-500" }), children: [_jsx("span", { className: "text-sm font-medium text-amber-600 dark:text-amber-400", children: t('emptyState.notInstalled', { label: status.label }) }), status.installCommand ? _jsx(CopyableCommand, { command: status.installCommand }) : null, _jsx("button", { type: "button", onClick: onRetry, className: "text-xs text-amber-600 underline underline-offset-2 hover:text-amber-800 dark:text-amber-400", children: t('emptyState.reCheck') })] }));
    }
    return (_jsxs(ChecklistRow, { icon: _jsx(AlertCircle, { className: "h-4 w-4 text-amber-500" }), children: [_jsx("span", { className: "text-sm font-medium text-amber-600 dark:text-amber-400", children: t('emptyState.needsAuth', { label: status.label }) }), status.authCommand ? _jsx(CopyableCommand, { command: status.authCommand }) : null, _jsxs("div", { className: "flex items-center gap-3", children: [status.binaryName ? (_jsxs("button", { type: "button", "data-testid": "auth-banner-open-terminal", onClick: async () => {
                            try {
                                const toolId = status.agentType === 'claude-code' ? 'claude-code' : status.agentType;
                                await fetch(`/api/tools/${toolId}/launch`, { method: 'POST' });
                            }
                            catch {
                                /* best effort */
                            }
                        }, className: "flex items-center gap-1 text-xs font-medium text-amber-600 underline underline-offset-2 hover:text-amber-800 dark:text-amber-400", children: [_jsx(Terminal, { className: "h-3 w-3" }), t('emptyState.open', { label: status.label })] })) : null, _jsx("button", { type: "button", onClick: onRetry, className: "text-xs text-amber-600 underline underline-offset-2 hover:text-amber-800 dark:text-amber-400", children: t('emptyState.reCheck') })] })] }));
}
function ToolStatusRow({ label, status, missingHint, }) {
    const { t } = useTranslation('web');
    if (!status) {
        return (_jsx(ChecklistRow, { icon: _jsx(Loader2, { className: "text-muted-foreground/50 h-4 w-4 animate-spin" }), children: _jsx("span", { className: "text-muted-foreground/50 text-sm", children: t('emptyState.checking', { label }) }) }));
    }
    if (status.installed) {
        return (_jsx(ChecklistRow, { icon: _jsx(CheckCircle2, { className: "h-4 w-4 text-emerald-500" }), children: _jsxs("span", { className: "flex items-baseline gap-2", children: [_jsx("span", { className: "text-sm text-emerald-600 dark:text-emerald-400", children: t('emptyState.ready', { label }) }), status.version ? (_jsxs("span", { className: "text-muted-foreground/40 text-xs", children: ["v", status.version] })) : null] }) }));
    }
    return (_jsxs(ChecklistRow, { icon: _jsx(AlertCircle, { className: "h-4 w-4 text-amber-500" }), children: [_jsx("span", { className: "text-sm font-medium text-amber-600 dark:text-amber-400", children: t('emptyState.notFound', { label }) }), _jsx("span", { className: "text-muted-foreground/50 text-xs", children: missingHint }), status.installCommand ? _jsx(CopyableCommand, { command: status.installCommand }) : null, status.installUrl ? (_jsxs("a", { href: status.installUrl, target: "_blank", rel: "noopener noreferrer", className: "inline-flex items-center gap-1 text-xs text-amber-600 underline underline-offset-2 hover:text-amber-800 dark:text-amber-400", children: [t('emptyState.docs'), " ", _jsx(ExternalLink, { className: "h-3 w-3" })] })) : null] }));
}
function ChecklistRow({ icon, children }) {
    return (_jsxs("div", { className: "animate-in fade-in flex items-start gap-2.5", children: [_jsx("div", { className: "mt-0.5 shrink-0", children: icon }), _jsx("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: children })] }));
}
function CopyableCommand({ command }) {
    const [copied, setCopied] = useState(false);
    return (_jsxs("button", { type: "button", onClick: async () => {
            await navigator.clipboard.writeText(command);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        }, className: "group/cmd flex cursor-pointer items-center justify-between gap-2 rounded-md bg-zinc-100 py-1 ps-2.5 pe-2 text-start transition-colors hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700", children: [_jsx("code", { className: "min-w-0 truncate text-[11px] leading-relaxed text-zinc-600 dark:text-zinc-300", children: command }), copied ? (_jsx(Check, { className: "h-3 w-3 shrink-0 text-emerald-500" })) : (_jsx(Copy, { className: "h-3 w-3 shrink-0 text-zinc-400 opacity-0 transition-opacity group-hover/cmd:opacity-100" }))] }));
}
