<?php
/**
 * Register and conditionally enqueue self-hosted webfont stylesheets.
 *
 * @package DiviSupreme
 */

declare(strict_types=1);

namespace DiviSupreme\Extensions\IconLibraries;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

/**
 * Webfont CSS registration and per-page enqueue.
 */
final class WebfontAssetLoader {

	/**
	 * @var bool
	 */
	private static bool $styles_registered = false;

	/**
	 * Normalize stored variant (maps deprecated duotone → regular).
	 *
	 * @param string $library_id Library slug.
	 * @param string $variant    Raw variant slug.
	 * @return string
	 */
	public static function normalize_variant( string $library_id, string $variant ): string {
		$variant = sanitize_key( $variant );

		if ( 'duotone' === $variant ) {
			return 'regular';
		}

		$library = IconLibraryRegistry::get( $library_id );

		if ( null === $library ) {
			return '';
		}

		$valid = array_keys( $library->get_variants() );

		if ( in_array( $variant, $valid, true ) ) {
			return $variant;
		}

		return $library->get_default_variant();
	}

	/**
	 * Register self-hosted webfont stylesheets for all enabled libraries (once).
	 *
	 * @return void
	 */
	public static function register_stylesheets(): void {
		if ( self::$styles_registered ) {
			return;
		}

		self::$styles_registered = true;

		$version = defined( 'DSM_PRO_VERSION' ) ? DSM_PRO_VERSION : '1.0.0';

		foreach ( IconLibraryRegistry::enabled() as $library ) {
			foreach ( $library->get_webfont_stylesheets() as $sheet ) {
				$handle = (string) ( $sheet['handle'] ?? '' );
				$path   = (string) ( $sheet['path'] ?? '' );
				$url    = (string) ( $sheet['url'] ?? '' );

				if ( '' === $handle || '' === $url || ! is_readable( $path ) ) {
					continue;
				}

				if ( ! wp_style_is( $handle, 'registered' ) ) {
					wp_register_style(
						$handle,
						$url,
						array(),
						$version . '-' . (string) filemtime( $path )
					);
				}
			}
		}
	}

	/**
	 * Enqueue only the webfont CSS files required by icons on the current page.
	 *
	 * @param array<string, array<string, mixed>> $icons Unique icon settings keyed by cache key.
	 * @return void
	 */
	public static function enqueue_for_icons( array $icons ): void {
		if ( array() === $icons ) {
			return;
		}

		self::register_stylesheets();

		/** @var array<string, array<string, true>> $needed_variants */
		$needed_variants = array();

		foreach ( $icons as $icon ) {
			if ( ! is_array( $icon ) || ! IconLibraryRegistry::is_dsm_library_icon( $icon ) ) {
				continue;
			}

			$library_id = sanitize_key( (string) ( $icon['type'] ?? '' ) );
			$variant    = self::normalize_variant(
				$library_id,
				IconLibraryRegistry::resolve_variant_from_icon( $icon )
			);

			if ( '' === $library_id ) {
				continue;
			}

			if ( ! isset( $needed_variants[ $library_id ] ) ) {
				$needed_variants[ $library_id ] = array();
			}

			// Empty variant is valid for single-style libraries (e.g. Lucide).
			$needed_variants[ $library_id ][ $variant ] = true;
		}

		foreach ( $needed_variants as $library_id => $variants ) {
			$library = IconLibraryRegistry::get( $library_id );

			if ( null === $library ) {
				continue;
			}

			foreach ( $library->get_webfont_stylesheets() as $sheet ) {
				$sheet_variant = (string) ( $sheet['variant'] ?? '' );
				$handle        = (string) ( $sheet['handle'] ?? '' );

				if ( isset( $variants[ $sheet_variant ] ) && '' !== $handle ) {
					wp_enqueue_style( $handle );
				}
			}
		}
	}

	/**
	 * Load sample webfont CSS on plugin settings (card previews).
	 *
	 * @return void
	 */
	public static function enqueue_admin_previews(): void {
		if ( ! is_admin() ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

		if ( null === $screen || ! str_contains( (string) $screen->id, 'divi_supreme' ) ) {
			return;
		}

		self::register_stylesheets();

		foreach ( IconLibraryRegistry::enabled() as $library ) {
			$default_variant = $library->get_default_variant();

			foreach ( $library->get_webfont_stylesheets() as $sheet ) {
				if ( (string) ( $sheet['variant'] ?? '' ) !== $default_variant ) {
					continue;
				}

				$handle = (string) ( $sheet['handle'] ?? '' );

				if ( '' !== $handle ) {
					wp_enqueue_style( $handle );
				}
			}
		}
	}
}
