<?php
/**
 * Template helper functions.
 *
 * @package HaPantheon
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Return one of the theme's inline SVG icons.
 *
 * The SVG strings are internal, fixed theme assets and are not user input.
 *
 * @param string $name  Icon key.
 * @param string $class Optional CSS class.
 * @return string
 */
function hapantheon_icon( $name, $class = '' ) {
	$class_attr = $class ? ' class="' . esc_attr( $class ) . '"' : '';
	$icons      = array(
		'temple'    => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 3 8h18l-9-5Z"/><path d="M5 10v8M9.5 10v8M14.5 10v8M19 10v8M3 20h18"/></svg>',
		'search'    => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>',
		'sun'       => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>',
		'moon'      => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z"/></svg>',
		'menu'      => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" aria-hidden="true"><path d="M4 7h16M4 12h16M4 17h16"/></svg>',
		'close'     => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',
		'arrow'     => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>',
		'instagram' => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.2" cy="6.8" r=".8" fill="currentColor"/></svg>',
		'facebook'  => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 8h3V4.5h-3A4.5 4.5 0 0 0 9.5 9v2.5H7V15h2.5v6H13v-6h3l.7-3.5H13V9a1 1 0 0 1 1-1Z"/></svg>',
		'youtube'   => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2.5" y="6" width="19" height="12.5" rx="3.5"/><path d="m10.5 9.8 4.5 2.5-4.5 2.5v-5Z"/></svg>',
		'mail'      => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="3"/><path d="m3 7 9 6 9-6"/></svg>',
		'rss'       => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 11a9 9 0 0 1 9 9M4 4a16 16 0 0 1 16 16"/><circle cx="5" cy="19" r="1.4" fill="currentColor"/></svg>',
		'whatsapp'  => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3a9 9 0 0 0-7.8 13.5L3 21l4.6-1.2A9 9 0 1 0 12 3Z"/><path d="M9 9.5c.3 2.5 3 5.2 5.5 5.5l1.5-1.5-2-1.2-1 .7c-.8-.4-1.6-1.2-2-2l.7-1-1.2-2L9 9.5Z"/></svg>',
		'telegram'  => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 4 3 11l5.5 2L10 19l3-3.5 4.5 3L21 4Z"/></svg>',
		'link'      => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 6 .5l3-3a4 4 0 0 0-5.7-5.7l-1.6 1.6"/><path d="M14 10a4 4 0 0 0-6-.5l-3 3a4 4 0 0 0 5.7 5.7l1.6-1.6"/></svg>',
		'up'        => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M6 11l6-6 6 6"/></svg>',
		'clock'     => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="13" r="8"/><path d="M12 9v4l2.5 2.5M9 2h6"/></svg>',
		'hourglass' => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 22h14M5 2h14M7 22v-4.2a2 2 0 0 1 .6-1.4L11 13l-3.4-3.4A2 2 0 0 1 7 8.2V2M17 22v-4.2a2 2 0 0 0-.6-1.4L13 13l3.4-3.4a2 2 0 0 0 .6-1.4V2"/></svg>',
		'glass'     => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2h8l1 7a5 5 0 0 1-10 0l1-7Z"/><path d="M12 14v6M8 22h8"/></svg>',
		'star'      => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2 9.5 8.5 2.5 9l5.2 4.6L6 21l6-3.6L18 21l-1.7-7.4L21.5 9l-7-.5L12 2Z"/></svg>',
		'send'      => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 3 3 10.5l7 3.5M21 3l-7.5 18-3.5-7M21 3 10 14"/></svg>',
		'shield'    => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 5 6v5c0 4.5 3 8.1 7 10 4-1.9 7-5.5 7-10V6l-7-3Z"/></svg>',
		'yes-alt'   => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 4 4L19 6"/></svg>',
		'visibility'=> '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"/><circle cx="12" cy="12" r="2.6"/></svg>',
		'backup'    => '<svg' . $class_attr . ' viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7v5h5"/><path d="M5.4 16.5A8 8 0 1 0 4 12"/><path d="M12 8v4l3 2"/></svg>',
	);

	return isset( $icons[ $name ] ) ? $icons[ $name ] : '';
}

