<?php

/**
 * fahrschultermin.de — Frontend entry point
 * Patches fetch() to proxy /api/v1/* calls to api.fahrschultermin.de
 * so the JS bundle (with hardcoded /api/v1 paths) just works.
 */

const API_BASE = 'https://api.fahrschultermin.de';

$assetManifestPath = __DIR__ . '/assets/.vite/manifest.json';
$mainAsset = '/assets/index.js';
$styleAsset = '/assets/index.css';

if (is_file($assetManifestPath)) {
    $manifest = json_decode(file_get_contents($assetManifestPath), true);
    $entry = $manifest['src/main.jsx'] ?? null;
    if (is_array($entry)) {
        $mainAsset = '/assets/' . ltrim((string) $entry['file'], '/');
        if (!empty($entry['css'][0])) {
            $styleAsset = '/assets/' . ltrim((string) $entry['css'][0], '/');
        }
    }
}

?><!doctype html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DriveTime Planner</title>
    <link rel="stylesheet" href="<?= htmlspecialchars($styleAsset, ENT_QUOTES) ?>">
</head>
<body>
    <div id="root"></div>
    <script>
        // Patch fetch to redirect /api/v1/* → api.fahrschultermin.de/api/v1/*
        window.__API_BASE__ = '<?= API_BASE ?>';
        const _fetch = window.fetch.bind(window);
        window.fetch = function (resource, options = {}) {
            let url = typeof resource === 'string' ? resource : resource.url;
            if (typeof url === 'string' && url.startsWith('/api/v1')) {
                url = '<?= API_BASE ?>' + url;
                const req = new Request(url, options);
                req.credentials = 'include';
                return _fetch(req);
            }
            return _fetch(resource, options);
        };
    </script>
    <script type="module" src="<?= htmlspecialchars($mainAsset, ENT_QUOTES) ?>"></script>
</body>
</html>