'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import { MagnifyingGlass, CaretRight, CaretDown, ArrowSquareOut, X } from '@phosphor-icons/react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import * as PhosphorIcons from '@phosphor-icons/react';
/**
 * Docs Sidebar Navigation Component
 * 
 * Matches the API docs sidebar styling for visual consistency
 */ // Dynamic icon resolver
function getIcon(iconName) {
    if (!iconName) return null;
    const pascalCase = iconName.split(/[-_]/).map((word)=>word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join('');
    const Icon = PhosphorIcons[pascalCase];
    return Icon || null;
}
// Helper to check if item is a NavItem (has href)
function isNavItem(item) {
    return 'href' in item && typeof item.href === 'string';
}
// Recursively check if any item matches the path
function hasMatchingItem(items, path) {
    for (const item of items){
        if (isNavItem(item)) {
            if (item.href === path || path.startsWith(item.href + '/')) {
                return true;
            }
        }
        if ('items' in item && Array.isArray(item.items)) {
            if (hasMatchingItem(item.items, path)) {
                return true;
            }
        }
    }
    return false;
}
// Filter navigation based on search query
function filterNavigation(navigation, query) {
    if (!query.trim()) return navigation;
    const lowerQuery = query.toLowerCase();
    const filterItems = (items)=>{
        return items.reduce((acc, item)=>{
            if (isNavItem(item)) {
                if (item.title.toLowerCase().includes(lowerQuery)) {
                    acc.push(item);
                }
            } else {
                // It's a NavGroup
                const filteredNestedItems = filterItems(item.items);
                if (filteredNestedItems.length > 0 || item.title.toLowerCase().includes(lowerQuery)) {
                    acc.push({
                        ...item,
                        items: filteredNestedItems.length > 0 ? filteredNestedItems : item.items
                    });
                }
            }
            return acc;
        }, []);
    };
    const filterGroups = (groups)=>{
        return groups.reduce((acc, group)=>{
            const filteredItems = filterItems(group.items);
            if (filteredItems.length > 0 || group.title.toLowerCase().includes(lowerQuery)) {
                acc.push({
                    ...group,
                    items: filteredItems.length > 0 ? filteredItems : group.items
                });
            }
            return acc;
        }, []);
    };
    return {
        tabs: navigation.tabs?.map((tab)=>({
                ...tab,
                groups: filterGroups(tab.groups)
            })).filter((tab)=>tab.groups.length > 0),
        groups: navigation.groups ? filterGroups(navigation.groups) : undefined,
        anchors: navigation.anchors
    };
}
export function DocsSidebar({ navigation, siteName = 'Documentation', className, isMobile = false, isOpen = true, onClose }) {
    const pathname = usePathname();
    const [searchQuery, setSearchQuery] = useState('');
    const [activeTab, setActiveTab] = useState(navigation.tabs?.[0]?.slug || '');
    // Filter navigation based on search
    const filteredNav = useMemo(()=>filterNavigation(navigation, searchQuery), [
        navigation,
        searchQuery
    ]);
    // Find active tab from current path
    React.useEffect(()=>{
        if (navigation.tabs) {
            for (const tab of navigation.tabs){
                for (const group of tab.groups){
                    if (hasMatchingItem(group.items, pathname)) {
                        setActiveTab(tab.slug);
                        return;
                    }
                }
            }
        }
    }, [
        pathname,
        navigation.tabs
    ]);
    const currentTabData = filteredNav.tabs?.find((t)=>t.slug === activeTab);
    const groups = currentTabData?.groups || filteredNav.groups || [];
    return /*#__PURE__*/ _jsxs(_Fragment, {
        children: [
            isMobile && isOpen && /*#__PURE__*/ _jsx("div", {
                className: "fixed inset-0 bg-black/50 z-[55] lg:hidden",
                onClick: onClose
            }),
            /*#__PURE__*/ _jsxs("aside", {
                className: cn("flex flex-col border-r bg-sidebar border-sidebar-border overflow-hidden", // Desktop: always visible, fixed width
                "lg:relative lg:w-72 lg:h-full lg:z-auto", // Mobile: drawer behavior - z-[60] to appear above header (z-50)
                "fixed inset-y-0 left-0 z-[60] w-[280px] h-full", "transform transition-transform duration-300 ease-in-out", "lg:transform-none lg:translate-x-0", isMobile && !isOpen && "-translate-x-full", isMobile && isOpen && "translate-x-0", className),
                children: [
                    /*#__PURE__*/ _jsxs("div", {
                        className: "px-4 h-[41px] flex items-center justify-between border-b border-sidebar-border shrink-0",
                        children: [
                            /*#__PURE__*/ _jsx("h2", {
                                className: "text-sm font-semibold text-sidebar-foreground truncate",
                                children: siteName
                            }),
                            isMobile && /*#__PURE__*/ _jsx(Button, {
                                variant: "ghost",
                                size: "icon",
                                onClick: onClose,
                                className: "h-7 w-7 lg:hidden",
                                children: /*#__PURE__*/ _jsx(X, {
                                    className: "h-4 w-4",
                                    weight: "bold"
                                })
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsx("div", {
                        className: "px-3 py-2 border-b border-sidebar-border shrink-0",
                        children: /*#__PURE__*/ _jsxs("div", {
                            className: "relative",
                            children: [
                                /*#__PURE__*/ _jsx(MagnifyingGlass, {
                                    className: "absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground/60"
                                }),
                                /*#__PURE__*/ _jsx(Input, {
                                    type: "text",
                                    placeholder: "Search...",
                                    value: searchQuery,
                                    onChange: (e)=>setSearchQuery(e.target.value),
                                    className: "w-full pl-8 h-8 text-sm bg-muted/40 border-0 focus-visible:ring-1 focus-visible:ring-border placeholder:text-muted-foreground/50"
                                }),
                                searchQuery && /*#__PURE__*/ _jsx("button", {
                                    onClick: ()=>setSearchQuery(''),
                                    className: "absolute right-2 top-1/2 transform -translate-y-1/2 text-muted-foreground/60 hover:text-muted-foreground",
                                    children: /*#__PURE__*/ _jsx("span", {
                                        className: "text-xs",
                                        children: "✕"
                                    })
                                })
                            ]
                        })
                    }),
                    filteredNav.tabs && filteredNav.tabs.length > 1 && /*#__PURE__*/ _jsx("div", {
                        className: "flex border-b border-sidebar-border px-2 py-1 gap-1 shrink-0",
                        children: filteredNav.tabs.map((tab)=>/*#__PURE__*/ _jsx("button", {
                                onClick: ()=>setActiveTab(tab.slug),
                                className: cn('px-3 py-1.5 text-xs font-medium rounded-md transition-colors', activeTab === tab.slug ? 'bg-sidebar-primary text-sidebar-primary-foreground' : 'text-sidebar-foreground/70 hover:text-sidebar-foreground hover:bg-sidebar-accent/50'),
                                children: tab.title
                            }, tab.slug))
                    }),
                    /*#__PURE__*/ _jsx("div", {
                        className: "flex-1 overflow-y-auto overflow-x-hidden",
                        children: groups.map((group, index)=>/*#__PURE__*/ _jsx(DocsSidebarSection, {
                                title: group.title,
                                className: index > 0 ? 'border-t border-sidebar-border' : '',
                                children: group.items.map((item, itemIndex)=>{
                                    // Handle nested NavGroup
                                    if (!isNavItem(item)) {
                                        return /*#__PURE__*/ _jsx(DocsSidebarNestedGroup, {
                                            group: item,
                                            pathname: pathname,
                                            onItemSelect: ()=>isMobile && onClose?.()
                                        }, `group-${item.title}-${itemIndex}`);
                                    }
                                    return /*#__PURE__*/ _jsx(DocsSidebarItem, {
                                        item: item,
                                        selected: item.href === pathname,
                                        onSelect: ()=>isMobile && onClose?.()
                                    }, `${item.href}-${itemIndex}`);
                                })
                            }, `${group.title}-${index}`))
                    }),
                    filteredNav.anchors && filteredNav.anchors.length > 0 && /*#__PURE__*/ _jsx("div", {
                        className: "border-t border-sidebar-border px-2 py-2 shrink-0",
                        children: filteredNav.anchors.map((anchor, index)=>/*#__PURE__*/ _jsx(DocsSidebarItem, {
                                item: anchor,
                                selected: false
                            }, `anchor-${index}`))
                    })
                ]
            })
        ]
    });
}
function DocsSidebarSection({ title, children, className }) {
    return /*#__PURE__*/ _jsxs("div", {
        className: cn('flex flex-col', className),
        children: [
            /*#__PURE__*/ _jsx("div", {
                className: "px-4 py-2.5",
                children: /*#__PURE__*/ _jsx("span", {
                    className: "text-[11px] font-semibold text-sidebar-foreground/60 uppercase tracking-wider",
                    children: title
                })
            }),
            /*#__PURE__*/ _jsx("ul", {
                className: "flex flex-col gap-px px-2 pb-2",
                children: children
            })
        ]
    });
}
function DocsSidebarNestedGroup({ group, pathname, onItemSelect }) {
    const hasActiveChild = hasMatchingItem(group.items, pathname);
    const [isOpen, setIsOpen] = React.useState(hasActiveChild);
    return /*#__PURE__*/ _jsxs("li", {
        className: "mb-1",
        children: [
            /*#__PURE__*/ _jsxs("button", {
                type: "button",
                onClick: ()=>setIsOpen(!isOpen),
                className: cn("flex items-center justify-between w-full py-1.5 px-2 text-sm rounded-md transition-colors", hasActiveChild ? "text-sidebar-foreground font-medium" : "text-sidebar-foreground/70 hover:text-sidebar-foreground hover:bg-sidebar-accent/50"),
                children: [
                    /*#__PURE__*/ _jsxs("span", {
                        className: "flex items-center gap-2",
                        children: [
                            group.icon && (()=>{
                                const Icon = getIcon(group.icon);
                                return Icon ? /*#__PURE__*/ _jsx(Icon, {
                                    className: "w-4 h-4"
                                }) : null;
                            })(),
                            group.title
                        ]
                    }),
                    /*#__PURE__*/ _jsx(CaretRight, {
                        className: cn("w-4 h-4 transition-transform", isOpen && "rotate-90")
                    })
                ]
            }),
            isOpen && /*#__PURE__*/ _jsx("ul", {
                className: "ml-4 pl-2 border-l border-sidebar-border space-y-0.5 mt-1",
                children: group.items.map((item, idx)=>{
                    if (!isNavItem(item)) {
                        return /*#__PURE__*/ _jsx(DocsSidebarNestedGroup, {
                            group: item,
                            pathname: pathname,
                            onItemSelect: onItemSelect
                        }, `nested-group-${item.title}-${idx}`);
                    }
                    return /*#__PURE__*/ _jsx(DocsSidebarItem, {
                        item: item,
                        selected: item.href === pathname,
                        onSelect: onItemSelect
                    }, `${item.href}-${idx}`);
                })
            })
        ]
    });
}
function DocsSidebarItem({ item, selected, indent = 0, onSelect }) {
    const Icon = item.icon ? getIcon(item.icon) : null;
    const content = /*#__PURE__*/ _jsxs(_Fragment, {
        children: [
            Icon && /*#__PURE__*/ _jsx(Icon, {
                className: cn('h-4 w-4 shrink-0 mr-2', selected ? 'text-sidebar-primary-foreground' : 'text-sidebar-foreground/60'),
                weight: selected ? 'fill' : 'regular'
            }),
            /*#__PURE__*/ _jsx("span", {
                className: "flex-1 truncate",
                children: item.title
            }),
            item.external && /*#__PURE__*/ _jsx(ArrowSquareOut, {
                className: "h-3 w-3 shrink-0 ml-1 text-sidebar-foreground/40"
            }),
            item.badge && /*#__PURE__*/ _jsx("span", {
                className: "ml-2 px-1.5 py-0.5 text-[10px] font-medium rounded bg-sidebar-primary/10 text-sidebar-primary",
                children: item.badge
            }),
            item.deprecated && /*#__PURE__*/ _jsx("span", {
                className: "ml-2 px-1.5 py-0.5 text-[10px] font-medium rounded bg-amber-500/10 text-amber-600 dark:text-amber-400",
                children: "deprecated"
            })
        ]
    });
    const className = cn('group/button flex items-center rounded-sm px-3 py-1.5 w-full text-left', 'text-sm leading-5 transition-colors duration-150', selected ? 'bg-sidebar-primary text-sidebar-primary-foreground font-medium' : 'text-sidebar-foreground hover:bg-sidebar-accent/50 hover:text-sidebar-accent-foreground');
    const style = indent > 0 ? {
        paddingLeft: `${indent * 12 + 12}px`
    } : undefined;
    if (item.external) {
        return /*#__PURE__*/ _jsx("li", {
            className: "flex flex-col",
            children: /*#__PURE__*/ _jsx("a", {
                href: item.href,
                target: "_blank",
                rel: "noopener noreferrer",
                className: className,
                style: style,
                children: content
            })
        });
    }
    return /*#__PURE__*/ _jsx("li", {
        className: "flex flex-col",
        children: /*#__PURE__*/ _jsx(Link, {
            href: item.href,
            className: className,
            style: style,
            onClick: onSelect,
            children: content
        })
    });
}
export function DocsSidebarGroup({ title, items, icon, defaultOpen = false, currentPath, onItemSelect }) {
    const hasActiveItem = items.some((item)=>item.href === currentPath);
    const [isOpen, setIsOpen] = useState(defaultOpen || hasActiveItem);
    const Icon = icon ? getIcon(icon) : null;
    return /*#__PURE__*/ _jsxs("li", {
        className: "flex flex-col gap-px",
        children: [
            /*#__PURE__*/ _jsxs("button", {
                type: "button",
                "aria-expanded": isOpen,
                onClick: ()=>setIsOpen(!isOpen),
                className: cn('group/button flex items-center rounded-sm px-3 py-1.5 w-full text-left', 'text-sm leading-5 transition-colors duration-150', 'text-sidebar-foreground hover:bg-sidebar-accent/50 hover:text-sidebar-accent-foreground'),
                children: [
                    /*#__PURE__*/ _jsx("span", {
                        className: "mr-1.5 text-sidebar-foreground/60 group-hover/button:text-sidebar-foreground",
                        children: isOpen ? /*#__PURE__*/ _jsx(CaretDown, {
                            weight: "bold",
                            className: "h-3.5 w-3.5"
                        }) : /*#__PURE__*/ _jsx(CaretRight, {
                            weight: "bold",
                            className: "h-3.5 w-3.5"
                        })
                    }),
                    Icon && /*#__PURE__*/ _jsx(Icon, {
                        className: "h-4 w-4 mr-2 text-sidebar-foreground/60",
                        weight: "regular"
                    }),
                    /*#__PURE__*/ _jsx("span", {
                        className: "flex-1 truncate",
                        children: title
                    })
                ]
            }),
            isOpen && /*#__PURE__*/ _jsx("ul", {
                className: "flex flex-col gap-px",
                children: items.map((item, index)=>/*#__PURE__*/ _jsx(DocsSidebarItem, {
                        item: item,
                        selected: item.href === currentPath,
                        indent: 1,
                        onSelect: onItemSelect
                    }, `${item.href}-${index}`))
            })
        ]
    });
}
export { DocsSidebarSection, DocsSidebarItem };
