import {jsxs,jsx}from'react/jsx-runtime';import {useState,useRef,useEffect}from'react';import {useLocation,Outlet,Link}from'@remix-run/react';import {SidebarSearch}from'../../components/SidebarSearch.js';import {getDocsNavigation,getDocsNavigationAsync}from'../../utils/docsNavigation.js';import {useTheme}from'@admin-layout/tailwind-ui';import {cn}from'../../utils/index.js';const MarkdownPageLayout = ({
  children
}) => {
  const location = useLocation();
  const [navItems, setNavItems] = useState(getDocsNavigation());
  const [expandedItems, setExpandedItems] = useState(new Set());
  const [headings, setHeadings] = useState([]);
  const [activeHeadingId, setActiveHeadingId] = useState('');
  const observerRef = useRef(null);
  const {
    setMode,
    mode
  } = useTheme();
  const isDark = mode === 'dark';
  // Load navigation asynchronously to ensure manifest is loaded
  useEffect(() => {
    getDocsNavigationAsync().then(items => {
      if (items && items.length > 0) {
        setNavItems(items);
      } else {
        console.warn('⚠️ No navigation items loaded');
      }
    }).catch(error => {
      console.error('❌ Error loading navigation:', error);
    });
  }, []);
  // Helper function to check if an item or any of its descendants contain the active path
  const itemContainsActivePath = (item, activePath) => {
    if (item.path && (activePath === item.path || activePath.startsWith(item.path + '/'))) {
      return true;
    }
    if (item.children && item.children.length > 0) {
      return item.children.some(child => itemContainsActivePath(child, activePath));
    }
    return false;
  };
  // Helper function to get all items that should be expanded for the active path
  const getItemsToExpandForActivePath = (items, activePath, pathPrefix = '') => {
    const itemsToExpand = new Set();
    function checkAndExpand(items, pathPrefix = '') {
      items.forEach(item => {
        const itemPath = pathPrefix ? `${pathPrefix}/${item.title}` : item.title;
        if (item.path && (activePath === item.path || activePath.startsWith(item.path + '/'))) {
          itemsToExpand.add(itemPath);
          if (item.children && item.children.length > 0) {
            checkAndExpand(item.children, itemPath);
          }
        } else if (item.children && item.children.length > 0) {
          // Check if any child is active
          const hasActiveChild = item.children.some(child => child.path && (activePath === child.path || activePath.startsWith(child.path + '/')));
          if (hasActiveChild) {
            itemsToExpand.add(itemPath);
            checkAndExpand(item.children, itemPath);
          }
        }
      });
    }
    checkAndExpand(items, pathPrefix);
    return itemsToExpand;
  };
  // Auto-expand items that contain the active path when pathname or navItems change
  useEffect(() => {
    const activePath = location.pathname;
    const itemsToExpand = getItemsToExpandForActivePath(navItems, activePath);
    // Merge: keep existing expandedItems and add items containing active path
    setExpandedItems(prev => {
      const merged = new Set(prev);
      itemsToExpand.forEach(path => merged.add(path));
      return merged;
    });
  }, [location.pathname, navItems]);
  // Toggle item expansion - allow all items to be toggled (including collapsing parent when its page is active)
  // Items containing active path will be re-expanded automatically by useEffect
  const toggleItem = itemPath => {
    setExpandedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(itemPath)) {
        newSet.delete(itemPath);
      } else {
        newSet.add(itemPath);
      }
      return newSet;
    });
  };
  // Extract headings from the current page content
  useEffect(() => {
    // Wait for content to load, then extract headings
    const extractHeadings = () => {
      const contentArea = document.querySelector('[data-content-area]');
      if (contentArea) {
        const headingElements = contentArea.querySelectorAll('h1, h2, h3, h4, h5, h6');
        const extractedHeadings = [];
        headingElements.forEach(heading => {
          const id = heading.id || heading.textContent?.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '') || '';
          if (id) {
            extractedHeadings.push({
              id,
              text: heading.textContent || '',
              level: parseInt(heading.tagName.charAt(1))
            });
          }
        });
        setHeadings(extractedHeadings);
      }
    };
    // Extract immediately
    extractHeadings();
    // Also extract after a short delay to catch dynamically loaded content
    const timeoutId = setTimeout(extractHeadings, 100);
    // Use MutationObserver to watch for content changes
    const observer = new MutationObserver(extractHeadings);
    const contentArea = document.querySelector('[data-content-area]');
    if (contentArea) {
      observer.observe(contentArea, {
        childList: true,
        subtree: true
      });
    }
    return () => {
      clearTimeout(timeoutId);
      observer.disconnect();
    };
  }, [location.pathname]);
  // Scroll spy for table of contents
  useEffect(() => {
    if (headings.length === 0) return;
    // Clean up previous observer
    if (observerRef.current) {
      observerRef.current.disconnect();
    }
    // Create new intersection observer
    observerRef.current = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          setActiveHeadingId(entry.target.id);
        }
      });
    }, {
      rootMargin: '-20% 0px -70% 0px',
      threshold: 0
    });
    // Observe all headings
    headings.forEach(heading => {
      const element = document.getElementById(heading.id);
      if (element && observerRef.current) {
        observerRef.current.observe(element);
      }
    });
    // Cleanup function
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [headings]);
  // Determine active section based on current path
  const isActivePath = path => {
    if (!path) return false;
    return location.pathname === path || location.pathname.startsWith(path + '/');
  };
  // Recursive component to render navigation items. Index ensures unique keys when same title appears multiple times.
  const renderNavItem = (item, level = 0, pathPrefix = '', index = 0) => {
    const itemPath = pathPrefix ? `${pathPrefix}/${item.title}` : item.title;
    const hasChildren = item.children && item.children.length > 0;
    const activePath = location.pathname;
    // Item is expanded if it's in expandedItems (user can collapse even when a child page is active)
    const isExpanded = expandedItems.has(itemPath);
    const isActive = item.path ? isActivePath(item.path) : false;
    const containsActive = itemContainsActivePath(item, activePath);
    const indentLevel = level * 16; // 16px per level
    const uniqueKey = `${itemPath}-${index}`;
    return jsxs("li", {
      className: "w-full",
      children: [jsx("div", {
        className: "flex items-center w-full",
        children: hasChildren ? jsxs("button", {
          onClick: e => {
            e.preventDefault();
            toggleItem(itemPath);
          },
          className: cn('flex items-center justify-between w-full px-3 py-2 text-sm rounded-md transition-colors text-left', isActive ? 'bg-primary/10 dark:bg-primary/20 text-primary dark:text-primary font-medium' : containsActive ? 'text-primary dark:text-primary font-medium hover:bg-gray-50 dark:hover:bg-gray-800' : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800'),
          style: {
            paddingLeft: `${12 + indentLevel}px`
          },
          children: [jsx("span", {
            className: "flex-1 truncate",
            children: item.title
          }), jsx("svg", {
            className: cn('w-4 h-4 transition-transform flex-shrink-0 ml-2', isExpanded ? 'rotate-90' : ''),
            fill: "none",
            stroke: "currentColor",
            viewBox: "0 0 24 24",
            children: jsx("path", {
              strokeLinecap: "round",
              strokeLinejoin: "round",
              strokeWidth: 2,
              d: "M9 5l7 7-7 7"
            })
          })]
        }) : item.path ? jsx(Link, {
          to: item.path,
          className: cn('block px-3 py-2 text-sm rounded-md transition-colors truncate', isActive ? 'bg-primary/10 dark:bg-primary/20 text-primary dark:text-primary font-medium' : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800'),
          style: {
            paddingLeft: `${12 + indentLevel}px`
          },
          children: item.title
        }) : jsx("span", {
          className: cn('block px-3 py-2 text-sm rounded-md truncate text-gray-500 dark:text-gray-400'),
          style: {
            paddingLeft: `${12 + indentLevel}px`
          },
          children: item.title
        })
      }), hasChildren && isExpanded && jsx("ul", {
        className: "mt-1 space-y-1",
        children: item.children.map((child, i) => renderNavItem(child, level + 1, itemPath, i))
      })]
    }, uniqueKey);
  };
  return jsxs("div", {
    className: "min-h-screen bg-background text-foreground mt-20",
    children: [jsx("aside", {
      className: "hidden lg:block fixed left-0 top-20 h-screen w-64 z-10",
      children: jsxs("div", {
        className: "flex flex-col h-[calc(100vh-64px)] w-64 border-r border-gray-200 dark:border-gray-800 bg-background text-foreground",
        children: [jsx("div", {
          className: "sticky top-0 z-20 p-4 pb-0 bg-background text-foreground ",
          children: jsx("div", {
            className: "mb-4",
            children: jsx(SidebarSearch, {
              placeholder: "Search..."
            })
          })
        }), jsx("nav", {
          className: "flex-1 overflow-y-auto p-4 min-h-0",
          children: jsx("ul", {
            className: "space-y-1",
            children: navItems.map((item, i) => renderNavItem(item, 0, '', i))
          })
        }), jsx("div", {
          className: "p-4 border-t border-gray-200 dark:border-gray-800 flex-shrink-0",
          children: jsxs("div", {
            className: "flex items-center justify-center gap-2",
            children: [jsx("div", {
              className: cn('p-1.5 rounded-full transition-colors cursor-pointer', !isDark ? 'bg-gray-100 dark:bg-gray-700' : 'bg-transparent'),
              onClick: () => setMode('light'),
              children: jsx("svg", {
                className: "w-4 h-4 text-gray-700 dark:text-gray-300",
                fill: "none",
                stroke: "currentColor",
                viewBox: "0 0 24 24",
                children: jsx("path", {
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: 2,
                  d: "M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
                })
              })
            }), jsx("div", {
              className: cn('p-1.5 rounded-full transition-colors cursor-pointer', isDark ? 'bg-gray-100 dark:bg-gray-700' : 'bg-transparent'),
              onClick: () => setMode('dark'),
              children: jsx("svg", {
                className: "w-4 h-4 text-gray-700 dark:text-gray-300",
                fill: "none",
                stroke: "currentColor",
                viewBox: "0 0 24 24",
                children: jsx("path", {
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: 2,
                  d: "M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"
                })
              })
            })]
          })
        })]
      })
    }), jsx("main", {
      className: "lg:pl-64 flex flex-col min-h-screen",
      children: jsx("div", {
        className: "flex-1 flex",
        children: jsx("div", {
          className: "flex-1 min-w-0",
          children: jsx("div", {
            className: "max-w-full mx-auto px-6 py-8",
            "data-content-area": true,
            children: children || jsx(Outlet, {})
          })
        })
      })
    })]
  });
};export{MarkdownPageLayout};//# sourceMappingURL=MarkdownPageLayout.js.map
