<?php

declare(strict_types=1);

namespace FleekDash\Frontend;

use FleekDash\Traits\Base;
use FleekDash\Traits\ThemeInjector;

/**
 * Class VoxelAssets
 *
 * Handles enqueue of voxel.css for specific URL parameters.
 *
 * @package FleekDash\Frontend
 */
class VoxelAssets
{
    use Base;
    use ThemeInjector;

    /**
     * CSS handle for voxel assets
     */
    const HANDLE = 'fleekdash-voxel';

    /**
     * URL parameters that trigger the enqueue
     */
    const REQUIRED_PARAMS = [
        'vx' => '1',
        'action' => 'admin.get_fields_form'
    ];

    /**
     * Frontend bootstrapper.
     *
     * @return void
     */
    public function bootstrap()
    {
        // Register theme injection for specific URL parameters
        $this->registerThemeInjectionHooks(self::REQUIRED_PARAMS);

        // Enqueue theme sync module for Voxel pages
        \add_action('wp_enqueue_scripts', [$this, 'enqueueThemeSyncModule']);
        \add_action('admin_enqueue_scripts', [$this, 'enqueueThemeSyncModule']);

        // Register voxel CSS enqueue for specific URL parameters
        // CRITICAL: voxel.css must load AFTER base CSS to have CSS cascade priority
        $this->registerCssForUrlParams(
            self::HANDLE,
            \FleekDash\Libs\Assets\getCssUrl('voxel'),
            ['fleekdash-css-includes', 'fleekdash-css-iframe-tokens'],
            \FleekDash\Libs\Assets\getCssVersion('voxel'),
            self::REQUIRED_PARAMS,
        );

        // Register body style injection
        \add_action('wp_head', [$this, 'injectBodyOverflow'], 2);
        \add_action('admin_head', [$this, 'injectBodyOverflow'], 2);
    }

    /**
     * Enqueue theme sync module on Voxel pages
     *
     * @return void
     */
    public function enqueueThemeSyncModule()
    {
        // Check if voxel parameters are present
        $should_load = true;
        foreach (self::REQUIRED_PARAMS as $param => $value) {
            if (!isset($_GET[$param]) || $_GET[$param] != $value) {
                $should_load = false;
                break;
            }
        }

        if (!$should_load) {
            return;
        }

        // Enqueue theme sync module (must load before ThemeInjector script)
        // CRITICAL: This script is required for theme synchronization in Voxel iframes
        \wp_enqueue_script(
            'fleekdash-iframe-theme-sync',
            \FleekDash\Libs\Assets\getJsUrl('iframe-theme-mode-sync'),
            array(),
            FLEEKDASH_VERSION,
            false // Load in header, before ThemeInjector
        );

        // CRITICAL FIX: Also enqueue FleekDash CSS for theme variables
        // Without this, CSS variables won't be available in Voxel iframes
        \wp_enqueue_style(
            'fleekdash-css-iframe-tokens',
            \FleekDash\Libs\Assets\getIframeTokensCssUrl(),
            array(),
            \FleekDash\Libs\Assets\getIframeTokensCssVersion(),
        );

        \wp_enqueue_style(
            'fleekdash-css-includes',
            \FleekDash\Libs\Assets\getCssUrl('index'),
            array('fleekdash-css-iframe-tokens'),
            \FleekDash\Libs\Assets\getCssVersion('index'),
        );
    }

    /**
     * Check if voxel assets should be loaded
     *
     * @return bool
     */
    public function shouldLoadVoxelAssets(): bool
    {
        $result = true;
        foreach (self::REQUIRED_PARAMS as $param => $value) {
            if (!isset($_GET[$param]) || $_GET[$param] != $value) {
                $result = false;
                break;
            }
        }

        // Debug log
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log('VoxelAssets: URL params check - ' . ($result ? 'MATCH' : 'NO MATCH'));
        //     error_log('VoxelAssets: Current GET params - ' . print_r($_GET, true));
        // }

        return $result;
    }

    /**
     * Get voxel assets configuration
     *
     * @return array
     */
    public function getConfig(): array
    {
        return [
            'handle' => self::HANDLE,
            'src' => \FleekDash\Libs\Assets\getCssUrl('voxel'),
            'dependencies' => [],
            'version' => \FleekDash\Libs\Assets\getCssVersion('voxel'),
            'media' => 'all'
        ];
    }

    /**
     * Inject overflow-y: auto to body when voxel parameters are present
     *
     * @return void
     */
    public function injectBodyOverflow()
    {
        // Check if voxel assets should be loaded
        if (!$this->shouldLoadVoxelAssets()) {
            return;
        }

        // Debug log
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log('VoxelAssets: Injecting body overflow-y: auto');
        // }

        ?>
        <style type="text/css">
            body {
                overflow-y: auto !important;
            }
        </style>
        <?php
    }
}
