<?php
/**
 * Icon helper.
 *
 * @package Kutby
 * @since   2.5.0
 */

declare(strict_types=1);

namespace Kutby\Icons;

use Kutby\Helpers\Utils;

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

/**
 * Class Icon
 */
final class Icon {

	/**
	 * Default size class map.
	 *
	 * @var array<string, string>
	 */
	private const SIZES = array(
		'sm' => 'kutby-icon--sm',
		'md' => 'kutby-icon--md',
		'lg' => 'kutby-icon--lg',
	);

	/**
	 * Render SVG icon markup.
	 *
	 * @param string $name  Icon name.
	 * @param string $class Optional CSS class.
	 * @param string $size  sm|md|lg.
	 * @return string
	 */
	public static function render( string $name, string $class = '', string $size = 'md' ): string {
		$html = Utils::icon( $name );

		// Registered alias → different file.
		if ( '' === $html && isset( Registry::all()[ $name ] ) ) {
			$file = Registry::all()[ $name ];
			$base = preg_replace( '/\.svg$/i', '', basename( $file ) ) ?: $name;
			$html = Utils::icon( (string) $base );
		}

		if ( '' === $html ) {
			return '';
		}

		$classes = array( 'kutby-icon', self::SIZES[ $size ] ?? self::SIZES['md'] );
		if ( '' !== $class ) {
			$classes[] = $class;
		}

		$attr = ' class="' . esc_attr( implode( ' ', $classes ) ) . '"';
		$html = preg_replace( '/<svg\b/', '<svg' . $attr, $html, 1 ) ?? $html;

		return $html;
	}

	/**
	 * Echo icon.
	 *
	 * @param string $name  Name.
	 * @param string $class Class.
	 * @param string $size  Size.
	 * @return void
	 */
	public static function print( string $name, string $class = '', string $size = 'md' ): void {
		echo self::render( $name, $class, $size ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG kses in Utils.
	}
}
