'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useRef, useEffect, useCallback } from 'react';
import { Copy, Check, ExternalLink, Download, Rocket, Loader2, Monitor, Terminal, GitBranch, Package, } from 'lucide-react';
import { Button } from '../../ui/button.js';
import { BaseDrawer } from '../../common/base-drawer/base-drawer.js';
import { useToolInstallStream } from '../../../hooks/use-tool-install-stream.js';
const PLATFORM_LABELS = {
    linux: 'Linux',
    darwin: 'macOS',
    win32: 'Windows',
};
const TAG_CONFIG = {
    ide: { label: 'IDE', icon: Monitor },
    'cli-agent': { label: 'CLI Agent', icon: Terminal },
    vcs: { label: 'VCS', icon: GitBranch },
    terminal: { label: 'Terminal', icon: Terminal },
};
const AUTO_SCROLL_THRESHOLD = 50;
function StatusBadge({ status }) {
    if (status === 'available') {
        return (_jsxs("span", { className: "inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400", children: [_jsx(Check, { className: "h-3 w-3" }), "Installed"] }));
    }
    if (status === 'error') {
        return (_jsx("span", { className: "inline-flex items-center gap-1 rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700 dark:bg-red-900/30 dark:text-red-400", children: "Error" }));
    }
    return (_jsx("span", { className: "inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-400", children: "Missing" }));
}
export function ToolDetailDrawer({ tool, open, onClose, onRefresh, autoStart, }) {
    const [copied, setCopied] = useState(false);
    const [isLaunching, setIsLaunching] = useState(false);
    const { logs, status, startInstall } = useToolInstallStream(tool.id);
    const logRef = useRef(null);
    const isAtBottomRef = useRef(true);
    const autoStartedRef = useRef(false);
    const isInstalled = tool.status.status === 'available';
    const isError = tool.status.status === 'error';
    const canLaunch = isInstalled && Boolean(tool.openDirectory);
    const canInstall = !isInstalled && !isError && tool.autoInstall;
    // Auto-start install when drawer opens with autoStart flag
    useEffect(() => {
        if (open && autoStart && canInstall && status === 'idle' && !autoStartedRef.current) {
            autoStartedRef.current = true;
            startInstall();
        }
        if (!open) {
            autoStartedRef.current = false;
        }
    }, [open, autoStart, canInstall, status, startInstall]);
    function handleCopy() {
        if (!tool.installCommand)
            return;
        void navigator.clipboard.writeText(tool.installCommand).then(() => {
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        });
    }
    async function handleLaunch() {
        setIsLaunching(true);
        try {
            await fetch(`/api/tools/${tool.id}/launch`, { method: 'POST' });
        }
        finally {
            setIsLaunching(false);
        }
    }
    const handleScroll = useCallback(() => {
        const el = logRef.current;
        if (!el)
            return;
        isAtBottomRef.current =
            el.scrollTop + el.clientHeight >= el.scrollHeight - AUTO_SCROLL_THRESHOLD;
    }, []);
    useEffect(() => {
        if (isAtBottomRef.current && logRef.current) {
            logRef.current.scrollTop = logRef.current.scrollHeight;
        }
    }, [logs, status]);
    // Refresh tool status after install completes
    useEffect(() => {
        if (status === 'done' && onRefresh) {
            void onRefresh();
        }
    }, [status, onRefresh]);
    const header = (_jsxs("div", { className: "flex flex-col gap-1.5 pe-6", children: [_jsxs("div", { className: "flex items-center gap-2", children: [tool.iconUrl ? (
                    /* eslint-disable-next-line @next/next/no-img-element */
                    _jsx("img", { src: tool.iconUrl, alt: "", width: 24, height: 24, className: "shrink-0 dark:invert" })) : (_jsx(Package, { className: "text-muted-foreground h-6 w-6 shrink-0" })), _jsx("h2", { className: "text-base font-bold", children: tool.name }), _jsx(StatusBadge, { status: tool.status.status })] }), _jsx("div", { className: "flex items-center gap-2", children: tool.tags.map((tag) => {
                    const config = TAG_CONFIG[tag] ?? { label: tag, icon: Monitor };
                    const TagIcon = config.icon;
                    return (_jsxs("span", { className: "text-muted-foreground/70 inline-flex items-center gap-0.5 text-[10px]", children: [_jsx(TagIcon, { className: "h-3 w-3" }), config.label] }, tag));
                }) })] }));
    return (_jsx(BaseDrawer, { open: open, onClose: onClose, size: "md", modal: true, title: tool.name, header: header, "data-testid": "tool-detail-drawer", children: _jsxs("div", { className: "flex flex-1 flex-col gap-4 overflow-y-auto p-4", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: tool.description }), tool.author || tool.platforms ? (_jsxs("div", { className: "flex flex-wrap items-center gap-x-4 gap-y-1 text-xs", children: [tool.author ? (_jsxs("span", { className: "text-muted-foreground", children: ["by", ' ', tool.website ? (_jsx("a", { href: tool.website, target: "_blank", rel: "noopener noreferrer", className: "text-foreground hover:underline", children: tool.author })) : (_jsx("span", { className: "text-foreground", children: tool.author }))] })) : null, tool.platforms && tool.platforms.length > 0 ? (_jsx("span", { className: "text-muted-foreground", children: tool.platforms.map((p) => PLATFORM_LABELS[p] ?? p).join(' · ') })) : null] })) : null, tool.installCommand ? (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("span", { className: "text-muted-foreground text-xs font-semibold tracking-wide uppercase", children: "Install command" }), _jsxs("div", { className: "relative rounded-md bg-zinc-900 text-zinc-100", children: [_jsx("pre", { className: "overflow-x-auto px-3 py-2.5 pe-16 font-mono text-xs leading-relaxed break-all whitespace-pre-wrap", children: _jsx("code", { children: tool.installCommand }) }), _jsxs(Button, { variant: "ghost", size: "sm", className: "absolute top-1.5 right-1.5 h-7 cursor-pointer px-2 text-zinc-400 hover:text-zinc-100", onClick: handleCopy, "aria-label": copied ? 'Copied!' : 'Copy install command', children: [copied ? (_jsx(Check, { className: "h-3.5 w-3.5 text-emerald-500" })) : (_jsx(Copy, { className: "h-3.5 w-3.5" })), _jsx("span", { className: "ms-1 text-[10px]", children: copied ? 'Copied!' : 'Copy' })] })] })] })) : null, _jsxs("div", { className: "flex items-center gap-2", children: [canInstall ? (_jsxs(Button, { size: "sm", onClick: startInstall, disabled: status === 'streaming', "aria-label": `Install ${tool.name}`, className: "cursor-pointer", children: [status === 'streaming' ? (_jsx(Loader2, { className: "me-1.5 h-3.5 w-3.5 animate-spin" })) : (_jsx(Download, { className: "me-1.5 h-3.5 w-3.5" })), status === 'streaming' ? 'Installing...' : 'Install'] })) : null, canLaunch ? (_jsxs(Button, { size: "sm", variant: "outline", onClick: () => void handleLaunch(), disabled: isLaunching, "aria-label": `Launch ${tool.name}`, className: "cursor-pointer", children: [isLaunching ? (_jsx(Loader2, { className: "me-1.5 h-3.5 w-3.5 animate-spin" })) : (_jsx(Rocket, { className: "me-1.5 h-3.5 w-3.5" })), "Launch"] })) : null, tool.documentationUrl ? (_jsx(Button, { variant: "outline", size: "sm", className: "cursor-pointer", asChild: true, children: _jsxs("a", { href: tool.documentationUrl, target: "_blank", rel: "noopener noreferrer", children: ["Docs", _jsx(ExternalLink, { className: "ms-1 h-3 w-3" })] }) })) : null] }), (status === 'streaming' || status === 'done' || status === 'error') && logs.length > 0 ? (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("span", { className: "text-muted-foreground text-xs font-semibold tracking-wide uppercase", children: "Install log" }), _jsxs("div", { ref: logRef, onScroll: handleScroll, className: "max-h-60 overflow-auto rounded-md bg-zinc-900 p-3 font-mono text-xs leading-relaxed text-zinc-100", "data-testid": "tool-install-log", children: [logs.map((line, idx) => (
                                // eslint-disable-next-line react/no-array-index-key -- logs are append-only, never reorder
                                _jsx("div", { className: "break-all whitespace-pre-wrap", children: line }, idx))), status === 'done' ? (_jsx("div", { className: "mt-2 border-t border-zinc-700 pt-2 text-emerald-400", children: "Installation complete" })) : null, status === 'error' ? (_jsx("div", { className: "mt-2 border-t border-zinc-700 pt-2 text-red-400", children: "Installation failed" })) : null] })] })) : null] }) }));
}
