<?php

declare(strict_types=1);

namespace PpPhp\Core\Assets;

use PpPhp\Core\IconManager\IconManager;

final class SpaAssetManager
{
    public static function renderIconCss(string $baseUrl = ''): string
    {
        $assets = IconManager::assets();
        $html = [];

        foreach (($assets['css'] ?? []) as $path) {
            $url = self::assetUrl($baseUrl, $path);
            $html[] = '<link rel="stylesheet" href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">';
        }

        return implode(PHP_EOL, array_values(array_unique($html)));
    }

    public static function renderIconJs(string $baseUrl = ''): string
    {
        $assets = IconManager::assets();
        $html = [];

        foreach (($assets['js'] ?? []) as $path) {
            $url = self::assetUrl($baseUrl, $path);
            $html[] = '<script src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></script>';
        }

        return implode(PHP_EOL, array_values(array_unique($html)));
    }

    public static function renderSharedIconManagerJs(string $baseUrl = ''): string
    {
        $url = self::assetUrl($baseUrl, 'assets/ppphp/js/ppphp-icon-manager.js');

        return '<script src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></script>';
    }

    public static function renderDesignerAssetRuntimeJs(string $baseUrl = ''): string
    {
        $url = self::assetUrl($baseUrl, 'modules/Designer/Views/scripts/designer-asset-runtime.js');

        return '<script src="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></script>';
    }

    public static function renderDesignerAssetRuntimeCss(string $baseUrl = ''): string
    {
        $url = self::assetUrl($baseUrl, 'modules/Designer/Views/styles/designer-asset-runtime.css');

        return '<link rel="stylesheet" href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">';
    }

    public static function renderAssetPackages(array $packageIds, string $baseUrl = ''): array
    {
        $runtime = new AssetRuntime();

        return [
            'head' => $runtime->renderPackageHead($packageIds, $baseUrl),
            'footer' => $runtime->renderPackageFooter($packageIds, $baseUrl),
        ];
    }

    private static function assetUrl(string $baseUrl, string $path): string
    {
        if (preg_match('/^https?:\/\//i', $path)) {
            return $path;
        }

        return rtrim($baseUrl, '/') . '/' . ltrim($path, '/');
    }
}
