<?php
/**
 * Color
 *
 * Single color normalization utility.
 * Replaces three duplicate implementations that existed in v1.9.x
 * (class-core.php, class-admin.php, class-theme-manager.php).
 *
 * @package Relatedly\Utilities
 * @since   2.0.0
 */

namespace Relatedly\Utilities;

defined( 'ABSPATH' ) || exit;

/**
 * Normalizes user-configurable color values.
 *
 * @since 2.0.0
 */
class Color {

	/**
	 * Normalize a color value to a consistent format.
	 *
	 * Rules:
	 *  - 3-digit hex  → 6-digit lowercase hex  (#abc → #aabbcc)
	 *  - "none"       → "transparent"
	 *  - rgba(...)    → returned as-is
	 *  - Invalid      → $fallback
	 *
	 * @param string $value    Raw color value.
	 * @param string $fallback Returned when value is empty or invalid.
	 * @return string
	 */
	public static function normalize( string $value, string $fallback = '#000000' ): string {
		$value = trim( $value );

		if ( '' === $value ) {
			return $fallback;
		}

		if ( 'none' === strtolower( $value ) ) {
			return 'transparent';
		}

		// Pass rgba() / rgb() through unchanged.
		if ( preg_match( '/^rgba?\s*\(/i', $value ) ) {
			return $value;
		}

		// Normalise hex.
		$hex = ltrim( $value, '#' );
		if ( strlen( $hex ) === 3 ) {
			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
		}
		if ( preg_match( '/^[0-9a-fA-F]{6}$/', $hex ) ) {
			return '#' . strtolower( $hex );
		}

		return $fallback;
	}
}
