<?php
defined('ABSPATH') || exit;

$active_product_slug = (string) ($active_product_slug ?? '');
$active_version_slug = (string) ($active_version_slug ?? '');
$active_page_slug = (string) ($active_page_slug ?? '');
?>
<div class="kb-docs-wrap kb-docs-app">
    <aside class="kb-app-sidebar" aria-label="<?php esc_attr_e('Dokumentationsnavigation', 'kb-markdown-importer'); ?>">
        <div class="kb-app-sidebar__brand">
            <a href="<?php echo esc_url($url_builder::docsIndex()); ?>"><?php esc_html_e('Dokumentation', 'kb-markdown-importer'); ?></a>
        </div>
        <div class="kb-app-sidebar__search">
            <?php echo do_shortcode('[kb_search]'); ?>
        </div>
        <nav class="kb-app-nav">
            <?php foreach ((array) $products as $item) : ?>
                <?php
                $term = $item['term'];
                $versions = (array) $item['versions'];
                $latest = $versions[0] ?? null;
                $isActiveProduct = $term->slug === $active_product_slug;
                ?>
                <section class="kb-app-product <?php echo $isActiveProduct ? 'is-active' : ''; ?>">
                    <a class="kb-app-product__link" href="<?php echo esc_url($latest ? $url_builder::version($term->slug, $latest->slug) : $url_builder::product($term->slug)); ?>">
                        <?php echo esc_html($term->name); ?>
                    </a>
                    <?php if ($isActiveProduct && $active_version_slug && ! empty($active_pages)) : ?>
                        <ul class="kb-app-page-list">
                            <?php foreach ((array) $active_pages as $page) : ?>
                                <?php
                                $pageSlug = (string) get_post_meta($page->ID, '_kb_page_slug', true);
                                $isActivePage = $pageSlug === $active_page_slug || ('' === $active_page_slug && in_array($pageSlug, ['', 'index'], true));
                                ?>
                                <li class="<?php echo $isActivePage ? 'is-active' : ''; ?>">
                                    <a href="<?php echo esc_url($url_builder::page($term->slug, $active_version_slug, $pageSlug)); ?>"><?php echo esc_html(get_the_title($page)); ?></a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </section>
            <?php endforeach; ?>
        </nav>
    </aside>
    <section class="kb-app-main">
        <?php echo $content; ?>
    </section>
</div>
