'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState, useCallback, useRef, useMemo } from 'react';
import { Spinner } from '@phosphor-icons/react';
import { DocsSidebar } from './sidebar';
import { NotFoundPage } from './content/not-found-page';
import { ApiPlayground } from './playground';
import { RightSidebar } from './sidebar/right-sidebar';
import { RequestDetails } from './content/request-details';
import { DocPage } from './content/doc-page';
import { ChangelogPage } from './content/changelog-page';
import { GraphQLPlayground } from './playground/graphql-playground';
import { makeBrainfishCollection } from '@/lib/api-docs/factories';
import { buildSchema, isNonNullType, isListType } from 'graphql';
import { GlobalAuthModal } from './global-auth-modal';
import { AuthProvider } from '@/lib/api-docs/auth';
import { PlaygroundProvider, usePlaygroundPrefill } from '@/lib/api-docs/playground/context';
import { PlaygroundNavigationProvider, usePlaygroundNavigation } from '@/lib/api-docs/playground/navigation-context';
import { NavigationProvider } from '@/lib/api-docs/navigation-context';
import { ModeProvider, useModeContext } from '@/lib/api-docs/code-editor';
import { NotesMode } from './code-editor';
import { DocsHeader } from '@/components/docs-header';
import { Notice } from '../docs/notice';
import { DocsNavigationProvider } from '@/lib/docs-navigation-context';
import { Button } from '@/components/ui/button';
import { Code, TestTube, Book } from '@phosphor-icons/react';
import { cn } from '@/lib/utils';
import { SearchDialog, useSearch } from './search';
import { useTheme } from 'next-themes';
import { useRouteState } from '@/hooks/use-route-state';
import { navigateToPage, navigateToEndpoint, navigateToSection, navigateToTab } from '@/lib/docs-navigation';
import { useMobile } from '@/lib/api-docs/mobile-context';
import { AgentPopupButton } from './agent/agent-popup-button';
import { buildEndpointIndex } from '@/lib/api-docs/agent/indexer';
// Helper to convert GraphQL type to string representation
function graphqlTypeToString(type) {
    if (isNonNullType(type)) {
        return `${graphqlTypeToString(type.ofType)}!`;
    }
    if (isListType(type)) {
        return `[${graphqlTypeToString(type.ofType)}]`;
    }
    // Named type
    return type.name || 'Unknown';
}
// Parse GraphQL schema using buildSchema (for SDL)
function parseGraphQLSchema(schemaSDL) {
    const operations = [];
    try {
        const schema = buildSchema(schemaSDL);
        // Get root operation types
        const rootTypes = [
            {
                type: schema.getQueryType(),
                operationType: 'query'
            },
            {
                type: schema.getMutationType(),
                operationType: 'mutation'
            },
            {
                type: schema.getSubscriptionType(),
                operationType: 'subscription'
            }
        ];
        for (const { type: rootType, operationType } of rootTypes){
            if (!rootType) continue;
            const fields = rootType.getFields();
            for (const [fieldName, field] of Object.entries(fields)){
                // Skip internal fields
                if (fieldName.startsWith('_')) continue;
                const returnType = graphqlTypeToString(field.type);
                const query = generateGraphQLQueryFromField(operationType, fieldName, field.args, returnType, schema);
                const exampleVariables = generateGraphQLVariablesFromArgs(field.args, schema);
                operations.push({
                    id: `${operationType}-${fieldName}`,
                    name: fieldName,
                    description: field.description || null,
                    operationType,
                    query,
                    exampleVariables
                });
            }
        }
    } catch (err) {
        console.error('[GraphQL Parser] Failed to parse schema:', err);
    }
    return operations;
}
// Get default fields for a type from schema
function getDefaultFieldsForType(typeName, schema) {
    const type = schema.getType(typeName);
    if (!type || !('getFields' in type)) return [];
    const fields = type.getFields();
    const fieldNames = Object.keys(fields);
    // Priority order for default fields
    const priorityFields = [
        'code',
        'id',
        'name',
        'title',
        'slug'
    ];
    const selectedFields = [];
    // First, add priority fields if they exist
    for (const pf of priorityFields){
        if (fieldNames.includes(pf)) {
            selectedFields.push(pf);
            if (selectedFields.length >= 3) break;
        }
    }
    // If we don't have enough, add other scalar fields
    if (selectedFields.length < 3) {
        for (const [fname, fdef] of Object.entries(fields)){
            if (selectedFields.includes(fname)) continue;
            const ftype = graphqlTypeToString(fdef.type).replace(/[\[\]!]/g, '').trim();
            if ([
                'String',
                'Int',
                'Float',
                'Boolean',
                'ID'
            ].includes(ftype)) {
                selectedFields.push(fname);
                if (selectedFields.length >= 3) break;
            }
        }
    }
    return selectedFields.length > 0 ? selectedFields : [
        '__typename'
    ];
}
// Generate example GraphQL query from schema field
function generateGraphQLQueryFromField(operationType, name, args, returnType, schema) {
    let query = `${operationType} ${name.charAt(0).toUpperCase() + name.slice(1)}`;
    if (args.length > 0) {
        const varDefs = args.map((arg)=>`$${arg.name}: ${graphqlTypeToString(arg.type)}`).join(', ');
        query += `(${varDefs})`;
    }
    query += ` {\n  ${name}`;
    if (args.length > 0) {
        const argPairs = args.map((arg)=>`${arg.name}: $${arg.name}`).join(', ');
        query += `(${argPairs})`;
    }
    const baseType = returnType.replace(/[\[\]!]/g, '').trim();
    if ([
        'String',
        'Int',
        'Float',
        'Boolean',
        'ID'
    ].includes(baseType)) {
        query += '\n}';
    } else {
        // Get actual fields from the schema for this type
        const defaultFields = getDefaultFieldsForType(baseType, schema);
        const fieldsStr = defaultFields.map((f)=>`    ${f}`).join('\n');
        query += ` {\n${fieldsStr}\n  }\n}`;
    }
    return query;
}
// Generate example value for a GraphQL type
function generateExampleValue(type, schema, depth = 0) {
    // Prevent infinite recursion
    if (depth > 3) return null;
    // Unwrap NonNull
    if (isNonNullType(type)) {
        return generateExampleValue(type.ofType, schema, depth);
    }
    // Handle List types - return array with one example element
    if (isListType(type)) {
        const itemValue = generateExampleValue(type.ofType, schema, depth);
        return itemValue !== null ? [
            itemValue
        ] : [];
    }
    // Get the named type
    const typeName = type.name;
    if (!typeName) return null;
    // Built-in scalar types
    switch(typeName){
        case 'String':
            return 'example';
        case 'Int':
            return 10;
        case 'Float':
            return 1.5;
        case 'Boolean':
            return true;
        case 'ID':
            return 'example-id';
        // Common custom scalars
        case 'DateTime':
            return new Date().toISOString();
        case 'Date':
            return new Date().toISOString().split('T')[0];
        case 'Time':
            return '12:00:00';
        case 'JSON':
            return {};
        case 'JSONObject':
            return {};
        case 'URL':
            return 'https://example.com';
        case 'URI':
            return 'https://example.com';
        case 'Email':
            return 'user@example.com';
        case 'EmailAddress':
            return 'user@example.com';
        case 'UUID':
            return '550e8400-e29b-41d4-a716-446655440000';
        case 'BigInt':
            return '9007199254740991';
        case 'Long':
            return 9007199254740991;
    }
    // Check if it's an enum type
    const schemaType = schema.getType(typeName);
    if (schemaType && 'getValues' in schemaType) {
        const enumType = schemaType;
        const values = enumType.getValues();
        if (values.length > 0) {
            return values[0].name // Return first enum value
            ;
        }
    }
    // Check if it's an input object type
    if (schemaType && 'getFields' in schemaType) {
        const inputType = schemaType;
        const fields = inputType.getFields();
        const result = {};
        // Only include required fields to keep examples concise
        for (const [fieldName, field] of Object.entries(fields)){
            if (isNonNullType(field.type)) {
                // Use default value if available, otherwise generate
                if (field.defaultValue !== undefined) {
                    result[fieldName] = field.defaultValue;
                } else {
                    result[fieldName] = generateExampleValue(field.type, schema, depth + 1);
                }
            }
        }
        // If no required fields, include first optional field
        if (Object.keys(result).length === 0) {
            const firstField = Object.entries(fields)[0];
            if (firstField) {
                const [fname, fdef] = firstField;
                // Use default value if available
                if (fdef.defaultValue !== undefined) {
                    result[fname] = fdef.defaultValue;
                } else {
                    result[fname] = generateExampleValue(fdef.type, schema, depth + 1);
                }
            }
        }
        return result;
    }
    // Unknown type - return null
    return null;
}
// Generate example variables from GraphQL arguments
function generateGraphQLVariablesFromArgs(args, schema) {
    const variables = {};
    for (const arg of args){
        // First, check if the argument has a default value in the schema
        if (arg.defaultValue !== undefined) {
            variables[arg.name] = arg.defaultValue;
        } else {
            // Generate example value for arguments without defaults
            const value = generateExampleValue(arg.type, schema, 0);
            if (value !== null) {
                variables[arg.name] = value;
            }
        }
    }
    return variables;
}
// Convert GraphQL operations to BrainfishCollection for sidebar
function convertGraphQLToCollection(operations, endpoint) {
    const queries = operations.filter((op)=>op.operationType === 'query');
    const mutations = operations.filter((op)=>op.operationType === 'mutation');
    const subscriptions = operations.filter((op)=>op.operationType === 'subscription');
    const toRequest = (op)=>({
            id: op.id,
            name: op.name,
            description: op.description || '',
            method: 'POST',
            endpoint,
            params: [],
            headers: [],
            auth: {
                authType: 'none',
                authActive: false
            },
            body: {
                contentType: 'application/json',
                body: JSON.stringify({
                    query: op.query,
                    variables: op.exampleVariables
                }, null, 2)
            },
            requestVariables: [],
            responses: {},
            tags: [
                op.operationType
            ]
        });
    const folders = [];
    if (queries.length > 0) {
        folders.push(makeBrainfishCollection({
            name: 'Queries',
            description: 'GraphQL Query operations',
            requests: queries.map(toRequest),
            folders: [],
            variables: [],
            auth: {
                authType: 'none',
                authActive: false
            },
            headers: []
        }));
    }
    if (mutations.length > 0) {
        folders.push(makeBrainfishCollection({
            name: 'Mutations',
            description: 'GraphQL Mutation operations',
            requests: mutations.map(toRequest),
            folders: [],
            variables: [],
            auth: {
                authType: 'none',
                authActive: false
            },
            headers: []
        }));
    }
    if (subscriptions.length > 0) {
        folders.push(makeBrainfishCollection({
            name: 'Subscriptions',
            description: 'GraphQL Subscription operations',
            requests: subscriptions.map(toRequest),
            folders: [],
            variables: [],
            auth: {
                authType: 'none',
                authActive: false
            },
            headers: []
        }));
    }
    return makeBrainfishCollection({
        name: 'GraphQL API',
        description: 'GraphQL operations',
        folders,
        requests: [],
        variables: [],
        auth: {
            authType: 'none',
            authActive: false
        },
        headers: []
    });
}
// Helper to find request by ID in collection
function findRequestById(collection, id) {
    // Check direct requests
    const found = collection.requests.find((r)=>r.id === id);
    if (found) return found;
    // Check folders recursively
    for (const folder of collection.folders){
        const request = findRequestById(folder, id);
        if (request) return request;
    }
    return null;
}
// Helper to get the first endpoint from collection
function getFirstEndpoint(collection) {
    // Check direct requests first
    if (collection.requests.length > 0) {
        return collection.requests[0];
    }
    // Check folders recursively
    for (const folder of collection.folders){
        const firstInFolder = getFirstEndpoint(folder);
        if (firstInFolder) return firstInFolder;
    }
    return null;
}
// Helper to check if a doc group belongs to a specific tab
// Group IDs are formatted as: group-{tab-id}-{group-name}
function isGroupForTab(groupId, tabId) {
    // Check if the group ID starts with "group-{tabId}-"
    const prefix = `group-${tabId}-`;
    return groupId.startsWith(prefix);
}
// Helper to check if a tab has doc groups (MDX pages)
function hasDocGroupsForTab(docGroups, tabId) {
    if (!docGroups || docGroups.length === 0) return false;
    // Check if any doc group belongs to this tab and has pages
    return docGroups.some((g)=>isGroupForTab(g.id, tabId) && g.pages.length > 0);
}
// Helper to get the first page from doc groups for a tab
function getFirstDocPageForTab(docGroups, tabId) {
    if (!docGroups || docGroups.length === 0) return null;
    const tabDocGroup = docGroups.find((g)=>isGroupForTab(g.id, tabId) && g.pages.length > 0);
    return tabDocGroup?.pages[0]?.slug || null;
}
function DocsContent() {
    const [collection, setCollection] = useState(null);
    const [selectedApiVersion, setSelectedApiVersion] = useState(null);
    const [loading, setLoading] = useState(true);
    const [isVersionLoading, setIsVersionLoading] = useState(false) // For version switch only
    ;
    const [error, setError] = useState(null);
    const [showAuthModal, setShowAuthModal] = useState(false);
    // URL-based route state - single source of truth for selection
    const routeState = useRouteState();
    // Derive active tab from URL (with default fallback)
    const activeTab = routeState.tab || 'api-reference';
    // Derive selected doc page from URL
    const selectedDocPage = routeState.contentType === 'page' ? routeState.contentId : null;
    // Derive selected doc section from URL
    const selectedDocSection = routeState.contentType === 'section' ? routeState.contentId : null;
    // Derive selected request from URL by looking up in collection
    const selectedRequest = useMemo(()=>{
        if (routeState.contentType !== 'endpoint' || !routeState.contentId || !collection) {
            return null;
        }
        return findRequestById(collection, routeState.contentId);
    }, [
        routeState.contentType,
        routeState.contentId,
        collection
    ]);
    // Derive not found slug from URL when endpoint doesn't exist
    const notFoundSlug = useMemo(()=>{
        if (routeState.contentType === 'endpoint' && routeState.contentId && collection) {
            const request = findRequestById(collection, routeState.contentId);
            if (!request) {
                return `endpoint/${routeState.contentId}`;
            }
        }
        return null;
    }, [
        routeState.contentType,
        routeState.contentId,
        collection
    ]);
    // Prefill context for agent
    const { setPrefill } = usePlaygroundPrefill();
    // Playground navigation context for tab navigation
    const { navigateAndHighlight, resetNavigation } = usePlaygroundNavigation();
    // Mode context for switching modes
    const { switchToDocs } = useModeContext();
    // Ref for the scrollable content area
    const contentRef = useRef(null);
    // Track if initial navigation has been done (prevents re-navigation on effect re-runs)
    const hasInitialNavigated = useRef(false);
    // Handle selecting a request - just navigates to URL
    const handleSelectRequest = useCallback((request)=>{
        navigateToEndpoint(activeTab, request.id);
        // Reset tab navigation so the new endpoint can determine its default tab
        resetNavigation();
        // Switch to Docs mode to show endpoint documentation first
        switchToDocs();
    }, [
        activeTab,
        resetNavigation,
        switchToDocs
    ]);
    // Handle selecting a documentation section (scroll to heading)
    const handleSelectDocumentation = useCallback((headingId)=>{
        const isIntro = headingId === 'introduction';
        if (isIntro) {
            // Scroll to top
            navigateToTab(activeTab);
            setTimeout(()=>{
                contentRef.current?.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            }, 50);
        } else {
            // Navigate to section and scroll
            navigateToSection(activeTab, headingId);
            setTimeout(()=>{
                const element = document.getElementById(headingId);
                if (element) {
                    element.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            }, 50);
        }
        // Switch to Docs mode when selecting documentation
        switchToDocs();
    }, [
        activeTab,
        switchToDocs
    ]);
    // Handle selecting a doc page
    const handleSelectDocPage = useCallback((slug)=>{
        // Find which tab this doc page belongs to
        let targetTab = activeTab;
        let releaseSlug = null;
        let sectionId = null;
        // Parse section from slug (e.g., "essentials/markdown#headings" -> slug: "essentials/markdown", section: "headings")
        let pageSlug = slug;
        if (slug.includes('#')) {
            const [pagePart, sectionPart] = slug.split('#');
            pageSlug = pagePart;
            sectionId = sectionPart;
        }
        // Special handling for changelog pages
        if (pageSlug.startsWith('changelog/') || pageSlug === 'changelog') {
            // Find the changelog tab
            const changelogTab = collection?.navigationTabs?.find((t)=>t.type === 'changelog');
            if (changelogTab) {
                targetTab = changelogTab.id;
            }
            // Extract the release slug for scrolling (e.g., "changelog/v1.2.0" -> "v1.2.0")
            if (pageSlug.startsWith('changelog/')) {
                releaseSlug = pageSlug.replace('changelog/', '');
            }
        } else if (collection?.docGroups) {
            for (const group of collection.docGroups){
                const hasPage = (pages)=>{
                    for (const page of pages){
                        if (page.slug === pageSlug) return true;
                        if (page.children && hasPage(page.children)) return true;
                    }
                    return false;
                };
                if (hasPage(group.pages)) {
                    // Extract tab from group ID (e.g., "group-guides-getting-started" -> "guides")
                    const tabPart = group.id.replace('group-', '').split('-')[0];
                    // Find the actual tab ID that matches
                    const matchingTab = collection.navigationTabs?.find((t)=>t.id === tabPart || t.id.startsWith(tabPart));
                    if (matchingTab) {
                        targetTab = matchingTab.id;
                    }
                    break;
                }
            }
        }
        // Navigate to the page via URL
        navigateToPage(targetTab, pageSlug);
        switchToDocs();
        // Scroll to specific release if navigating to a changelog entry
        if (releaseSlug) {
            // Wait for the changelog page to render, then scroll to the release
            setTimeout(()=>{
                const releaseElement = document.getElementById(`release-${releaseSlug}`);
                if (releaseElement) {
                    releaseElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            }, 600);
        } else if (sectionId) {
            // Scroll to section within the page after it renders
            setTimeout(()=>{
                const sectionElement = document.getElementById(sectionId);
                if (sectionElement) {
                    sectionElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            }, 300);
        } else {
            // Scroll to top of content when navigating to a new page
            setTimeout(()=>{
                contentRef.current?.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            }, 50);
        }
    }, [
        switchToDocs,
        collection,
        activeTab
    ]);
    // Handle API version change
    const handleApiVersionChange = useCallback((version)=>{
        if (version !== selectedApiVersion) {
            setSelectedApiVersion(version);
            // Navigate to tab only (clears selection) when switching versions
            navigateToTab(activeTab);
        }
    }, [
        selectedApiVersion,
        activeTab
    ]);
    // Handle tab change from header
    const handleTabChange = useCallback((tabId)=>{
        // Reset mode to docs when switching tabs (exit sandbox/api-client mode)
        switchToDocs();
        // Find the tab config to check its type
        const tabConfig = collection?.navigationTabs?.find((t)=>t.id === tabId);
        const isApiTab = tabConfig?.type === 'openapi' || tabConfig?.type === 'graphql' || tabId === 'api-reference';
        if (tabId === 'changelog') {
            // Switch to Changelog tab
            navigateToTab(tabId);
        } else if (isApiTab) {
            // API Reference or GraphQL tab
            // Check if there are doc groups for this tab (MDX pages)
            const hasGroups = hasDocGroupsForTab(collection?.docGroups, tabId);
            if (hasGroups) {
                // Has doc groups - select the first page from groups
                const firstPage = getFirstDocPageForTab(collection?.docGroups, tabId);
                if (firstPage) {
                    navigateToPage(tabId, firstPage);
                    switchToDocs();
                } else {
                    // No pages in groups - auto-select first endpoint
                    const firstEndpoint = collection ? getFirstEndpoint(collection) : null;
                    if (firstEndpoint) {
                        navigateToEndpoint(tabId, firstEndpoint.id);
                    } else {
                        navigateToTab(tabId);
                    }
                }
            } else {
                // No doc groups - auto-select first endpoint
                const firstEndpoint = collection ? getFirstEndpoint(collection) : null;
                if (firstEndpoint) {
                    navigateToEndpoint(tabId, firstEndpoint.id);
                } else {
                    navigateToTab(tabId);
                }
            }
        } else {
            // Switch to a doc group tab - find and select the first page in that tab
            // Find the first doc group for this tab and select its first page
            if (collection?.docGroups) {
                const tabDocGroup = collection.docGroups.find((g)=>isGroupForTab(g.id, tabId));
                if (tabDocGroup && tabDocGroup.pages.length > 0) {
                    const firstPage = tabDocGroup.pages[0];
                    navigateToPage(tabId, firstPage.slug);
                    switchToDocs();
                } else {
                    navigateToTab(tabId);
                }
            }
        }
    }, [
        collection,
        switchToDocs
    ]);
    // Handler for agent navigation
    const handleAgentNavigate = useCallback((endpointId)=>{
        if (!collection) return;
        const request = findRequestById(collection, endpointId);
        if (request) {
            // Navigate to the endpoint in api-reference tab
            navigateToEndpoint('api-reference', endpointId);
            // Reset tab navigation so the new endpoint can determine its default tab
            resetNavigation();
        }
    }, [
        collection,
        resetNavigation
    ]);
    // Handler for agent prefilling parameters
    const handleAgentPrefill = useCallback((data)=>{
        console.log('[Agent] Prefill requested:', data);
        setPrefill(data);
    }, [
        setPrefill
    ]);
    // State for debug context - used to trigger agent debugging
    const [debugContext, setDebugContext] = useState(null);
    // Handler for debug requests from playground
    const handleDebugRequest = useCallback((context)=>{
        setDebugContext(context);
    }, []);
    // Clear debug context after it's been used
    const clearDebugContext = useCallback(()=>{
        setDebugContext(null);
    }, []);
    // State for explain context - used to trigger agent explanation
    const [explainContext, setExplainContext] = useState(null);
    // Handler for explain requests from playground
    const handleExplainRequest = useCallback((context)=>{
        setExplainContext(context);
    }, []);
    // Clear explain context after it's been used
    const clearExplainContext = useCallback(()=>{
        setExplainContext(null);
    }, []);
    // Note: Browser back/forward is now handled by useRouteState hook automatically
    // Dynamically set favicon from docs.json config
    useEffect(()=>{
        if (!collection?.docsFavicon) return;
        const faviconPath = collection.docsFavicon;
        // Update or create link elements for favicon
        const updateFaviconLink = (rel, href)=>{
            let link = document.querySelector(`link[rel="${rel}"]`);
            if (!link) {
                link = document.createElement('link');
                link.rel = rel;
                document.head.appendChild(link);
            }
            link.href = href;
        };
        // Determine the type based on file extension
        const ext = faviconPath.split('.').pop()?.toLowerCase();
        const type = ext === 'svg' ? 'image/svg+xml' : ext === 'png' ? 'image/png' : ext === 'ico' ? 'image/x-icon' : 'image/png';
        // Update the favicon link with type
        let iconLink = document.querySelector('link[rel="icon"]');
        if (!iconLink) {
            iconLink = document.createElement('link');
            iconLink.rel = 'icon';
            document.head.appendChild(iconLink);
        }
        iconLink.type = type;
        iconLink.href = faviconPath;
        // Also update shortcut icon and apple-touch-icon
        updateFaviconLink('shortcut icon', faviconPath);
        updateFaviconLink('apple-touch-icon', faviconPath);
    }, [
        collection?.docsFavicon
    ]);
    useEffect(()=>{
        async function fetchCollection() {
            try {
                // Only show full loading on initial load
                const isInitialLoad = !collection;
                if (isInitialLoad) {
                    setLoading(true);
                } else {
                    setIsVersionLoading(true);
                }
                setError(null);
                // Build URL with version param if selected
                const url = selectedApiVersion ? `/api/collections?version=${encodeURIComponent(selectedApiVersion)}` : '/api/collections';
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`Failed to fetch collection: ${response.status}`);
                }
                const data = await response.json();
                setCollection(data);
                // Set initial API version if not already set
                if (!selectedApiVersion && data?.selectedApiVersion) {
                    setSelectedApiVersion(data.selectedApiVersion);
                }
                // Only run initial navigation logic on first load
                if (isInitialLoad && !hasInitialNavigated.current) {
                    hasInitialNavigated.current = true;
                    // Helper: Navigate to first content for a given tab
                    const navigateToFirstContent = (tabId)=>{
                        const tabConfig = data.navigationTabs?.find((t)=>t.id === tabId);
                        const isApiTab = tabConfig?.type === 'openapi' || tabConfig?.type === 'graphql' || tabId === 'api-reference';
                        // Try doc pages first, then endpoints
                        const firstPage = isApiTab ? getFirstDocPageForTab(data.docGroups, tabId) : data.docGroups?.find((g)=>isGroupForTab(g.id, tabId))?.pages[0]?.slug;
                        if (firstPage) {
                            navigateToPage(tabId, firstPage);
                            return;
                        }
                        // Fall back to first endpoint for API tabs
                        if (isApiTab) {
                            const firstEndpoint = getFirstEndpoint(data);
                            if (firstEndpoint) {
                                navigateToEndpoint(tabId, firstEndpoint.id);
                                return;
                            }
                        }
                        // No content found, just navigate to tab
                        navigateToTab(tabId);
                    };
                    // Get default tab (first tab in config)
                    let defaultTabId = 'api-reference';
                    if (data?.navigationTabs?.length > 0) {
                        const sortedTabs = [
                            ...data.navigationTabs
                        ].sort((a, b)=>a.order - b.order);
                        defaultTabId = sortedTabs[0].id;
                    }
                    // Handle initial navigation after collection loads
                    setTimeout(()=>{
                        const hash = window.location.hash.slice(1);
                        const isTabOnly = hash && !hash.includes('/');
                        if (!hash) {
                            // No hash - navigate to first content of default tab
                            navigateToFirstContent(defaultTabId);
                        } else if (isTabOnly) {
                            // Just a tab name (e.g., #guides) - navigate to first content
                            navigateToFirstContent(hash);
                        }
                    // View mode (docs/playground/notes) is derived from URL by ModeProvider
                    }, 0);
                }
            // Version changes are handled by handleApiVersionChange callback
            } catch (err) {
                console.error('Error fetching collection:', err);
                setError(err instanceof Error ? err.message : 'Failed to load API documentation');
            } finally{
                setLoading(false);
                setIsVersionLoading(false);
            }
        }
        fetchCollection();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
        selectedApiVersion
    ]);
    // Only show full-page loading on initial load
    if (loading && !collection) {
        return /*#__PURE__*/ _jsx("div", {
            className: "flex items-center justify-center h-screen",
            children: /*#__PURE__*/ _jsxs("div", {
                className: "text-center",
                children: [
                    /*#__PURE__*/ _jsx(Spinner, {
                        size: 32,
                        className: "text-muted-foreground animate-spin mx-auto mb-3"
                    }),
                    /*#__PURE__*/ _jsx("p", {
                        className: "text-sm text-muted-foreground",
                        children: "Loading API documentation..."
                    })
                ]
            })
        });
    }
    if (error) {
        return /*#__PURE__*/ _jsx("div", {
            className: "flex items-center justify-center h-screen",
            children: /*#__PURE__*/ _jsxs("div", {
                className: "text-center",
                children: [
                    /*#__PURE__*/ _jsx("p", {
                        className: "text-destructive text-lg mb-2",
                        children: "Error loading documentation"
                    }),
                    /*#__PURE__*/ _jsx("p", {
                        className: "text-muted-foreground",
                        children: error
                    })
                ]
            })
        });
    }
    if (!collection) {
        return /*#__PURE__*/ _jsx("div", {
            className: "flex items-center justify-center h-screen",
            children: /*#__PURE__*/ _jsxs("div", {
                className: "text-center max-w-md",
                children: [
                    /*#__PURE__*/ _jsx("p", {
                        className: "text-muted-foreground mb-2",
                        children: "No API documentation available"
                    }),
                    /*#__PURE__*/ _jsx("p", {
                        className: "text-sm text-muted-foreground",
                        children: "Please configure your Brainfish API credentials in your environment variables."
                    })
                ]
            })
        });
    }
    // Only show "configure credentials" if there are no endpoints AND no doc groups
    // Multi-tenant docs may have only doc groups without API endpoints
    const hasDocGroups = collection.docGroups && collection.docGroups.length > 0;
    const hasEndpoints = collection.requests.length > 0 || collection.folders.length > 0;
    if (!hasEndpoints && !hasDocGroups) {
        return /*#__PURE__*/ _jsx("div", {
            className: "flex items-center justify-center h-screen",
            children: /*#__PURE__*/ _jsxs("div", {
                className: "text-center max-w-lg p-8",
                children: [
                    /*#__PURE__*/ _jsx("h2", {
                        className: "text-2xl font-semibold mb-2",
                        children: collection.name || 'Documentation'
                    }),
                    /*#__PURE__*/ _jsx("p", {
                        className: "text-muted-foreground mb-6",
                        children: collection.description || 'No documentation content available yet.'
                    }),
                    /*#__PURE__*/ _jsxs("div", {
                        className: "bg-muted/50 rounded-lg p-5 text-left text-sm space-y-4",
                        children: [
                            /*#__PURE__*/ _jsx("p", {
                                className: "font-medium",
                                children: "Get started with DevDoc:"
                            }),
                            /*#__PURE__*/ _jsxs("div", {
                                className: "space-y-3",
                                children: [
                                    /*#__PURE__*/ _jsxs("div", {
                                        children: [
                                            /*#__PURE__*/ _jsx("p", {
                                                className: "text-muted-foreground text-xs mb-1",
                                                children: "Create a new project"
                                            }),
                                            /*#__PURE__*/ _jsx("code", {
                                                className: "block bg-background px-3 py-2 rounded-md font-mono text-xs",
                                                children: "npx create-devdoc-doc my-docs"
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ _jsxs("div", {
                                        children: [
                                            /*#__PURE__*/ _jsx("p", {
                                                className: "text-muted-foreground text-xs mb-1",
                                                children: "Start local development"
                                            }),
                                            /*#__PURE__*/ _jsx("code", {
                                                className: "block bg-background px-3 py-2 rounded-md font-mono text-xs",
                                                children: "npx devdoc dev"
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ _jsxs("div", {
                                        children: [
                                            /*#__PURE__*/ _jsx("p", {
                                                className: "text-muted-foreground text-xs mb-1",
                                                children: "Deploy to production"
                                            }),
                                            /*#__PURE__*/ _jsx("code", {
                                                className: "block bg-background px-3 py-2 rounded-md font-mono text-xs",
                                                children: "npx devdoc deploy"
                                            })
                                        ]
                                    })
                                ]
                            }),
                            /*#__PURE__*/ _jsxs("a", {
                                href: "https://devdoc.sh",
                                target: "_blank",
                                rel: "noopener noreferrer",
                                className: "inline-flex items-center gap-1.5 text-primary hover:underline text-sm font-medium",
                                children: [
                                    "Learn more at devdoc.sh",
                                    /*#__PURE__*/ _jsx("svg", {
                                        className: "h-3.5 w-3.5",
                                        fill: "none",
                                        viewBox: "0 0 24 24",
                                        stroke: "currentColor",
                                        strokeWidth: 2,
                                        children: /*#__PURE__*/ _jsx("path", {
                                            strokeLinecap: "round",
                                            strokeLinejoin: "round",
                                            d: "M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                                        })
                                    })
                                ]
                            })
                        ]
                    })
                ]
            })
        });
    }
    return /*#__PURE__*/ _jsx(NavigationProvider, {
        collection: collection,
        onSelectRequest: handleSelectRequest,
        children: /*#__PURE__*/ _jsx(DocsWithMode, {
            collection: collection,
            selectedRequest: selectedRequest,
            selectedDocSection: selectedDocSection,
            selectedDocPage: selectedDocPage,
            activeTab: activeTab,
            onTabChange: handleTabChange,
            contentRef: contentRef,
            showAuthModal: showAuthModal,
            setShowAuthModal: setShowAuthModal,
            handleSelectRequest: handleSelectRequest,
            handleSelectDocumentation: handleSelectDocumentation,
            handleSelectDocPage: handleSelectDocPage,
            handleDebugRequest: handleDebugRequest,
            handleExplainRequest: handleExplainRequest,
            handleAgentNavigate: handleAgentNavigate,
            handleAgentPrefill: handleAgentPrefill,
            debugContext: debugContext,
            clearDebugContext: clearDebugContext,
            explainContext: explainContext,
            clearExplainContext: clearExplainContext,
            navigateAndHighlight: navigateAndHighlight,
            selectedApiVersion: selectedApiVersion,
            handleApiVersionChange: handleApiVersionChange,
            isVersionLoading: isVersionLoading,
            notFoundSlug: notFoundSlug
        })
    });
}
// Mode toggle tabs - switches between Docs, API Client, and Notes
function ModeToggleTabs({ hasEndpoint }) {
    const { mode, switchToDocs, switchToApiClient, switchToNotes } = useModeContext();
    return /*#__PURE__*/ _jsxs("div", {
        className: "flex items-center gap-1 p-1 rounded-lg bg-muted/50 shrink-0",
        children: [
            /*#__PURE__*/ _jsxs(Button, {
                variant: mode === 'docs' ? 'secondary' : 'ghost',
                size: "sm",
                onClick: ()=>switchToDocs(),
                className: cn("text-xs h-7 px-2 sm:px-3 gap-1.5", mode === 'docs' ? 'bg-background shadow-sm' : 'text-muted-foreground hover:text-foreground'),
                children: [
                    /*#__PURE__*/ _jsx(Book, {
                        className: "h-3.5 w-3.5",
                        weight: "bold"
                    }),
                    /*#__PURE__*/ _jsx("span", {
                        className: "hidden xs:inline",
                        children: "Docs"
                    })
                ]
            }),
            hasEndpoint && /*#__PURE__*/ _jsxs(Button, {
                variant: mode === 'api_client' ? 'secondary' : 'ghost',
                size: "sm",
                onClick: ()=>switchToApiClient(),
                className: cn("text-xs h-7 px-2 sm:px-3 gap-1.5", mode === 'api_client' ? 'bg-background shadow-sm' : 'text-muted-foreground hover:text-foreground'),
                children: [
                    /*#__PURE__*/ _jsx(TestTube, {
                        className: "h-3.5 w-3.5",
                        weight: "bold"
                    }),
                    /*#__PURE__*/ _jsx("span", {
                        className: "hidden xs:inline",
                        children: "API Client"
                    })
                ]
            }),
            /*#__PURE__*/ _jsxs(Button, {
                variant: mode === 'notes' ? 'secondary' : 'ghost',
                size: "sm",
                onClick: ()=>switchToNotes(),
                className: cn("text-xs h-7 px-2 sm:px-3 gap-1.5", mode === 'notes' ? 'bg-background shadow-sm' : 'text-muted-foreground hover:text-foreground'),
                children: [
                    /*#__PURE__*/ _jsx(Code, {
                        className: "h-3.5 w-3.5",
                        weight: "bold"
                    }),
                    /*#__PURE__*/ _jsx("span", {
                        className: "hidden xs:inline",
                        children: "Sandbox"
                    })
                ]
            })
        ]
    });
}
function DocsWithMode({ collection, selectedRequest, selectedDocSection, selectedDocPage, activeTab, onTabChange, contentRef, showAuthModal, setShowAuthModal, handleSelectRequest, handleSelectDocumentation, handleSelectDocPage, handleDebugRequest, handleExplainRequest, handleAgentNavigate, handleAgentPrefill, debugContext, clearDebugContext, explainContext, clearExplainContext, navigateAndHighlight, selectedApiVersion, handleApiVersionChange, isVersionLoading, notFoundSlug }) {
    const { mode, switchToDocs } = useModeContext();
    const { setTheme } = useTheme();
    // Agent panel state - controls popup button and push animation
    const { isRightSidebarOpen, openRightSidebar } = useMobile();
    // Build endpoint index for suggestions (memoized)
    const endpointIndex = useMemo(()=>buildEndpointIndex(collection), [
        collection
    ]);
    // GraphQL state
    const [graphqlOperations, setGraphqlOperations] = useState([]);
    const [graphqlCollection, setGraphqlCollection] = useState(null);
    const [graphqlSchemaSDL, setGraphqlSchemaSDL] = useState(undefined);
    // Use route state for URL-based selection
    const routeState = useRouteState();
    // Derive selected GraphQL operation from URL
    const selectedGraphQLOperation = useMemo(()=>{
        if (routeState.contentType !== 'endpoint' || !routeState.contentId) {
            return null;
        }
        return graphqlOperations.find((op)=>op.id === routeState.contentId) || null;
    }, [
        routeState.contentType,
        routeState.contentId,
        graphqlOperations
    ]);
    // Get API spec URL from environment or collection
    const apiSpecUrl = process.env.NEXT_PUBLIC_OPENAPI_URL || collection.name || 'default';
    // Check if there are endpoints
    const hasEndpoints = collection.folders.length > 0 || collection.requests.length > 0;
    // Search functionality
    const { isOpen: searchOpen, setIsOpen: setSearchOpen, openSearch, searchItems } = useSearch({
        requests: collection.requests,
        folders: collection.folders,
        docGroups: collection.docGroups
    });
    // Handle search item selection - use URL hash navigation
    const handleSearchSelect = useCallback((item)=>{
        if (item.type === 'endpoint') {
            // Navigate to endpoint via hash - format: #api-reference/endpoint/{id}
            window.location.hash = `api-reference/endpoint/${item.id}`;
        } else if (item.type === 'doc') {
            // Navigate to doc page via hash - the href already has the correct format
            // Extract tab and path from href (e.g., #guides/page/quickstart)
            const hashPath = item.href.replace('#', '');
            window.location.hash = hashPath;
        }
    }, []);
    // Wrap agent navigate to switch to Docs mode and navigate to endpoint
    const handleAgentNavigateWithModeSwitch = useCallback((endpointId)=>{
        // handleAgentNavigate navigates via URL
        handleAgentNavigate(endpointId);
    }, [
        handleAgentNavigate
    ]);
    // Get the current content title for header
    // Find the active tab's config
    const activeTabConfig = collection.navigationTabs?.find((t)=>t.id === activeTab);
    const activeTabType = activeTabConfig?.type || 'docs';
    // Filter doc groups for sidebar based on active tab
    // Group IDs are like "group-guides-getting-started", tab IDs are like "guides"
    // Filter doc groups for sidebar based on active tab
    // Group IDs are formatted as: group-{tab-id}-{group-name}
    const filteredDocGroups = collection.docGroups?.filter((g)=>isGroupForTab(g.id, activeTab)) || [];
    // Show endpoints in sidebar only when OpenAPI tab is active
    const showEndpoints = activeTabType === 'openapi';
    // Show changelog when changelog tab is active
    const showChangelog = activeTabType === 'changelog';
    // Show GraphQL playground when graphql tab is active
    const showGraphQL = activeTabType === 'graphql';
    const activeGraphQLSchemas = activeTabConfig?.graphqlSchemas || [];
    // Get the first schema path for stable dependency
    const schemaPath = activeGraphQLSchemas[0]?.schema;
    const schemaEndpoint = activeGraphQLSchemas[0]?.endpoint;
    // Load GraphQL operations when graphql tab is active
    useEffect(()=>{
        if (!showGraphQL || !schemaPath) {
            setGraphqlOperations([]);
            setGraphqlCollection(null);
            setGraphqlSchemaSDL(undefined);
            return;
        }
        // Load and parse GraphQL schema
        const loadGraphQLSchema = async ()=>{
            try {
                console.log('[DocsViewer] Loading GraphQL schema from:', schemaPath);
                const response = await fetch(`/api/schema?path=${encodeURIComponent(schemaPath)}`);
                if (!response.ok) {
                    console.error('[DocsViewer] Failed to fetch schema:', response.status);
                    return;
                }
                const schemaContent = await response.text();
                console.log('[DocsViewer] Schema loaded, length:', schemaContent.length);
                setGraphqlSchemaSDL(schemaContent); // Store schema SDL for autocomplete
                const operations = parseGraphQLSchema(schemaContent);
                console.log('[DocsViewer] Parsed operations:', operations.length);
                setGraphqlOperations(operations);
                // Convert to BrainfishCollection for sidebar
                const gqlCollection = convertGraphQLToCollection(operations, schemaEndpoint || '');
                setGraphqlCollection(gqlCollection);
            } catch (err) {
                console.error('[DocsViewer] Failed to load GraphQL schema:', err);
            }
        };
        loadGraphQLSchema();
    }, [
        showGraphQL,
        schemaPath,
        schemaEndpoint
    ]);
    // Auto-navigate to first GraphQL operation when none selected and no doc pages
    useEffect(()=>{
        if (!showGraphQL || graphqlOperations.length === 0) {
            return;
        }
        // If there's already content selected (page or endpoint), don't auto-navigate
        if (routeState.contentType) {
            return;
        }
        // Check if there are doc groups for this tab
        const hasGroups = hasDocGroupsForTab(collection?.docGroups, activeTab);
        if (!hasGroups) {
            // No doc groups - auto-navigate to first GraphQL operation
            const firstOperation = graphqlOperations[0];
            navigateToEndpoint(activeTab, firstOperation.id);
        }
    }, [
        showGraphQL,
        graphqlOperations,
        activeTab,
        collection?.docGroups,
        routeState.contentType
    ]);
    // Handle GraphQL operation selection from sidebar - just navigates via URL
    const handleSelectGraphQLOperation = useCallback((request)=>{
        navigateToEndpoint(activeTab, request.id);
        switchToDocs();
    }, [
        activeTab,
        switchToDocs
    ]);
    // Inject custom CSS and color variables
    useEffect(()=>{
        // Create or update style element for custom CSS
        let styleEl = document.getElementById('docs-custom-css');
        if (!styleEl) {
            styleEl = document.createElement('style');
            styleEl.id = 'docs-custom-css';
            document.head.appendChild(styleEl);
        }
        // Build CSS with color variables
        let cssContent = '';
        // Add color variables if provided
        // We set both --docs-primary (for custom CSS) and --primary (for Tailwind's bg-primary class)
        if (collection.docsColors) {
            const colors = collection.docsColors;
            cssContent += `:root {\n`;
            if (colors.primary) {
                cssContent += `  --docs-primary: ${colors.primary};\n`;
                cssContent += `  --primary: ${colors.primary};\n`;
            }
            if (colors.primaryLight) cssContent += `  --docs-primary-light: ${colors.primaryLight};\n`;
            if (colors.primaryDark) cssContent += `  --docs-primary-dark: ${colors.primaryDark};\n`;
            cssContent += `}\n`;
            // Also set for dark mode
            cssContent += `.dark {\n`;
            if (colors.primary) cssContent += `  --primary: ${colors.primary};\n`;
            cssContent += `}\n\n`;
        }
        // Add custom CSS if provided
        if (collection.customCss) {
            cssContent += collection.customCss;
        }
        styleEl.textContent = cssContent;
        return ()=>{
            // Cleanup on unmount
            const el = document.getElementById('docs-custom-css');
            if (el) el.remove();
        };
    }, [
        collection.customCss,
        collection.docsColors
    ]);
    // Apply default theme from theme.json on initial load
    // Use a ref to track if we've already applied the default theme
    const hasAppliedDefaultTheme = useRef(false);
    useEffect(()=>{
        if (collection?.defaultTheme && !hasAppliedDefaultTheme.current) {
            setTheme(collection.defaultTheme);
            hasAppliedDefaultTheme.current = true;
        }
    }, [
        collection?.defaultTheme,
        setTheme
    ]);
    return /*#__PURE__*/ _jsxs("div", {
        className: "docs-viewer-root flex flex-col h-screen overflow-hidden",
        children: [
            collection.notice && /*#__PURE__*/ _jsx(Notice, {
                config: collection.notice,
                storageKey: "docs-notice"
            }),
            /*#__PURE__*/ _jsx(SearchDialog, {
                open: searchOpen,
                onOpenChange: setSearchOpen,
                items: searchItems,
                onSelect: handleSearchSelect
            }),
            /*#__PURE__*/ _jsx(DocsHeader, {
                docGroups: collection.docGroups,
                navigationTabs: collection.navigationTabs,
                activeTab: activeTab,
                onTabChange: onTabChange,
                hasEndpoints: hasEndpoints,
                docsName: collection.docsName,
                docsLogo: collection.docsLogo,
                onSearchClick: openSearch,
                docsHeader: collection.docsHeader,
                docsNavbar: collection.docsNavbar
            }),
            /*#__PURE__*/ _jsxs("div", {
                className: cn("docs-layout flex flex-1 overflow-hidden relative z-0 min-h-0", "transition-[margin] duration-300 ease-in-out", // Push content left when agent panel is open (only on larger screens)
                isRightSidebarOpen && "lg:mr-96"),
                children: [
                    !showChangelog && /*#__PURE__*/ _jsx(DocsSidebar, {
                        collection: {
                            ...collection,
                            // Show GraphQL operations when GraphQL tab is active, else show REST endpoints
                            folders: showGraphQL && graphqlCollection ? graphqlCollection.folders : showEndpoints ? collection.folders : [],
                            requests: showGraphQL && graphqlCollection ? graphqlCollection.requests : showEndpoints ? collection.requests : [],
                            // Only show filtered doc groups
                            docGroups: filteredDocGroups
                        },
                        selectedRequest: showGraphQL ? selectedGraphQLOperation ? {
                            id: selectedGraphQLOperation.id
                        } : null : selectedRequest,
                        selectedDocSection: selectedDocSection,
                        selectedDocPage: selectedDocPage,
                        activeTab: activeTab,
                        onSelectRequest: showGraphQL ? handleSelectGraphQLOperation : handleSelectRequest,
                        onSelectDocumentation: handleSelectDocumentation,
                        onSelectDocPage: handleSelectDocPage,
                        apiVersions: collection.apiVersions,
                        selectedApiVersion: selectedApiVersion,
                        onApiVersionChange: handleApiVersionChange,
                        isVersionLoading: isVersionLoading
                    }),
                    /*#__PURE__*/ _jsxs("div", {
                        className: "docs-main flex-1 flex flex-col overflow-hidden",
                        style: {
                            minWidth: 0,
                            flexBasis: 0,
                            flexGrow: 1
                        },
                        children: [
                            /*#__PURE__*/ _jsx("div", {
                                className: "docs-main-header flex items-center justify-end px-3 sm:px-4 h-[41px] border-b border-border bg-muted/30 flex-shrink-0",
                                children: /*#__PURE__*/ _jsx(ModeToggleTabs, {
                                    hasEndpoint: !!selectedRequest
                                })
                            }),
                            mode === 'docs' ? /*#__PURE__*/ _jsx(DocsNavigationProvider, {
                                onNavigateToPage: handleSelectDocPage,
                                onSwitchTab: onTabChange,
                                activeTab: activeTab,
                                children: /*#__PURE__*/ _jsx("div", {
                                    ref: contentRef,
                                    className: cn("docs-content-area flex-1 bg-background min-w-0", showChangelog || showGraphQL && selectedGraphQLOperation && !selectedDocPage ? "overflow-hidden flex flex-col" : "overflow-y-auto scroll-smooth"),
                                    children: showGraphQL && selectedGraphQLOperation && !selectedDocPage ? /*#__PURE__*/ _jsx("div", {
                                        className: "flex-1 flex flex-col h-full",
                                        children: /*#__PURE__*/ _jsx(GraphQLPlayground, {
                                            endpoint: activeGraphQLSchemas[0]?.endpoint || '',
                                            defaultQuery: selectedGraphQLOperation?.query,
                                            operations: graphqlOperations,
                                            selectedOperationId: selectedGraphQLOperation?.id,
                                            hideExplorer: true,
                                            headers: {},
                                            theme: "dark",
                                            schemaSDL: graphqlSchemaSDL
                                        })
                                    }) : showChangelog ? /*#__PURE__*/ _jsx(ChangelogPage, {
                                        releases: collection.changelogReleases || [],
                                        tabName: activeTabConfig?.tab
                                    }) : selectedRequest ? /*#__PURE__*/ _jsx(RequestDetails, {
                                        request: selectedRequest
                                    }) : selectedDocPage ? /*#__PURE__*/ _jsx(DocPage, {
                                        slug: selectedDocPage,
                                        onSearch: openSearch
                                    }) : notFoundSlug ? /*#__PURE__*/ _jsx(NotFoundPage, {
                                        slug: notFoundSlug,
                                        onSearch: openSearch
                                    }) : /*#__PURE__*/ _jsx("div", {
                                        className: "flex-1 flex items-center justify-center bg-background",
                                        children: /*#__PURE__*/ _jsxs("div", {
                                            className: "text-center text-muted-foreground",
                                            children: [
                                                /*#__PURE__*/ _jsx(Book, {
                                                    className: "h-12 w-12 mx-auto mb-3 opacity-40"
                                                }),
                                                /*#__PURE__*/ _jsx("p", {
                                                    className: "text-sm",
                                                    children: "Select an endpoint from the sidebar"
                                                })
                                            ]
                                        })
                                    })
                                })
                            }) : mode === 'notes' ? /*#__PURE__*/ _jsx("div", {
                                className: "flex-1 flex flex-col min-h-0 overflow-hidden",
                                children: /*#__PURE__*/ _jsx(NotesMode, {
                                    apiSpecUrl: apiSpecUrl,
                                    apiName: collection.name
                                })
                            }) : selectedRequest ? /*#__PURE__*/ _jsx("div", {
                                className: "flex-1 flex flex-col min-h-0 overflow-hidden",
                                children: /*#__PURE__*/ _jsx(ApiPlayground, {
                                    request: selectedRequest,
                                    onDebugRequest: handleDebugRequest,
                                    onExplainRequest: handleExplainRequest
                                })
                            }) : /*#__PURE__*/ _jsx("div", {
                                className: "flex-1 flex items-center justify-center bg-background",
                                children: /*#__PURE__*/ _jsxs("div", {
                                    className: "text-center text-muted-foreground",
                                    children: [
                                        /*#__PURE__*/ _jsx(TestTube, {
                                            className: "h-12 w-12 mx-auto mb-3 opacity-40"
                                        }),
                                        /*#__PURE__*/ _jsx("p", {
                                            className: "text-sm",
                                            children: "Select an endpoint from the sidebar to test"
                                        })
                                    ]
                                })
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsx(RightSidebar, {
                        request: selectedRequest,
                        collection: collection,
                        apiSummary: collection.apiSummary,
                        onNavigateToEndpoint: handleAgentNavigateWithModeSwitch,
                        onPrefillParameters: handleAgentPrefill,
                        debugContext: debugContext,
                        onClearDebugContext: clearDebugContext,
                        explainContext: explainContext,
                        onClearExplainContext: clearExplainContext,
                        onOpenGlobalAuth: ()=>setShowAuthModal(true),
                        onNavigateToAuthTab: ()=>{
                            navigateAndHighlight('auth', {
                                type: 'auth'
                            }, true);
                        },
                        onNavigateToParamsTab: ()=>{
                            navigateAndHighlight('params', {
                                type: 'param'
                            }, true);
                        },
                        onNavigateToBodyTab: ()=>{
                            navigateAndHighlight('body', {
                                type: 'body'
                            }, true);
                        },
                        onNavigateToHeadersTab: ()=>{
                            navigateAndHighlight('headers', {
                                type: 'header'
                            }, true);
                        },
                        onNavigateToDocSection: handleSelectDocumentation,
                        onNavigateToDocPage: handleSelectDocPage
                    })
                ]
            }),
            /*#__PURE__*/ _jsx(GlobalAuthModal, {
                open: showAuthModal,
                onClose: ()=>setShowAuthModal(false)
            }),
            !isRightSidebarOpen && /*#__PURE__*/ _jsx(AgentPopupButton, {
                onClick: openRightSidebar,
                currentEndpoint: selectedRequest ? {
                    id: selectedRequest.id,
                    name: selectedRequest.name
                } : null,
                endpointIndex: endpointIndex
            })
        ]
    });
}
// Wrapper component with providers
export function Docs() {
    return /*#__PURE__*/ _jsx(AuthProvider, {
        children: /*#__PURE__*/ _jsx(ModeProvider, {
            children: /*#__PURE__*/ _jsx(PlaygroundProvider, {
                children: /*#__PURE__*/ _jsx(PlaygroundNavigationProvider, {
                    children: /*#__PURE__*/ _jsx(DocsContent, {})
                })
            })
        })
    });
}
