<?php

namespace ThimPress\ThimBlocks\Gutenberg\Blocks\Accordion;

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

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

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


	public $block_name = 'accordion';

	public function get_supports(): array {
		return array(
			'align'           => true,
			'anchor'          => false,
			'customClassName' => true,
			'spacing'         => array(
				'margin'   => true,
				'padding'  => true,
				'blockGap' => true,
			),
			'layout'          => true,
			'color'           => array(
				'text'       => true,
				'background' => true,
			),
		);
	}

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

		try {
			wp_enqueue_script( 'thim-blocks-view-' . $this->block_name );

			// Classes
			$classes = array( 'thim-blocks-accordion' );
			if ( ! empty( $attributes['iconPosition'] ) ) {
				$classes[] = 'thim-blocks-accordion-icon-' . $attributes['iconPosition'];
			}

			// Style variables
			$style = array();

			// Icon space
			if ( isset( $attributes['iconSpace'] ) && $attributes['iconSpace'] !== '' ) {
				$style['--icon-space'] = $attributes['iconSpace'] . 'px';
			}

			// Icon font size
			$iconFontSize = $attributes['iconFontSize'] ?? array();
			foreach ( array( 'desktop', 'tablet', 'mobile' ) as $device ) {
				if ( ! empty( $iconFontSize[ $device ] ) ) {
					$style[ "--icon-font-size-$device" ] = $iconFontSize[ $device ];
				}
			}

			// Colors
			$Colors = $attributes['Colors'] ?? array();
			foreach ( array( 'normal', 'active' ) as $state ) {
				if ( ! empty( $Colors[ $state ] ) ) {
					foreach ( array( 'title', 'background', 'icon', 'description' ) as $prop ) {
						if ( isset( $Colors[ $state ][ $prop ] ) && $Colors[ $state ][ $prop ] !== '' ) {
							$style[ "--accordion-$prop-$state" ] = $Colors[ $state ][ $prop ];
						}
					}
				}
			}

			// Convert style array to inline string
			$inline_style = '';
			foreach ( $style as $prop => $value ) {
				$inline_style .= $prop . ':' . esc_attr( $value ) . ';';
			}

			// Wrapper attributes
			$wrapper_attributes = get_block_wrapper_attributes(
				array(
					'class' => implode( ' ', $classes ),
					'style' => $inline_style ?: null,
				)
			);

			$html = sprintf(
				'<div %s>%s</div>',
				wp_kses_post( $wrapper_attributes ),
				$content
			);
		} catch ( Throwable $e ) {
			return $html;
		}

		return $html;
	}

}
