'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, Children, isValidElement } from 'react';
import { cn } from '@/lib/utils';
import { Copy, Check } from '@phosphor-icons/react';
// Extract text content from nested React elements
function extractTextContent(node) {
    if (typeof node === 'string') return node;
    if (typeof node === 'number') return String(node);
    if (Array.isArray(node)) return node.map(extractTextContent).join('');
    if (/*#__PURE__*/ isValidElement(node)) {
        const props = node.props;
        if (props.children) {
            return extractTextContent(props.children);
        }
    }
    return '';
}
// Extract title from code comment on first line (e.g., "// npm" or "# yarn")
function extractTitleFromComment(code) {
    const firstLine = code.trim().split('\n')[0];
    // Match various comment styles
    const patterns = [
        /^\/\/\s*(.+)$/,
        /^#\s*(.+)$/,
        /^\/\*\s*(.+?)\s*\*\/$/,
        /^<!--\s*(.+?)\s*-->$/,
        /^--\s*(.+)$/
    ];
    for (const pattern of patterns){
        const match = firstLine.match(pattern);
        if (match && match[1] && match[1].length < 30) {
            return match[1].trim();
        }
    }
    return null;
}
// Check if element type matches a tag name (handles both string and component types)
function isElementType(element, tagName) {
    const type = element.type;
    if (typeof type === 'string') {
        return type === tagName;
    }
    // Check displayName or name for components
    if (typeof type === 'function') {
        const funcType = type;
        return funcType.displayName === tagName || funcType.name === tagName;
    }
    return false;
}
// Recursively find all pre elements
function findPreElements(children, results = []) {
    Children.forEach(children, (child)=>{
        if (!child) return;
        if (/*#__PURE__*/ isValidElement(child)) {
            const props = child.props;
            // Check if it's a pre element (either native or component)
            if (isElementType(child, 'pre')) {
                const codeChild = props.children;
                let language = 'text';
                let content = '';
                if (/*#__PURE__*/ isValidElement(codeChild)) {
                    const codeProps = codeChild.props;
                    const className = codeProps.className || '';
                    const match = className.match(/language-(\w+)/);
                    language = match ? match[1] : 'text';
                    content = extractTextContent(codeProps.children);
                } else if (typeof codeChild === 'string') {
                    content = codeChild;
                } else {
                    // Try to get content from nested structure
                    content = extractTextContent(codeChild);
                }
                // Also check pre element's className for language
                const preClassName = props.className || '';
                const preMatch = preClassName.match(/language-(\w+)/);
                if (preMatch) {
                    language = preMatch[1];
                }
                // Check data-language attribute
                if (props['data-language']) {
                    language = props['data-language'];
                }
                // Extract title from various possible locations
                // Priority: data-title > title prop > comment in code > language name
                const commentTitle = extractTitleFromComment(content);
                const title = props['data-title'] || props.title || commentTitle || getDisplayName(language);
                results.push({
                    title,
                    language,
                    content,
                    element: child
                });
            } else if (isElementType(child, 'figure') && props['data-rehype-pretty-code-figure'] !== undefined) {
                // Find pre inside figure
                findPreElements(props.children, results);
            } else if (props.children) {
                findPreElements(props.children, results);
            }
        }
    });
    return results;
}
// Get display name for language
function getDisplayName(language) {
    const displayNames = {
        javascript: 'JavaScript',
        typescript: 'TypeScript',
        python: 'Python',
        java: 'Java',
        go: 'Go',
        rust: 'Rust',
        ruby: 'Ruby',
        php: 'PHP',
        csharp: 'C#',
        cpp: 'C++',
        c: 'C',
        swift: 'Swift',
        kotlin: 'Kotlin',
        bash: 'Bash',
        shell: 'Shell',
        json: 'JSON',
        yaml: 'YAML',
        html: 'HTML',
        css: 'CSS',
        sql: 'SQL',
        markdown: 'Markdown',
        text: 'Text',
        plaintext: 'Text'
    };
    return displayNames[language.toLowerCase()] || language.charAt(0).toUpperCase() + language.slice(1);
}
export function CodeGroup({ children, className, variant = 'default' }) {
    const blocks = findPreElements(children);
    const [activeIndex, setActiveIndex] = useState(0);
    const [copied, setCopied] = useState(false);
    // If no code blocks found, just render children as-is
    if (blocks.length === 0) {
        return /*#__PURE__*/ _jsx("div", {
            className: className,
            children: children
        });
    }
    const activeBlock = blocks[activeIndex];
    const handleCopy = async ()=>{
        if (activeBlock?.content) {
            try {
                await navigator.clipboard.writeText(activeBlock.content.trim());
                setCopied(true);
                setTimeout(()=>setCopied(false), 2000);
            } catch (err) {
                console.error('Failed to copy:', err);
            }
        }
    };
    // Tabs variant - dark theme with border tabs
    if (variant === 'tabs') {
        return /*#__PURE__*/ _jsxs("div", {
            className: cn('docs-code-group docs-code-group-tabs my-4 rounded-xl border border-zinc-800 overflow-hidden bg-[#1a1a1a]', className),
            children: [
                /*#__PURE__*/ _jsxs("div", {
                    className: "docs-code-group-header flex items-center justify-between border-b border-zinc-800 bg-[#262626]",
                    children: [
                        /*#__PURE__*/ _jsx("div", {
                            className: "flex overflow-x-auto",
                            children: blocks.map((block, index)=>/*#__PURE__*/ _jsx("button", {
                                    type: "button",
                                    onClick: ()=>setActiveIndex(index),
                                    className: cn('docs-code-group-tab px-4 py-2.5 text-sm font-medium whitespace-nowrap transition-colors border-b-2 -mb-px', 'hover:text-white', 'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50', activeIndex === index ? 'text-white border-emerald-500' : 'text-zinc-400 border-transparent hover:border-zinc-600'),
                                    children: block.title
                                }, index))
                        }),
                        /*#__PURE__*/ _jsx("button", {
                            type: "button",
                            onClick: handleCopy,
                            className: cn('mr-3 p-1.5 rounded text-zinc-500 hover:text-zinc-300', 'hover:bg-zinc-700/50 transition-colors', 'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50'),
                            title: "Copy code",
                            children: copied ? /*#__PURE__*/ _jsx(Check, {
                                className: "h-4 w-4 text-emerald-500",
                                weight: "bold"
                            }) : /*#__PURE__*/ _jsx(Copy, {
                                className: "h-4 w-4"
                            })
                        })
                    ]
                }),
                /*#__PURE__*/ _jsx("div", {
                    className: cn('docs-code-group-content', '[&>pre]:my-0 [&>pre]:rounded-none [&>pre]:border-0 [&>pre]:bg-[#1a1a1a]', '[&_pre]:my-0 [&_pre]:rounded-none [&_pre]:border-0 [&_pre]:bg-[#1a1a1a]', '[&_code]:bg-transparent [&_pre]:p-4', '[&_pre]:text-sm [&_code]:text-sm'),
                    children: activeBlock?.element
                })
            ]
        });
    }
    // Pills variant - pill-shaped buttons with dark theme
    if (variant === 'pills') {
        return /*#__PURE__*/ _jsxs("div", {
            className: cn('docs-code-group docs-code-group-pills my-4 rounded-xl border border-zinc-800 overflow-hidden bg-[#1a1a1a]', className),
            children: [
                /*#__PURE__*/ _jsxs("div", {
                    className: "docs-code-group-header flex items-center justify-between p-2 bg-[#262626] border-b border-zinc-800",
                    children: [
                        /*#__PURE__*/ _jsx("div", {
                            className: "flex gap-1 overflow-x-auto",
                            children: blocks.map((block, index)=>/*#__PURE__*/ _jsx("button", {
                                    type: "button",
                                    onClick: ()=>setActiveIndex(index),
                                    className: cn('docs-code-group-tab px-3 py-1.5 text-xs font-medium whitespace-nowrap rounded-full transition-colors', 'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50', activeIndex === index ? 'bg-emerald-500 text-white' : 'text-zinc-400 hover:text-white hover:bg-zinc-700'),
                                    children: block.title
                                }, index))
                        }),
                        /*#__PURE__*/ _jsx("button", {
                            type: "button",
                            onClick: handleCopy,
                            className: cn('p-1.5 rounded text-zinc-500 hover:text-zinc-300', 'hover:bg-zinc-700/50 transition-colors', 'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50'),
                            title: "Copy code",
                            children: copied ? /*#__PURE__*/ _jsx(Check, {
                                className: "h-4 w-4 text-emerald-500",
                                weight: "bold"
                            }) : /*#__PURE__*/ _jsx(Copy, {
                                className: "h-4 w-4"
                            })
                        })
                    ]
                }),
                /*#__PURE__*/ _jsx("div", {
                    className: cn('docs-code-group-content', '[&>pre]:my-0 [&>pre]:rounded-none [&>pre]:border-0 [&>pre]:bg-[#1a1a1a]', '[&_pre]:my-0 [&_pre]:rounded-none [&_pre]:border-0 [&_pre]:bg-[#1a1a1a]', '[&_code]:bg-transparent [&_pre]:p-4', '[&_pre]:text-sm [&_code]:text-sm'),
                    children: activeBlock?.element
                })
            ]
        });
    }
    // Default variant - dark theme with underline indicator
    return /*#__PURE__*/ _jsxs("div", {
        className: cn('docs-code-group docs-code-group-default my-4 rounded-xl border border-zinc-800 overflow-hidden bg-[#1a1a1a]', className),
        children: [
            /*#__PURE__*/ _jsxs("div", {
                className: "docs-code-group-header flex items-center justify-between bg-[#262626] px-2",
                children: [
                    /*#__PURE__*/ _jsx("div", {
                        className: "flex overflow-x-auto",
                        children: blocks.map((block, index)=>/*#__PURE__*/ _jsxs("button", {
                                type: "button",
                                onClick: ()=>setActiveIndex(index),
                                className: cn('docs-code-group-tab px-4 py-2.5 text-sm font-medium whitespace-nowrap transition-colors relative', 'hover:text-white', 'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50', activeIndex === index ? 'text-white' : 'text-zinc-400'),
                                children: [
                                    block.title,
                                    activeIndex === index && /*#__PURE__*/ _jsx("span", {
                                        className: "absolute bottom-0 left-0 right-0 h-0.5 bg-emerald-500 rounded-full"
                                    })
                                ]
                            }, index))
                    }),
                    /*#__PURE__*/ _jsx("div", {
                        className: "docs-code-group-actions flex items-center gap-1 pr-2",
                        children: /*#__PURE__*/ _jsx("button", {
                            type: "button",
                            onClick: handleCopy,
                            className: cn('p-1.5 rounded text-zinc-500 hover:text-zinc-300', 'hover:bg-zinc-700/50 transition-colors', 'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50'),
                            title: "Copy code",
                            children: copied ? /*#__PURE__*/ _jsx(Check, {
                                className: "h-4 w-4 text-emerald-500",
                                weight: "bold"
                            }) : /*#__PURE__*/ _jsx(Copy, {
                                className: "h-4 w-4"
                            })
                        })
                    })
                ]
            }),
            /*#__PURE__*/ _jsx("div", {
                className: cn('docs-code-group-content', '[&>pre]:my-0 [&>pre]:rounded-none [&>pre]:border-0 [&>pre]:bg-[#1a1a1a]', '[&_pre]:my-0 [&_pre]:rounded-none [&_pre]:border-0 [&_pre]:bg-[#1a1a1a]', '[&_code]:bg-transparent [&_pre]:p-4', '[&_pre]:text-sm [&_code]:text-sm'),
                children: activeBlock?.element
            })
        ]
    });
}
export function CodeBlockItem({ children, title, language, className }) {
    return /*#__PURE__*/ _jsx("pre", {
        className: cn('p-4 overflow-x-auto', className),
        "data-title": title,
        "data-language": language,
        children: /*#__PURE__*/ _jsx("code", {
            className: language ? `language-${language}` : '',
            children: children
        })
    });
}
