<?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-b24e2866" data-analytics-pause="aae72767e30b" data-test-dimension="ce5f3b559837" data-test-checked="f4a61b85d" data-bs-fixture="5e90e5021835">
<div class="g-71e7e3e9" data-element-status="deleted" data-bs-testid="1b25136" data-widget-trigger="8fc7ca64577c" data-analytics-mock="67b1e4" data-bs-interval="59771283ff1d">
	<?php if ( $show_sidebar ) : ?>
		<aside class="g-7d20eb38" aria-label="Post information" id="elem-b1c171b4211abe4c">
			<div class="g-2cbff5ec" data-element-action="focus" data-mui-toggle="collapse" data-module-target="1b909d65ab4">
				<div class="g-d5946514" id="elem-e37ee2d498641a7f">
					<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-0b27f196 g-8c0d7ac6">
						Reading time: <?php echo esc_html( $read_time ); ?> min.
					</span>
				</div>
				<?php if ( ! empty( $headings ) ) : ?>
					<nav class="g-7c93797f" aria-label="Table of contents" data-element-target="ab8eba21bfa" data-section-position="center" data-element-size="large" data-test-disabled="d143c00f051d">
						<div class="g-e84ad4f5 g-fc21ac9a" id="elem-d57b207ba25f363d">
						Contents:
						</div>
						<ol class="g-1f874709" data-module-layout="f2f11ef66" data-component-theme="auto" data-element-animation="none">
							<?php foreach ( $headings as $heading ) : ?>
								<li class="g-916e906f level-<?php echo esc_attr( $heading['level'] ); ?>">
									<a class="g-fa6488c4" 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-8ef1064b" id="elem-bdfc01116b4cc388">
		<?php echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		<footer class="g-bba7eee5" data-test-selected="0a8fe36" data-component-content="65bdc5f">
			<?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-7c93797f 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-37b7a69b');
            }

            tocItems[index]
                .link
                .classList
                .add('g-37b7a69b');
        }

        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; ?>