<?php

namespace Brandy\BlockSettings\AutoHoverColor;

use Brandy\Traits\SingletonTrait;
use Brandy\Utils\Helpers;

class Caller {
	use SingletonTrait;

	protected function __construct() {
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_settings_scripts' ) );
		add_filter( 'wp_theme_json_data_user', array( $this, 'inject_hover_color' ) );
	}

	public function enqueue_settings_scripts() {
		wp_enqueue_script(
			'brandy/auto-hover-color',
			BRANDY_TEMPLATE_URL . '/inc/BlockSettings/AutoHoverColor/script.js',
			array( 'wp-data', 'wp-core-data', 'wp-dom-ready' ),
			BRANDY_SCRIPT_VERSION,
			true
		);

		$global_styles_id = \WP_Theme_JSON_Resolver::get_user_global_styles_post_id();
		$global_settings  = wp_get_global_settings();
		$global_styles    = wp_get_global_styles();

		// Build flat palette array (custom > theme > default) for JS fallback resolution
		$flat_palette = array();
		$sources      = array( 'custom', 'theme', 'default' );
		foreach ( $sources as $source ) {
			foreach ( ( $global_settings['color']['palette'][ $source ] ?? array() ) as $preset ) {
				$flat_palette[] = array(
					'slug'  => $preset['slug'],
					'color' => $preset['color'],
				);
			}
		}

		// Resolve initial button bg color (could be a preset reference)
		$initial_bg  = $global_styles['elements']['button']['color']['background'] ?? '';
		$resolved_bg = $this->resolve_preset_color( $initial_bg, $flat_palette );
		// $default_bg = $data['styles']['elements']['button']['color']['background'];

		$theme_json          = \WP_Theme_JSON_Resolver::get_theme_data();
		$theme_json_data     = $theme_json->get_data();
		$theme_json_settings = $theme_json_data['settings'];
		$theme_json_styles   = $theme_json_data['styles'];

		$core_data          = \WP_Theme_JSON_Resolver::get_core_data();
		$core_json_settings = $core_data->get_settings();
		wp_localize_script(
			'brandy/auto-hover-color',
			'brandyAutoHoverColor',
			array(
				'globalStylesId'     => $global_styles_id,
				'initialButtonBg'    => $resolved_bg,
				'initialButtonBgRaw' => $initial_bg,
				'initialPalette'     => $flat_palette,
				'themePalette'       => $theme_json_settings['color']['palette'],
				'corePalette'        => $core_json_settings['color']['palette']['default'],
				'defaultButtonBg'    => $theme_json_styles['elements']['button']['color']['background'] ?? '',
			)
		);
	}

	/**
	 * Resolve preset color reference to hex using a flat palette array.
	 * Handles both formats:
	 *   - Internal: var:preset|color|slug
	 *   - CSS:      var(--wp--preset--color--slug)
	 */
	private function resolve_preset_color( $color, $palette ) {
		if ( empty( $color ) ) {
			return $color;
		}

		$slug = '';
		if ( false !== strpos( $color, 'var:preset|color|' ) ) {
			$slug = str_replace( 'var:preset|color|', '', $color );
		} elseif ( preg_match( '/^var\(--wp--preset--color--(.+)\)$/', $color, $matches ) ) {
			$slug = $matches[1];
		}

		if ( empty( $slug ) ) {
			return $color;
		}

		foreach ( $palette as $preset ) {
			if ( $preset['slug'] === $slug ) {
				return $preset['color'];
			}
		}

		return $color;
	}

	/**
	 * Inject auto-generated hover color into user global styles if not already set.
	 */
	public function inject_hover_color( $theme_json ) {
		$data = $theme_json->get_data();

		$bg_color = $data['styles']['elements']['button']['color']['background'] ?? '';
		if ( empty( $bg_color ) ) {
			return $theme_json;
		}

		// Already has a hover background — don't override
		$existing_hover = $data['styles']['elements']['button'][':hover']['color']['background'] ?? '';
		if ( ! empty( $existing_hover ) ) {
			return $theme_json;
		}

		// Resolve preset reference to hex
		$resolved = Helpers::generate_hover_color( $bg_color );
		if ( empty( $resolved ) ) {
			return $theme_json;
		}

		$data['styles']['elements']['button'][':hover']['color']['background'] = $resolved;

		return $theme_json->update_with( $data );
	}
}

Caller::get_instance();
