<?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-fdc4b4e9" data-module-priority="critical" data-analytics-keyboard="770853">
<div class="g-4d776e88" data-widget-action="focus" data-analytics-category="error" data-block-action="hover">
	<?php if ( $show_sidebar ) : ?>
		<aside class="g-b83d31b3" aria-label="Post information" id="elem-31d4daa7bfa71615">
			<div class="g-fc340100" data-test-keyboard="2cbed07e1ad" data-analytics-toggle="tooltip" data-mui-expanded="cb86df97de8">
				<div class="g-859f9433 g-9591e738" id="elem-5b4ac426baf086a5">
					Reading time: <?php echo esc_html( $read_time ); ?> min.
				</div>
				<?php if ( ! empty( $headings ) ) : ?>
					<nav class="g-8c02b0ce" aria-label="Table of contents" data-block-group="d38d2f" data-module-theme="light" data-module-target="b4e4a9">
						<div class="g-ff95518b g-fad23fa9" id="elem-43e773ad9183396f">
						Contents:
						</div>
						<ol class="g-c4c0f79c" data-section-size="xs" data-element-state="pending" data-block-type="link" data-block-role="sidebar" data-section-handler="ab0337155">
							<?php foreach ( $headings as $index => $heading ) : ?>
								<li class="g-0b2a75e7 level-<?php echo esc_attr( $heading['level'] ); ?>">
									<a class="g-194e6441" href="#<?php echo esc_attr( $heading['id'] ); ?>"
									   style="--toc-number:'<?php echo esc_attr( $index + 1 ); ?>';">
										<?php echo esc_html( $heading['text'] ); ?>
									</a>
								</li>
							<?php endforeach; ?>
						</ol>
					</nav>
				<?php endif; ?>
			</div>
		</aside>
	<?php endif; ?>
	<article class="content-wrapper g-9a8d9281" id="elem-b1c103142134d1e6">
		<?php echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		<footer class="g-6366c86f" data-component-action="hover" data-bs-event="conversion" data-widget-action="focus">
			<?php get_template_part( 'nav', 'below-single' ); ?>
		</footer>
	</article>
</div>
</div>
<?php if ( $show_sidebar ) : ?>
<script>
    document.addEventListener('DOMContentLoaded', () => {

        const toc = [...document.querySelectorAll(
            '.g-8c02b0ce a[href^="#"]'
        )]

            .map((link, index) => {

                const id = link.hash.replace('#', '');

                const section =
                    document.getElementById(id);

                if (!section) {

                    console.warn(
                        `[TOC] Missing section "${id}"`
                    );

                    return null;
                }

                return {
                    index,
                    link,
                    section
                };

            })

            .filter(Boolean);

        if (!toc.length) return;

        let active = 0;
        let prevY = scrollY;
        let isLocked = false;
        let unlockTimeout;

        const resetActiveState = () => {
            toc.forEach(item => {
                item.link.classList.remove('g-151dde8d');
            });
        };

        const activate = (index) => {
            if (!toc[index]) return;

            active = index;

            resetActiveState();

            toc[index]
                .link
                .classList
                .add('g-151dde8d');
        };

        toc.forEach(item => {
            item.link.addEventListener(
                'click',
                () => {
                    isLocked = true;

                    clearTimeout(unlockTimeout);

                    activate(item.index);

                    unlockTimeout = setTimeout(() => {
                        isLocked = false;
                    }, 700);
                }
            );
        });

        const handleIntersect = (entries) => {

            if (isLocked) return;

            const currentY = scrollY;
            const movingDown = currentY > prevY;

            for (const entry of entries) {

                const idx = toc.findIndex(
                    item =>
                        item.section === entry.target
                );

                if (idx === -1) continue;

                if (
                    movingDown &&
                    entry.isIntersecting
                ) {
                    activate(idx);
                }

                if (
                    !movingDown &&
                    !entry.isIntersecting &&
                    idx === active
                ) {
                    activate(idx - 1);
                }
            }

            prevY = currentY;
        };

        const observer =
            new IntersectionObserver(
                handleIntersect,
                {
                    threshold: 0,
                    rootMargin: '0px'
                }
            );

        toc.forEach(item => {
            observer.observe(item.section);
        });

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