/**
 * URL for the assigned posts/archive page.
 *
 * @return string
 */
function hapantheon_get_archive_url() {
	$page_for_posts = (int) get_option( 'page_for_posts' );
	if ( $page_for_posts ) {
		return get_permalink( $page_for_posts );
	}

	return home_url( '/archive/' );
}

/**
 * Resolve a page URL by slug, with a safe home fallback.
 *
 * @param string $slug Page slug.
 * @return string
 */
function hapantheon_get_page_url_by_slug( $slug ) {
	$page = get_page_by_path( sanitize_title( $slug ) );
	return $page ? get_permalink( $page ) : home_url( '/' . trim( $slug, '/' ) . '/' );
}

/**
 * Fallback primary menu displayed before demo import.
 *
 * @param stdClass $args Menu arguments.
 */
function hapantheon_primary_menu_fallback( $args = null ) {
	$items = array(
		array( 'דף הבית', home_url( '/' ) ),
		array( 'הארכיון', hapantheon_get_archive_url() ),
		array( 'האורקל', hapantheon_get_page_url_by_slug( 'oracle' ) ),
		array( 'אודות', hapantheon_get_page_url_by_slug( 'about' ) ),
		array( 'שו״ת', hapantheon_get_page_url_by_slug( 'faq' ) ),
		array( 'צור קשר', hapantheon_get_page_url_by_slug( 'contact' ) ),
	);

	echo '<ul class="links" id="primary-menu">';
	foreach ( $items as $item ) {
		printf(
			'<li><a href="%1$s">%2$s</a></li>',
			esc_url( $item[1] ),
			esc_html( $item[0] )
		);
	}
	echo '</ul>';
}

/**
 * Fallback legal menu displayed before demo import.
 *
 * @param stdClass $args Menu arguments.
 */
function hapantheon_footer_legal_menu_fallback( $args = null ) {
	$items = array(
		array( __( 'תנאי שימוש', 'hapantheon' ), hapantheon_get_page_url_by_slug( 'terms' ) ),
		array( __( 'פרטיות', 'hapantheon' ), get_privacy_policy_url() ? get_privacy_policy_url() : hapantheon_get_page_url_by_slug( 'privacy-policy' ) ),
		array( __( 'נגישות', 'hapantheon' ), hapantheon_get_page_url_by_slug( 'accessibility' ) ),
	);

	echo '<ul class="footer-legal-menu">';
	foreach ( $items as $item ) {
		printf(
			'<li><a href="%1$s">%2$s</a></li>',
			esc_url( $item[1] ),
			esc_html( $item[0] )
		);
	}
	echo '</ul>';
}

/**
 * Hall metadata keyed by category slug.
 *
 * @param string $slug Category slug.
 * @return array
 */
function hapantheon_hall_data( $slug ) {
	$halls = array(
		'recipes' => array(
			'glyph' => 'ALPHA',
			'label' => __( 'מתכונים', 'hapantheon' ),
			'class' => '',
		),
		'stories' => array(
			'glyph' => 'BETA',
			'label' => __( 'סיפורים', 'hapantheon' ),
			'class' => '',
		),
		'travel' => array(
			'glyph' => 'GAMMA',
			'label' => __( 'טיולים', 'hapantheon' ),
			'class' => '',
		),
		'diy' => array(
			'glyph' => 'DELTA',
			'label' => __( 'מלאכה', 'hapantheon' ),
			'class' => '',
		),
		'oracle' => array(
			'glyph' => 'EPSILON',
			'label' => __( 'האורקל', 'hapantheon' ),
			'class' => 'tealc',
		),
	);

	if ( isset( $halls[ $slug ] ) ) {
		return $halls[ $slug ];
	}

	return array(
		'glyph' => 'INDEX',
		'label' => __( 'ארכיון', 'hapantheon' ),
		'class' => '',
	);
}

