<?php
namespace Jet_Engine_Divi_Views\Utils;

/**
 * @param $v
 * @return array|mixed|null
 */
function unwrap_responsive_value( $v ) {
	if ( empty( $v ) ) {
		return null;
	}

	if ( is_array( $v ) && ( isset( $v['styles'] ) || isset( $v['radius'] ) ) ) {
		return $v;
	}

	if ( isset( $v['desktop']['value'] ) )   return $v['desktop']['value'];
	if ( isset( $v['desktop']['default'] ) ) return $v['desktop']['default'];

	if ( isset( $v['value'] ) ) return $v['value'];

	return $v;
}

/**
 * @param $scalar
 * @return array[]|null
 */
function as_responsive( $scalar ) {
	return isset( $scalar ) ? [ 'desktop' => [ 'default' => $scalar ] ] : null;
}

/**
 * @param $v
 * @return \array[][]|null[]
 */
function extract_border_attrs( $v = null ) {
	$val   = unwrap_responsive_value( $v );

	$all_style = $val['styles']['all']['style'] ?? '';
	$all_width = $val['styles']['all']['width'] ?? '';
	$all_color = $val['styles']['all']['color'] ?? '';

	$top_style = $val['styles']['top']['style'] ?? $all_style;
	$right_style = $val['styles']['right']['style'] ?? $all_style;
	$bottom_style = $val['styles']['bottom']['style'] ?? $all_style;
	$left_style = $val['styles']['left']['style'] ?? $all_style;

	$top_width = $val['styles']['top']['width'] ?? $all_width;
	$right_width = $val['styles']['right']['width'] ?? $all_width;
	$bottom_width = $val['styles']['bottom']['width'] ?? $all_width;
	$left_width = $val['styles']['left']['width'] ?? $all_width;

	$top_color = $val['styles']['top']['color'] ?? $all_color;
	$right_color = $val['styles']['right']['color'] ?? $all_color;
	$bottom_color = $val['styles']['bottom']['color'] ?? $all_color;
	$left_color = $val['styles']['left']['color'] ?? $all_color;

	$r      = $val['radius'] ?? [];
	$radius = ( isset( $r['sync'] ) && 'on' === $r['sync'] )
		? ( $r['topLeft'] ?? '0' )
		: sprintf(
			'%s %s %s %s',
			$r['topLeft']     ?? '0',
			$r['topRight']    ?? '0',
			$r['bottomRight'] ?? '0',
			$r['bottomLeft']  ?? '0'
		);

	return [
		'style'  => as_responsive( $all_style ),
		'width'  => as_responsive( $all_width ),
		'color'  => as_responsive( $all_color ),
		'styleTop' => as_responsive( $top_style ),
		'styleRight' => as_responsive( $right_style ),
		'styleBottom' => as_responsive( $bottom_style ),
		'styleLeft' => as_responsive( $left_style ),
		'widthTop' => as_responsive( $top_width ),
		'widthRight' => as_responsive( $right_width ),
		'widthBottom' => as_responsive( $bottom_width ),
		'widthLeft' => as_responsive( $left_width ),
		'colorTop' => as_responsive( $top_color ),
		'colorRight' => as_responsive( $right_color ),
		'colorBottom' => as_responsive( $bottom_color ),
		'colorLeft' => as_responsive( $left_color ),
		'radius' => as_responsive( $radius ),
	];
}

/**
 * Normalize typography value (Divi font settings) into simple responsive-like structure.
 *
 * @param array|null $v
 * @return array
 */
function extract_typography_attrs( $v = null ) {

	// Unwrap responsive or nested font payload
	$src = isset( $v['font'] ) ? $v['font'] : $v;

	if ( isset( $src['desktop']['value'] ) ) {
		$val = $src['desktop']['value'];
	} elseif ( isset( $src['desktop']['default'] ) ) {
		$val = $src['desktop']['default'];
	} elseif ( isset( $src['value'] ) ) {
		$val = $src['value'];
	} else {
		$val = $src;
	}

	$as_resp = function ( $x ) {
		return isset( $x ) ? [ 'desktop' => [ 'default' => $x ] ] : null;
	};

	// Base fields from Divi font object
	$family = $val['family'] ?? 'inherit';
	$size = $val['size'] ?? null;
	$line_height = $val['lineHeight'] ?? null;
	$letter_spacing = $val['letterSpacing'] ?? null;
	$weight = $val['weight'] ?? null;
	$text_align = $val['textAlign'] ?? null;
	$style_arr = isset( $val['style'] ) && is_array( $val['style'] ) ? $val['style'] : [];

	// Derive text-transform
	$text_transform = null;
	if ( in_array( 'uppercase', $style_arr, true ) ) {
		$text_transform = 'uppercase';
	} elseif ( in_array( 'lowercase', $style_arr, true ) ) {
		$text_transform = 'lowercase';
	} elseif ( in_array( 'capitalize', $style_arr, true ) ) {
		$text_transform = 'capitalize';
	}

	// Derive font-style
	$font_style = in_array( 'italic', $style_arr, true ) ? 'italic' : null;

	// Derive text-decoration
	$decorations = [];
	if ( in_array( 'underline', $style_arr, true ) ) {
		$decorations[] = 'underline';
	}
	if ( in_array( 'line-through', $style_arr, true ) ) {
		$decorations[] = 'line-through';
	}
	$text_decoration = !empty( $decorations ) ? implode( ' ', $decorations ) : null;

	return [
		'fontFamily' => $as_resp( $family ),
		'fontSize' => $as_resp( $size ),
		'lineHeight' => $as_resp( $line_height ),
		'letterSpacing' => $as_resp( $letter_spacing ),
		'fontWeight' => $as_resp( $weight ),
		'fontStyle' => $as_resp( $font_style ),
		'textTransform' => $as_resp( $text_transform ),
		'textDecoration' => $as_resp( $text_decoration ),
		'textAlign' => $as_resp( $text_align ),
	];
}

