<!DOCTYPE html>
<html lang="en">

<head>
    <?php
    if (!isset($assetsUrl)) {
        $assetsUrl = isset($baseUrl) ? rtrim($baseUrl, '/') . '/assets' : '/assets';
    }
    if (!isset($title) || $title === '') { $title = 'Help'; }
    if (!isset($topics)) { $topics = []; }
    if (!isset($topicsMeta)) { $topicsMeta = []; }
    if (!isset($activeTopic)) { $activeTopic = ''; }
    if (!isset($content)) { $content = ''; }
    $b = rtrim((string) ($baseUrl ?? ''), '/');
    // Sidebar sections come pre-grouped + ordered from the controller ($grouped /
    // $groups). Older callers (search page) may not pass them — fall back gracefully.
    if (!isset($grouped) || !isset($groups)) {
        $groups  = ['components' => ['label' => 'Components', 'icon' => 'bi-grid-1x2-fill'], 'client' => ['label' => 'Client API', 'icon' => 'bi-braces'], 'server' => ['label' => 'Server API', 'icon' => 'bi-server'], 'developer' => ['label' => 'Developer', 'icon' => 'bi-shield-lock']];
        $grouped = [];
        foreach ($topicsMeta as $t) { $grouped[$t['group'] ?? 'server'][] = $t; }
    }
    ?>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($title) ?> – <?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> Help</title>
    <?php include constant('BASE_PATH') . '/core/views/favicon.php'; ?>
    <link href="<?= $assetsUrl ?>/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?= $assetsUrl ?>/icons/bootstrap-icons.css" rel="stylesheet">
    <?php include constant('BASE_PATH') . '/core/views/theme-head.php'; ?>
    <?= \PpPhp\Core\ModuleAssets::style('Help', 'Views/help-theme.css') ?>
</head>

