<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>{{ output_path_raw }}</title>
    <style>
        html, body { margin: 0; padding: 0; height: 100%; background: #fff; }
        replay-web-page { display: block; width: 100%; height: 100%; }
    </style>
    <script>
    // Pre-activate the replay SW before loading ui.js. Otherwise
    // <replay-web-page>'s Embed class resolves doRegister() on the
    // 'registered' event (not 'activated'), then sets inited=true and
    // navigates the iframe to /replay/replay.html before the SW is
    // controlling its scope — that races into a 404 + visible error-page
    // flash and forces ui.js to silently reload the iframe up to twice
    // (~200ms each) while it waits for the SW to claim. Awaiting
    // 'activated' here moves the wait out of the iframe's load cycle.
    function appendReplayUi() {
        if (document.querySelector('script[src="/replay/ui.js"]')) return;
        const s = document.createElement('script');
        s.src = '/replay/ui.js';
        document.head.appendChild(s);
    }

    function withTimeout(promise, timeoutMs) {
        return Promise.race([
            promise,
            new Promise((_, reject) => {
                setTimeout(() => reject(new Error('timed out')), timeoutMs);
            }),
        ]);
    }

    async function waitForActivation(reg) {
        if (reg.active && reg.active.state === 'activated') return;
        const worker = reg.installing || reg.waiting || reg.active;
        if (!worker || worker.state === 'activated') return;
        await Promise.race([
            new Promise((resolve) => {
                worker.addEventListener('statechange', () => {
                    if (worker.state === 'activated') resolve();
                });
            }),
            new Promise((resolve) => setTimeout(resolve, 3000)),
        ]);
    }

    (async () => {
        appendReplayUi();
        if ('serviceWorker' in navigator) {
            try {
                const reg = await withTimeout(
                    navigator.serviceWorker.register(
                        '/replay/sw.js?serveIndex=1',
                        { scope: '/replay/' },
                    ),
                    3000,
                );
                await waitForActivation(reg);
            } catch (_) { /* fall through: ui.js will register + retry itself */ }
        }
    })().catch(() => {});
    </script>
</head>
<body>
    <replay-web-page source="{{ output_path }}"
                     {% if archived_url %}url="{{ archived_url }}"{% endif %}
                     embed="replayonly"
                     replaybase="/replay/"></replay-web-page>
</body>
</html>
