<?php
/**
 * Central hook seam for custom icon library types on `process_font_icon` resolution.
 *
 * Divi 5 exposes `divi_icon_library_font_icon_types` inside Utils::process_font_icon() but
 * does not filter its return value. DSM webfont icons (Tabler/Phosphor) intentionally resolve
 * to null so modules keep native `Utils::process_font_icon()` calls; rendering is handled via:
 *
 * - PHP: `divi_module_wrapper_render` → IconModuleRenderBridge (frontend + VB SSR)
 * - JS:  `divi.module.wrapper.render` → module-icon-vb-wrapper.js (Visual Builder canvas)
 *
 * @package DiviSupreme
 */

declare(strict_types=1);

namespace DiviSupreme\Extensions\IconLibraries;

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

/**
 * Registers extension-side filters for icon resolution and documents the hook contract.
 */
final class IconProcessFontIconBridge {

	/**
	 * @return void
	 */
	public static function register(): void {
		add_filter( 'divi_icon_library_font_icon_types', array( self::class, 'filter_font_icon_types' ) );
		add_filter( 'divi_icon_library_process_font_icon', array( self::class, 'filter_process_font_icon' ), 10, 4 );
	}

	/**
	 * Register enabled library ids with Divi's native font icon type list.
	 *
	 * @param array<int, string> $types Divi default types (`divi`, `fa`, …).
	 * @return array<int, string>
	 */
	public static function filter_font_icon_types( array $types ): array {
		if ( ! function_exists( 'dsm_is_icon_libraries_extension_enabled' ) || ! dsm_is_icon_libraries_extension_enabled() ) {
			return $types;
		}

		foreach ( IconLibraryRegistry::enabled() as $library ) {
			$types[] = $library->get_id();
		}

		return array_values( array_unique( $types ) );
	}

	/**
	 * Extension hook for `dsm_process_font_icon()` / future callers.
	 *
	 * Webfont library icons render via DOM injection (IconModuleRenderBridge), not CSS `content`.
	 * This filter keeps the resolved glyph null for enabled DSM libraries so native module CSS
	 * paths skip pseudo-element content while the bridge supplies `<i class="…">` glyphs.
	 *
	 * @param string|null               $result             Resolved glyph from Divi Utils (or null).
	 * @param array<string, mixed>|string $icon               Icon picker settings.
	 * @param bool                        $is_font_icons_down Down-icon list flag.
	 * @param bool                        $is_unicode         Unicode output flag.
	 * @return string|null
	 */
	public static function filter_process_font_icon( $result, $icon, bool $is_font_icons_down, bool $is_unicode ): ?string {
		unset( $is_font_icons_down, $is_unicode );

		if ( ! is_array( $icon ) ) {
			return is_string( $result ) ? $result : null;
		}

		if (
			ExtensionSettings::is_extension_enabled()
			&& IconLibraryRegistry::is_dsm_library_icon( $icon )
		) {
			return null;
		}

		return is_string( $result ) ? $result : null;
	}
}
