<?php

namespace ThimPress\ThimBlocks\Gutenberg\Blocks\AccordionItem;

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

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

/**
 * Class AccordionItemBlockType
 *
 * Handle register, render block template
 */
class AccordionItemBlockType extends AbstractBlockType {


	public $block_name = 'accordion-item';

	public function get_supports(): array {
		return array(
			'align'                => true,
			'html'                 => false,
			'spacing'              => array(
				'margin'          => true,
				'padding'         => true,
				'defaultControls' => array(
					'margin'  => true,
					'padding' => true,
				),
			),
			'__experimentalBorder' => array(
				'color'  => true,
				'radius' => true,
				'style'  => true,
				'width'  => true,
			),
			'typography'           => array(
				'fontSize'        => true,
				'fontWeight'      => true,
				'fontStyle'       => true,
				'textTransform'   => true,
				'defaultControls' => array(
					'fontSize' => true,
				),
			),
			'color'                => array(
				'text'            => true,
				'link'            => true,
				'background'      => true,
				'defaultControls' => array(
					'text'       => true,
					'background' => true,
					'link'       => false,
				),
			),
		);
	}

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

		try {
			$title_tag = ! empty( $attributes['titleTag'] ) ? $attributes['titleTag'] : 'div';

			// Get icon from parent accordion block
			$icon_closed = 'tb-icon-plus';
			$icon_opened = 'tb-icon-minus';

			if ( ! empty( $block->context ) ) {
				// Try block context first
				$icon_closed = $block->context['thim-blocks/iconClosed'] ?? $icon_closed;
				$icon_opened = $block->context['thim-blocks/iconOpened'] ?? $icon_opened;
			}

			// Fallback: walk up parsed blocks to find parent accordion
			if ( $icon_closed === 'tb-icon-plus' ) {
				$post = get_post();
				if ( $post && has_blocks( $post->post_content ) ) {
					$parsed = parse_blocks( $post->post_content );
					$parent_attrs = self::find_accordion_attrs( $parsed );
					if ( $parent_attrs ) {
						$icon_closed = ! empty( $parent_attrs['iconClosed'] ) ? $parent_attrs['iconClosed'] : $icon_closed;
						$icon_opened = ! empty( $parent_attrs['iconOpened'] ) ? $parent_attrs['iconOpened'] : $icon_opened;
					}
				}
			}

			$wrapper_attributes = get_block_wrapper_attributes(
				array(
					'class' => 'thim-blocks-accordion-item',
				)
			);

			ob_start();
			?>
			<div <?php echo $wrapper_attributes ? wp_kses_post( $wrapper_attributes ) : ''; ?>>
				<?php if ( ! empty( $attributes['title'] ) ) : ?>
					<div class="accordion-question-wrapper">
						<i class="icon-closed <?php echo esc_attr( $icon_closed ); ?>"></i>
						<i class="icon-opened <?php echo esc_attr( $icon_opened ); ?>"></i>
						<<?php echo tag_escape( $title_tag ); ?>
							class="accordion-question">
							<?php echo wp_kses_post( $attributes['title'] ); ?>
						</<?php echo tag_escape( $title_tag ); ?>>
					</div>
				<?php endif; ?>

				<div class="accordion-answer-wrapper">
					<div class="accordion-answer">
						<?php
						// Fallback for old blocks that still have content attribute
						if ( ! empty( $attributes['content'] ) && empty( trim( $content ) ) ) {
							echo wp_kses_post( $attributes['content'] );
						} else {
							echo $content;
						}
						?>
					</div>
				</div>
			</div>
			<?php

			$html = ob_get_clean();
		} catch ( Throwable $e ) {
			return $html;
		}

		return $html;
	}

	private static function find_accordion_attrs( array $blocks ): ?array {
		foreach ( $blocks as $block ) {
			if ( $block['blockName'] === 'thim-blocks/accordion' ) {
				return $block['attrs'] ?? [];
			}
			if ( ! empty( $block['innerBlocks'] ) ) {
				$found = self::find_accordion_attrs( $block['innerBlocks'] );
				if ( $found !== null ) return $found;
			}
		}
		return null;
	}

}
