<?php
/** Shared schemas, state handling and reads for the Kadence design bridge. */

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

define( 'WPAGENT_KADENCE_MIN_VERSION', '1.5.0' );
define( 'WPAGENT_KADENCE_SETTINGS_OPTION', 'kadence_settings' );
define( 'WPAGENT_KADENCE_PALETTE_OPTION', 'kadence_global_palette' );
define( 'WPAGENT_KADENCE_LOCK_OPTION', 'wp_agent_kadence_settings_lock' );
define( 'WPAGENT_KADENCE_LOCK_TTL', 300 );
define( 'WPAGENT_KADENCE_MAX_OPTION_BYTES', 2097152 );
define( 'WPAGENT_KADENCE_MAX_ITEMS', 5000 );

/** @return array<string,mixed> */
function wpagent_kadence_responsive_number_schema( float $minimum, float $maximum, array $units ): array {
	$number = array( 'type' => 'number', 'minimum' => $minimum, 'maximum' => $maximum );
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'desktop' => $number,
			'tablet'  => $number,
			'mobile'  => $number,
			'unit'    => array( 'type' => 'string', 'enum' => $units ),
		),
		'minProperties'        => 1,
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_kadence_color_schema(): array {
	return array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 64 );
}

/** @return array<string,mixed> */
function wpagent_kadence_layout_schema(): array {
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'content_width'      => array( 'type' => 'integer', 'minimum' => 200, 'maximum' => 4096 ),
			'content_width_unit' => array( 'type' => 'string', 'enum' => array( 'px', 'em', 'rem', 'vw', '%' ) ),
			'narrow_width'       => array( 'type' => 'integer', 'minimum' => 200, 'maximum' => 4096 ),
			'narrow_width_unit'  => array( 'type' => 'string', 'enum' => array( 'px', 'em', 'rem', 'vw', '%' ) ),
		),
		'minProperties'        => 1,
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_kadence_palette_schema(): array {
	$properties = array();
	for ( $index = 1; $index <= 15; $index++ ) {
		$properties[ 'palette' . $index ] = wpagent_kadence_color_schema();
	}
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'active' => array( 'type' => 'string', 'enum' => array( 'palette', 'second-palette', 'third-palette' ) ),
			'colors' => array(
				'type'                 => 'object',
				'properties'           => $properties,
				'minProperties'        => 1,
				'additionalProperties' => false,
			),
		),
		'minProperties'        => 1,
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_kadence_colors_schema(): array {
	$color = wpagent_kadence_color_schema();
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'site_background'    => $color,
			'content_background' => $color,
			'link'               => $color,
			'link_hover'         => $color,
		),
		'minProperties'        => 1,
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_kadence_typography_schema(): array {
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'target'       => array( 'type' => 'string', 'enum' => array( 'body', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ) ),
			'font_family'  => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 200 ),
			'google_font'  => array( 'type' => 'boolean' ),
			'font_weight'  => array( 'type' => 'string', 'enum' => array( 'normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900' ) ),
			'font_size'    => wpagent_kadence_responsive_number_schema( 1, 400, array( 'px', 'em', 'rem', 'vw' ) ),
			'line_height'  => wpagent_kadence_responsive_number_schema( 0.5, 5, array( '', 'px', 'em', 'rem' ) ),
			'color'        => wpagent_kadence_color_schema(),
		),
		'required'             => array( 'target' ),
		'minProperties'        => 2,
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_kadence_buttons_schema(): array {
	$color = wpagent_kadence_color_schema();
	$unit  = array( 'type' => 'string', 'enum' => array( 'px', 'em', 'rem', '%' ) );
	$radius = wpagent_kadence_responsive_number_schema( 0, 100, array( 'px', 'em', 'rem', '%' ) );
	$radius['properties']['units'] = array(
		'type'                 => 'object',
		'properties'           => array( 'desktop' => $unit, 'tablet' => $unit, 'mobile' => $unit ),
		'minProperties'        => 1,
		'additionalProperties' => false,
	);
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'text'             => $color,
			'text_hover'       => $color,
			'background'       => $color,
			'background_hover' => $color,
			'border_radius'    => $radius,
		),
		'minProperties'        => 1,
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_kadence_header_schema(): array {
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'target'    => array( 'type' => 'string', 'enum' => array( 'desktop', 'mobile' ) ),
			'component' => array(
				'type' => 'string',
				'enum' => array( 'logo', 'navigation', 'navigation-2', 'search', 'button', 'social', 'html', 'mobile-logo', 'mobile-navigation', 'mobile-button', 'mobile-social', 'mobile-html', 'popup-toggle' ),
			),
			'placement' => array(
				'type' => array( 'string', 'null' ),
				'enum' => array( null, 'popup_content', 'top_left', 'top_left_center', 'top_center', 'top_right_center', 'top_right', 'main_left', 'main_left_center', 'main_center', 'main_right_center', 'main_right', 'bottom_left', 'bottom_left_center', 'bottom_center', 'bottom_right_center', 'bottom_right' ),
			),
			'position'  => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 6 ),
		),
		'required'             => array( 'target', 'component', 'placement' ),
		'minProperties'        => 3,
		'maxProperties'        => 4,
		'additionalProperties' => false,
	);
}

