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

$render_nav = static function (array $nodes) use (&$render_nav, $base_slug, $product_slug, $version_slug, $url_builder): void {
    if (! $nodes) {
        return;
    }

    echo '<ul>';
    foreach ($nodes as $node) {
        $target = (string) ($node['target'] ?? '');
        $label = (string) ($node['title'] ?? '');
        $href = '';

        if ($target) {
            $slug = preg_replace('/\.md(#.+)?$/', '', basename($target)) ?: basename($target);
            $slug = in_array(strtolower($slug), ['doku', 'index'], true) ? '' : sanitize_title($slug);
            $href = $url_builder::page($product_slug, $version_slug, $slug);
        }

        echo '<li>';
        if ($href) {
            printf('<a href="%s">%s</a>', esc_url($href), esc_html($label));
        } else {
            echo '<span>' . esc_html($label) . '</span>';
        }
        $render_nav((array) ($node['children'] ?? []));
        echo '</li>';
    }
    echo '</ul>';
};
?>
<main class="kb-docs-wrap kb-doc-layout">
    <aside class="kb-sidebar">
        <label class="screen-reader-text" for="kb-version-switcher"><?php esc_html_e('Version', 'kb-markdown-importer'); ?></label>
        <select id="kb-version-switcher">
            <?php foreach ((array) $versions as $item) : ?>
                <option value="<?php echo esc_attr($item->slug); ?>" data-url="<?php echo esc_url($url_builder::version($product_slug, $item->slug)); ?>" <?php selected($item->slug, $version_slug); ?>><?php echo esc_html($item->name); ?></option>
            <?php endforeach; ?>
        </select>
        <nav class="kb-sidebar-nav" aria-label="<?php esc_attr_e('Documentation navigation', 'kb-markdown-importer'); ?>">
            <?php $render_nav((array) $nav_tree); ?>
        </nav>
    </aside>
    <article class="kb-doc-content">
        <nav class="kb-breadcrumbs">
            <a href="<?php echo esc_url($url_builder::docsIndex()); ?>"><?php esc_html_e('Docs', 'kb-markdown-importer'); ?></a><span>/</span>
            <a href="<?php echo esc_url($url_builder::product($product_slug)); ?>"><?php echo esc_html($product ? $product->name : $product_slug); ?></a><span>/</span>
            <a href="<?php echo esc_url($url_builder::version($product_slug, $version_slug)); ?>"><?php echo esc_html($version ? $version->name : $version_slug); ?></a>
        </nav>
        <h1><?php echo esc_html(get_the_title($post)); ?></h1>
        <div class="kb-rendered-content">
            <?php
            $rendered_content = $url_builder::rewriteHtml(apply_filters('the_content', $post->post_content));
            echo wp_kses_post($rendered_content);
            ?>
        </div>
    </article>
</main>
