'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useMemo, useEffect } from 'react';
import { Folder, FolderOpen } from '@phosphor-icons/react';
import { MethodBadge } from '../shared/method-badge';
import { SidebarItem } from './sidebar-item';
import { SidebarGroup } from './sidebar-group';
/**
 * Find the folder ID that contains a request (recursive)
 */ function _findFolderContainingRequest(collection, requestId) {
    // Check if request is directly in this collection's folders
    for (const folder of collection.folders){
        // Check direct requests in folder
        if (folder.requests.some((r)=>r.id === requestId)) {
            return folder.id;
        }
        // Check nested folders recursively
        const nestedFolderId = _findFolderContainingRequest(folder, requestId);
        if (nestedFolderId) {
            return folder.id // Return this folder's ID so it gets expanded too
            ;
        }
    }
    return null;
}
/**
 * Get all folder IDs that need to be expanded to show a request
 */ function getFoldersToExpand(collection, requestId, path = []) {
    for (const folder of collection.folders){
        // Check direct requests in folder
        if (folder.requests.some((r)=>r.id === requestId)) {
            return [
                ...path,
                folder.id
            ];
        }
        // Check nested folders recursively
        const nestedPath = getFoldersToExpand(folder, requestId, [
            ...path,
            folder.id
        ]);
        if (nestedPath.length > path.length) {
            return nestedPath;
        }
    }
    return path;
}
export function CollectionTree({ collection, selectedRequest, onSelectRequest, searchQuery = '', level = 0 }) {
    // Track which folders are expanded
    const [expandedFolders, setExpandedFolders] = useState(()=>{
        const expanded = new Set();
        // Expand all folders at root level by default
        if (level === 0) {
            collection.folders.forEach((folder)=>{
                expanded.add(folder.id);
            });
        }
        return expanded;
    });
    // Re-expand all folders when collection folders change (e.g., tab switch)
    // This ensures folders are expanded when switching between tabs with different folder sets
    const folderIds = useMemo(()=>collection.folders.map((f)=>f.id).sort().join(','), [
        collection.folders
    ]);
    useEffect(()=>{
        if (level === 0 && collection.folders.length > 0) {
            setExpandedFolders((prev)=>{
                const newExpanded = new Set(prev);
                // Add all current folder IDs to expanded set
                collection.folders.forEach((folder)=>{
                    newExpanded.add(folder.id);
                });
                return newExpanded;
            });
        }
    }, [
        folderIds,
        level,
        collection.folders
    ]);
    // Auto-expand folder when selectedRequest changes (e.g., via agent navigation)
    useEffect(()=>{
        if (selectedRequest && level === 0) {
            const foldersToExpand = getFoldersToExpand(collection, selectedRequest.id);
            if (foldersToExpand.length > 0) {
                setExpandedFolders((prev)=>{
                    const newExpanded = new Set(prev);
                    foldersToExpand.forEach((folderId)=>newExpanded.add(folderId));
                    return newExpanded;
                });
            }
        }
    }, [
        selectedRequest,
        collection,
        level
    ]);
    const toggleFolder = (folderId)=>{
        const newExpanded = new Set(expandedFolders);
        if (newExpanded.has(folderId)) {
            newExpanded.delete(folderId);
        } else {
            newExpanded.add(folderId);
        }
        setExpandedFolders(newExpanded);
    };
    // Filter items based on search query
    const filteredData = useMemo(()=>{
        if (!searchQuery.trim()) {
            return {
                folders: collection.folders,
                requests: collection.requests
            };
        }
        const query = searchQuery.toLowerCase();
        const filteredFolders = [];
        const filteredRequests = [];
        // Filter folders
        for (const folder of collection.folders){
            const folderMatches = folder.name.toLowerCase().includes(query);
            const folderRequests = folder.requests.filter((req)=>req.name.toLowerCase().includes(query) || req.endpoint.toLowerCase().includes(query) || req.description?.toLowerCase().includes(query));
            if (folderMatches || folderRequests.length > 0) {
                filteredFolders.push({
                    ...folder,
                    requests: folderMatches ? folder.requests : folderRequests
                });
            }
        }
        // Filter root requests
        filteredRequests.push(...collection.requests.filter((req)=>req.name.toLowerCase().includes(query) || req.endpoint.toLowerCase().includes(query) || req.description?.toLowerCase().includes(query)));
        return {
            folders: filteredFolders,
            requests: filteredRequests
        };
    }, [
        collection,
        searchQuery
    ]);
    // Show message if no content
    if (filteredData.folders.length === 0 && filteredData.requests.length === 0) {
        if (level === 0) {
            return /*#__PURE__*/ _jsx("li", {
                className: "py-4 px-2 text-center",
                children: /*#__PURE__*/ _jsx("p", {
                    className: "text-sm text-muted-foreground",
                    children: "No endpoints found"
                })
            });
        }
        return null;
    }
    return /*#__PURE__*/ _jsxs(_Fragment, {
        children: [
            filteredData.folders.map((folder)=>{
                const isExpanded = expandedFolders.has(folder.id);
                const hasContent = folder.requests.length > 0 || folder.folders.length > 0;
                if (!hasContent) {
                    // Empty folder - render as disabled item
                    return /*#__PURE__*/ _jsx(SidebarItem, {
                        indent: level,
                        disabled: true,
                        asideContent: /*#__PURE__*/ _jsx(Folder, {
                            className: "h-4 w-4 text-sidebar-foreground/40",
                            weight: "fill"
                        }),
                        children: folder.name
                    }, folder.id);
                }
                return /*#__PURE__*/ _jsxs(SidebarGroup, {
                    title: /*#__PURE__*/ _jsxs("span", {
                        className: "flex items-center gap-2",
                        children: [
                            isExpanded ? /*#__PURE__*/ _jsx(FolderOpen, {
                                className: "h-4 w-4 text-sidebar-foreground/60 shrink-0",
                                weight: "fill"
                            }) : /*#__PURE__*/ _jsx(Folder, {
                                className: "h-4 w-4 text-sidebar-foreground/60 shrink-0",
                                weight: "fill"
                            }),
                            /*#__PURE__*/ _jsx("span", {
                                className: "truncate",
                                children: folder.name
                            })
                        ]
                    }),
                    defaultOpen: isExpanded,
                    indent: level,
                    onClick: ()=>toggleFolder(folder.id),
                    children: [
                        folder.folders.length > 0 && /*#__PURE__*/ _jsx(CollectionTree, {
                            collection: folder,
                            selectedRequest: selectedRequest,
                            onSelectRequest: onSelectRequest,
                            searchQuery: searchQuery,
                            level: level + 1
                        }),
                        folder.requests.map((request)=>/*#__PURE__*/ _jsx(SidebarItem, {
                                selected: selectedRequest?.id === request.id,
                                indent: level + 1,
                                onClick: ()=>onSelectRequest(request),
                                asideContent: /*#__PURE__*/ _jsx(MethodBadge, {
                                    method: request.method,
                                    size: "sm"
                                }),
                                children: request.name
                            }, request.id))
                    ]
                }, folder.id);
            }),
            filteredData.requests.map((request)=>/*#__PURE__*/ _jsx(SidebarItem, {
                    selected: selectedRequest?.id === request.id,
                    indent: level,
                    onClick: ()=>onSelectRequest(request),
                    asideContent: /*#__PURE__*/ _jsx(MethodBadge, {
                        method: request.method,
                        size: "sm"
                    }),
                    children: request.name
                }, request.id))
        ]
    });
}