/**
 * Return the first assigned category, preferring the five theme halls.
 *
 * @param int $post_id Post ID.
 * @return WP_Term|null
 */
function hapantheon_primary_category( $post_id = 0 ) {
	$post_id    = $post_id ? (int) $post_id : get_the_ID();
	$categories = get_the_category( $post_id );
	if ( empty( $categories ) ) {
		return null;
	}

	$priority = array( 'recipes', 'stories', 'travel', 'diy', 'oracle' );
	foreach ( $priority as $slug ) {
		foreach ( $categories as $category ) {
			if ( $category->slug === $slug ) {
				return $category;
			}
		}
	}

	return $categories[0];
}

/**
 * Render category eyebrow text.
 *
 * @param int $post_id Post ID.
 * @return string
 */
function hapantheon_category_label( $post_id = 0 ) {
	$custom = get_post_meta( $post_id ? $post_id : get_the_ID(), '_hapantheon_eyebrow', true );
	if ( $custom ) {
		return $custom;
	}

	$category = hapantheon_primary_category( $post_id );
	if ( ! $category ) {
		return 'INDEX · הארכיון';
	}
	$hall = hapantheon_hall_data( $category->slug );

	return $hall['glyph'] . ' · ' . $category->name;
}

/**
 * Calculate or retrieve reading time.
 *
 * @param int $post_id Post ID.
 * @return int
 */
function hapantheon_reading_time( $post_id = 0 ) {
	$post_id = $post_id ? (int) $post_id : get_the_ID();
	$stored  = absint( get_post_meta( $post_id, '_hapantheon_reading_time', true ) );
	if ( $stored ) {
		return $stored;
	}

	$content = wp_strip_all_tags( get_post_field( 'post_content', $post_id ) );
	$words   = 0;
	if ( preg_match_all( '/[\p{L}\p{N}]+(?:[׳״’\'-][\p{L}\p{N}]+)*/u', $content, $matches ) ) {
		$words = count( $matches[0] );
	}

	return max( 1, (int) ceil( $words / 200 ) );
}

/**
 * Featured-image URL with a remote demo-image fallback.
 *
 * @param int          $post_id Post ID.
 * @param string|array $size    Image size.
 * @return string
 */
function hapantheon_featured_image_url( $post_id = 0, $size = 'large' ) {
	$post_id = $post_id ? (int) $post_id : get_the_ID();

	if ( has_post_thumbnail( $post_id ) ) {
		$url = get_the_post_thumbnail_url( $post_id, $size );
		if ( $url ) {
			return $url;
		}
	}

	$remote = esc_url_raw( get_post_meta( $post_id, '_hapantheon_featured_url', true ) );
	if ( $remote ) {
		return $remote;
	}

	return HAPANTHEON_URI . '/assets/images/placeholder.svg';
}

/**
 * Render a post card used by archives and related-content sections.
 *
 * @param int $post_id Post ID.
 */
function hapantheon_post_card( $post_id = 0 ) {
	$post_id  = $post_id ? (int) $post_id : get_the_ID();
	$category = hapantheon_primary_category( $post_id );
	$slug     = $category ? $category->slug : 'all';
	$hall     = hapantheon_hall_data( $slug );
	$excerpt  = get_the_excerpt( $post_id );
	if ( ! $excerpt ) {
		$excerpt = wp_trim_words( wp_strip_all_tags( get_post_field( 'post_content', $post_id ) ), 22 );
	}
	?>
	<a class="entry rv" href="<?php echo esc_url( get_permalink( $post_id ) ); ?>" data-cat="<?php echo esc_attr( $slug ); ?>">
		<div class="entry-media">
			<img decoding="async" loading="lazy" src="<?php echo esc_url( hapantheon_featured_image_url( $post_id, 'hapantheon-card' ) ); ?>" alt="<?php echo esc_attr( get_the_title( $post_id ) ); ?>">
		</div>
		<div class="entry-body">
			<span class="entry-cat <?php echo esc_attr( $hall['class'] ); ?>"><?php echo esc_html( hapantheon_category_label( $post_id ) ); ?></span>
			<h3><?php echo esc_html( get_the_title( $post_id ) ); ?></h3>
			<p><?php echo esc_html( $excerpt ); ?></p>
			<div class="entry-meta">
				<span><span class="num"><?php echo esc_html( hapantheon_reading_time( $post_id ) ); ?></span> דק׳ קריאה</span>
				<span><?php echo esc_html( get_the_date( '', $post_id ) ); ?></span>
			</div>
		</div>
	</a>
	<?php
}

