<?php

namespace FleekDash\Admin\Editor;

use FleekDash\Core\PluginHelper;

/**
 * Conditionally loads third-party editor CSS only when the related plugin is active.
 *
 * Keeps plugin-specific admin/editor styles out of the base FleekDash bundles so
 * Gutenberg and classic wp-admin do not inherit unrelated CSS by default.
 */
class ThirdPartyEditorCssManager
{
    private const STYLE_HANDLE_PREFIX = 'fleekdash-third-party-editor-css-';

    /**
     * @return array<string, array{pluginFile:string, cssEntry:string}>
     */
    private static function getRegisteredStyles(): array
    {
        return [
            'rankmath' => [
                'pluginFile' => 'seo-by-rank-math/rank-math.php',
                'cssEntry' => 'rankmath',
            ],
            'woocommerce' => [
                'pluginFile' => 'woocommerce/woocommerce.php',
                'cssEntry' => 'woocommerce',
            ],
        ];
    }

    public static function enqueueActiveStyles(string $baseDependencyHandle = ''): void
    {
        self::ensurePluginFunctionsLoaded();

        foreach (self::getRegisteredStyles() as $styleKey => $styleConfig) {
            if (!self::isPluginCurrentlyActive($styleConfig['pluginFile'])) {
                continue;
            }

            $dependencies = [];
            if ($baseDependencyHandle !== '') {
                $dependencies[] = $baseDependencyHandle;
            }

            \wp_enqueue_style(
                self::STYLE_HANDLE_PREFIX . $styleKey,
                \FleekDash\Libs\Assets\getCssUrl($styleConfig['cssEntry']),
                $dependencies,
                \FleekDash\Libs\Assets\getCssVersion($styleConfig['cssEntry']),
            );
        }
    }

    private static function ensurePluginFunctionsLoaded(): void
    {
        if (\class_exists(PluginHelper::class)) {
            PluginHelper::ensurePluginApiLoaded();
        }
    }

    private static function isPluginCurrentlyActive(string $pluginFile): bool
    {
        $isActive = false;

        if (\function_exists('is_plugin_active')) {
            $isActive = \is_plugin_active($pluginFile);
        }

        if (!$isActive && \function_exists('is_plugin_active_for_network')) {
            $isActive = \is_plugin_active_for_network($pluginFile);
        }

        return $isActive;
    }
}
