<?php

if (! function_exists('vite_tags')) {
    /**
     * @param list<string> $entries
     */
    function vite_tags(array $entries = ['resources/js/app.js']): string
    {
        $manifestPath = ROOTPATH . 'public/build/.vite/manifest.json';

        if (! is_file($manifestPath)) {
            return '<!-- Vite manifest missing. Run npm run build. -->';
        }

        /** @var array<string, array<string, mixed>>|null $manifest */
        static $manifest = null;
        if ($manifest === null) {
            $manifest = json_decode((string) file_get_contents($manifestPath), true);
        }

        $html = [];

        foreach ($entries as $entry) {
            if (! isset($manifest[$entry])) {
                continue;
            }

            $item = $manifest[$entry];

            foreach ($item['css'] ?? [] as $css) {
                $href   = base_url('build/' . ltrim($css, '/'));
                $html[] = '<link rel="stylesheet" href="' . esc($href, 'attr') . '">';
            }

            $src    = base_url('build/' . ltrim($item['file'], '/'));
            $html[] = '<script type="module" src="' . esc($src, 'attr') . '"></script>';
        }

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