/** @return array<string,array<string,mixed>> */
function wpagent_kadence_section_schemas(): array {
	return array(
		'layout'     => wpagent_kadence_layout_schema(),
		'palette'    => wpagent_kadence_palette_schema(),
		'colors'     => wpagent_kadence_colors_schema(),
		'typography' => wpagent_kadence_typography_schema(),
		'buttons'    => wpagent_kadence_buttons_schema(),
		'header'     => wpagent_kadence_header_schema(),
	);
}

function wpagent_kadence_is_active(): bool {
	return 'kadence' === get_template();
}

function wpagent_kadence_version(): string {
	$theme = wp_get_theme( 'kadence' );
	return $theme->exists() ? (string) $theme->get( 'Version' ) : '';
}

function wpagent_kadence_runtime_ready(): bool {
	if ( ! wpagent_kadence_is_active()
		|| ! function_exists( 'Kadence\\kadence' )
		|| ! defined( 'KADENCE_VERSION' )
		|| version_compare( (string) KADENCE_VERSION, WPAGENT_KADENCE_MIN_VERSION, '<' ) ) {
		return false;
	}
	$type = (string) \Kadence\kadence()->get_option_type();
	return ( 'theme_mod' === $type && '' !== get_stylesheet() )
		|| ( 'option' === $type && WPAGENT_KADENCE_SETTINGS_OPTION === (string) \Kadence\kadence()->get_option_name() );
}

function wpagent_kadence_settings_option_name(): string {
	return 'theme_mod' === (string) \Kadence\kadence()->get_option_type()
		? 'theme_mods_' . get_stylesheet()
		: WPAGENT_KADENCE_SETTINGS_OPTION;
}

function wpagent_kadence_json_safe( $value, int $depth = 0, int &$nodes = 0 ): bool {
	if ( $depth > 12 || ++$nodes > WPAGENT_KADENCE_MAX_ITEMS ) {
		return false;
	}
	if ( is_array( $value ) ) {
		foreach ( $value as $key => $child ) {
			if ( ( ! is_int( $key ) && ! is_string( $key ) ) || ! wpagent_kadence_json_safe( $child, $depth + 1, $nodes ) ) {
				return false;
			}
		}
		return true;
	}
	if ( is_string( $value ) ) {
		return strlen( $value ) <= 65536 && wp_check_invalid_utf8( $value ) === $value && ! preg_match( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', $value );
	}
	return is_null( $value ) || is_bool( $value ) || is_int( $value ) || is_float( $value );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_kadence_decode_palette( string $value ) {
	$decoded = json_decode( $value, true );
	if ( ! is_array( $decoded ) || JSON_ERROR_NONE !== json_last_error() ) {
		return wpagent_kadence_invalid_provider_state();
	}
	return $decoded;
}

function wpagent_kadence_option_autoload( string $name ): ?string {
	global $wpdb;
	$value = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT autoload FROM {$wpdb->options} WHERE option_name = %s",
			$name
		)
	);
	return is_string( $value ) ? $value : null;
}

