<?php

namespace TotalTheme\Helpers;

defined( 'ABSPATH' ) || exit;

/**
 * Text Shadow Parser.
 *
 * Provides methods to parse a stored text shadow string into an array
 * of its components (color, horizontal offset, vertical offset, blur)
 * and to build a CSS text-shadow value.
 *
 * Usage:
 * ```
 * $shadow_string = 'c:#000000|x:2|y:3|b:10';
 * $parsed        = Text_Shadow_Parser::parse( $shadow_string );
 * $css           = Text_Shadow_Parser::render_css( $shadow_string );
 * ```
 *
 * @package TotalTheme\Helpers
 * @since 6.6
 */
final class Text_Shadow_Parser {

	/**
	 * Parse text shadow string into an array.
	 *
	 * Expected format: c:#000000|x:2|y:2|b:5
	 *
	 * @param string|array $value
	 * @return array
	 */
	public static function parse( $value ): array {
		if ( is_array( $value ) ) {
			return $value;
		}

		if ( ! is_string( $value ) || ! str_contains( $value, '|' ) ) {
			return [];
		}

		$result = [];

		foreach ( explode( '|', $value ) as $part ) {
			[ $key, $val ] = array_pad( explode( ':', $part, 2 ), 2, '' );
			if ( $key !== '' ) {
				$result[ $key ] = $val;
			}
		}

		return $result;
	}

	/**
	 * Build CSS text-shadow from parsed value.
	 *
	 * @param string|array $shadow
	 * @return string
	 */
	public static function render_css( $shadow ): string {
		$shadow = self::parse( $shadow );

		if ( empty( $shadow['c'] ) ) {
			return '';
		}

		$color = wpex_parse_color( $shadow['c'] );

		if ( ! $color ) {
			return '';
		}
	
		$x    = isset( $shadow['x'] ) ? intval( $shadow['x'] ) : 0;
		$y    = isset( $shadow['y'] ) ? intval( $shadow['y'] ) : 0;
		$blur = isset( $shadow['b'] ) ? intval( $shadow['b'] ) : 10;

		return sprintf(
			'%dpx %dpx %dpx %s',
			$x,
			$y,
			$blur,
			$color
		);
	}
}
