<?php

namespace Daylight\Core\Modules\Admin\Providers;

use Daylight\Core\Modules\Admin\Entities\Script;
use Daylight\Core\Modules\Admin\Entities\Stylesheet;
use Daylight\Core\Modules\Admin\Registries\AssetRegistry;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AssetServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(AssetRegistry::class, function () {
            return new AssetRegistry;
        });

        Blade::directive('daylightStyles', function ($entry) {
            $links = app(AssetRegistry::class)->stylesheets()->map(function (Stylesheet $stylesheet) {
                return '<link rel="stylesheet" href="' . $stylesheet->getPath() . '">';
            })->join(PHP_EOL);

            return "<?php echo '$links'; ?>";
        });

        Blade::directive('daylightScripts', function ($entry) {
            $links = app(AssetRegistry::class)->scripts()->map(function (Script $script) {
                return '<script src="' . $script->getPath() . '" type="module"></script>';
            })->join(PHP_EOL);

            return "
                <?php echo '<script>window.daylight = Object.assign({}, window.daylight, { apiBase: `' . route('daylight.api') . '`, cdnUrl: `'.config('services.bytescale.cdn_url').'`, accountId: `'.config('services.bytescale.account_id').'`, cdnDirectory: `'.config('services.bytescale.path').'`, publicKey: `'.config('services.bytescale.public_key').'`, locale: `'.app()->getLocale().'`, fallbackLocale: `'.config('app.fallback_locale').'`, translationsUrl: `'.route('daylight.api.translations').'` })</script>'; ?>
                <?php echo '$links'; ?>
            ";
        });
    }
}