/** @return array{settings:array{exists:bool,value:array,autoload:?string},palette:array{exists:bool,value:string,decoded:array,autoload:?string}}|WP_Error */
function wpagent_kadence_snapshot() {
	$settings_option = wpagent_kadence_settings_option_name();
	$missing         = new stdClass();
	$settings_value  = get_option( $settings_option, $missing );
	$settings_exists = ! ( $settings_value instanceof stdClass );
	if ( $settings_exists && ! is_array( $settings_value ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$settings_value = $settings_exists ? $settings_value : array();
	$settings_autoload = $settings_exists ? wpagent_kadence_option_autoload( $settings_option ) : null;
	if ( $settings_exists && null === $settings_autoload ) {
		return wpagent_kadence_invalid_provider_state();
	}

	$missing        = new stdClass();
	$palette_value  = get_option( WPAGENT_KADENCE_PALETTE_OPTION, $missing );
	$palette_exists = ! ( $palette_value instanceof stdClass );
	if ( $palette_exists && ! is_string( $palette_value ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$palette_autoload = $palette_exists ? wpagent_kadence_option_autoload( WPAGENT_KADENCE_PALETTE_OPTION ) : null;
	if ( $palette_exists && null === $palette_autoload ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$effective_palette = $palette_exists && '' !== $palette_value
		? $palette_value
		: (string) \Kadence\kadence()->get_default_palette();
	$palette_decoded = wpagent_kadence_decode_palette( $effective_palette );
	if ( is_wp_error( $palette_decoded ) ) {
		return $palette_decoded;
	}

	$nodes = 0;
	if ( strlen( maybe_serialize( $settings_value ) ) > WPAGENT_KADENCE_MAX_OPTION_BYTES || ! wpagent_kadence_json_safe( $settings_value, 0, $nodes ) ) {
		return new WP_Error( 'wpagent_kadence_state_too_large', __( 'Der Kadence-Einstellungsstand ist zu groß oder ungültig für eine sichere Transaktion.', 'wp-agent-companion' ), array( 'status' => 502 ) );
	}
	$nodes = 0;
	if ( strlen( $effective_palette ) > WPAGENT_KADENCE_MAX_OPTION_BYTES || ! wpagent_kadence_json_safe( $palette_decoded, 0, $nodes ) ) {
		return new WP_Error( 'wpagent_kadence_state_too_large', __( 'Die Kadence-Palette ist zu groß oder ungültig für eine sichere Transaktion.', 'wp-agent-companion' ), array( 'status' => 502 ) );
	}
	return array(
		'settings' => array( 'exists' => $settings_exists, 'value' => $settings_value, 'autoload' => $settings_autoload ),
		'palette'  => array( 'exists' => $palette_exists, 'value' => $palette_exists ? $palette_value : '', 'decoded' => $palette_decoded, 'autoload' => $palette_autoload ),
	);
}

/** @param array{settings:array{exists:bool,value:array,autoload:?string},palette:array{exists:bool,value:string,decoded:array,autoload:?string}} $snapshot */
function wpagent_kadence_state_hash( array $snapshot ): string {
	$parent   = wp_get_theme( get_template() );
	$child    = wp_get_theme( get_stylesheet() );
	$identity = get_template() . '@' . $parent->get( 'Version' ) . '|' . get_stylesheet() . '@' . $child->get( 'Version' )
		. '|' . (string) \Kadence\kadence()->get_option_type() . '|' . wpagent_kadence_settings_option_name();
	return hash(
		'sha256',
		$identity . "\0" . ( $snapshot['settings']['exists'] ? '1' : '0' ) . "\0" . maybe_serialize( $snapshot['settings']['value'] )
		. "\0" . (string) $snapshot['settings']['autoload'] . "\0" . ( $snapshot['palette']['exists'] ? '1' : '0' ) . "\0" . $snapshot['palette']['value']
		. "\0" . (string) $snapshot['palette']['autoload']
	);
}

/** @return mixed */
function wpagent_kadence_setting( array $settings, string $key ) {
	if ( array_key_exists( $key, $settings ) && '' !== $settings[ $key ] ) {
		return $settings[ $key ];
	}
	return \Kadence\kadence()->default( $key );
}

function wpagent_kadence_invalid_provider_state(): WP_Error {
	return new WP_Error( 'wpagent_kadence_invalid_provider_state', __( 'Kadence enthält einen ungültigen Einstellungsstand.', 'wp-agent-companion' ), array( 'status' => 502 ) );
}

/** @return array<string,array<int,string>> */
function wpagent_kadence_header_zones( string $target ): array {
	if ( 'desktop' === $target ) {
		return array(
			'top'    => array( 'top_left', 'top_left_center', 'top_center', 'top_right_center', 'top_right' ),
			'main'   => array( 'main_left', 'main_left_center', 'main_center', 'main_right_center', 'main_right' ),
			'bottom' => array( 'bottom_left', 'bottom_left_center', 'bottom_center', 'bottom_right_center', 'bottom_right' ),
		);
	}
	if ( 'mobile' === $target ) {
		return array(
			'popup'  => array( 'popup_content' ),
			'top'    => array( 'top_left', 'top_center', 'top_right' ),
			'main'   => array( 'main_left', 'main_center', 'main_right' ),
			'bottom' => array( 'bottom_left', 'bottom_center', 'bottom_right' ),
		);
	}
	return array();
}

/** @return string[] */
function wpagent_kadence_header_components( string $target ): array {
	return 'desktop' === $target
		? array( 'logo', 'navigation', 'navigation-2', 'search', 'button', 'social', 'html' )
		: ( 'mobile' === $target
			? array( 'mobile-logo', 'mobile-navigation', 'search', 'mobile-button', 'mobile-social', 'mobile-html', 'popup-toggle' )
			: array() );
}

/** @return array<string,array<string,array<int,string>>>|WP_Error */
function wpagent_kadence_validate_header_provider( string $target, $value ) {
	$zones = wpagent_kadence_header_zones( $target );
	if ( ! $zones || ! is_array( $value ) || count( $value ) !== count( $zones ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$actual_rows   = array_keys( $value );
	$expected_rows = array_keys( $zones );
	sort( $actual_rows );
	sort( $expected_rows );
	if ( $actual_rows !== $expected_rows ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$seen = array();
	foreach ( $zones as $row => $placements ) {
		if ( ! is_array( $value[ $row ] ) || count( $value[ $row ] ) !== count( $placements ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$actual_placements   = array_keys( $value[ $row ] );
		$expected_placements = $placements;
		sort( $actual_placements );
		sort( $expected_placements );
		if ( $actual_placements !== $expected_placements ) {
			return wpagent_kadence_invalid_provider_state();
		}
		foreach ( $placements as $placement ) {
			$items = $value[ $row ][ $placement ];
			if ( ! is_array( $items ) || array_values( $items ) !== $items || count( $items ) > 7 ) {
				return wpagent_kadence_invalid_provider_state();
			}
			foreach ( $items as $item ) {
				if ( ! is_string( $item ) || ! preg_match( '/^[a-z0-9][a-z0-9-]{0,63}$/', $item ) || isset( $seen[ $item ] ) ) {
					return wpagent_kadence_invalid_provider_state();
				}
				$seen[ $item ] = true;
			}
		}
	}
	if ( count( $seen ) > 20 ) {
		return wpagent_kadence_invalid_provider_state();
	}
	return $value;
}

/** @return array<string,array<string,array<int,string>>>|WP_Error */
function wpagent_kadence_header_provider_value( string $target, array $settings ) {
	$key   = 'desktop' === $target ? 'header_desktop_items' : 'header_mobile_items';
	$value = array_key_exists( $key, $settings ) ? $settings[ $key ] : \Kadence\kadence()->default( $key );
	return wpagent_kadence_validate_header_provider( $target, $value );
}

/** @return array<string,array<int,string>> */
function wpagent_kadence_flatten_header_provider( string $target, array $provider ): array {
	$result = array();
	foreach ( wpagent_kadence_header_zones( $target ) as $row => $placements ) {
		foreach ( $placements as $placement ) {
			$result[ $placement ] = $provider[ $row ][ $placement ];
		}
	}
	return $result;
}

/** @return array{desktop:array<string,array<int,string>>,mobile:array<string,array<int,string>>}|WP_Error */
function wpagent_kadence_read_header( array $settings ) {
	$desktop = wpagent_kadence_header_provider_value( 'desktop', $settings );
	$mobile  = wpagent_kadence_header_provider_value( 'mobile', $settings );
	if ( is_wp_error( $desktop ) || is_wp_error( $mobile ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	return array(
		'desktop' => wpagent_kadence_flatten_header_provider( 'desktop', $desktop ),
		'mobile'  => wpagent_kadence_flatten_header_provider( 'mobile', $mobile ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_kadence_read_section( string $section, array $snapshot ) {
	$settings = $snapshot['settings']['value'];
	switch ( $section ) {
		case 'layout':
			return wpagent_kadence_read_layout( $settings );
		case 'palette':
			return wpagent_kadence_read_palette( $snapshot['palette']['decoded'] );
		case 'colors':
			return wpagent_kadence_read_colors( $settings );
		case 'typography':
			return wpagent_kadence_read_typography( $settings );
		case 'buttons':
			return wpagent_kadence_read_buttons( $settings );
		case 'header':
			return wpagent_kadence_read_header( $settings );
	}
	return new WP_Error( 'wpagent_kadence_unknown_section', __( 'Unbekannter Kadence-Designbereich.', 'wp-agent-companion' ), array( 'status' => 400 ) );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_kadence_read_layout( array $settings ) {
	$result = array();
	foreach ( array( 'content_width' => 'content_width', 'narrow_width' => 'content_narrow_width' ) as $public => $provider ) {
		$value = wpagent_kadence_setting( $settings, $provider );
		if ( ! is_array( $value ) || ! is_numeric( $value['size'] ?? null ) || (float) $value['size'] !== floor( (float) $value['size'] ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$size = (int) $value['size'];
		$unit = $value['unit'] ?? 'px';
		if ( $size < 200 || $size > 4096 || ! is_string( $unit ) || ! in_array( $unit, array( 'px', 'em', 'rem', 'vw', '%' ), true ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$result[ $public ]           = $size;
		$result[ $public . '_unit' ] = $unit;
	}
	return $result;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_kadence_read_palette( array $palette ) {
	$active = $palette['active'] ?? '';
	if ( ! is_string( $active ) || ! in_array( $active, array( 'palette', 'second-palette', 'third-palette' ), true ) || ! isset( $palette[ $active ] ) || ! is_array( $palette[ $active ] ) || 15 !== count( $palette[ $active ] ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$colors = array();
	foreach ( array_values( $palette[ $active ] ) as $index => $item ) {
		$slug = 'palette' . ( $index + 1 );
		if ( ! is_array( $item ) || $slug !== ( $item['slug'] ?? null ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$color = wpagent_kadence_validate_color( $item['color'] ?? null, false, false );
		if ( is_wp_error( $color ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$colors[ $slug ] = $color;
	}
	return array( 'active' => $active, 'colors' => $colors );
}

/** @return array<string,string>|WP_Error */
function wpagent_kadence_read_colors( array $settings ) {
	$site    = wpagent_kadence_setting( $settings, 'site_background' );
	$content = wpagent_kadence_setting( $settings, 'content_background' );
	$links   = wpagent_kadence_setting( $settings, 'link_color' );
	if (
		! is_array( $site )
		|| ! is_array( $site['desktop'] ?? null )
		|| ! is_array( $content )
		|| ! is_array( $content['desktop'] ?? null )
		|| ! is_array( $links )
	) {
		return wpagent_kadence_invalid_provider_state();
	}
	$raw = array(
		'site_background'    => $site['desktop']['color'] ?? '',
		'content_background' => $content['desktop']['color'] ?? '',
		'link'               => $links['highlight'] ?? '',
		'link_hover'         => $links['highlight-alt'] ?? '',
	);
	$result = array();
	foreach ( $raw as $key => $value ) {
		$color = wpagent_kadence_validate_color( $value, true, true );
		if ( is_wp_error( $color ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$result[ $key ] = $color;
	}
	return $result;
}

/** @return array<int,array<string,mixed>>|WP_Error */
function wpagent_kadence_read_typography( array $settings ) {
	$result = array();
	foreach ( array( 'body' => 'base_font', 'h1' => 'h1_font', 'h2' => 'h2_font', 'h3' => 'h3_font', 'h4' => 'h4_font', 'h5' => 'h5_font', 'h6' => 'h6_font' ) as $target => $provider ) {
		$value = wpagent_kadence_setting( $settings, $provider );
		if ( ! is_array( $value ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$family = wpagent_kadence_validate_font_family( $value['family'] ?? 'inherit' );
		if ( is_wp_error( $family ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$row = array( 'target' => $target, 'font_family' => $family, 'google_font' => true === ( $value['google'] ?? false ) );
		if ( isset( $value['weight'] ) && '' !== $value['weight'] ) {
			if ( ! is_string( $value['weight'] ) || ! in_array( $value['weight'], array( 'normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900' ), true ) ) {
				return wpagent_kadence_invalid_provider_state();
			}
			$row['font_weight'] = $value['weight'];
		}
		$size = wpagent_kadence_read_responsive_number( $value['size'] ?? array(), $value['sizeType'] ?? 'px', 1, 400, array( 'px', 'em', 'rem', 'vw' ) );
		$line = wpagent_kadence_read_responsive_number( $value['lineHeight'] ?? array(), '-' === ( $value['lineType'] ?? '' ) ? '' : ( $value['lineType'] ?? '' ), 0.5, 5, array( '', 'px', 'em', 'rem' ) );
		if ( is_wp_error( $size ) || is_wp_error( $line ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		if ( $size ) {
			$row['font_size'] = $size;
		}
		if ( $line ) {
			$row['line_height'] = $line;
		}
		if ( isset( $value['color'] ) && '' !== $value['color'] ) {
			$color = wpagent_kadence_validate_color( $value['color'], true, true );
			if ( is_wp_error( $color ) ) {
				return wpagent_kadence_invalid_provider_state();
			}
			$row['color'] = $color;
		}
		$result[] = $row;
	}
	return $result;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_kadence_read_buttons( array $settings ) {
	$text       = wpagent_kadence_setting( $settings, 'buttons_color' );
	$background = wpagent_kadence_setting( $settings, 'buttons_background' );
	$radius     = wpagent_kadence_setting( $settings, 'buttons_border_radius' );
	if ( ! is_array( $text ) || ! is_array( $background ) || ! is_array( $radius ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$result = array();
	foreach ( array( 'text' => $text['color'] ?? '', 'text_hover' => $text['hover'] ?? '', 'background' => $background['color'] ?? '', 'background_hover' => $background['hover'] ?? '' ) as $key => $value ) {
		$color = wpagent_kadence_validate_color( $value, true, true );
		if ( is_wp_error( $color ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$result[ $key ] = $color;
	}
	if ( ! is_array( $radius['size'] ?? null ) || ! is_array( $radius['unit'] ?? null ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$sizes = $radius['size'];
	$units = $radius['unit'];
	$unit  = $units['desktop'] ?? 'px';
	if ( ! is_string( $unit ) || ! in_array( $unit, array( 'px', 'em', 'rem', '%' ), true ) ) {
		return wpagent_kadence_invalid_provider_state();
	}
	$radius_result = array( 'units' => array() );
	$all_same      = true;
	foreach ( array( 'desktop', 'tablet', 'mobile' ) as $device ) {
		$device_unit = $units[ $device ] ?? $unit;
		$value       = $sizes[ $device ] ?? '';
		if ( ! is_string( $device_unit ) || ! in_array( $device_unit, array( 'px', 'em', 'rem', '%' ), true ) || ( '' !== $value && ( ! is_numeric( $value ) || (float) $value < 0 || (float) $value > 100 ) ) ) {
			return wpagent_kadence_invalid_provider_state();
		}
		$radius_result['units'][ $device ] = $device_unit;
		$radius_result[ $device ]          = '' === $value ? 0 : wpagent_kadence_normalize_number( $value );
		$all_same = $all_same && $device_unit === $unit;
	}
	if ( $all_same ) {
		$radius_result['unit'] = $unit;
	}
	$result['border_radius'] = $radius_result;
	return $result;
}
