<html lang="en" class="h-full antialiased light scroll-smooth"
    style="color-scheme: light;">

<head>
    <%- include('./Partials/Head.ejs', {
        enableGoogleTagManager: typeof enableGoogleTagManager !== 'undefined' ? enableGoogleTagManager : false,
        link: typeof link !== 'undefined' ? link : null
    }) %>
    <style>
        /* Custom scrollbar for sidebar */
        .custom-scrollbar::-webkit-scrollbar {
            width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
            background: transparent;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #e2e8f0;
            border-radius: 3px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #cbd5e1;
        }

        /* Smooth transitions */
        * {
            scroll-behavior: smooth;
        }

        /* Better focus styles */
        a:focus-visible, button:focus-visible {
            outline: 2px solid #6366f1;
            outline-offset: 2px;
            border-radius: 4px;
        }
    </style>
</head>

<body class="flex min-h-full bg-white">
    <!-- Scroll progress bar -->
    <div id="scroll-progress" class="scroll-progress" style="width: 0%;"></div>

    <div class="flex w-full flex-col">
        <%- include('./Partials/Header.ejs') %>

        <!-- Mobile top bar with menu button -->
        <div class="flex items-center justify-between lg:hidden border-b border-slate-200/80 px-4 py-3 bg-slate-50/50">
            <button aria-label="Open navigation"
                    data-mobile-menu-open
                    class="inline-flex items-center gap-2 rounded-lg bg-white px-3 py-2 text-sm font-medium text-slate-700 shadow-sm ring-1 ring-slate-200 hover:bg-slate-50 hover:ring-slate-300 active:scale-[.98] transition-all">
                <svg class="h-5 w-5 text-slate-500" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24">
                    <path d="M4 6h16M4 12h16M4 18h16"/>
                </svg>
                Menu
            </button>
            <h1 class="text-sm font-medium text-slate-600 truncate max-w-[200px]"><%- link.title %></h1>
        </div>

        <!-- Mobile nav overlay -->
        <div data-mobile-menu-overlay class="fixed inset-0 z-40 bg-slate-900/50 backdrop-blur-sm lg:hidden hidden transition-opacity"></div>

        <!-- Mobile nav drawer -->
        <aside data-mobile-menu-drawer
               class="fixed inset-y-0 left-0 z-50 w-80 max-w-[calc(100vw-3rem)] overflow-y-auto bg-white px-6 py-6 shadow-2xl ring-1 ring-slate-900/10 lg:hidden transform transition-transform ease-out duration-300 -translate-x-full">
            <div class="flex items-center justify-between mb-6 pb-4 border-b border-slate-200">
                <span class="text-base font-semibold text-slate-900">Documentation</span>
                <button aria-label="Close navigation"
                        data-mobile-menu-close
                        class="rounded-lg p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 transition-colors">
                    <svg class="h-5 w-5" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M18 6L6 18M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <%- include('./Partials/Nav.ejs') %>
        </aside>

        <!-- Main content area: 3-column layout on xl -->
        <div class="relative z-0 mx-auto flex w-full max-w-8xl flex-auto justify-center sm:px-2 lg:px-8 xl:px-12">
            <!-- Desktop sidebar (left) -->
            <div class="hidden lg:relative lg:block lg:flex-none">
                <div class="absolute inset-y-0 right-0 w-[50vw] bg-gradient-to-r from-slate-50 to-slate-50/0"></div>
                <div class="sticky top-[3.5rem] -ml-0.5 h-[calc(100vh-3.5rem)] w-64 overflow-y-auto overflow-x-hidden py-8 pl-0.5 pr-8 xl:w-72 xl:pr-12 custom-scrollbar">
                    <%- include('./Partials/Nav.ejs') %>
                </div>
            </div>

            <!-- Article content (center) -->
            <div class="min-w-0 max-w-2xl flex-auto px-4 py-8 md:py-10 lg:py-12 lg:max-w-none lg:pl-8 lg:pr-0 xl:px-16">
                <%- include('./Partials/Content.ejs', { category: category, link: link, content: content }) %>

                <%- include('./Partials/Pagination.ejs', {
                    prevLink: typeof prevLink !== 'undefined' ? prevLink : null,
                    nextLink: typeof nextLink !== 'undefined' ? nextLink : null
                }) %>

                <%- include('./Partials/OpenSourceCommitment.ejs', { githubPath: githubPath }) %>

                <!-- Footer spacing -->
                <div class="h-16"></div>
            </div>

            <!-- TOC sidebar (right) - visible on xl only -->
            <div class="hidden xl:block xl:flex-none xl:w-56 2xl:w-64">
                <div class="toc-sidebar py-12 pl-6" id="toc-sidebar">
                    <h4 class="text-xs font-semibold uppercase tracking-wide text-slate-900 mb-4">On This Page</h4>
                    <ul id="toc-list" class="space-y-0.5">
                        <!-- Populated by JS -->
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Search modal -->
    <div id="search-overlay" class="search-overlay"></div>
    <div id="search-modal" class="search-modal">
        <div class="flex items-center gap-3 px-4 py-3 border-b border-slate-200">
            <svg class="h-5 w-5 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
            </svg>
            <input id="search-input" type="text" placeholder="Search documentation..." class="flex-1 bg-transparent border-none outline-none text-sm text-slate-900 placeholder-slate-400" autocomplete="off">
            <kbd class="hidden sm:inline-flex items-center rounded border border-slate-300 bg-slate-50 px-1.5 py-0.5 text-[10px] font-medium text-slate-400">ESC</kbd>
        </div>
        <div id="search-results" class="search-results">
            <div id="search-empty" class="px-4 py-8 text-center text-sm text-slate-500">
                Type to search documentation...
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script>
        (function(){
            // === Mobile menu toggle ===
            var openBtn = document.querySelector('[data-mobile-menu-open]');
            var closeBtn = document.querySelector('[data-mobile-menu-close]');
            var overlay = document.querySelector('[data-mobile-menu-overlay]');
            var drawer = document.querySelector('[data-mobile-menu-drawer]');
            if(openBtn && overlay && drawer){
                function openMenu(){
                    overlay.classList.remove('hidden');
                    drawer.classList.remove('hidden');
                    requestAnimationFrame(function(){
                        drawer.classList.remove('-translate-x-full');
                        overlay.classList.add('opacity-100');
                    });
                    document.body.classList.add('overflow-hidden');
                }
                function closeMenu(){
                    drawer.classList.add('-translate-x-full');
                    overlay.classList.remove('opacity-100');
                    document.body.classList.remove('overflow-hidden');
                    drawer.addEventListener('transitionend', function handler(e){
                        if(e.propertyName === 'transform'){
                            if(drawer.classList.contains('-translate-x-full')){
                                drawer.classList.add('hidden');
                                overlay.classList.add('hidden');
                            }
                            drawer.removeEventListener('transitionend', handler);
                        }
                    });
                }
                openBtn.addEventListener('click', openMenu);
                overlay.addEventListener('click', closeMenu);
                if(closeBtn) closeBtn.addEventListener('click', closeMenu);
            }

            // === Sidebar collapse/expand ===
            document.querySelectorAll('.nav-category-btn').forEach(function(btn){
                btn.addEventListener('click', function(){
                    var idx = btn.getAttribute('data-category-index');
                    var links = document.querySelectorAll('[data-category-links="' + idx + '"]');
                    var chevron = btn.querySelector('.nav-chevron');
                    var isExpanded = btn.getAttribute('aria-expanded') === 'true';
                    btn.setAttribute('aria-expanded', isExpanded ? 'false' : 'true');
                    links.forEach(function(el){
                        if(isExpanded){
                            el.classList.remove('expanded');
                        } else {
                            el.classList.add('expanded');
                        }
                    });
                    if(chevron){
                        if(isExpanded){
                            chevron.classList.remove('rotated');
                        } else {
                            chevron.classList.add('rotated');
                        }
                    }
                });
            });

            // Auto-scroll active nav item into view
            var activeLink = document.querySelector('.nav-active-link');
            if(activeLink){
                setTimeout(function(){
                    activeLink.scrollIntoView({ block: 'center', behavior: 'auto' });
                }, 100);
            }

            // === TOC generation + scroll spy ===
            var tocList = document.getElementById('toc-list');
            var tocSidebar = document.getElementById('toc-sidebar');
            if(tocList){
                var article = document.querySelector('.docs-article');
                if(article){
                    var headings = article.querySelectorAll('h2[id], h3[id]');
                    if(headings.length === 0){
                        // Hide the entire TOC sidebar when no headings
                        if(tocSidebar && tocSidebar.parentElement){
                            tocSidebar.parentElement.style.display = 'none';
                        }
                    }
                    headings.forEach(function(h){
                        var li = document.createElement('li');
                        var a = document.createElement('a');
                        a.href = '#' + h.id;
                        a.textContent = h.textContent.replace(/#$/, '').trim();
                        a.className = 'toc-link' + (h.tagName === 'H3' ? ' toc-h3' : '');
                        a.setAttribute('data-toc-id', h.id);
                        li.appendChild(a);
                        tocList.appendChild(li);
                    });

                    // Scroll spy with IntersectionObserver
                    if(headings.length > 0 && 'IntersectionObserver' in window){
                        var tocLinks = tocList.querySelectorAll('.toc-link');
                        var observer = new IntersectionObserver(function(entries){
                            entries.forEach(function(entry){
                                if(entry.isIntersecting){
                                    tocLinks.forEach(function(l){ l.classList.remove('active'); });
                                    var active = tocList.querySelector('[data-toc-id="' + entry.target.id + '"]');
                                    if(active) active.classList.add('active');
                                }
                            });
                        }, { rootMargin: '-80px 0px -70% 0px', threshold: 0 });
                        headings.forEach(function(h){ observer.observe(h); });
                    }
                }
            }

            // === Search modal ===
            var searchOverlay = document.getElementById('search-overlay');
            var searchModal = document.getElementById('search-modal');
            var searchInput = document.getElementById('search-input');
            var searchResults = document.getElementById('search-results');
            var searchEmpty = document.getElementById('search-empty');
            var searchTrigger = document.getElementById('search-trigger');
            var searchTriggerMobile = document.getElementById('search-trigger-mobile');

            // Build search index from nav
            var searchIndex = [];
            <% for(var i=0; i<nav.length; i++) { %>
                <% for(var j=0; j<nav[i].links.length; j++) { %>
                    searchIndex.push({
                        title: '<%= nav[i].links[j].title.replace(/'/g, "\\'") %>',
                        url: '<%= nav[i].links[j].url %>',
                        category: '<%= nav[i].title.replace(/'/g, "\\'") %>'
                    });
                <% } %>
            <% } %>

            var highlightedIndex = -1;

            function openSearch(){
                searchOverlay.classList.add('active');
                searchModal.classList.add('active');
                searchInput.value = '';
                searchInput.focus();
                renderSearchResults('');
                document.body.classList.add('overflow-hidden');
            }
            function closeSearch(){
                searchOverlay.classList.remove('active');
                searchModal.classList.remove('active');
                document.body.classList.remove('overflow-hidden');
                highlightedIndex = -1;
            }

            function renderSearchResults(query){
                var q = query.toLowerCase().trim();
                if(!q){
                    searchResults.innerHTML = '<div class="px-4 py-8 text-center text-sm text-slate-500">Type to search documentation...</div>';
                    highlightedIndex = -1;
                    return;
                }
                var matches = searchIndex.filter(function(item){
                    return item.title.toLowerCase().indexOf(q) !== -1 || item.category.toLowerCase().indexOf(q) !== -1;
                });
                if(matches.length === 0){
                    searchResults.innerHTML = '<div class="px-4 py-8 text-center text-sm text-slate-500">No results found for "' + q.replace(/</g,'&lt;') + '"</div>';
                    highlightedIndex = -1;
                    return;
                }
                highlightedIndex = 0;
                var html = '';
                matches.forEach(function(item, idx){
                    html += '<a href="' + item.url + '" class="search-result-item flex items-center gap-3' + (idx === 0 ? ' highlighted' : '') + '" data-search-idx="' + idx + '">';
                    html += '<svg class="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>';
                    html += '<div class="flex-1 min-w-0">';
                    html += '<div class="text-sm font-medium text-slate-900 truncate">' + item.title + '</div>';
                    html += '<div class="text-xs text-slate-500">' + item.category + '</div>';
                    html += '</div>';
                    html += '<svg class="w-3.5 h-3.5 text-slate-300 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>';
                    html += '</a>';
                });
                searchResults.innerHTML = html;
            }

            if(searchTrigger) searchTrigger.addEventListener('click', openSearch);
            if(searchTriggerMobile) searchTriggerMobile.addEventListener('click', openSearch);
            searchOverlay.addEventListener('click', closeSearch);

            searchInput.addEventListener('input', function(){
                renderSearchResults(searchInput.value);
            });

            document.addEventListener('keydown', function(e){
                // Cmd+K or Ctrl+K to open
                if((e.metaKey || e.ctrlKey) && e.key === 'k'){
                    e.preventDefault();
                    if(searchModal.classList.contains('active')){
                        closeSearch();
                    } else {
                        openSearch();
                    }
                }
                // Escape to close
                if(e.key === 'Escape'){
                    if(searchModal.classList.contains('active')){
                        closeSearch();
                    }
                    // Also close mobile menu
                    if(typeof closeMenu === 'function') closeMenu();
                }
                // Arrow navigation in search
                if(searchModal.classList.contains('active')){
                    var items = searchResults.querySelectorAll('.search-result-item');
                    if(e.key === 'ArrowDown'){
                        e.preventDefault();
                        highlightedIndex = Math.min(highlightedIndex + 1, items.length - 1);
                        items.forEach(function(it, i){ it.classList.toggle('highlighted', i === highlightedIndex); });
                        if(items[highlightedIndex]) items[highlightedIndex].scrollIntoView({ block: 'nearest' });
                    }
                    if(e.key === 'ArrowUp'){
                        e.preventDefault();
                        highlightedIndex = Math.max(highlightedIndex - 1, 0);
                        items.forEach(function(it, i){ it.classList.toggle('highlighted', i === highlightedIndex); });
                        if(items[highlightedIndex]) items[highlightedIndex].scrollIntoView({ block: 'nearest' });
                    }
                    if(e.key === 'Enter' && highlightedIndex >= 0 && items[highlightedIndex]){
                        e.preventDefault();
                        window.location.href = items[highlightedIndex].href;
                    }
                }
            });

            // === Scroll progress bar ===
            var progressBar = document.getElementById('scroll-progress');
            function updateScrollProgress(){
                var scrollTop = window.scrollY || document.documentElement.scrollTop;
                var docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
                var pct = docHeight > 0 ? (scrollTop / docHeight) * 100 : 0;
                progressBar.style.width = pct + '%';
            }

            // === Header scroll behavior ===
            var header = document.getElementById('docs-header');
            function updateHeaderScroll(){
                var scrollTop = window.scrollY || document.documentElement.scrollTop;
                if(scrollTop > 10){
                    header.classList.remove('border-transparent');
                    header.classList.add('border-slate-900/10');
                    header.style.boxShadow = '0 1px 3px 0 rgba(0,0,0,0.05)';
                } else {
                    header.classList.add('border-transparent');
                    header.classList.remove('border-slate-900/10');
                    header.style.boxShadow = 'none';
                }
            }

            // Throttled scroll handler
            var scrollTicking = false;
            window.addEventListener('scroll', function(){
                if(!scrollTicking){
                    requestAnimationFrame(function(){
                        updateScrollProgress();
                        updateHeaderScroll();
                        scrollTicking = false;
                    });
                    scrollTicking = true;
                }
            }, { passive: true });

            // Initial calls
            updateScrollProgress();
            updateHeaderScroll();
        })();
    </script>
</body>

</html>
