<?php

namespace EasyLinkAutomations\Views;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Config;
use EasyLinkAutomations\Hooks\Hooks;

/**
 * Modifies script and link tags generated by WordPress.
 *
 * - Adds `type="module"` to our ES module scripts so the browser treats them
 *   as native modules (required by Vite).
 * - Transforms `rel="stylesheet"` to `rel="preconnect"` for font preconnect links.
 * - Strips the `?ver=` query string from production JS to avoid caching issues.
 */
final class HtmlTagModifier
{
    public function __construct()
    {
        Hooks::addFilter('style_loader_tag', [$this, 'modifyLinkTags'], 0, 2);
        Hooks::addFilter('script_loader_tag', [$this, 'modifyScriptTags'], 0, 1);
        Hooks::addFilter('script_loader_src', [$this, 'removeVersionQueryParam'], 99999, 2);
    }

    public function modifyScriptTags(string $html): string
    {
        $slug          = Config::SLUG;
        $typeAttribute = 'type="module"';

        $moduleHandles = Config::isDev()
            ? ['-vite-client-helper-MODULE-js', '-vite-client-MODULE-js', '-index-MODULE-js']
            : ['-index-MODULE-js'];

        foreach ($moduleHandles as $key) {
            $handle = 'id="' . $slug . $key . '"';

            if (str_contains($html, $handle)) {
                $html = str_replace($handle, $handle . ' ' . $typeAttribute, $html);
            }
        }

        return $html;
    }

    public function modifyLinkTags(string $html, string $handle): string
    {
        if (!str_contains($handle, Config::SLUG)) {
            return $html;
        }

        if (str_contains($handle, 'PRECONNECT')) {
            $html = str_replace("rel='stylesheet'", 'rel="preconnect"', $html);
        }

        if (str_contains($handle, 'PRELOAD')) {
            $html = str_replace("rel='stylesheet'", 'rel="preload"', $html);
        }

        if (str_contains($handle, 'CROSSORIGIN')) {
            $id   = "id='{$handle}-css'";
            $html = str_replace($id, $id . ' crossorigin', $html);
        }

        return $html;
    }

    public function removeVersionQueryParam(string $src, string $handle): string
    {
        if ($handle === Config::SLUG . '-index-MODULE') {
            $src = strtok($src, '?');
        }

        return $src;
    }
}
