'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import dynamic from 'next/dynamic';
import { useTranslation } from 'react-i18next';
import { Direction } from 'radix-ui';
import { SidebarProvider, SidebarInset } from '../../ui/sidebar.js';
import { AppSidebar } from '../../layouts/app-sidebar/index.js';
import { pickFolder } from '../../common/add-repository-button/pick-folder.js';
import { buildCreateUrl } from '../../../lib/url-params.js';
// Heavy global overlays — defer their JS chunks until the user actually
// needs them. Each pulls in a non-trivial dependency chain (assistant-ui,
// radix-dialog content, etc.) that we don't want on the critical path of
// the initial page load. `ssr: false` because none of them need to render
// during SSR (they're modals/popovers triggered by client interaction).
const GlobalChatPopup = dynamic(() => import('../../features/chat/ChatSheet.js').then((m) => m.GlobalChatPopup), { ssr: false });
const GlobalSearchDialog = dynamic(() => import('../../features/search/global-search-dialog.js').then((m) => m.GlobalSearchDialog), { ssr: false });
const GitHubImportDialog = dynamic(() => import('../../common/github-import-dialog/index.js').then((m) => m.GitHubImportDialog), { ssr: false });
const ReactFileManagerDialog = dynamic(() => import('../../common/react-file-manager-dialog/index.js').then((m) => m.ReactFileManagerDialog), { ssr: false });
import { AgentEventsProvider } from '../../../hooks/agent-events-provider.js';
import { DrawerCloseGuardProvider, useDrawerCloseGuard } from '../../../hooks/drawer-close-guard.js';
import { SidebarFeaturesProvider, useSidebarFeaturesContext, } from '../../../hooks/sidebar-features-context.js';
import { TurnStatusesProvider } from '../../../hooks/turn-statuses-provider.js';
import { useNotifications } from '../../../hooks/use-notifications.js';
import { useFeatureFlags } from '../../../hooks/feature-flags-context.js';
import { AppsOnlyShell } from './apps-only-shell.js';
function AppShellInner({ children, sidebarOpen, variant = 'full' }) {
    const router = useRouter();
    const pathname = usePathname();
    const { guardedNavigate } = useDrawerCloseGuard();
    const featureFlags = useFeatureFlags();
    // Application-centric routes own their own primary actions (smart
    // deploy split-button in the top bar, create FAB on the list page)
    // so the global chat FAB is redundant there and was colliding with
    // the page-level FAB. Hide it entirely on /applications (list) and
    // /application/[id] (individual app page).
    const hideGlobalChat = pathname === '/applications' ||
        pathname?.startsWith('/applications/') ||
        pathname?.startsWith('/application/');
    // Subscribe to agent lifecycle events and dispatch toast/browser
    // notifications. The apps-only desktop surface suppresses toasts
    // entirely — the StepTracker + operation logs drawer already tell
    // the story inside the app, and a stack of toasts over the preview
    // pane just adds noise.
    useNotifications(variant !== 'apps-only');
    const { features } = useSidebarFeaturesContext();
    const handleFeatureClick = useCallback((featureId) => {
        guardedNavigate(() => router.push(`/feature/${featureId}`));
    }, [router, guardedNavigate]);
    const handleAddFeature = useCallback((repositoryPath) => {
        guardedNavigate(() => router.push(buildCreateUrl({ repo: repositoryPath })));
    }, [router, guardedNavigate]);
    const [addingRepo, setAddingRepo] = useState(false);
    const [githubDialogOpen, setGithubDialogOpen] = useState(false);
    const [showReactPicker, setShowReactPicker] = useState(false);
    const handleAddRepository = useCallback(async () => {
        if (addingRepo)
            return;
        if (featureFlags.reactFileManager) {
            setShowReactPicker(true);
            return;
        }
        setAddingRepo(true);
        try {
            const path = await pickFolder();
            if (path) {
                window.dispatchEvent(new CustomEvent('shep:add-repository', { detail: { path } }));
            }
        }
        catch {
            // Native picker failed — fall back to React file manager
            setShowReactPicker(true);
        }
        finally {
            setAddingRepo(false);
        }
    }, [addingRepo, featureFlags.reactFileManager]);
    // Listen for pick-folder events from the canvas toolbar
    useEffect(() => {
        const handler = () => {
            void handleAddRepository();
        };
        window.addEventListener('shep:pick-folder', handler);
        return () => window.removeEventListener('shep:pick-folder', handler);
    }, [handleAddRepository]);
    // Listen for GitHub import event from (+) FAB
    useEffect(() => {
        const handler = () => setGithubDialogOpen(true);
        window.addEventListener('shep:open-github-import', handler);
        return () => window.removeEventListener('shep:open-github-import', handler);
    }, []);
    const handleReactPickerSelect = useCallback((path) => {
        if (path) {
            window.dispatchEvent(new CustomEvent('shep:add-repository', { detail: { path } }));
        }
        setShowReactPicker(false);
    }, []);
    const handleGitHubImportComplete = useCallback((repository) => {
        if (repository.path) {
            window.dispatchEvent(new CustomEvent('shep:add-repository', { detail: { path: repository.path } }));
        }
    }, []);
    if (variant === 'apps-only') {
        return _jsx(AppsOnlyShell, { children: children });
    }
    return (_jsxs(SidebarProvider, { defaultOpen: sidebarOpen ?? false, children: [_jsx(AppSidebar, { features: features, featureFlags: featureFlags, onFeatureClick: handleFeatureClick, onAddFeature: handleAddFeature }), _jsx(SidebarInset, { children: _jsxs("div", { className: "relative h-dvh", children: [_jsx("main", { className: "h-full min-h-0", children: children }), hideGlobalChat ? null : _jsx(GlobalChatPopup, {}), _jsx(GlobalSearchDialog, {}), _jsx(GitHubImportDialog, { open: githubDialogOpen, onOpenChange: setGithubDialogOpen, onImportComplete: handleGitHubImportComplete })] }) }), _jsx(ReactFileManagerDialog, { open: showReactPicker, onOpenChange: (open) => {
                    if (!open)
                        setShowReactPicker(false);
                }, onSelect: handleReactPickerSelect })] }));
}
/** Wraps children with TurnStatusesProvider (polls all active statuses from backend). */
function TurnStatusesBridge({ children }) {
    return _jsx(TurnStatusesProvider, { children: children });
}
export function AppShell({ children, sidebarOpen, variant = 'full' }) {
    const { i18n } = useTranslation();
    const dir = i18n.dir();
    return (_jsx(Direction.Provider, { dir: dir, children: _jsx(AgentEventsProvider, { children: _jsx(DrawerCloseGuardProvider, { children: _jsx(SidebarFeaturesProvider, { children: _jsx(TurnStatusesBridge, { children: _jsx(AppShellInner, { sidebarOpen: sidebarOpen, variant: variant, children: children }) }) }) }) }) }));
}
