<?php
/**
 * @var string $component
 * @var ?string $id
 * @var array $props
 * @var App\View\GlobalSections $sections
 * @var App\Entity\Api\Vue\AppGlobals $globalProps
 * @var App\Environment $environment
 * @var App\Service\Vite $vite
 */

$componentDeps = $vite->getScriptAndDependencies('js/pages/' . $component . '.js');

$jsonFlags = $environment->isProduction()
    ? JSON_THROW_ON_ERROR
    : JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT;

$globalProps->componentProps = $props;
$propsJson = json_encode($globalProps, $jsonFlags);

$headScripts = [];

foreach ($componentDeps->css as $cssDep) {
    $headScripts[] = <<<HTML
        <link rel="stylesheet" href="{$cssDep}" />
    HTML;
}

foreach ($componentDeps->prefetch as $prefetchDep) {
    $headScripts[] = <<<HTML
        <link rel="modulepreload" href="{$prefetchDep}" />
    HTML;
}

$sections->append('head', implode("\n", $headScripts));

$scriptLines = [];
$componentName = 'Vue_' . str_replace('/', '', $component);

$scriptLines[] = <<<HTML
    <script type="module" src="{$componentDeps->js}"></script>
    <script type="text/javascript">
        let {$componentName};
        ready(() => {
            {$componentName} = window.vueComponent('#{$id}', {$propsJson});
        });
    </script>
HTML;

$sections->append('bodyjs', implode("\n", $scriptLines));
?>

<div id="<?= $id ?>" class="vue-component">Loading...</div>
