'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { ApplicationStatus } from '../../../../../../packages/core/src/domain/generated/output.js';
import { featureIdForApplication } from '../../../../../../packages/core/src/domain/shared/feature-id.js';
import { ChatTab } from '../../features/chat/ChatTab.js';
import { APPLICATION_CREATION_PLACEHOLDER_STEPS } from '../../features/chat/workflow-placeholder.js';
import { useCloudDeployAction } from '../../../hooks/use-cloud-deploy-action.js';
import { useDeployAction } from '../../../hooks/use-deploy-action.js';
import { useTurnStatus } from '../../../hooks/turn-statuses-provider.js';
import { AppTopBar } from './app-top-bar.js';
import { ResizableSplit } from './resizable-split.js';
import { useDevServerCoordinator } from './use-dev-server-coordinator.js';
import { ViewBody } from './view-body.js';
export function ApplicationPage({ application, initialChatState }) {
    // Hoisted dev-server state — subscribes to the shared
    // DeploymentStatusProvider scoped to this application's id. The server
    // component seeds the provider with `initialDeployment` (if any) so
    // the first paint already has the running URL; the provider's
    // `ensureHydrated` effect fills in fresh state on mount when the seed
    // is absent (e.g. test environments where the server couldn't reach
    // the deployment service).
    const deploy = useDeployAction({
        targetId: application.id,
        targetType: 'application',
        repositoryPath: application.repositoryPath,
    });
    const cloudDeploy = useCloudDeployAction(application.id);
    // ── Agent-running detection ────────────────────────────────
    // While the agent is processing, the dev server is likely being
    // modified — disable preview and auto-restart when done.
    const turnStatus = useTurnStatus(featureIdForApplication(application.id));
    const agentRunning = turnStatus === 'processing';
    // All dev-server coordination lives in this hook — stop/restart
    // around agent turns, auto-switch to Web on Ready, prevent manual
    // Web selection while the agent is running.
    const { activeView, handleViewChange } = useDevServerCoordinator({
        deploy,
        agentRunning,
    });
    // Derive the synthetic scaffolding card state from the Application
    // entity. Scaffolding (`BunShadcnScaffolder`) runs BEFORE the agent
    // turn and has no real `workflow_steps` row, so the tracker would
    // otherwise show all-pending cards during an expensive `bun install`.
    // The card uses `application.createdAt` as the approximate start —
    // the Application row is persisted moments before the scaffolder
    // kicks off, so the duration is a couple of hundred ms high at most.
    //   - Error state: Application.status flipped to `Error` → failed.
    //   - Completed: `setupComplete` flipped to `true` → done.
    //   - Otherwise: still running.
    // `ChatTab` additionally forces `done` once real workflow rows arrive,
    // which covers the window between `setupComplete=false` and the
    // first workflow step SSE chunk.
    const scaffoldingState = application.setupComplete
        ? {
            status: 'done',
            startedAt: new Date(application.createdAt).getTime(),
        }
        : application.status === ApplicationStatus.Error
            ? {
                status: 'failed',
                startedAt: new Date(application.createdAt).getTime(),
                error: 'Scaffolding failed — check the logs for details.',
            }
            : {
                status: 'running',
                startedAt: new Date(application.createdAt).getTime(),
            };
    // Derive a recovery-banner payload for ChatTab when the application
    // is in a broken state. The server-side
    // `application.status === Error` flag is the authoritative signal:
    // the setup / build pipeline crashed, was logged, and the row was
    // stamped. Without a visible banner the user would otherwise only
    // see a red "ERROR" pill in the top bar with no explanation. The
    // `/resume` endpoint re-runs the last failed step, so the banner
    // is always retryable when we render it.
    const applicationError = application.status === ApplicationStatus.Error
        ? {
            kind: 'Setup failed',
            message: 'The last setup run errored out before it could finish. Click Try again to re-run the failed step, or open the Smart Deploy activity log from the top bar to see what went wrong.',
            retryable: true,
        }
        : null;
    return (
    // `h-full` (not `h-dvh`) so the page fills its shell's main area
    // exactly — in the apps-only surface the main is `viewport - topbar`,
    // and `h-dvh` would make this 40px taller than its container and
    // trigger an outer scrollbar over the whole window.
    _jsxs("div", { className: "bg-background flex h-full flex-col", children: [_jsx(AppTopBar, { application: application, activeView: activeView, onViewChange: handleViewChange, agentRunning: agentRunning, initialChatState: initialChatState, deploy: deploy, cloudDeploy: cloudDeploy }), _jsx(ResizableSplit, { left: _jsx(ChatTab, { featureId: featureIdForApplication(application.id), applicationId: application.id, worktreePath: application.repositoryPath, initialAgent: application.agentType, initialModel: application.modelOverride, initialChatState: initialChatState, hideHeader: true, workflowPlaceholder: APPLICATION_CREATION_PLACEHOLDER_STEPS, scaffoldingState: scaffoldingState, onResumeWorkflow: () => {
                        void fetch(`/api/applications/${application.id}/resume`, { method: 'POST' });
                    }, applicationError: applicationError }), right: _jsx(ViewBody, { activeView: activeView, applicationId: application.id, terminalCwd: application.repositoryPath, deploy: deploy, isBuilding: !application.setupComplete || agentRunning }) })] }));
}
