'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useRef } from 'react';
import { cn } from '@/lib/utils';
import { Play, ArrowClockwise, Copy, Check, Spinner, X, FileText, BracketsCurly, Key, CaretRight, CaretDown, MagnifyingGlass, Lightning, ArrowsClockwise } from '@phosphor-icons/react';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import Editor, { loader } from '@monaco-editor/react';
import { buildSchema } from 'graphql';
import { getAutocompleteSuggestions, CompletionItemKind } from 'graphql-language-service';
// Configure Monaco to load from CDN
loader.config({
    paths: {
        vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs'
    }
});
// Store parsed schema and completion provider disposable
let parsedSchema = null;
let completionProviderDisposable = null;
// Map graphql-language-service completion kinds to Monaco kinds
function toMonacoCompletionKind(kind, monaco) {
    const mKinds = monaco.languages.CompletionItemKind;
    switch(kind){
        case CompletionItemKind.Field:
            return mKinds.Field;
        case CompletionItemKind.Variable:
            return mKinds.Variable;
        case CompletionItemKind.Property:
            return mKinds.Property;
        case CompletionItemKind.EnumMember:
            return mKinds.EnumMember;
        case CompletionItemKind.Class:
            return mKinds.Class;
        case CompletionItemKind.Interface:
            return mKinds.Interface;
        case CompletionItemKind.Function:
            return mKinds.Function;
        case CompletionItemKind.Snippet:
            return mKinds.Snippet;
        case CompletionItemKind.Keyword:
            return mKinds.Keyword;
        case CompletionItemKind.Constant:
            return mKinds.Constant;
        case CompletionItemKind.Enum:
            return mKinds.Enum;
        default:
            return mKinds.Text;
    }
}
// Find fields already selected in the current selection set
function getExistingFieldsInSelectionSet(documentText, cursorOffset) {
    const existingFields = new Set();
    // Find the opening brace of the current selection set
    let braceCount = 0;
    let selectionSetStart = -1;
    for(let i = cursorOffset - 1; i >= 0; i--){
        const char = documentText[i];
        if (char === '}') braceCount++;
        if (char === '{') {
            if (braceCount === 0) {
                selectionSetStart = i;
                break;
            }
            braceCount--;
        }
    }
    if (selectionSetStart === -1) return existingFields;
    // Find the closing brace
    braceCount = 1;
    let selectionSetEnd = documentText.length;
    for(let i = selectionSetStart + 1; i < documentText.length; i++){
        const char = documentText[i];
        if (char === '{') braceCount++;
        if (char === '}') {
            braceCount--;
            if (braceCount === 0) {
                selectionSetEnd = i;
                break;
            }
        }
    }
    // Extract the selection set content
    const selectionSetContent = documentText.slice(selectionSetStart + 1, selectionSetEnd);
    // Parse field names - match field names that appear on their own or with arguments/aliases
    // Matches: fieldName, fieldName(args), alias: fieldName, ...fieldName
    const lines = selectionSetContent.split('\n');
    for (const line of lines){
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith('#')) continue; // Skip empty lines and comments
        // Match field name at start of line (possibly with alias)
        // Pattern: optionalAlias: fieldName or just fieldName
        const fieldMatch = trimmed.match(/^(?:\.\.\.)?(?:[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*)?([a-zA-Z_][a-zA-Z0-9_]*)/);
        if (fieldMatch) {
            const fieldName = fieldMatch[1];
            // Skip GraphQL keywords but include __typename
            if (![
                'query',
                'mutation',
                'subscription',
                'fragment',
                'on'
            ].includes(fieldName)) {
                existingFields.add(fieldName);
            }
        }
    }
    return existingFields;
}
// Register GraphQL completion provider using graphql-language-service
function registerGraphQLCompletionProvider(monaco, schema) {
    // Dispose previous provider if exists
    if (completionProviderDisposable) {
        completionProviderDisposable.dispose();
    }
    completionProviderDisposable = monaco.languages.registerCompletionItemProvider('graphql', {
        triggerCharacters: [
            '{',
            '(',
            ' ',
            ':',
            '$',
            '@',
            '.',
            '\n'
        ],
        provideCompletionItems: (model, position)=>{
            const documentText = model.getValue();
            const cursorOffset = model.getOffsetAt(position);
            // graphql-language-service Position interface
            const gqlPosition = {
                line: position.lineNumber - 1,
                character: position.column - 1,
                setLine: (line)=>{
                    gqlPosition.line = line;
                },
                setCharacter: (char)=>{
                    gqlPosition.character = char;
                },
                lessThanOrEqualTo: (other)=>{
                    return gqlPosition.line < other.line || gqlPosition.line === other.line && gqlPosition.character <= other.character;
                }
            };
            try {
                // Get completions from graphql-language-service
                const completions = getAutocompleteSuggestions(schema, documentText, gqlPosition);
                // Get existing fields in current selection set to filter them out
                const existingFields = getExistingFieldsInSelectionSet(documentText, cursorOffset);
                // Filter out already-selected fields (only for Field kind suggestions)
                const filteredCompletions = completions.filter((item)=>{
                    // Only filter out Field suggestions (kind = 5), keep keywords, types, etc.
                    if (item.kind === CompletionItemKind.Field) {
                        return !existingFields.has(item.label);
                    }
                    return true;
                });
                const word = model.getWordUntilPosition(position);
                const range = {
                    startLineNumber: position.lineNumber,
                    endLineNumber: position.lineNumber,
                    startColumn: word.startColumn,
                    endColumn: word.endColumn
                };
                const suggestions = filteredCompletions.map((item, index)=>({
                        label: item.label,
                        kind: toMonacoCompletionKind(item.kind, monaco),
                        insertText: item.insertText || item.label,
                        insertTextRules: item.insertText?.includes('$') ? monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet : undefined,
                        detail: item.detail || undefined,
                        documentation: item.documentation || undefined,
                        sortText: String(index).padStart(5, '0'),
                        range
                    }));
                return {
                    suggestions
                };
            } catch (err) {
                console.error('[GraphQL Playground] Completion error:', err);
                return {
                    suggestions: []
                };
            }
        }
    });
}
const STORAGE_KEY = 'brainfish-graphql-playground';
// ============================================================================
// Helpers
// ============================================================================
function loadStoredState() {
    if (typeof window === 'undefined') return null;
    try {
        const stored = localStorage.getItem(STORAGE_KEY);
        if (stored) return JSON.parse(stored);
    } catch  {}
    return null;
}
function saveStoredState(state) {
    if (typeof window === 'undefined') return;
    try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
    } catch  {}
}
function SchemaExplorer({ operations, onSelectOperation, selectedOperationId }) {
    const [searchQuery, setSearchQuery] = useState('');
    const [expandedSections, setExpandedSections] = useState({
        query: true,
        mutation: true,
        subscription: true
    });
    // Group operations by type
    const queries = operations.filter((op)=>op.operationType === 'query');
    const mutations = operations.filter((op)=>op.operationType === 'mutation');
    const subscriptions = operations.filter((op)=>op.operationType === 'subscription');
    // Filter by search
    const filterOps = (ops)=>{
        if (!searchQuery.trim()) return ops;
        const query = searchQuery.toLowerCase();
        return ops.filter((op)=>op.name.toLowerCase().includes(query) || op.description?.toLowerCase().includes(query));
    };
    const filteredQueries = filterOps(queries);
    const filteredMutations = filterOps(mutations);
    const filteredSubscriptions = filterOps(subscriptions);
    const toggleSection = (section)=>{
        setExpandedSections((prev)=>({
                ...prev,
                [section]: !prev[section]
            }));
    };
    const renderSection = (title, icon, ops, sectionKey, iconColor)=>{
        if (ops.length === 0) return null;
        const isExpanded = expandedSections[sectionKey];
        return /*#__PURE__*/ _jsxs("div", {
            className: "mb-2",
            children: [
                /*#__PURE__*/ _jsxs("button", {
                    onClick: ()=>toggleSection(sectionKey),
                    className: "w-full flex items-center gap-2 px-3 py-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground hover:bg-muted/50 transition-colors",
                    children: [
                        isExpanded ? /*#__PURE__*/ _jsx(CaretDown, {
                            className: "w-3 h-3"
                        }) : /*#__PURE__*/ _jsx(CaretRight, {
                            className: "w-3 h-3"
                        }),
                        /*#__PURE__*/ _jsx("span", {
                            className: iconColor,
                            children: icon
                        }),
                        /*#__PURE__*/ _jsx("span", {
                            children: title
                        }),
                        /*#__PURE__*/ _jsx("span", {
                            className: "ml-auto text-[10px] font-normal opacity-60",
                            children: ops.length
                        })
                    ]
                }),
                isExpanded && /*#__PURE__*/ _jsx("div", {
                    className: "ml-2",
                    children: ops.map((op)=>/*#__PURE__*/ _jsx("button", {
                            onClick: ()=>onSelectOperation(op),
                            className: cn('w-full flex items-start gap-2 px-3 py-2 text-left', 'hover:bg-muted/50 transition-colors rounded-sm', 'border-l-2', selectedOperationId === op.id ? 'bg-muted/70 border-primary' : 'border-transparent'),
                            children: /*#__PURE__*/ _jsxs("div", {
                                className: "flex-1 min-w-0",
                                children: [
                                    /*#__PURE__*/ _jsx("div", {
                                        className: "text-sm font-medium truncate",
                                        children: op.name
                                    }),
                                    op.description && /*#__PURE__*/ _jsx("div", {
                                        className: "text-xs text-muted-foreground truncate mt-0.5",
                                        children: op.description
                                    })
                                ]
                            })
                        }, op.id))
                })
            ]
        });
    };
    const hasOperations = operations.length > 0;
    const hasFilteredResults = filteredQueries.length > 0 || filteredMutations.length > 0 || filteredSubscriptions.length > 0;
    return /*#__PURE__*/ _jsxs("div", {
        className: "flex flex-col h-full border-r border-border bg-muted/20",
        children: [
            /*#__PURE__*/ _jsx("div", {
                className: "p-2 border-b border-border",
                children: /*#__PURE__*/ _jsxs("div", {
                    className: "relative",
                    children: [
                        /*#__PURE__*/ _jsx(MagnifyingGlass, {
                            className: "absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"
                        }),
                        /*#__PURE__*/ _jsx("input", {
                            type: "text",
                            value: searchQuery,
                            onChange: (e)=>setSearchQuery(e.target.value),
                            placeholder: "Search operations...",
                            className: cn('w-full pl-8 pr-3 py-1.5 text-sm rounded-md', 'bg-background border border-border', 'focus:outline-none focus:ring-1 focus:ring-primary', 'placeholder:text-muted-foreground')
                        })
                    ]
                })
            }),
            /*#__PURE__*/ _jsx("div", {
                className: "flex-1 overflow-y-auto py-2",
                children: !hasOperations ? /*#__PURE__*/ _jsxs("div", {
                    className: "flex flex-col items-center justify-center h-full px-4 text-center",
                    children: [
                        /*#__PURE__*/ _jsx(FileText, {
                            className: "w-8 h-8 text-muted-foreground/50 mb-2"
                        }),
                        /*#__PURE__*/ _jsx("p", {
                            className: "text-sm text-muted-foreground",
                            children: "No schema loaded"
                        }),
                        /*#__PURE__*/ _jsx("p", {
                            className: "text-xs text-muted-foreground/60 mt-1",
                            children: "Operations will appear here"
                        })
                    ]
                }) : !hasFilteredResults ? /*#__PURE__*/ _jsx("div", {
                    className: "flex flex-col items-center justify-center h-32 px-4 text-center",
                    children: /*#__PURE__*/ _jsx("p", {
                        className: "text-sm text-muted-foreground",
                        children: "No matching operations"
                    })
                }) : /*#__PURE__*/ _jsxs(_Fragment, {
                    children: [
                        renderSection('Queries', /*#__PURE__*/ _jsx(MagnifyingGlass, {
                            className: "w-3.5 h-3.5",
                            weight: "bold"
                        }), filteredQueries, 'query', 'text-blue-500'),
                        renderSection('Mutations', /*#__PURE__*/ _jsx(Lightning, {
                            className: "w-3.5 h-3.5",
                            weight: "bold"
                        }), filteredMutations, 'mutation', 'text-orange-500'),
                        renderSection('Subscriptions', /*#__PURE__*/ _jsx(ArrowsClockwise, {
                            className: "w-3.5 h-3.5",
                            weight: "bold"
                        }), filteredSubscriptions, 'subscription', 'text-purple-500')
                    ]
                })
            })
        ]
    });
}
// ============================================================================
// Main Component
// ============================================================================
export function GraphQLPlayground({ endpoint, defaultQuery = `# Welcome to the GraphQL Playground!
#
# Select an operation from the sidebar, or
# type your query below and press Ctrl+Enter

query {
  __typename
}
`, headers: defaultHeaders = {}, operations = [], selectedOperationId: externalSelectedId, hideExplorer = false, className, theme = 'dark', schemaSDL }) {
    const [query, setQuery] = useState(defaultQuery);
    const [variables, setVariables] = useState('{}');
    const [customHeaders, setCustomHeaders] = useState(Object.keys(defaultHeaders).length > 0 ? JSON.stringify(defaultHeaders, null, 2) : '{}');
    const [response, setResponse] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [copied, setCopied] = useState(false);
    const [activeTab, setActiveTab] = useState('variables');
    const [responseTime, setResponseTime] = useState(null);
    const [internalSelectedId, setInternalSelectedId] = useState();
    // Use external selection if provided, otherwise use internal
    const selectedOperationId = externalSelectedId ?? internalSelectedId;
    const abortControllerRef = useRef(null);
    const hasLoadedRef = useRef(false);
    const monacoRef = useRef(null);
    // Initialize Monaco GraphQL when editor mounts
    const handleEditorDidMount = useCallback((editor, monaco)=>{
        monacoRef.current = monaco;
        // Parse schema and register completion provider
        if (schemaSDL) {
            try {
                parsedSchema = buildSchema(schemaSDL);
                registerGraphQLCompletionProvider(monaco, parsedSchema);
            } catch (err) {
                console.error('[GraphQL Playground] Failed to parse schema:', err);
            }
        }
    }, [
        schemaSDL
    ]);
    // Update completion provider when schema changes
    useEffect(()=>{
        if (schemaSDL && monacoRef.current) {
            try {
                parsedSchema = buildSchema(schemaSDL);
                registerGraphQLCompletionProvider(monacoRef.current, parsedSchema);
            } catch (err) {
                console.error('[GraphQL Playground] Failed to update schema:', err);
            }
        }
    }, [
        schemaSDL
    ]);
    // Load from localStorage on mount
    useEffect(()=>{
        const stored = loadStoredState();
        if (stored) {
            if (stored.query) setQuery(stored.query);
            if (stored.variables) setVariables(stored.variables);
            if (stored.headers) setCustomHeaders(stored.headers);
        }
        hasLoadedRef.current = true;
    }, []);
    // Save to localStorage when values change
    useEffect(()=>{
        if (!hasLoadedRef.current) return;
        const timeoutId = setTimeout(()=>{
            saveStoredState({
                query,
                variables,
                headers: customHeaders
            });
        }, 500);
        return ()=>clearTimeout(timeoutId);
    }, [
        query,
        variables,
        customHeaders
    ]);
    // Handle operation selection from sidebar (internal)
    const handleSelectOperation = useCallback((operation)=>{
        setQuery(operation.query);
        setInternalSelectedId(operation.id);
        // Set example variables if available
        if (operation.exampleVariables && Object.keys(operation.exampleVariables).length > 0) {
            setVariables(JSON.stringify(operation.exampleVariables, null, 2));
        } else {
            setVariables('{}');
        }
        // Clear previous response
        setResponse(null);
        setError(null);
        setResponseTime(null);
    }, []);
    // Sync with external selection (from main sidebar)
    useEffect(()=>{
        if (externalSelectedId && operations.length > 0) {
            const op = operations.find((o)=>o.id === externalSelectedId);
            if (op) {
                setQuery(op.query);
                if (op.exampleVariables && Object.keys(op.exampleVariables).length > 0) {
                    setVariables(JSON.stringify(op.exampleVariables, null, 2));
                } else {
                    setVariables('{}');
                }
                setResponse(null);
                setError(null);
                setResponseTime(null);
            }
        }
    }, [
        externalSelectedId,
        operations
    ]);
    // Execute GraphQL query
    const executeQuery = useCallback(async ()=>{
        setIsLoading(true);
        setError(null);
        setResponse(null);
        setResponseTime(null);
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }
        abortControllerRef.current = new AbortController();
        const startTime = performance.now();
        try {
            let parsedVariables = {};
            try {
                parsedVariables = variables.trim() && variables.trim() !== '{}' ? JSON.parse(variables) : {};
            } catch  {
                setError('Invalid JSON in variables');
                setIsLoading(false);
                return;
            }
            let parsedHeaders = {};
            try {
                parsedHeaders = customHeaders.trim() && customHeaders.trim() !== '{}' ? JSON.parse(customHeaders) : {};
            } catch  {
                setError('Invalid JSON in headers');
                setIsLoading(false);
                return;
            }
            const res = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                    ...defaultHeaders,
                    ...parsedHeaders
                },
                body: JSON.stringify({
                    query,
                    variables: parsedVariables
                }),
                signal: abortControllerRef.current.signal
            });
            const endTime = performance.now();
            setResponseTime(Math.round(endTime - startTime));
            const data = await res.json();
            setResponse(data);
        } catch (err) {
            if (err instanceof Error && err.name === 'AbortError') return;
            setError(err instanceof Error ? err.message : 'Request failed');
        } finally{
            setIsLoading(false);
        }
    }, [
        query,
        variables,
        customHeaders,
        endpoint,
        defaultHeaders
    ]);
    const handleCancel = useCallback(()=>{
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
            abortControllerRef.current = null;
        }
        setIsLoading(false);
    }, []);
    useEffect(()=>{
        const handleKeyDown = (e)=>{
            if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                e.preventDefault();
                if (!isLoading) executeQuery();
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return ()=>window.removeEventListener('keydown', handleKeyDown);
    }, [
        executeQuery,
        isLoading
    ]);
    const copyResponse = useCallback(()=>{
        if (response) {
            navigator.clipboard.writeText(JSON.stringify(response, null, 2));
            setCopied(true);
            setTimeout(()=>setCopied(false), 2000);
        }
    }, [
        response
    ]);
    const handleReset = useCallback(()=>{
        setQuery(defaultQuery);
        setVariables('{}');
        setCustomHeaders(Object.keys(defaultHeaders).length > 0 ? JSON.stringify(defaultHeaders, null, 2) : '{}');
        setResponse(null);
        setError(null);
        setResponseTime(null);
        setInternalSelectedId(undefined);
        localStorage.removeItem(STORAGE_KEY);
    }, [
        defaultQuery,
        defaultHeaders
    ]);
    const monacoTheme = theme === 'dark' ? 'vs-dark' : 'vs';
    const hasErrors = response?.errors && response.errors.length > 0;
    const statusColor = hasErrors ? 'text-red-400' : response ? 'text-emerald-400' : 'text-zinc-500';
    return /*#__PURE__*/ _jsx(TooltipProvider, {
        children: /*#__PURE__*/ _jsxs("div", {
            className: cn('flex flex-col h-full bg-background', className),
            children: [
                /*#__PURE__*/ _jsxs("div", {
                    className: "flex items-center justify-between gap-2 px-4 py-2 border-b border-border bg-muted/50",
                    children: [
                        /*#__PURE__*/ _jsx("div", {
                            className: "flex items-center gap-2",
                            children: /*#__PURE__*/ _jsxs("div", {
                                className: "hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-md bg-background border border-border",
                                children: [
                                    /*#__PURE__*/ _jsx("span", {
                                        className: "text-xs font-medium text-emerald-500",
                                        children: "POST"
                                    }),
                                    /*#__PURE__*/ _jsx("span", {
                                        className: "text-xs text-muted-foreground font-mono truncate max-w-[200px] md:max-w-[400px]",
                                        children: endpoint
                                    })
                                ]
                            })
                        }),
                        /*#__PURE__*/ _jsxs("div", {
                            className: "flex items-center gap-2",
                            children: [
                                /*#__PURE__*/ _jsx(Button, {
                                    onClick: isLoading ? handleCancel : executeQuery,
                                    variant: isLoading ? 'destructive' : 'default',
                                    size: "sm",
                                    className: "px-4",
                                    children: isLoading ? /*#__PURE__*/ _jsxs(_Fragment, {
                                        children: [
                                            /*#__PURE__*/ _jsx(X, {
                                                className: "h-4 w-4 mr-2",
                                                weight: "bold"
                                            }),
                                            "Cancel"
                                        ]
                                    }) : /*#__PURE__*/ _jsxs(_Fragment, {
                                        children: [
                                            /*#__PURE__*/ _jsx(Play, {
                                                className: "h-4 w-4 mr-2",
                                                weight: "fill"
                                            }),
                                            "Run"
                                        ]
                                    })
                                }),
                                /*#__PURE__*/ _jsxs(Tooltip, {
                                    children: [
                                        /*#__PURE__*/ _jsx(TooltipTrigger, {
                                            asChild: true,
                                            children: /*#__PURE__*/ _jsx(Button, {
                                                variant: "outline",
                                                size: "icon",
                                                onClick: handleReset,
                                                children: /*#__PURE__*/ _jsx(ArrowClockwise, {
                                                    className: "h-4 w-4",
                                                    weight: "bold"
                                                })
                                            })
                                        }),
                                        /*#__PURE__*/ _jsx(TooltipContent, {
                                            children: "Reset to defaults"
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                }),
                /*#__PURE__*/ _jsxs("div", {
                    className: "flex-1 flex overflow-hidden",
                    children: [
                        !hideExplorer && operations.length > 0 && /*#__PURE__*/ _jsx("div", {
                            className: "w-64 flex-shrink-0 hidden md:block",
                            children: /*#__PURE__*/ _jsx(SchemaExplorer, {
                                operations: operations,
                                onSelectOperation: handleSelectOperation,
                                selectedOperationId: selectedOperationId
                            })
                        }),
                        /*#__PURE__*/ _jsxs("div", {
                            className: "flex-1 flex flex-col lg:flex-row overflow-hidden",
                            children: [
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "flex-1 flex flex-col border-b lg:border-b-0 lg:border-r border-border min-h-[200px] lg:min-h-0",
                                    children: [
                                        /*#__PURE__*/ _jsxs("div", {
                                            className: "flex-1 flex flex-col min-h-0",
                                            children: [
                                                /*#__PURE__*/ _jsxs("div", {
                                                    className: "flex items-center px-3 py-2 border-b border-border bg-muted/30",
                                                    children: [
                                                        /*#__PURE__*/ _jsx(FileText, {
                                                            className: "h-4 w-4 mr-2 text-muted-foreground"
                                                        }),
                                                        /*#__PURE__*/ _jsx("span", {
                                                            className: "text-xs font-medium text-muted-foreground uppercase tracking-wider",
                                                            children: "Query"
                                                        }),
                                                        /*#__PURE__*/ _jsx("span", {
                                                            className: "ml-auto text-xs text-muted-foreground",
                                                            children: "Ctrl+Enter to run"
                                                        })
                                                    ]
                                                }),
                                                /*#__PURE__*/ _jsx("div", {
                                                    className: "flex-1 min-h-0",
                                                    children: /*#__PURE__*/ _jsx(Editor, {
                                                        height: "100%",
                                                        language: "graphql",
                                                        value: query,
                                                        onMount: handleEditorDidMount,
                                                        onChange: (value)=>{
                                                            setQuery(value || '');
                                                            setInternalSelectedId(undefined); // Clear internal selection when manually editing
                                                        },
                                                        theme: monacoTheme,
                                                        options: {
                                                            minimap: {
                                                                enabled: false
                                                            },
                                                            scrollBeyondLastLine: false,
                                                            fontSize: 13,
                                                            fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, monospace",
                                                            lineNumbers: 'on',
                                                            renderLineHighlight: 'line',
                                                            scrollbar: {
                                                                vertical: 'auto',
                                                                horizontal: 'auto'
                                                            },
                                                            padding: {
                                                                top: 12,
                                                                bottom: 12
                                                            },
                                                            wordWrap: 'on',
                                                            automaticLayout: true,
                                                            tabSize: 2,
                                                            quickSuggestions: true,
                                                            suggestOnTriggerCharacters: true
                                                        },
                                                        loading: /*#__PURE__*/ _jsxs("div", {
                                                            className: "flex items-center justify-center h-full text-muted-foreground text-sm",
                                                            children: [
                                                                /*#__PURE__*/ _jsx(Spinner, {
                                                                    className: "w-5 h-5 animate-spin mr-2"
                                                                }),
                                                                "Loading editor..."
                                                            ]
                                                        })
                                                    })
                                                })
                                            ]
                                        }),
                                        /*#__PURE__*/ _jsxs("div", {
                                            className: "border-t border-border h-[180px] flex flex-col",
                                            children: [
                                                /*#__PURE__*/ _jsxs("div", {
                                                    className: "flex border-b border-border bg-muted/30",
                                                    children: [
                                                        /*#__PURE__*/ _jsxs("button", {
                                                            onClick: ()=>setActiveTab('variables'),
                                                            className: cn('flex items-center gap-1.5 px-4 py-2 text-xs font-medium uppercase tracking-wider transition-colors', activeTab === 'variables' ? 'text-primary border-b-2 border-primary -mb-px bg-background' : 'text-muted-foreground hover:text-foreground'),
                                                            children: [
                                                                /*#__PURE__*/ _jsx(BracketsCurly, {
                                                                    className: "h-3.5 w-3.5"
                                                                }),
                                                                "Variables"
                                                            ]
                                                        }),
                                                        /*#__PURE__*/ _jsxs("button", {
                                                            onClick: ()=>setActiveTab('headers'),
                                                            className: cn('flex items-center gap-1.5 px-4 py-2 text-xs font-medium uppercase tracking-wider transition-colors', activeTab === 'headers' ? 'text-primary border-b-2 border-primary -mb-px bg-background' : 'text-muted-foreground hover:text-foreground'),
                                                            children: [
                                                                /*#__PURE__*/ _jsx(Key, {
                                                                    className: "h-3.5 w-3.5"
                                                                }),
                                                                "Headers"
                                                            ]
                                                        })
                                                    ]
                                                }),
                                                /*#__PURE__*/ _jsx("div", {
                                                    className: "flex-1 min-h-0",
                                                    children: /*#__PURE__*/ _jsx(Editor, {
                                                        height: "100%",
                                                        language: "json",
                                                        value: activeTab === 'variables' ? variables : customHeaders,
                                                        onChange: (value)=>activeTab === 'variables' ? setVariables(value || '{}') : setCustomHeaders(value || '{}'),
                                                        theme: monacoTheme,
                                                        options: {
                                                            minimap: {
                                                                enabled: false
                                                            },
                                                            scrollBeyondLastLine: false,
                                                            fontSize: 13,
                                                            fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, monospace",
                                                            lineNumbers: 'off',
                                                            renderLineHighlight: 'none',
                                                            scrollbar: {
                                                                vertical: 'auto',
                                                                horizontal: 'auto'
                                                            },
                                                            padding: {
                                                                top: 8,
                                                                bottom: 8
                                                            },
                                                            wordWrap: 'on',
                                                            automaticLayout: true,
                                                            tabSize: 2,
                                                            folding: false
                                                        },
                                                        loading: /*#__PURE__*/ _jsx("div", {
                                                            className: "flex items-center justify-center h-full text-muted-foreground text-sm",
                                                            children: "Loading..."
                                                        })
                                                    })
                                                })
                                            ]
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "flex-1 flex flex-col min-h-[200px] lg:min-h-0",
                                    children: [
                                        /*#__PURE__*/ _jsxs("div", {
                                            className: "flex items-center justify-between px-3 py-2 border-b border-border bg-muted/30",
                                            children: [
                                                /*#__PURE__*/ _jsxs("div", {
                                                    className: "flex items-center gap-3",
                                                    children: [
                                                        /*#__PURE__*/ _jsx("span", {
                                                            className: "text-xs font-medium text-muted-foreground uppercase tracking-wider",
                                                            children: "Response"
                                                        }),
                                                        responseTime !== null && /*#__PURE__*/ _jsxs("span", {
                                                            className: "text-xs text-muted-foreground",
                                                            children: [
                                                                responseTime,
                                                                "ms"
                                                            ]
                                                        }),
                                                        response && /*#__PURE__*/ _jsx("span", {
                                                            className: cn('text-xs font-medium', statusColor),
                                                            children: hasErrors ? 'Error' : 'Success'
                                                        })
                                                    ]
                                                }),
                                                response && /*#__PURE__*/ _jsxs(Tooltip, {
                                                    children: [
                                                        /*#__PURE__*/ _jsx(TooltipTrigger, {
                                                            asChild: true,
                                                            children: /*#__PURE__*/ _jsx(Button, {
                                                                variant: "ghost",
                                                                size: "sm",
                                                                onClick: copyResponse,
                                                                className: "h-7 px-2",
                                                                children: copied ? /*#__PURE__*/ _jsxs(_Fragment, {
                                                                    children: [
                                                                        /*#__PURE__*/ _jsx(Check, {
                                                                            className: "h-3.5 w-3.5 mr-1 text-emerald-500"
                                                                        }),
                                                                        /*#__PURE__*/ _jsx("span", {
                                                                            className: "text-xs",
                                                                            children: "Copied"
                                                                        })
                                                                    ]
                                                                }) : /*#__PURE__*/ _jsxs(_Fragment, {
                                                                    children: [
                                                                        /*#__PURE__*/ _jsx(Copy, {
                                                                            className: "h-3.5 w-3.5 mr-1"
                                                                        }),
                                                                        /*#__PURE__*/ _jsx("span", {
                                                                            className: "text-xs",
                                                                            children: "Copy"
                                                                        })
                                                                    ]
                                                                })
                                                            })
                                                        }),
                                                        /*#__PURE__*/ _jsx(TooltipContent, {
                                                            children: "Copy response"
                                                        })
                                                    ]
                                                })
                                            ]
                                        }),
                                        /*#__PURE__*/ _jsx("div", {
                                            className: "flex-1 min-h-0 overflow-hidden",
                                            children: isLoading ? /*#__PURE__*/ _jsxs("div", {
                                                className: "flex items-center justify-center h-full",
                                                children: [
                                                    /*#__PURE__*/ _jsx(Spinner, {
                                                        className: "w-6 h-6 animate-spin text-primary"
                                                    }),
                                                    /*#__PURE__*/ _jsx("span", {
                                                        className: "ml-2 text-sm text-muted-foreground",
                                                        children: "Executing query..."
                                                    })
                                                ]
                                            }) : error ? /*#__PURE__*/ _jsx("div", {
                                                className: "p-4",
                                                children: /*#__PURE__*/ _jsx("div", {
                                                    className: "p-4 bg-destructive/10 border border-destructive/20 rounded-lg",
                                                    children: /*#__PURE__*/ _jsx("p", {
                                                        className: "text-destructive text-sm font-mono",
                                                        children: error
                                                    })
                                                })
                                            }) : response ? /*#__PURE__*/ _jsx(Editor, {
                                                height: "100%",
                                                language: "json",
                                                value: JSON.stringify(response, null, 2),
                                                theme: monacoTheme,
                                                options: {
                                                    readOnly: true,
                                                    minimap: {
                                                        enabled: false
                                                    },
                                                    scrollBeyondLastLine: false,
                                                    fontSize: 13,
                                                    fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, monospace",
                                                    lineNumbers: 'on',
                                                    renderLineHighlight: 'none',
                                                    scrollbar: {
                                                        vertical: 'auto',
                                                        horizontal: 'auto'
                                                    },
                                                    padding: {
                                                        top: 12,
                                                        bottom: 12
                                                    },
                                                    wordWrap: 'on',
                                                    automaticLayout: true,
                                                    folding: true
                                                }
                                            }) : /*#__PURE__*/ _jsxs("div", {
                                                className: "flex flex-col items-center justify-center h-full text-muted-foreground",
                                                children: [
                                                    /*#__PURE__*/ _jsx(Play, {
                                                        className: "h-12 w-12 mb-3 opacity-20"
                                                    }),
                                                    /*#__PURE__*/ _jsx("p", {
                                                        className: "text-sm",
                                                        children: "Run a query to see results"
                                                    }),
                                                    /*#__PURE__*/ _jsx("p", {
                                                        className: "text-xs mt-1 opacity-60",
                                                        children: "Press Ctrl+Enter or click Run"
                                                    })
                                                ]
                                            })
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                })
            ]
        })
    });
}
export function GraphQLPlaygroundWithExplorer(props) {
    return /*#__PURE__*/ _jsx(GraphQLPlayground, {
        ...props
    });
}
export default GraphQLPlayground;
