<?php

namespace FleekDash\Traits;

/**
 * Trait ThemeInjector
 *
 * Provides methods for injecting theme classes and attributes into frontend and admin pages.
 *
 * How to use this trait in any integration:
 *
 * 1. Add "use ThemeInjector;" at the top of your class
 * 2. Call $this->registerThemeInjectionHooks(['param1' => 'value1']) to add theme classes
 * 3. Call $this->registerCssForUrlParams() to enqueue CSS on specific pages
 *
 * Example:
 * ```php
 * use FleekDash\Traits\ThemeInjector;
 *
 * class MyIntegration extends AbstractIntegration {
 *     use ThemeInjector;
 *
 *     protected function registerIntegrationHooks() {
 *         // Add theme classes to pages with ?page=my-page
 *         $this->registerThemeInjectionHooks(['page' => 'my-page']);
 *
 *         // Enqueue CSS on pages with ?page=my-page
 *         $this->registerCssForUrlParams(
 *             'my-css-handle',
 *             FLEEKDASH_PLUGIN_URL . 'path/to/file.css',
 *             [],
 *             FLEEKDASH_VERSION,
 *             ['page' => 'my-page']
 *         );
 *     }
 * }
 * ```
 *
 * @package FleekDash\Traits
 */
trait ThemeInjector
{

    /**
     * URL parameters to check for theme injection
     *
     * @var array
     */
    protected $themeInjectionUrlParams = [];

    /**
     * CSS configuration for URL-specific enqueuing
     *
     * @var array
     */
    protected $cssConfig = [];

    /**
     * Register theme injection hooks
     *
     * This will add the dark/light class and data-theme attribute to the HTML element
     * on pages where the URL parameters match the specified values.
     *
     * @param array $url_params Array of URL parameters to check for (key => value pairs)
     * @return void
     */
    protected function registerThemeInjectionHooks($url_params = [])
    {
        // Store URL parameters to check
        $this->themeInjectionUrlParams = $url_params;

        // Register hooks for frontend and admin
        \add_action('wp_head', [$this, 'injectThemeClasses'], 1);
        \add_action('admin_head', [$this, 'injectThemeClasses'], 1);
    }

    /**
     * Inject theme classes and data attributes into HTML
     *
     * @return void
     */
    public function injectThemeClasses()
    {
        // Skip if no URL parameters are defined
        if (empty($this->themeInjectionUrlParams)) {
            return;
        }

        // Check if all required URL parameters match
        foreach ($this->themeInjectionUrlParams as $param => $value) {
            if (!isset($_GET[$param]) || $_GET[$param] != $value) {
                return;
            }
        }

        // Skip if integration is not active (when implemented in an integration)
        if (method_exists($this, 'isActive') && !$this->isActive()) {
            return;
        }

        // MODERNIZED: Use localStorage-based system (v2) instead of user_meta (v1)
        // This makes it compatible with our current theme system
        // REFACTORED v2.0: Use shared FleekDashThemeSync module
        // This eliminates code duplication and ensures consistent behavior
        ?>
        <script type="text/javascript">
            (function() {
                // Wait for shared module to load
                function waitForThemeSync() {
                    if (typeof window.fleekDashThemeSync !== 'undefined') {
                        // Module loaded - setup theme sync with all listeners
                        window.fleekDashThemeSync.setupThemeSync({
                            verbose: false,
                            observeParent: false, // Don't observe in integrations (Iframe.php handles it)
                            listenStorage: true,
                            listenMessages: true
                        });
                        // Theme sync initialized
                    } else {
                        // Module not loaded yet - wait and retry
                        setTimeout(waitForThemeSync, 50);
                    }
                }

                // Start waiting for module
                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', waitForThemeSync);
                } else {
                    waitForThemeSync();
                }
            })();
        </script>
        <?php
    }

    /**
     * Register CSS enqueuing for specific pages
     *
     * This will enqueue the specified CSS file on pages where the URL parameters
     * match the specified values.
     *
     * @param string $handle The CSS handle
     * @param string $src The CSS source URL
     * @param array $deps An array of dependencies
     * @param string|bool $ver The version string or false
     * @param array $url_params Array of URL parameters to check for (key => value pairs)
     * @return void
     */
    protected function registerCssForUrlParams($handle, $src, $deps = [], $ver = false, $url_params = [])
    {
        // Store configuration
        $this->cssConfig = [
            'handle' => $handle,
            'src' => $src,
            'deps' => $deps,
            'ver' => $ver,
            'url_params' => $url_params
        ];

        // Register hooks for both frontend and admin
        \add_action('wp_enqueue_scripts', [$this, 'enqueueCssIfUrlMatches']);
        \add_action('admin_enqueue_scripts', [$this, 'enqueueCssIfUrlMatches']);
        \add_action('admin_print_styles', [$this, 'enqueueCssIfUrlMatches']);
        \add_action('wp_print_styles', [$this, 'enqueueCssIfUrlMatches']);

    }

    /**
     * Enqueue CSS if URL parameters match
     *
     * @return void
     */
    public function enqueueCssIfUrlMatches()
    {
        // Skip if no configuration is set
        if (empty($this->cssConfig)) {
            return;
        }

        // Skip if integration is not active (when implemented in an integration)
        if (method_exists($this, 'isActive') && !$this->isActive()) {
            return;
        }

        // Check if all required URL parameters match
        foreach ($this->cssConfig['url_params'] as $param => $value) {
            if (!isset($_GET[$param]) || $_GET[$param] != $value) {
                return;
            }
        }

        // Enqueue the CSS
        \wp_enqueue_style(
            $this->cssConfig['handle'],
            $this->cssConfig['src'],
            $this->cssConfig['deps'],
            $this->cssConfig['ver'],
        );
    }
}
