<!DOCTYPE html>
<html>

<head>
    <title>{{ title }}</title>
    <link rel="preconnect" href="{{ mount_path }}">
    <link rel="dns-prefetch" href="{{ url_for('static', path='favicon.ico') }}">
    <link rel="icon" type="image/x-icon" href="{{ url_for('static', path='favicon.ico') }}">
    <!-- Social Media Preview Tags -->
    <meta property="og:title" content="{{ title }}">
    <meta property="og:image" content="{{ url_for('static', path=preview_image) }}">
    <meta property="og:type" content="website">
    <style>
        /* Set background color for the entire viewport */
        html {
            background: var(--background);
            min-height: 100%;
        }

        body {
            opacity: 0;
            transition: opacity 1s ease-in;
            margin: 0 auto;
            background: var(--background);
            color: var(--text-color);
            padding: clamp(.5rem, 2vw, 2rem);
            width: clamp(300px, 90vw, 1200px);
            max-height: 90vh;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
                Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
        }

        body.visible {
            opacity: 1;
        }

        /* Terminal starts hidden and fades in when loaded */
        #terminal {
            width: 100%;
            height: 90vh;
            border: 0;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            visibility: hidden;
        }

        #terminal.loaded {
            visibility: visible;
            animation: fadeIn 0.4s ease-in forwards;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        #loading {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 1.2rem;
            color: var(--text-color);
            opacity: 0.8;
        }

        .error {
            color: #ff3e3e;
            text-align: center;
            padding: 1rem;
            margin: 1rem 0;
            background: rgba(255, 62, 62, 0.1);
            border-radius: 4px;
        }
    </style>
    <!-- Theme data storage -->
    <script id="theme-data" type="application/json">
        {{ theme | tojson | safe }}
    </script>
    <!-- Apply theme immediately to reduce flash of unstyled content -->
    <script>
        (function () {
            const themeData = JSON.parse(document.getElementById('theme-data').textContent);
            Object.entries(themeData).forEach(function (entry) {
                const [key, value] = entry;
                if (value) {
                    document.documentElement.style.setProperty(`--${key}`, value);
                }
            });
        })();
    </script>
</head>

<body>
    <div id="loading">Initializing terminal...</div>
    <iframe id="terminal" src="{{ mount_path }}"></iframe>

    <!-- Main script moved to end of body -->
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const terminal = document.getElementById('terminal');
            const loading = document.getElementById('loading');

            // Get current protocol for websocket connections
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            console.log(`Using ${protocol} for WebSocket connections`);

            function injectStyles() {
                try {
                    const doc = terminal.contentDocument;
                    const style = doc.createElement('style');
                    style.textContent = `
                        .xterm-viewport {
                            overflow: hidden !important;
                        }
                        .terminal.xterm {
                            display: flex !important;
                            justify-content: center !important;
                            align-items: center !important;
                        }
                    `;
                    doc.head.appendChild(style);
                    return true;
                } catch {
                    return false;
                }
            }

            function focusTerminal() {
                try {
                    // Focus the iframe
                    terminal.focus();
                    // Try to focus the terminal element inside the iframe
                    const terminalDoc = terminal.contentDocument || terminal.contentWindow.document;
                    // Find focusable elements in the iframe - first try terminal-specific elements
                    const terminalElement = terminalDoc.querySelector('.xterm-helper-textarea') ||
                        terminalDoc.querySelector('.xterm-textarea') ||
                        terminalDoc.querySelector('.terminal');
                    if (terminalElement) {
                        terminalElement.focus();
                    }
                } catch (err) {
                    console.warn('Could not auto-focus terminal:', err);
                }
            }

            // Set up event listeners
            window.addEventListener('focus', focusTerminal);
            document.addEventListener('click', function (e) {
                if (e.target.closest('#terminal')) {
                    focusTerminal();
                }
            });

            terminal.onload = function () {
                // Inject styles
                injectStyles();

                // Body fade-in first
                setTimeout(function () {
                    document.body.classList.add('visible');
                    if (loading) {
                        loading.style.display = 'none';
                    }

                    // Terminal fade-in second
                    setTimeout(function () {
                        terminal.classList.add('loaded');
                        // Focus after everything is visible
                        setTimeout(focusTerminal, 300);
                    }, 300);
                }, 200);
            };

            terminal.onerror = function () {
                const error = document.createElement('div');
                error.className = 'error';
                error.textContent = 'Failed to load terminal. Please refresh the page.';
                document.body.appendChild(error);
                if (loading) {
                    loading.style.display = 'none';
                }
            };
        });
    </script>
</body>

</html>