<?php
declare(strict_types=1);

namespace ROITheme\Public\LazyCSSLoader\Infrastructure\Services;

use ROITheme\Public\LazyCSSLoader\Infrastructure\Contracts\LazyCSSRegistrarInterface;

/**
 * Registra CSS para carga lazy (TIPO 5)
 *
 * Separa CSS de TIPO 2 (diferido inmediato) vs TIPO 5 (lazy loading)
 *
 * CSS incluidos en TIPO 5:
 * - Animaciones: requestIdleCallback (2s timeout)
 * - Print: beforeprint event
 *
 * @package ROITheme\Public\LazyCSSLoader\Infrastructure\Services
 */
final class LazyCSSRegistrar implements LazyCSSRegistrarInterface
{
    /**
     * CSS que se mueve de TIPO 2 a TIPO 5
     *
     * @var array<int, array{id: string, path: string, trigger: string, handle: string}>
     */
    private const LAZY_CSS_FILES = [
        [
            'id' => 'animations',
            'path' => '/Assets/Css/css-global-animations.css',
            'trigger' => 'idle',
            'handle' => 'roi-animations',
        ],
        [
            'id' => 'print',
            'path' => '/Assets/Css/css-global-print.css',
            'trigger' => 'print',
            'handle' => 'roi-print',
        ],
    ];

    /**
     * Timeout en ms para requestIdleCallback
     */
    private const IDLE_TIMEOUT = 2000;

    /**
     * Registra hooks de WordPress
     */
    public function register(): void
    {
        // Dequeue CSS que ahora es TIPO 5
        add_action('wp_enqueue_scripts', [$this, 'dequeueType5CSS'], 999);

        // Agregar script loader y configuracion
        add_action('wp_enqueue_scripts', [$this, 'enqueueLoader'], 20);

        // Agregar fallback noscript
        add_action('wp_head', [$this, 'addNoscriptFallback'], 99);
    }

    /**
     * Remueve CSS que ahora es TIPO 5 del enqueue normal
     */
    public function dequeueType5CSS(): void
    {
        foreach (self::LAZY_CSS_FILES as $file) {
            wp_dequeue_style($file['handle']);
            wp_deregister_style($file['handle']);
        }
    }

    /**
     * Encola el loader JavaScript con configuracion
     */
    public function enqueueLoader(): void
    {
        $loaderPath = get_template_directory() . '/Assets/Js/lazy-css-loader.js';

        // Solo encolar si el archivo existe
        if (!file_exists($loaderPath)) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('ROI Theme TIPO 5: lazy-css-loader.js not found');
            }
            return;
        }

        wp_enqueue_script(
            'roi-lazy-css-loader',
            get_template_directory_uri() . '/Assets/Js/lazy-css-loader.js',
            [],
            ROI_VERSION,
            true // En footer
        );

        // Pasar configuracion al JS
        wp_localize_script('roi-lazy-css-loader', 'roiLazyCSSConfig', [
            'baseUrl' => get_template_directory_uri(),
            'version' => ROI_VERSION,
            'idleTimeout' => self::IDLE_TIMEOUT,
            'cssFiles' => self::LAZY_CSS_FILES,
        ]);
    }

    /**
     * Agrega fallback noscript para accesibilidad
     */
    public function addNoscriptFallback(): void
    {
        echo '<noscript>' . "\n";

        foreach (self::LAZY_CSS_FILES as $file) {
            $href = esc_url(get_template_directory_uri() . $file['path'] . '?ver=' . ROI_VERSION);
            $media = $file['trigger'] === 'print' ? 'print' : 'all';

            printf(
                '<link rel="stylesheet" href="%s" media="%s">' . "\n",
                $href,
                $media
            );
        }

        echo '</noscript>' . "\n";
    }
}