<body class="help-page">
    <div class="help-container">
        <nav class="help-sidebar">
            <div class="help-sidebar-head">
                <a href="<?= $b ?>/help" class="help-brand" aria-label="Help home">
                    <?= \PpPhp\Core\Brand::lockup(26) ?>
                    <span><strong>Help Center</strong><small>documentation &amp; guides</small></span>
                </a>
                <?php include constant('BASE_PATH') . '/core/views/theme-toggle.php'; ?>
            </div>

            <form method="get" action="<?= $b ?>/help/search" class="help-search mt-2 mb-2">
                <div class="input-group input-group-sm">
                    <span class="input-group-text"><i class="bi bi-search"></i></span>
                    <input type="text" name="q" class="form-control" placeholder="Search the docs…" value="<?= htmlspecialchars($_GET['q'] ?? '') ?>">
                </div>
            </form>

            <div class="help-nav-scroll">
                <a href="<?= $b ?>/help" class="nav-link help-nav-home<?= $activeTopic === 'index' ? ' active' : '' ?>">
                    <i class="bi bi-house-door"></i><span>Home</span>
                </a>

                <?php foreach ($groups as $gk => $g): if (empty($grouped[$gk])) continue; ?>
                    <div class="help-nav-label"><i class="bi <?= htmlspecialchars($g['icon']) ?>"></i> <?= htmlspecialchars($g['label']) ?><?php if ($gk === 'developer'): ?> <i class="bi bi-shield-lock" title="Owner / administrator only"></i><?php endif; ?></div>
                    <?php foreach ($grouped[$gk] as $t): ?>
                        <a href="<?= $b ?>/help/<?= urlencode($t['name']) ?>" class="nav-link<?= $activeTopic === $t['name'] ? ' active' : '' ?>" title="<?= htmlspecialchars($t['blurb'] ?? '') ?>">
                            <i class="bi <?= htmlspecialchars($t['icon']) ?>"></i><span><?= htmlspecialchars($t['label']) ?></span>
                        </a>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </div>

            <div class="help-sidebar-foot">
                <a href="<?= $b ?>/projects" class="help-back-app">
                    <i class="bi bi-box-arrow-left"></i><span>Back to Application</span>
                </a>
            </div>
        </nav>

        <main class="help-content" id="helpContent">
            <div class="help-content-inner<?= ($activeTopic !== 'index' && $activeTopic !== '') ? ' has-toc' : '' ?>">
                <article class="help-article" id="helpArticle">
                    <?= $content ?>

                    <?php if (!empty($prev) || !empty($next)): ?>
                    <nav class="help-prevnext" aria-label="More guides">
                        <?php if (!empty($prev)): ?>
                        <a class="help-pn help-pn-prev" href="<?= $b ?>/help/<?= urlencode($prev['name']) ?>">
                            <span class="help-pn-dir"><i class="bi bi-arrow-left"></i> Previous</span>
                            <span class="help-pn-title"><?= htmlspecialchars($prev['label']) ?></span>
                        </a>
                        <?php else: ?><span></span><?php endif; ?>
                        <?php if (!empty($next)): ?>
                        <a class="help-pn help-pn-next" href="<?= $b ?>/help/<?= urlencode($next['name']) ?>">
                            <span class="help-pn-dir">Next <i class="bi bi-arrow-right"></i></span>
                            <span class="help-pn-title"><?= htmlspecialchars($next['label']) ?></span>
                        </a>
                        <?php endif; ?>
                    </nav>
                    <?php endif; ?>
                </article>

                <?php if ($activeTopic !== 'index' && $activeTopic !== ''): ?>
                <aside class="help-toc" id="helpToc" aria-label="On this page">
                    <div class="help-toc-h">On this page</div>
                    <nav class="help-toc-list" id="helpTocList"></nav>
                </aside>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- Floating actions: always reachable, no matter how far the page is scrolled. -->
    <div class="help-fab-stack">
        <button type="button" class="help-fab help-fab-top" id="helpScrollTop" aria-label="Scroll to top" title="Scroll to top">
            <i class="bi bi-arrow-up"></i>
        </button>
        <a href="<?= $b ?>/projects" class="help-fab help-fab-home" aria-label="Back to Projects" title="Back to Projects">
            <i class="bi bi-grid-1x2-fill"></i>
            <span class="help-fab-label">Back to Projects</span>
        </a>
    </div>

    <script src="<?= $assetsUrl ?>/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        (function () {
            var content = document.getElementById('helpContent');
            var topBtn = document.getElementById('helpScrollTop');
            if (!topBtn) return;
            // The scroll container is .help-content on desktop, the window on mobile.
            var scroller = function () {
                return (content && content.scrollHeight > content.clientHeight + 4) ? content : window;
            };
            var pos = function () {
                var s = scroller();
                return s === window ? (window.scrollY || document.documentElement.scrollTop || 0) : s.scrollTop;
            };
            var sync = function () { topBtn.classList.toggle('show', pos() > 260); };
            topBtn.addEventListener('click', function () {
                var s = scroller();
                if (s === window) window.scrollTo({ top: 0, behavior: 'smooth' });
                else s.scrollTo({ top: 0, behavior: 'smooth' });
            });
            if (content) content.addEventListener('scroll', sync, { passive: true });
            window.addEventListener('scroll', sync, { passive: true });
            window.addEventListener('resize', sync);
            sync();
        })();

        // ── "On this page" auto-TOC + heading anchors + scroll-spy ──────────
        (function () {
            var article = document.getElementById('helpArticle');
            var list = document.getElementById('helpTocList');
            if (!article || !list) return;
            var heads = article.querySelectorAll('h2, h3');
            var slug = function (s) { return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60); };
            var used = {};
            var items = [];
            heads.forEach(function (h) {
                if (h.closest('.help-callout, pre')) return;
                var id = h.id;
                if (!id) { id = slug(h.textContent) || 'sec'; while (used[id]) id += '-x'; h.id = id; }
                used[id] = 1;
                // hover anchor link to deep-link the section
                var a = document.createElement('a');
                a.href = '#' + id; a.className = 'help-anchor'; a.setAttribute('aria-label', 'Link to this section'); a.innerHTML = '#';
                h.appendChild(a);
                // TOC entry
                var t = document.createElement('a');
                t.href = '#' + id; t.className = 'help-toc-item lvl-' + h.tagName.toLowerCase();
                t.textContent = h.textContent.replace(/#$/, '').trim();
                t.dataset.for = id;
                list.appendChild(t);
                items.push({ el: h, link: t });
            });
            if (!items.length) { var toc = document.getElementById('helpToc'); if (toc) toc.style.display = 'none'; return; }
            // scroll-spy: highlight the section currently in view
            var setActive = function (id) {
                items.forEach(function (it) { it.link.classList.toggle('active', it.link.dataset.for === id); });
            };
            if ('IntersectionObserver' in window) {
                var visible = {};
                var obs = new IntersectionObserver(function (entries) {
                    entries.forEach(function (e) { if (e.isIntersecting) visible[e.target.id] = e.intersectionRatio; else delete visible[e.target.id]; });
                    var top = null, best = -1;
                    items.forEach(function (it) { var r = visible[it.el.id]; if (r != null && r > best) { best = r; top = it.el.id; } });
                    if (top) setActive(top);
                }, { rootMargin: '0px 0px -70% 0px', threshold: [0, 1] });
                items.forEach(function (it) { obs.observe(it.el); });
            }
            setActive(items[0].el.id);
        })();
    </script>
</body>

</html>
