<?php
/**
 * Reads active site/Elementor design tokens for generated template widgets.
 *
 * @package Niwa_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Niwa_AI_Template_Design_Context {
	public function apply_to_widget_config( $config ) {
		$config  = is_array( $config ) ? $config : array();
		$palette = $this->palette();
		if ( empty( $palette['has_site_palette'] ) ) {
			return $config;
		}

		$config['background_color']        = $palette['background'];
		$config['text_color']              = $palette['text'];
		$config['accent_color']            = $palette['accent'];
		$config['card_background']         = $palette['card_background'];
		$config['card_text_color']         = $palette['card_text'];
		$config['muted_color']             = $palette['muted'];
		$config['button_background']       = $palette['button_background'];
		$config['button_text_color']       = $palette['button_text'];
		$config['selected_card_background'] = $palette['selected_card_background'];
		$config['selected_card_text_color'] = $palette['selected_card_text'];
		$config['design_context']          = $palette['source'];

		return $config;
	}

	private function palette() {
		$theme_tokens     = $this->theme_colors();
		$elementor_tokens = $this->elementor_kit_colors();
		$tokens           = array_merge( $theme_tokens, $elementor_tokens );
		$source           = 'defaults';
		if ( ! empty( $elementor_tokens ) ) {
			$source = 'elementor_kit';
		} elseif ( ! empty( $theme_tokens ) ) {
			$source = 'theme';
		}

		$primary   = $this->pick_color( $tokens, array( 'primary', 'accent', 'link' ), '#d6b46a' );
		$secondary = $this->pick_color( $tokens, array( 'secondary' ), '#07100d' );
		$text      = $this->pick_color( $tokens, array( 'text' ), '#64748b' );
		$heading   = $this->pick_color( $tokens, array( 'heading', 'link' ), '#111827' );

		$dark_site = $this->is_dark( $secondary );
		if ( $dark_site ) {
			$background = $this->mix_hex( $secondary, '#000000', 0.42 );
			$card       = $this->mix_hex( $secondary, '#000000', 0.16 );
			$card_text  = ! $this->is_dark( $heading ) ? $heading : '#ffffff';
			$muted      = $this->normalize_hex( $text ) ? $text : '#a0a0a0';
			$selected   = $this->mix_hex( $secondary, '#000000', 0.58 );
		} else {
			$background = '#f8fafc';
			$card       = '#ffffff';
			$card_text  = $this->is_dark( $heading ) ? $heading : '#111827';
			$muted      = $this->is_dark( $text ) ? $text : '#64748b';
			$selected   = $this->is_dark( $secondary ) ? $secondary : '#07100d';
		}

		return array(
			'has_site_palette'         => ! empty( $tokens ),
			'source'                   => $source,
			'background'               => $background,
			'text'                     => $dark_site ? $card_text : '#111827',
			'accent'                   => $primary,
			'card_background'          => $card,
			'card_text'                => $card_text,
			'muted'                    => $muted,
			'button_background'        => $primary,
			'button_text'              => $this->contrast_text( $primary ),
			'selected_card_background' => $selected,
			'selected_card_text'       => $dark_site ? $card_text : '#ffffff',
		);
	}

	private function elementor_kit_colors() {
		if ( ! class_exists( '\Elementor\Plugin' ) || ! isset( \Elementor\Plugin::$instance->kits_manager ) ) {
			return array();
		}
		$kit_id = intval( \Elementor\Plugin::$instance->kits_manager->get_active_id() );
		if ( $kit_id <= 0 ) {
			return array();
		}
		$settings = get_post_meta( $kit_id, '_elementor_page_settings', true );
		if ( ! is_array( $settings ) ) {
			return array();
		}

		$colors = array();
		foreach ( array( 'system_colors', 'custom_colors' ) as $group ) {
			foreach ( isset( $settings[ $group ] ) && is_array( $settings[ $group ] ) ? $settings[ $group ] : array() as $item ) {
				if ( empty( $item['color'] ) ) {
					continue;
				}
				$key = ! empty( $item['_id'] ) ? sanitize_key( (string) $item['_id'] ) : sanitize_key( isset( $item['title'] ) ? (string) $item['title'] : '' );
				$color = $this->normalize_hex( (string) $item['color'] );
				if ( '' !== $key && $color ) {
					$colors[ $key ] = $color;
				}
			}
		}
		return $colors;
	}

	private function theme_colors() {
		$map = array(
			'primary'   => array( 'primary_color', 'primary', 'accent_color', 'theme_primary_color' ),
			'accent'    => array( 'accent_color', 'link_color', 'button_color', 'theme_accent_color' ),
			'link'      => array( 'link_color', 'links_color' ),
			'secondary' => array( 'secondary_color', 'background_color', 'theme_secondary_color' ),
			'text'      => array( 'text_color', 'body_text_color' ),
			'heading'   => array( 'heading_color', 'headings_color', 'header_textcolor' ),
		);
		$colors = array();
		foreach ( $map as $token => $mods ) {
			foreach ( $mods as $mod ) {
				$value = function_exists( 'get_theme_mod' ) ? get_theme_mod( $mod ) : '';
				if ( ! is_string( $value ) || '' === trim( $value ) ) {
					continue;
				}
				$value = trim( $value );
				if ( preg_match( '/^[0-9a-f]{6}$/i', $value ) ) {
					$value = '#' . $value;
				}
				$color = $this->normalize_hex( $value );
				if ( $color ) {
					$colors[ $token ] = $color;
					break;
				}
			}
		}
		return $colors;
	}

	private function pick_color( $tokens, $keys, $fallback ) {
		foreach ( $keys as $key ) {
			if ( isset( $tokens[ $key ] ) && $this->normalize_hex( $tokens[ $key ] ) ) {
				return $tokens[ $key ];
			}
		}
		$fallback = $this->normalize_hex( $fallback );
		return $fallback ? $fallback : '#111827';
	}

	private function normalize_hex( $color ) {
		$color = trim( (string) $color );
		if ( preg_match( '/^#([0-9a-f]{3})$/i', $color, $m ) ) {
			return '#' . $m[1][0] . $m[1][0] . $m[1][1] . $m[1][1] . $m[1][2] . $m[1][2];
		}
		return preg_match( '/^#[0-9a-f]{6}$/i', $color ) ? strtoupper( $color ) : '';
	}

	private function is_dark( $color ) {
		$rgb = $this->rgb( $color );
		if ( ! $rgb ) {
			return false;
		}
		$luma = ( 0.2126 * $rgb[0] + 0.7152 * $rgb[1] + 0.0722 * $rgb[2] ) / 255;
		return $luma < 0.46;
	}

	private function contrast_text( $background ) {
		return $this->is_dark( $background ) ? '#ffffff' : '#07100d';
	}

	private function mix_hex( $a, $b, $weight_b ) {
		$rgb_a = $this->rgb( $a );
		$rgb_b = $this->rgb( $b );
		if ( ! $rgb_a || ! $rgb_b ) {
			return $this->normalize_hex( $a ) ? $a : '#111827';
		}
		$weight_b = max( 0, min( 1, (float) $weight_b ) );
		$weight_a = 1 - $weight_b;
		return sprintf(
			'#%02X%02X%02X',
			(int) round( $rgb_a[0] * $weight_a + $rgb_b[0] * $weight_b ),
			(int) round( $rgb_a[1] * $weight_a + $rgb_b[1] * $weight_b ),
			(int) round( $rgb_a[2] * $weight_a + $rgb_b[2] * $weight_b )
		);
	}

	private function rgb( $color ) {
		$hex = $this->normalize_hex( $color );
		if ( ! $hex ) {
			return null;
		}
		return array(
			hexdec( substr( $hex, 1, 2 ) ),
			hexdec( substr( $hex, 3, 2 ) ),
			hexdec( substr( $hex, 5, 2 ) ),
		);
	}
}
