'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useRef, useEffect, useCallback } from 'react';
import { Terminal } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../../ui/dialog.js';
import { useDeploymentLogs } from '../../../hooks/use-deployment-logs.js';
const AUTO_SCROLL_THRESHOLD = 50;
export function ServerLogViewer({ open, onOpenChange, targetId }) {
    const { logs, isConnected } = useDeploymentLogs(open ? targetId : null);
    return (_jsx(ServerLogViewerContent, { open: open, onOpenChange: onOpenChange, logs: logs, isConnected: isConnected }));
}
export function ServerLogViewerContent({ open, onOpenChange, logs, isConnected, }) {
    const scrollRef = useRef(null);
    const isAtBottomRef = useRef(true);
    const handleScroll = useCallback(() => {
        const el = scrollRef.current;
        if (!el)
            return;
        isAtBottomRef.current =
            el.scrollTop + el.clientHeight >= el.scrollHeight - AUTO_SCROLL_THRESHOLD;
    }, []);
    useEffect(() => {
        if (isAtBottomRef.current && scrollRef.current) {
            scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
    }, [logs]);
    return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: "flex h-[calc(100vh-48px)] max-h-[calc(100vh-48px)] w-full max-w-[calc(100vw-48px)] flex-col gap-0 bg-zinc-950 p-0 text-zinc-100 sm:rounded-lg", "aria-describedby": undefined, children: [_jsxs(DialogHeader, { className: "flex flex-row items-center justify-between border-b border-zinc-800 px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Terminal, { className: "h-4 w-4 text-zinc-400" }), _jsx(DialogTitle, { className: "text-sm font-medium text-zinc-100", children: "Server Logs" })] }), _jsxs("div", { className: "flex items-center gap-2 pe-8", children: [_jsx("span", { className: `inline-block h-2 w-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-zinc-500'}` }), _jsx("span", { className: "text-xs text-zinc-400", children: isConnected ? 'Connected' : 'Disconnected' })] })] }), _jsxs("div", { ref: scrollRef, onScroll: handleScroll, className: "flex-1 overflow-auto p-4 font-mono text-sm leading-relaxed", children: [logs.length === 0 ? (_jsx("p", { className: "text-zinc-500", children: "Waiting for log output..." })) : (logs.map((entry) => (_jsx(LogLine, { entry: entry }, `${entry.timestamp}-${entry.stream}-${entry.line}`)))), !isConnected && logs.length > 0 && (_jsx("div", { className: "mt-2 border-t border-zinc-800 pt-2 text-zinc-500", children: "[Server stopped]" }))] })] }) }));
}
function LogLine({ entry }) {
    return (_jsx("div", { "data-stream": entry.stream, className: entry.stream === 'stderr' ? 'text-red-400' : 'text-zinc-200', children: _jsx("span", { className: "break-all whitespace-pre-wrap", children: entry.line }) }));
}
