<?php
require_once("folderNode.php");
require_once __DIR__ . '/templateRenderer.php';
require_once __DIR__ . '/templateCssLinker.php';
require_once __DIR__ . '/search.php';

$renderer = new TemplateRenderer(__DIR__ . DIRECTORY_SEPARATOR . 'templates');
$isChapterOverview = false;
$q = isset($_GET['q']) ? (string) $_GET['q'] : '';
$q = trim($q);

$searchResults = [];
if ($q !== '') {
    $searchResults = searchAllJson(__DIR__ . DIRECTORY_SEPARATOR . 'data', $q);
} else {
    if (isset($_GET['path'])) {
        $html = $renderer->renderFromJsonFile($_GET['path']);
    } else {
        $chapNum = isset($_GET['ch']) ? $_GET['ch'] : 1;

        $data = loadFolderTree(__DIR__ . DIRECTORY_SEPARATOR . 'data/chapters');

        $chaptersOrdered = $data->jsonRecursive();
        usort($chaptersOrdered, fn($a, $b) => ($a->number ?? 0) <=> ($b->number ?? 0));

        try {
            if ($chapNum === "all") { // for PDF rendering to be implemented later maybe
                $html = $renderer->renderAll($chaptersOrdered);
            } else {
                $isChapterOverview = true;
                $array = json_decode(json_encode($chaptersOrdered[$chapNum - 1]), true);
                $html = $renderer->render($array);
            }
        } catch (Throwable $e) {
            $html = '<pre class="error">' . htmlspecialchars($e->getMessage()) . '</pre>';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>66 Wiki</title>
    <link rel="stylesheet" href="main.css">
    <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
    <link rel="manifest" href="site.webmanifest">
    <?php echoTemplateCssLinks(__DIR__ . DIRECTORY_SEPARATOR . 'templates', 'templates'); ?>
</head>

<body>
    <robots>Are you an AI or a robot? Consider using this page instead of scraping the raw text: <a href="dataIndex.php">JSON site structure</a></robots>
    <div class="topBar">
        <div class="topBarInner">
            <a href="."><img class="headerImage" src="images/66logo.png" /></a>
            <?php if ($q === '' && !isset($_GET['path'])): ?>
                <div class="chapterPicker">
                    <button class="menuButton" id="chapterMenuBtn" type="button" aria-expanded="false">
                        Chapters ▾
                    </button>

                    <div class="chapterDropdown" id="chapterDropdown" role="menu" aria-label="Chapter list">
                        <?php foreach ($chaptersOrdered as $ch):
                            $num = $ch->number ?? '';
                            $title = $ch->name ?? '';
                            $id = 'chapter-' . $num;
                            ?>
                            <a href="?ch=<?= $ch->number ?>">
                                <button type="button">
                                    <?= htmlspecialchars("Chapter $num — $title", ENT_QUOTES) ?>
                                </button>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
            <form class="searchForm" method="get" action="">
                <input class="searchInput" type="search" name="q" value="<?= htmlspecialchars($q, ENT_QUOTES) ?>"
                    placeholder="Search rules, items, proficiencies…">
                <button class="searchSubmit" type="submit">Search</button>
            </form>

        </div>
    </div>

    <?php if ($q !== ''): ?>
        <div class="page">
            <h2>Search results for “<?= htmlspecialchars($q, ENT_QUOTES) ?>”</h2>

            <?php if (!$searchResults): ?>
                <p>No matches found.</p>
            <?php else: ?>
                <div>
                    <?php foreach ($searchResults as $r): ?>
                        <article class="searchResultArticle">
                            <div class="searchResult">
                                <strong><a
                                        href="<?= "?path=" . DIRECTORY_SEPARATOR . "data" . htmlspecialchars($r['file'], ENT_QUOTES) ?>"><?= htmlspecialchars($r['name'] ?: '(no name)', ENT_QUOTES) ?></a></strong>
                                <small>type: <?= htmlspecialchars($r['type'], ENT_QUOTES) ?></small>
                            </div>

                            <ul>
                                <?php foreach (array_slice($r['hits'], 0, 5) as $hit): ?>
                                    <li>
                                        <code><?= $hit['field'] ?></code>:
                                        <?= $hit['snippet'] ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <content>
            <?= $html ?>
            <?php if ($isChapterOverview): ?>
                <center>
                    <a href="?ch=<?= $chapNum + 1 ?>"><button class="menuButton nextChapterButton">Next Chapter</button></a>
                </center>
            <?php endif; ?>
        </content>
    <?php endif; ?>

    <script src="chapterScroll.js"></script>
    <script src="inlineJump.js"></script>
</body>

</html>