/**
 * Extract spacing (margin/padding) into responsive-ready structure.
 * - Unwraps responsive value (desktop.value/default/value)
 * - Respects syncHorizontal / syncVertical flags
 * - Returns margin/padding as single-line CSS strings: "top right bottom left"
 * - Also returns individual sides for flexible cases
 *
 * @param mixed $v
 * @return array
 */
function extract_spasing_attrs( $v = null ) {
	// unwrap responsive object similar to JS
	$val = unwrap_responsive_value( $v );

	// normalize sides with sync flags
	$normalize = static function ( $s ) {
		if ( empty( $s ) || !is_array( $s ) ) {
			return [];
		}
		$out = $s;

		$top = $s['top'] ?? null;
		$right = $s['right'] ?? null;
		$bottom = $s['bottom'] ?? null;
		$left = $s['left'] ?? null;

		// vertical sync (top ↔ bottom)
		if ( ( $s['syncVertical'] ?? '' ) === 'on' ) {
			$v = isset( $top ) ? $top : ( isset( $bottom ) ? $bottom : '0' );
			$out['top'] = $v;
			$out['bottom'] = $v;
		}

		// horizontal sync (left ↔ right)
		if ( ( $s['syncHorizontal'] ?? '' ) === 'on' ) {
			$h = isset( $left ) ? $left : ( isset( $right ) ? $right : '0' );
			$out['left'] = $h;
			$out['right'] = $h;
		}

		return $out;
	};

	$margin = $normalize( $val['margin'] ?? [] );
	$padding = $normalize( $val['padding'] ?? [] );

	// stringify "top right bottom left"
	$stringify = static function ( $s ) {
		$top = $s['top'] ?? '0';
		$right = $s['right'] ?? '0';
		$bottom = $s['bottom'] ?? '0';
		$left = $s['left'] ?? '0';
		return sprintf( '%s %s %s %s', $top, $right, $bottom, $left );
	};

	$margin_str = $stringify( $margin );
	$padding_str = $stringify( $padding );

	return [
		// single-line CSS strings (responsive-wrapped)
		'margin' => as_responsive( $margin_str ),
		'padding' => as_responsive( $padding_str ),

		// individual sides (responsive-wrapped)
		'marginTop' => as_responsive( $margin['top'] ?? null ),
		'marginRight' => as_responsive( $margin['right'] ?? null ),
		'marginBottom' => as_responsive( $margin['bottom'] ?? null ),
		'marginLeft' => as_responsive( $margin['left'] ?? null ),

		'paddingTop' => as_responsive( $padding['top'] ?? null ),
		'paddingRight' => as_responsive( $padding['right'] ?? null ),
		'paddingBottom' => as_responsive( $padding['bottom'] ?? null ),
		'paddingLeft' => as_responsive( $padding['left'] ?? null ),
	];
}

/**
 * @param string $selector
 * @param array $typography
 * @return array
 */
function build_typography_styles( string $selector, array $typography ): array {
	$map = [
		'font-family'     => 'fontFamily',
		'font-size'       => 'fontSize',
		'line-height'     => 'lineHeight',
		'letter-spacing'  => 'letterSpacing',
		'font-weight'     => 'fontWeight',
		'font-style'      => 'fontStyle',
		'text-transform'  => 'textTransform',
		'text-decoration' => 'textDecoration',
		'text-align'      => 'textAlign',
	];

	$result = [];

	foreach ( $map as $property => $attr_key ) {
		$result[] = [
			'componentName' => 'divi/common',
			'props'         => [
				'property' => $property,
				'selector' => $selector,
				'attr'     => $typography[ $attr_key ] ?? [],
			],
		];
	}

	return $result;
}

/**
 * @param string $selector
 * @param array $border
 * @return array
 */
function build_border_styles( string $selector, array $border ): array {
	$map = [
		'border-style'  => 'style',
		'border-width'  => 'width',
		'border-color'  => 'color',
		'border-top-style' => 'styleTop',
		'border-right-style' => 'styleRight',
		'border-bottom-style' => 'styleBottom',
		'border-left-style' => 'styleLeft',
		'border-top-width' => 'widthTop',
		'border-right-width' => 'widthRight',
		'border-bottom-width' => 'widthBottom',
		'border-left-width' => 'widthLeft',
		'border-top-color' => 'colorTop',
		'border-right-color' => 'colorRight',
		'border-bottom-color' => 'colorBottom',
		'border-left-color' => 'colorLeft',
		'border-radius' => 'radius',
	];

	$result = [];

	foreach ( $map as $property => $key ) {
		$result[] = [
			'componentName' => 'divi/common',
			'props'         => [
				'property' => $property,
				'selector' => $selector,
				'attr'     => $border[ $key ] ?? [],
			],
		];
	}

	return $result;
}

/**
 * @param string $selector
 * @param array $spacing
 * @return array
 */
function build_spacing_styles( string $selector, array $spacing ): array {
	$map = [
		'margin'  => 'margin',
		'padding' => 'padding',
	];

	$result = [];

	foreach ( $map as $property => $key ) {
		$result[] = [
			'componentName' => 'divi/common',
			'props'         => [
				'property' => $property,
				'selector' => $selector,
				'attr'     => $spacing[ $key ] ?? [],
			],
		];
	}

	return $result;
}
