import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react";
import { PanelRightClose, RefreshCw, RotateCcw } from "lucide-react";
import { ParheliaAgentIcon } from "../../ui/Icons";
import { LoadingState } from "../../ui/LoadingState";
import { Button } from "../../../components/ui/button";
import { AgentTerminal } from "../../ai/AgentTerminal";
import { getAiProfilesErrorMessage, loadAiProfiles, } from "../../services/aiService";
export function ProjectTemplateAgentPanel({ templateName, agentId, loading, resetting, error, initialMetadata, fullHeightBounds, onStartOver, onClose, headerStart, }) {
    const [profiles, setProfiles] = useState([]);
    const [profilesError, setProfilesError] = useState(null);
    const [panelFrameRect, setPanelFrameRect] = useState(null);
    const panelFrameRef = useRef(null);
    const updatePanelFrameRect = useCallback(() => {
        const element = panelFrameRef.current;
        if (!element) {
            setPanelFrameRect(null);
            return;
        }
        const rect = element.getBoundingClientRect();
        if (rect.width <= 0 || rect.height <= 0) {
            setPanelFrameRect(null);
            return;
        }
        const nextRect = {
            left: rect.left,
        };
        setPanelFrameRect((currentRect) => currentRect && Math.abs(currentRect.left - nextRect.left) < 0.5
            ? currentRect
            : nextRect);
    }, []);
    useLayoutEffect(() => {
        if (!fullHeightBounds) {
            setPanelFrameRect(null);
            return;
        }
        const element = panelFrameRef.current;
        updatePanelFrameRect();
        if (typeof window === "undefined") {
            return;
        }
        let frameId = null;
        const scheduleUpdate = () => {
            if (frameId != null) {
                window.cancelAnimationFrame(frameId);
            }
            frameId = window.requestAnimationFrame(() => {
                frameId = null;
                updatePanelFrameRect();
            });
        };
        const resizeObserver = typeof ResizeObserver !== "undefined" && element
            ? new ResizeObserver(scheduleUpdate)
            : null;
        if (resizeObserver && element) {
            resizeObserver.observe(element);
        }
        window.addEventListener("resize", scheduleUpdate);
        window.addEventListener("scroll", scheduleUpdate, true);
        return () => {
            if (frameId != null) {
                window.cancelAnimationFrame(frameId);
            }
            resizeObserver?.disconnect();
            window.removeEventListener("resize", scheduleUpdate);
            window.removeEventListener("scroll", scheduleUpdate, true);
        };
    }, [fullHeightBounds, updatePanelFrameRect]);
    useEffect(() => {
        let cancelled = false;
        setProfilesError(null);
        loadAiProfiles()
            .then((items) => {
            if (!cancelled) {
                setProfiles(items || []);
            }
        })
            .catch((loadError) => {
            if (!cancelled) {
                setProfiles([]);
                setProfilesError(getAiProfilesErrorMessage(loadError));
            }
        });
        return () => {
            cancelled = true;
        };
    }, []);
    const agentStub = useMemo(() => {
        if (!agentId)
            return null;
        return {
            id: agentId,
            name: "Project Template Assistant",
            userId: "",
            updatedDate: "",
            status: "idle",
        };
    }, [agentId]);
    const templateLabel = templateName?.trim() || null;
    const fullHeightStyle = fullHeightBounds && panelFrameRect
        ? {
            position: "fixed",
            top: fullHeightBounds.top,
            left: panelFrameRect.left,
            width: Math.max(0, fullHeightBounds.right - panelFrameRect.left),
            height: fullHeightBounds.height,
            zIndex: 40,
        }
        : undefined;
    const panelContent = (_jsxs("div", { className: "flex h-full min-h-0 flex-col bg-white", "data-testid": "project-template-agent-panel", style: fullHeightStyle, children: [_jsxs("div", { className: "border-border-default flex items-center justify-between gap-2 border-b px-4 py-3", children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2", children: [headerStart ? _jsx("div", { className: "shrink-0", children: headerStart }) : null, _jsx(ParheliaAgentIcon, { className: "text-neutral-grey-100 h-5 w-5 shrink-0" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "truncate text-sm font-medium", children: "Project Template Assistant" }), templateLabel ? (_jsxs("div", { className: "text-muted-foreground truncate text-xs", children: ["Template: ", templateLabel] })) : null] })] }), _jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [_jsxs(Button, { variant: "outline", size: "sm", onClick: onStartOver, disabled: !templateName || loading || resetting, title: "Create a fresh assistant conversation for this template", "data-testid": "project-template-agent-reset-button", children: [resetting ? (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin", strokeWidth: 1 })) : (_jsx(RotateCcw, { className: "h-4 w-4", strokeWidth: 1 })), "Start Over"] }), onClose ? (_jsx(Button, { type: "button", variant: "outline", size: "icon", className: "h-8 w-8 shrink-0", onClick: onClose, "aria-label": "Hide assistant", title: "Hide assistant", "data-testid": "project-template-agent-toggle-button", children: _jsx(PanelRightClose, { className: "h-4 w-4", strokeWidth: 1 }) })) : null] })] }), profilesError ? (_jsx("div", { className: "border-feedback-orange bg-feedback-orange-light text-feedback-orange border-b px-4 py-2 text-xs", children: profilesError })) : null, error ? (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red border-b px-4 py-2 text-xs", children: error })) : null, _jsx("div", { className: "min-h-0 flex-1", children: loading ? (_jsx(LoadingState, { variant: "fill", message: "Loading template assistant...", spinnerClassName: "text-muted-foreground/60" })) : !templateName ? (_jsxs("div", { className: "flex h-full flex-col items-center justify-center gap-3 p-6 text-center", children: [_jsx(ParheliaAgentIcon, { className: "text-muted-foreground/40 h-10 w-10" }), _jsxs("div", { className: "grid gap-1", children: [_jsx("div", { className: "text-muted-foreground text-sm font-medium", children: "No template selected" }), _jsx("div", { className: "text-muted-foreground text-xs", children: "Select a project template to open its dedicated assistant." })] })] })) : !agentStub ? (_jsxs("div", { className: "flex h-full flex-col items-center justify-center gap-3 p-6 text-center", children: [_jsx(ParheliaAgentIcon, { className: "text-muted-foreground/40 h-10 w-10" }), _jsxs("div", { className: "grid gap-1", children: [_jsx("div", { className: "text-muted-foreground text-sm font-medium", children: "Assistant unavailable" }), _jsx("div", { className: "text-muted-foreground text-xs", children: "Try selecting the template again or use Start Over to create a fresh session." })] })] })) : (_jsx(AgentTerminal, { agentStub: agentStub, initialMetadata: initialMetadata, profiles: profiles, isActive: true, compact: true, hideGreeting: true, displayMode: "full", showSummaryInput: false, className: "h-full" })) })] }));
    return (_jsx("div", { ref: panelFrameRef, className: "h-full min-h-0 bg-white", children: panelContent }));
}
export default ProjectTemplateAgentPanel;
//# sourceMappingURL=ProjectTemplateAgentPanel.js.map