<?php
namespace ThimPress\ThimBlocks\Gutenberg\Blocks\TabItem;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use ThimPress\ThimBlocks\Gutenberg\Blocks\AbstractBlockType;
use Throwable;

class TabItemBlockType extends AbstractBlockType {
	public $block_name = 'tab-item';

	public function get_supports(): array {
		return array(
			'anchor'   => false,
			'reusable' => false,
			'spacing'  => true,
		);
	}

	public function render_content_block_template( array $attributes, $content, $block ): string {
		$html = '';

		try {
			ob_start();
			echo wp_kses_post( $content );
			$raw_html = ob_get_clean();

			// Modify HTML with WP_HTML_Tag_Processor
			$p = new \WP_HTML_Tag_Processor( $raw_html );

			if ( $p->next_tag(
				array(
					'tag_name'   => 'div',
					'class_name' => 'thim-blocks-tab-item',
				)
			) ) {
				$p->set_attribute( 'role', 'tabpanel' );
				$p->set_attribute( 'aria-labelledby', 'thim-blocks-tabs-nav-' . ( $attributes['id'] ?? '' ) );
				$p->set_attribute( 'tabindex', '0' );
			}

			if ( $p->next_tag(
				array(
					'tag_name'   => 'h2',
					'class_name' => 'thim-blocks-tabs-item__title',
				)
			) ) {
				$p->set_attribute( 'hidden', 'true' );
				$p->set_attribute( 'style', 'display:none;' );
			}

			$html = $p->get_updated_html();
		} catch ( Throwable $e ) {
			return $html; // Return original HTML if any error occurs
		}

		return $html;
	}

}
