<?php
	if ( ! defined( 'ABSPATH' ) ) {
		exit;
	}

	$show_sidebar = ! is_page();

	/**
	 * Raw content
	 */
	$raw_content = get_the_content();

	/**
	 * Rendered content
	 */
	$content = apply_filters( 'the_content', $raw_content );

	/**
	 * Reading time
	 * Average speed: 200 words per minute
	 */
	$text_content = wp_strip_all_tags( $raw_content );
	$word_count   = str_word_count( $text_content, 0 );
	$read_time    = max( 1, (int) ceil( $word_count / 400 ) );

	/**
	 * Extract headings (h2-h4)
	 * IDs: anchor-1, anchor-2, anchor-3...
	 */
	$headings = [];

	preg_match_all(
		'/<h([2-4])([^>]*)>(.*?)<\/h\1>/is',
		$content,
		$matches,
		PREG_SET_ORDER
	);

	if ( ! empty( $matches ) ) {

		foreach ( $matches as $index => $match ) {

			$level = (int) $match[1];
			$text  = trim( wp_strip_all_tags( $match[3] ) );
			$id    = 'anchor-' . ( $index + 1 );

			$headings[] = [
				'level' => $level,
				'text'  => $text,
				'id'    => $id,
			];

			$old_heading = $match[0];

			$new_heading =
				'<h' . $level . $match[2] . ' id="' . esc_attr( $id ) . '">' .
				$match[3] .
				'</h' . $level . '>';

			$content = str_replace(
				$old_heading,
				$new_heading,
				$content
			);
		}
	}
?>
<div class="g-957a8097" data-test-qa="68d19a" data-test-value="dfcee3a8" data-test-unit="63565bd">
<div class="g-fe86a0e5" data-module-group="bfb803aea" data-widget-trigger="3ad537782ba" data-test-pause="62d1631" data-bs-label="ae1d1356">
	<?php if ( $show_sidebar ) : ?>
		<aside class="g-f9b6b9d2" aria-label="Post information" id="elem-173bc8111a68d237">
			<div class="g-34637e00" data-block-handler="97c94102de9" data-bs-e2e="9954ec308" data-mui-loading="8fb396d">
				<div class="g-c3d15a9f" id="elem-f47332610195c9da">
					<svg width="20" height="20" viewBox="0 0 20 20" fill="none"
					     xmlns="http://www.w3.org/2000/svg">
						<path
							d="M9.75 3.75V9.75H14.25M18.75 9.75C18.75 14.7206 14.7206 18.75 9.75 18.75C4.77944 18.75 0.75 14.7206 0.75 9.75C0.75 4.77944 4.77944 0.75 9.75 0.75C14.7206 0.75 18.75 4.77944 18.75 9.75Z"
							stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
							stroke-linejoin="round"/>
					</svg>
					<span class="g-67d9d250 g-69d5938a">
						Reading time: <?php echo esc_html( $read_time ); ?> min.
					</span>
				</div>
				<?php if ( ! empty( $headings ) ) : ?>
					<nav class="g-772b3590" aria-label="Table of contents" data-mui-selected="a714fbed2de" data-module-size="xs" data-bs-metric="de13dfe7" data-bs-source="4618947d70bf">
						<div class="g-730d3348 g-9b9886c1" id="elem-9369e7f701aac557">
						Contents:
						</div>
						<ol class="g-39cf901c" data-component-group="7388ba7cf1" data-section-position="left" data-test-ride="8a0ed0">
							<?php foreach ( $headings as $heading ) : ?>
								<li class="g-246d52ee level-<?php echo esc_attr( $heading['level'] ); ?>">
									<a class="g-e4392cd1" href="#<?php echo esc_attr( $heading['id'] ); ?>">
										<?php echo esc_html( $heading['text'] ); ?>
									</a>
								</li>
							<?php endforeach; ?>
						</ol>
					</nav>
				<?php endif; ?>
			</div>
		</aside>
	<?php endif; ?>
	<article class="content-wrapper g-6b8c546e" id="elem-6bbb9ad91004bf9b">
		<?php echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		<footer class="g-bba8ae7f" data-mui-testid="f1e3b68" data-mui-component="8e37b1e0a7" data-test-loading="958c0a" data-bs-ride="046ac13a">
			<?php get_template_part( 'nav', 'below-single' ); ?>
		</footer>
	</article>
</div>
</div>
<?php if ( $show_sidebar ) : ?>
<script>
    document.addEventListener('DOMContentLoaded', function () {

        var links = document.querySelectorAll(
            '.g-772b3590 a[href^="#"]'
        );

        if (links.length === 0) {
            return;
        }

        var tocItems = [];
        var currentActive = 0;
        var lastScrollTop = window.scrollY;
        var manualNavigation = false;
        var navigationTimer = null;

        for (var i = 0; i < links.length; i++) {

            var href = links[i].getAttribute('href');
            var id = href.replace('#', '');
            var section = document.getElementById(id);

            if (!section) {
                console.warn(
                    'TOC section not found:',
                    id
                );
                continue;
            }

            tocItems.push({
                link: links[i],
                block: section,
                position: i
            });
        }

        function setCurrent(index) {

            if (
                index < 0 ||
                index >= tocItems.length
            ) {
                return;
            }

            currentActive = index;

            for (var j = 0; j < links.length; j++) {
                links[j]
                    .classList
                    .remove('g-2e572ade');
            }

            tocItems[index]
                .link
                .classList
                .add('g-2e572ade');
        }

        for (var k = 0; k < tocItems.length; k++) {
            (function (item) {
                item.link.addEventListener(
                    'click',
                    function () {

                        manualNavigation = true;

                        clearTimeout(navigationTimer);

                        setCurrent(item.position);

                        navigationTimer = setTimeout(
                            function () {
                                manualNavigation = false;
                            },
                            700
                        );
                    }
                );
            })(tocItems[k]);
        }

        var observer = new IntersectionObserver(
            function (entries) {

                if (manualNavigation) {
                    return;
                }

                var currentScroll = window.scrollY;
                var scrollingDown =
                    currentScroll > lastScrollTop;

                for (var m = 0; m < entries.length; m++) {
                    var entry = entries[m];
                    var targetIndex = -1;

                    for (var n = 0; n < tocItems.length; n++) {

                        if (
                            tocItems[n].block ===
                            entry.target
                        ) {
                            targetIndex = n;
                            break;
                        }
                    }

                    if (targetIndex === -1) {
                        continue;
                    }

                    if (
                        scrollingDown &&
                        entry.isIntersecting
                    ) {
                        setCurrent(targetIndex);
                    }

                    if (
                        !scrollingDown &&
                        !entry.isIntersecting &&
                        targetIndex === currentActive
                    ) {
                        setCurrent(targetIndex - 1);
                    }
                }

                lastScrollTop = currentScroll;
            },
            {
                threshold: 0,
                rootMargin: '0px'
            }
        );

        for (var p = 0; p < tocItems.length; p++) {
            observer.observe(
                tocItems[p].block
            );
        }

        setCurrent(0);
    });
</script>
<?php endif; ?>