<?php

namespace Waypoint\Agent\Helpers;

class Blocks {

	public static function collect_names( array $blocks ): array {
		$names = [];
		foreach ( $blocks as $block ) {
			if ( ! empty( $block['blockName'] ) ) {
				$names[] = $block['blockName'];
			}
			if ( ! empty( $block['innerBlocks'] ) ) {
				$names = array_merge( $names, self::collect_names( $block['innerBlocks'] ) );
			}
		}
		return array_values( array_unique( array_filter( $names ) ) );
	}

	public static function extract_headings( string $content, int $level ): array {
		$headings = [];

		$walk = function ( array $blocks ) use ( &$walk, $level, &$headings ): void {
			foreach ( $blocks as $block ) {
				if ( 'core/heading' === $block['blockName'] ) {
					$block_level = isset( $block['attrs']['level'] ) ? (int) $block['attrs']['level'] : 2;
					if ( $block_level === $level && ! empty( $block['innerHTML'] ) ) {
						$text = trim( wp_strip_all_tags( $block['innerHTML'] ) );
						if ( '' !== $text ) {
							$headings[] = $text;
						}
					}
				}
				if ( ! empty( $block['innerBlocks'] ) ) {
					$walk( $block['innerBlocks'] );
				}
			}
		};

		$walk( parse_blocks( $content ) );
		return $headings;
	}
}
