'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';
import { notFound } from 'next/navigation';
import { DeploymentStatusProvider } from '../../../hooks/deployment-status-provider.js';
import { useApplicationUpdate } from '../../../hooks/agent-events-provider.js';
import { ApplicationPage } from './application-page.js';
export function ApplicationPageLoader({ applicationId }) {
    const queryClient = useQueryClient();
    const { data, isLoading, error } = useQuery({
        queryKey: ['application', applicationId],
        queryFn: async () => {
            const res = await fetch(`/api/applications/${applicationId}`);
            if (res.status === 404)
                throw new Error('not-found');
            if (!res.ok)
                throw new Error('Failed to fetch application');
            return res.json();
        },
        staleTime: 60_000,
        retry: (count, err) => {
            if (err instanceof Error && err.message === 'not-found')
                return false;
            return count < 2;
        },
    });
    // Merge typed `ApplicationUpdated` deltas into the cached AppData
    // in-place — no HTTP refetch, no blanket invalidation. The backend
    // emits a payload whenever server-owned fields flip; we patch the
    // cache so `setupComplete`, `status`, `gitRemoteUrl`, and
    // `cloudDeploymentProvider` update the moment the event arrives.
    const applicationUpdate = useApplicationUpdate(applicationId);
    useEffect(() => {
        if (!applicationUpdate)
            return;
        queryClient.setQueryData(['application', applicationId], (old) => {
            if (!old)
                return old;
            return {
                ...old,
                application: { ...old.application, ...applicationUpdate },
            };
        });
    }, [applicationUpdate, queryClient, applicationId]);
    if (error?.message === 'not-found') {
        notFound();
    }
    if (isLoading || !data) {
        return (_jsx("div", { className: "bg-background flex h-dvh items-center justify-center", children: _jsx(Loader2, { className: "text-muted-foreground h-6 w-6 animate-spin" }) }));
    }
    const { application, initialChatState, deployment } = data;
    const initialDeployment = deployment
        ? { state: deployment.state, url: deployment.url }
        : undefined;
    const initialDeployments = initialDeployment
        ? [
            {
                targetId: application.id,
                targetType: 'application',
                state: initialDeployment.state,
                url: initialDeployment.url,
            },
        ]
        : [];
    return (_jsx(DeploymentStatusProvider, { initialDeployments: initialDeployments, children: _jsx(ApplicationPage, { application: application, initialChatState: initialChatState, initialDeployment: initialDeployment }) }));
}
