<?php

namespace Brandy\BlockSettings\ResponsiveConditions;

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

class Caller implements ExternalBlockSettingsInterface {
	use SingletonTrait;

	/**
	 * Track if frontend styles already enqueued.
	 *
	 * @var bool
	 */
	private $frontend_styles_enqueued = false;

	protected function __construct() {
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_settings_scripts' ) );
		add_action( 'enqueue_block_assets', array( $this, 'enqueue_editor_styles' ) );
		add_filter( 'block_type_metadata_settings', array( $this, 'declare_attribute' ), 100 );
		add_filter( 'render_block', array( $this, 'apply_responsive_conditions' ), 100, 3 );
	}

	public function declare_attribute( $settings ) {
		if ( ! empty( $settings['attributes'] ) ) {
			$settings['attributes']['hideOnDesktop'] = array(
				'type'      => 'boolean',
				'default'   => false,
				'attribute' => 'data-hide-on-desktop',
			);
			$settings['attributes']['hideOnTablet'] = array(
				'type'      => 'boolean',
				'default'   => false,
				'attribute' => 'data-hide-on-tablet',
			);
			$settings['attributes']['hideOnMobile'] = array(
				'type'      => 'boolean',
				'default'   => false,
				'attribute' => 'data-hide-on-mobile',
			);
		}
		return $settings;
	}

	public function enqueue_settings_scripts() {
		// Helpers script must load BEFORE the controls script (sets up
		// window.BrandyResponsiveConditionsHelpers which controls consumes).
		wp_enqueue_script( 'brandy/responsive-conditions-helpers', BRANDY_TEMPLATE_URL . '/inc/BlockSettings/ResponsiveConditions/script-helpers.js', array(), BRANDY_SCRIPT_VERSION, true );
		// Single source of truth for WP version detection. Phase 3 (PHP render
		// bridge) uses the same version_compare; JS reads this flag. Attached
		// to the helpers script so it parses before either consumer runs.
		// Strip pre-release suffix (e.g. "7.0-RC4" → "7.0") so RC/beta builds
		// of 7.0+ are detected as 7.0+ — version_compare treats "-RC4" as < final.
		$wp_version = preg_replace( '/-.*$/', '', get_bloginfo( 'version' ) );
		wp_localize_script(
			'brandy/responsive-conditions-helpers',
			'BrandyResponsiveConditions',
			array(
				'isWp7Plus' => version_compare( $wp_version, '7.0', '>=' ),
			)
		);
		wp_enqueue_script( 'brandy/responsive-conditions-controls', BRANDY_TEMPLATE_URL . '/inc/BlockSettings/ResponsiveConditions/script.js', array( 'wp-edit-post', 'brandy/responsive-conditions-helpers' ), BRANDY_SCRIPT_VERSION, true );
	}

	public function enqueue_editor_styles() {
		wp_register_style( 'brandy/responsive-conditions-editor', false );
		wp_enqueue_style( 'brandy/responsive-conditions-editor' );
		wp_add_inline_style( 'brandy/responsive-conditions-editor', $this->get_editor_css() );
	}

	public function get_editor_css() {
		return '*[data-hide-ons]{position:relative;outline:1px dashed var(--wp-admin-theme-color)}';
	}

	/**
	 * Enqueue frontend styles only when needed.
	 */
	private function maybe_enqueue_frontend_styles( $admin_enqueue = false ) {
		if ( ! $admin_enqueue && is_admin() ) {
			return;
		}

		if ( $admin_enqueue && ! is_admin() ) {
			return;
		}

		if ( $this->frontend_styles_enqueued ) {
			return;
		}
		$this->frontend_styles_enqueued = true;
		wp_register_style( 'brandy/responsive-conditions-style', false );
		wp_enqueue_style( 'brandy/responsive-conditions-style' );
		wp_add_inline_style( 'brandy/responsive-conditions-style', $this->get_css() );
	}

	public function get_css() {
		ob_start();
		?>
	@media screen and (min-width:1024px){body [data-hide-on-desktop]{display:none!important}}@media screen and (min-width:480px) and (max-width:1023px){body [data-hide-on-tablet]{display:none!important}}@media screen and (max-width:479px){body [data-hide-on-mobile]{display:none!important}}
		<?php
		return ob_get_clean();
	}

	public function apply_responsive_conditions( $html, $block, $attributes ) {

		if ( ! isset( $block['blockName'] ) ) {
			return $html;
		}

		$has_responsive_condition = ! empty( $block['attrs']['hideOnDesktop'] )
			|| ! empty( $block['attrs']['hideOnTablet'] )
			|| ! empty( $block['attrs']['hideOnMobile'] );

		if ( ! $has_responsive_condition ) {
			return $html;
		}

		$this->maybe_enqueue_frontend_styles();

		$tag = new \WP_HTML_Tag_Processor( $html );

		if ( $tag->next_tag() ) {
			if ( ! empty( $block['attrs']['hideOnDesktop'] ) ) {
				$tag->set_attribute( 'data-hide-on-desktop', 'true' );
			}
			if ( ! empty( $block['attrs']['hideOnTablet'] ) ) {
				$tag->set_attribute( 'data-hide-on-tablet', 'true' );
			}
			if ( ! empty( $block['attrs']['hideOnMobile'] ) ) {
				$tag->set_attribute( 'data-hide-on-mobile', 'true' );
			}
			$html = $tag->get_updated_html();
		}

		return $html;
	}

}

Caller::get_instance();