/**
 * Standard post metadata row.
 *
 * @param bool $show_location Include the optional location line.
 */
function hapantheon_post_meta_row( $show_location = true ) {
	$location = get_post_meta( get_the_ID(), '_hapantheon_location', true );
	?>
	<div class="art-meta">
		<span><span class="num"><?php echo esc_html( hapantheon_reading_time() ); ?></span> דק׳ קריאה</span>
		<span><?php echo esc_html( get_the_date() ); ?></span>
		<?php if ( $show_location && $location ) : ?>
			<span><?php echo esc_html( $location ); ?></span>
		<?php endif; ?>
	</div>
	<?php
}

/**
 * Render sharing controls.
 *
 * @param string $class Additional wrapper classes.
 */
function hapantheon_share_row( $class = '' ) {
	$url      = get_permalink();
	$title    = get_the_title();
	$wa_url   = 'https://wa.me/?text=' . rawurlencode( $title . ' ' . $url );
	$tg_url   = 'https://t.me/share/url?url=' . rawurlencode( $url ) . '&text=' . rawurlencode( $title );
	$mail_url = 'mailto:?subject=' . rawurlencode( $title ) . '&body=' . rawurlencode( $url );
	?>
	<div class="share-row rv <?php echo esc_attr( $class ); ?>">
		<span>שתפו את המגילה</span>
		<a href="<?php echo esc_url( $wa_url ); ?>" target="_blank" rel="noopener noreferrer" aria-label="<?php esc_attr_e( 'שיתוף ב-WhatsApp', 'hapantheon' ); ?>"><?php echo hapantheon_icon( 'whatsapp' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></a>
		<a href="<?php echo esc_url( $tg_url ); ?>" target="_blank" rel="noopener noreferrer" aria-label="<?php esc_attr_e( 'שיתוף ב-Telegram', 'hapantheon' ); ?>"><?php echo hapantheon_icon( 'telegram' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></a>
		<button type="button" data-copy-url="<?php echo esc_url( $url ); ?>" aria-label="<?php esc_attr_e( 'העתקת קישור', 'hapantheon' ); ?>"><?php echo hapantheon_icon( 'link' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></button>
		<a href="<?php echo esc_url( $mail_url ); ?>" aria-label="<?php esc_attr_e( 'שיתוף בדוא״ל', 'hapantheon' ); ?>"><?php echo hapantheon_icon( 'mail' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></a>
	</div>
	<?php
}

/**
 * Render the current author's profile.
 */
function hapantheon_author_box() {
	$author_id   = (int) get_the_author_meta( 'ID' );
	$description = get_the_author_meta( 'description', $author_id );
	if ( ! $description ) {
		$description = 'אוצר הארכיון. כותב על מה שנבדק, נחווה או ראוי להישמר.';
	}
	?>
	<div class="author-box rv">
		<img decoding="async" loading="lazy" src="<?php echo esc_url( get_avatar_url( $author_id, array( 'size' => 200 ) ) ); ?>" alt="<?php echo esc_attr( get_the_author_meta( 'display_name', $author_id ) ); ?>">
		<div>
			<small class="eyebrow" style="letter-spacing:.2em;font-size:.62rem">נכתב על ידי</small>
			<b><?php echo esc_html( get_the_author_meta( 'display_name', $author_id ) ); ?></b>
			<p><?php echo esc_html( $description ); ?></p>
		</div>
	</div>
	<?php
}

/**
 * Adjacent post navigation.
 */
function hapantheon_adjacent_navigation() {
	$previous = get_previous_post();
	$next     = get_next_post();

	if ( ! $previous && ! $next ) {
		return;
	}
	?>
	<nav class="prevnext rv" aria-label="<?php esc_attr_e( 'מגילות סמוכות', 'hapantheon' ); ?>">
		<?php if ( $previous ) : ?>
			<a class="pn" href="<?php echo esc_url( get_permalink( $previous ) ); ?>"><small>המגילה הקודמת</small><b><?php echo esc_html( get_the_title( $previous ) ); ?></b></a>
		<?php endif; ?>
		<?php if ( $next ) : ?>
			<a class="pn next" href="<?php echo esc_url( get_permalink( $next ) ); ?>"><small>המגילה הבאה</small><b><?php echo esc_html( get_the_title( $next ) ); ?></b></a>
		<?php endif; ?>
	</nav>
	<?php
}

/**
 * Related posts from the current category.
 *
 * @param int $count Number of cards.
 */
function hapantheon_related_posts( $count = 3 ) {
	$category = hapantheon_primary_category();
	$args     = array(
		'post_type'           => 'post',
		'posts_per_page'      => absint( $count ),
		'post__not_in'        => array( get_the_ID() ),
		'ignore_sticky_posts' => true,
		'no_found_rows'       => true,
	);
	if ( $category ) {
		$args['category__in'] = array( $category->term_id );
	}

	$query = new WP_Query( $args );
	if ( ! $query->have_posts() ) {
		return;
	}
	?>
	<section class="related">
		<div class="wrap">
			<div class="sec-head rv">
				<span class="eyebrow">מאותו אולם</span>
				<h2>עוד מגילות שכדאי לפתוח</h2>
			</div>
			<div class="entries" style="padding-bottom:0">
				<?php
				while ( $query->have_posts() ) {
					$query->the_post();
					hapantheon_post_card();
				}
				?>
			</div>
		</div>
	</section>
	<?php
	wp_reset_postdata();
}

/**
 * Newsletter callout displayed after standard posts.
 */
function hapantheon_post_newsletter() {
	?>
	<section class="news" style="padding-top:20px">
		<div class="wrap" style="max-width:880px">
			<div class="news-card rv">
				<span class="eyebrow">עוד מגילות כאלה</span>
				<h2>המגילה הבאה, ישירות אליכם</h2>
				<?php echo do_shortcode( '[hapantheon_newsletter source="single"]' ); ?>
			</div>
		</div>
	</section>
	<?php
}

/**
 * Add deterministic IDs to H2 headings and return a table of contents.
 *
 * @param string $content Filtered post content.
 * @return array Array with content and toc keys.
 */
function hapantheon_content_with_toc( $content ) {
	$toc   = array();
	$index = 0;

	$content = preg_replace_callback(
		'/<h2([^>]*)>(.*?)<\/h2>/is',
		function ( $matches ) use ( &$toc, &$index ) {
			++$index;
			$attributes = $matches[1];
			$label      = trim( wp_strip_all_tags( $matches[2] ) );
			$id         = 'section-' . $index;

			if ( preg_match( '/\sid=(["\'])(.*?)\1/i', $attributes, $id_match ) ) {
				$id = sanitize_html_class( $id_match[2] );
			} else {
				$attributes .= ' id="' . esc_attr( $id ) . '"';
			}

			$toc[] = array(
				'id'    => $id,
				'label' => $label,
			);

			return '<h2' . $attributes . '>' . $matches[2] . '</h2>';
		},
		$content
	);

	return array(
		'content' => $content,
		'toc'     => $toc,
	);
}
