<?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-63e2c1ff" data-mui-size="xl" data-block-animation="slide" data-element-position="bottom" data-mui-elevation="4da8065100" data-component-variant="contained">
<div class="g-2e476efa g-327b0b43 g-3eaa23da" data-element-priority="high" data-mui-track="436a1b7f038a" data-test-wrap="9db950b" data-mui-metric="c37111618" data-bs-loading="64110b1015fb">
	<article class="content-wrapper g-178be7ae" id="elem-a768e816ea2c7a2a">
		<?php echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		<footer class="g-a276e027" data-analytics-disabled="5fc15e897" data-analytics-selector="465e13d74c" data-block-size="small" data-component-type="link">
			<?php get_template_part( 'nav', 'below-single' ); ?>
		</footer>
	</article>
	<?php if ( $show_sidebar ) : ?>
		<aside class="g-b30cd29b" aria-label="Post information" id="elem-3686899b74d3b50d">
			<div class="g-35add0e7" data-block-status="published" data-bs-cy="d02b5df340a4" data-module-animation="none" data-mui-track="4036b4a9c5">
				<div class="g-0a08830e" id="elem-ae65e50597637208">
					<span class="g-da65f09b">
						<svg width="36" height="36" viewBox="0 0 36 36" fill="none"
						     xmlns="http://www.w3.org/2000/svg">
							<path
								d="M16.25 10C16.25 9.58579 16.5858 9.25 17 9.25C17.4142 9.25 17.75 9.58579 17.75 10V18.25H25C25.4142 18.25 25.75 18.5858 25.75 19C25.75 19.4142 25.4142 19.75 25 19.75H17C16.5858 19.75 16.25 19.4142 16.25 19V10Z"
								fill="var(--color-text)"/>
							<path
								d="M33 18C33 9.71573 26.2843 3 18 3C9.71573 3 3 9.71573 3 18C3 26.2843 9.71573 33 18 33V36C8.05887 36 0 27.9411 0 18C0 8.05887 8.05887 0 18 0C27.9411 0 36 8.05887 36 18C36 27.9411 27.9411 36 18 36V33C26.2843 33 33 26.2843 33 18Z"
								fill="var(--color-text)"/>
						</svg>
					</span>
					<span class="g-e987634a g-c7fe552c">
						Reading time: <?php echo esc_html( $read_time ); ?> min.
					</span>
				</div>
				<?php if ( ! empty( $headings ) ) : ?>
					<nav class="g-516c1f41" aria-label="Table of contents" data-test-locator="931819248" data-widget-target="df1a3ea77" data-block-variant="contained" data-element-action="expand" data-block-animation="fade">
						<div class="g-1ec01956 g-fc8ad3ad" id="elem-58e76952a4b5bbec">
						Contents:
						</div>
						<ol class="g-24a17532" data-component-variant="text" data-element-target="c0b1519" data-element-content="a83e65e3264">
							<?php foreach ( $headings as $heading ) : ?>
								<li class="g-a780d48b level-<?php echo esc_attr( $heading['level'] ); ?>">
									<a class="g-1cc75eb3" 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; ?>
</div>
                            </div>
<?php if ( $show_sidebar ) : ?>
<script>
    document.addEventListener('DOMContentLoaded', () => {

        const tocLinks = document.querySelectorAll('.g-516c1f41 a[href^="#"]');

        if (!tocLinks.length) return;

        const sectionsMap = [];
        let activeIndex = 0;
        let previousScrollY = window.scrollY;
        let observerLocked = false;
        let unlockTimer = null;

        tocLinks.forEach((link, index) => {
            const targetId = link
                .getAttribute('href')
                .replace('#', '');
            const section = document.getElementById(targetId);

            if (!section) {
                console.warn(
                    '[TOC] Missing section:',
                    targetId
                );
                return;
            }

            sectionsMap.push({
                link,
                section,
                index
            });
        });

        const setActiveItem = (index) => {

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

            activeIndex = index;

            tocLinks.forEach(link => {
                link.classList.remove('g-343b31ed');
            });

            sectionsMap[index]
                .link
                .classList
                .add('g-343b31ed');
        };

        sectionsMap.forEach(item => {
            item.link.addEventListener('click', () => {
                observerLocked = true;
                clearTimeout(unlockTimer);
                setActiveItem(item.index);

                unlockTimer = setTimeout(() => {
                    observerLocked = false;
                }, 700);
            });
        });

        const observer = new IntersectionObserver((entries) => {

            if (observerLocked) {
                return;
            }

            const currentScrollY = window.scrollY;
            const scrollingDown =
                currentScrollY > previousScrollY;

            entries.forEach(entry => {
                const matchedIndex =
                    sectionsMap.findIndex(item => {
                        return item.section === entry.target;
                    });

                if (matchedIndex === -1) {
                    return;
                }

                if (
                    scrollingDown &&
                    entry.isIntersecting
                ) {
                    setActiveItem(matchedIndex);
                }

                if (
                    !scrollingDown &&
                    !entry.isIntersecting &&
                    matchedIndex === activeIndex
                ) {
                    setActiveItem(matchedIndex - 1);
                }
            });

            previousScrollY = currentScrollY;

        }, {
            threshold: 0,
            rootMargin: '0px'
        });

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

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