<?php

namespace Brandy\BlockSettings\ContentResponsiveControls;

use Brandy\Traits\SingletonTrait;
use Brandy\Interfaces\ExternalBlockSettingsInterface;

class Caller implements ExternalBlockSettingsInterface {
	use SingletonTrait;

	protected $supported_blocks = array(
		'core/group',
		'core/columns',
		'core/column',
		'core/buttons',
		'core/paragraph',
		'core/heading',
	);

	protected function __construct() {
		add_filter( 'block_type_metadata_settings', array( $this, 'declare_attribute' ), 100 );
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_settings_scripts' ) );

		foreach ( $this->supported_blocks as $block ) {
			add_filter( 'render_block_' . $block, array( $this, 'apply_responsive_controls' ), 100, 3 );
		}

	}

	public function declare_attribute( $settings ) {

		if ( empty( $settings['name'] ) ) {
			return $settings;
		}

		if ( ! $this->is_supported_block( $settings ) ) {
			return $settings;
		}

		if ( ! empty( $settings['attributes'] ) ) {
			$settings['attributes']['responsiveControls'] = array(
				'type'    => 'object',
				'default' => array(),
			);
		}
		return $settings;
	}

	public function is_supported_block( $block ) {
		if ( empty( $block['name'] ) ) {
			return false;
		}
		return in_array( $block['name'], $this->supported_blocks );
	}

	public function enqueue_settings_scripts() {
		wp_enqueue_script( 'brandy/content-responsive-controls', BRANDY_TEMPLATE_URL . '/inc/BlockSettings/ContentResponsiveControls/script.js', array( 'wp-edit-post' ), BRANDY_SCRIPT_VERSION, true );
	}

	public function apply_responsive_controls( $html, $_, $block ) {

		$tag = new \WP_HTML_Tag_Processor( $html );

		if ( $tag->next_tag() ) {
			$responsive_controls = $block->attributes['responsiveControls'] ?? array();
			$class               = $tag->get_attribute( 'class' );

			// Device prefix mapping: desktop=lg, tablet=md, mobile=sm
			$device_map = array(
				'desktop' => 'lg',
				'tablet'  => 'md',
				'mobile'  => 'sm',
			);

			foreach ( $device_map as $device => $prefix ) {
				if ( 'desktop' === $device ) {
					$prefix = '';
				} else {
					$prefix .= '-';
				}
				if ( ! empty( $responsive_controls['textAlign'][ $device ]['enabled'] ) ) {
					$value = $responsive_controls['textAlign'][ $device ]['value'] ?? 'center';
					$class = $class . ' ' . $prefix . 'text-' . $value;
				}

				// Always use "justify" prefix — CSS differentiates via .is-layout-flex / .is-vertical selectors
				if ( ! empty( $responsive_controls['justifyContent'][ $device ]['enabled'] ) ) {
					$value = $responsive_controls['justifyContent'][ $device ]['value'] ?? 'center';
					$class = $class . ' ' . $prefix . 'justify-' . $value;
				}
			}

			if ( empty( $class ) ) {
				return $html;
			}

			$tag->set_attribute( 'class', $class );

			$html = $tag->get_updated_html();
		}

		return $html;

	}

}

Caller::get_instance();
