<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($session['title']) ?> — BOAFO Video Call</title>
    <link rel="icon" type="image/x-icon" href="<?= APP_URL ?>/favicon.ico">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Outfit:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- JaaS External API -->
    <script src="https://8x8.vc/vpaas-magic-cookie-926d93abf1d34ff38e08fd398d4f2941/external_api.js" async></script>
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --primary:    #6366f1;
            --primary-dk: #4f46e5;
            --bg-dark:    #0f0f1a;
            --bg-panel:   #16162a;
            --text:       #e2e2f0;
            --text-muted: #8888aa;
            --border:     rgba(255,255,255,0.08);
            --success:    #22c55e;
            --danger:     #ef4444;
        }

        html, body {
            height: 100%;
            background: var(--bg-dark);
            color: var(--text);
            font-family: 'Inter', sans-serif;
            overflow: hidden;
        }

        /* ── Top Bar ── */
        .meeting-topbar {
            position: fixed;
            top: 0; left: 0; right: 0;
            height: 56px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
            background: var(--bg-panel);
            border-bottom: 1px solid var(--border);
            z-index: 100;
            backdrop-filter: blur(12px);
        }

        .meeting-brand {
            display: flex;
            align-items: center;
            gap: 10px;
            font-family: 'Outfit', sans-serif;
            font-weight: 700;
            font-size: 1.1rem;
        }

        .meeting-brand .brand-icon {
            width: 32px; height: 32px;
            background: linear-gradient(135deg, var(--primary), var(--primary-dk));
            border-radius: 8px;
            display: flex; align-items: center; justify-content: center;
            font-size: 0.85rem;
        }

        .meeting-info {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .meeting-info .session-title {
            font-size: 0.9rem;
            font-weight: 600;
            color: var(--text);
        }

        .meeting-info .session-time {
            font-size: 0.72rem;
            color: var(--text-muted);
        }

        .meeting-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .btn-leave {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 7px 18px;
            background: var(--danger);
            color: #fff;
            border: none;
            border-radius: 24px;
            font-size: 0.82rem;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            transition: background 0.2s, transform 0.1s;
        }

        .btn-leave:hover {
            background: #dc2626;
            color: #fff;
            transform: scale(1.03);
        }

        /* ── Loading Splash ── */
        #loading-screen {
            position: fixed;
            inset: 56px 0 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: var(--bg-dark);
            z-index: 50;
            gap: 24px;
            transition: opacity 0.5s ease;
        }

        .loading-spinner {
            width: 56px; height: 56px;
            border: 4px solid var(--border);
            border-top-color: var(--primary);
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin { to { transform: rotate(360deg); } }

        .loading-text {
            font-size: 1rem;
            color: var(--text-muted);
            font-weight: 500;
        }

        /* ── Meeting Frame ── */
        #jaas-container {
            position: fixed;
            inset: 56px 0 0;
            background: var(--bg-dark);
        }

        /* ── Error Panel ── */
        #error-panel {
            display: none;
            position: fixed;
            inset: 56px 0 0;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 16px;
            background: var(--bg-dark);
            z-index: 60;
        }

        #error-panel .error-icon {
            font-size: 3rem;
            color: var(--danger);
        }

        #error-panel h4 {
            font-family: 'Outfit', sans-serif;
            font-weight: 700;
        }

        #error-panel p {
            color: var(--text-muted);
            font-size: 0.9rem;
            max-width: 420px;
            text-align: center;
        }

        .btn-back {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 24px;
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: 24px;
            font-weight: 600;
            font-size: 0.9rem;
            text-decoration: none;
            transition: background 0.2s;
        }

        .btn-back:hover { background: var(--primary-dk); color: #fff; }

        /* Live badge */
        .live-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            background: rgba(239,68,68,0.15);
            border: 1px solid rgba(239,68,68,0.35);
            color: var(--danger);
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 700;
            letter-spacing: 0.04em;
        }

        .live-dot {
            width: 7px; height: 7px;
            background: var(--danger);
            border-radius: 50%;
            animation: pulse-dot 1.4s ease infinite;
        }

        @keyframes pulse-dot {
            0%, 100% { opacity: 1; transform: scale(1); }
            50%       { opacity: 0.4; transform: scale(0.7); }
        }
    </style>
</head>
<body>

<!-- Top Bar -->
<div class="meeting-topbar">
    <div class="meeting-brand">
        <div class="brand-icon"><i class="fa-solid fa-graduation-cap text-white"></i></div>
        <span>BOAFO</span>
    </div>

    <div class="meeting-info">
        <span class="session-title"><?= htmlspecialchars($session['title']) ?></span>
        <span class="session-time">
            <i class="fa-regular fa-clock me-1"></i>
            <?= date('D, d M Y · g:i A', strtotime($session['scheduled_at'])) ?>
        </span>
    </div>

    <div class="meeting-actions">
        <span class="live-badge"><span class="live-dot"></span> LIVE</span>
        <a href="<?= APP_URL ?>/sessions" class="btn-leave" id="leave-btn">
            <i class="fa-solid fa-phone-slash"></i> Leave Meeting
        </a>
    </div>
</div>

<!-- Loading Screen -->
<div id="loading-screen">
    <div class="loading-spinner"></div>
    <span class="loading-text">Connecting to your meeting room…</span>
</div>

<!-- Error Panel -->
<div id="error-panel">
    <div class="error-icon"><i class="fa-solid fa-triangle-exclamation"></i></div>
    <h4>Unable to Connect</h4>
    <p id="error-msg">Could not load the video conference. Please check your browser permissions and try again.</p>
    <a href="<?= APP_URL ?>/sessions" class="btn-back"><i class="fa-solid fa-arrow-left"></i> Back to Sessions</a>
</div>

<!-- JaaS Container -->
<div id="jaas-container"></div>

<script>
const JAAS_APP_ID  = '<?= JAAS_APP_ID ?>';
const ROOM_NAME    = '<?= htmlspecialchars($roomName) ?>';
const JWT_TOKEN    = '<?= htmlspecialchars($jwt) ?>';
const DISPLAY_NAME = '<?= htmlspecialchars($currentUser['name']) ?>';
const USER_EMAIL   = '<?= htmlspecialchars($currentUser['email']) ?>';
const IS_MODERATOR = <?= $isModerator ? 'true' : 'false' ?>;
const SESSIONS_URL = '<?= APP_URL ?>/sessions';

function initJaas() {
    const loadingScreen = document.getElementById('loading-screen');
    const errorPanel    = document.getElementById('error-panel');

    if (typeof JitsiMeetExternalAPI === 'undefined') {
        loadingScreen.style.display = 'none';
        errorPanel.style.display = 'flex';
        document.getElementById('error-msg').textContent =
            'Failed to load the JaaS API script. Please check your internet connection.';
        return;
    }

    const options = {
        roomName: `${JAAS_APP_ID}/${ROOM_NAME}`,
        parentNode: document.getElementById('jaas-container'),
        userInfo: {
            displayName: DISPLAY_NAME,
            email: USER_EMAIL,
        },
        configOverwrite: {
            startWithAudioMuted: false,
            startWithVideoMuted: false,
            disableDeepLinking: true,
            enableNoisyMicDetection: true,
            prejoinPageEnabled: false,   // Skip pre-join — go straight into the call
        },
        interfaceConfigOverwrite: {
            SHOW_JITSI_WATERMARK: false,
            SHOW_WATERMARK_FOR_GUESTS: false,
            SHOW_BRAND_WATERMARK: false,
            BRAND_WATERMARK_LINK: '',
            DEFAULT_BACKGROUND: '#0f0f1a',
            TOOLBAR_BUTTONS: [
                'microphone', 'camera', 'closedcaptions', 'desktop',
                'fullscreen', 'fodeviceselection', 'hangup', 'chat',
                'settings', 'raisehand', 'videoquality', 'filmstrip',
                'tileview', 'select-background', 'mute-everyone',
            ],
            MOBILE_APP_PROMO: false,
        },
        width: '100%',
        height: '100%',
    };

    // Only pass JWT if it is actually set (avoids anonymous rejection)
    if (JWT_TOKEN && JWT_TOKEN.length > 10) {
        options.jwt = JWT_TOKEN;
    }

    try {
        const api = new JitsiMeetExternalAPI(`8x8.vc`, options);

        // *** KEY FIX: hide loading after 2s so users can see the Jitsi UI immediately ***
        setTimeout(() => {
            loadingScreen.style.opacity = '0';
            loadingScreen.style.transition = 'opacity 0.5s ease';
            setTimeout(() => { loadingScreen.style.display = 'none'; }, 500);
        }, 2000);

        // Also hide immediately when conference fully joins
        api.addEventListener('videoConferenceJoined', () => {
            loadingScreen.style.display = 'none';
        });

        // Redirect when user leaves
        api.addEventListener('readyToClose', () => {
            window.location.href = SESSIONS_URL;
        });

        api.addEventListener('videoConferenceLeft', () => {
            window.location.href = SESSIONS_URL;
        });

        api.addEventListener('connectionFailed', () => {
            loadingScreen.style.display = 'none';
            errorPanel.style.display = 'flex';
            document.getElementById('error-msg').textContent =
                'Connection failed. Please check your network or try refreshing.';
        });

    } catch (err) {
        loadingScreen.style.display = 'none';
        errorPanel.style.display = 'flex';
        document.getElementById('error-msg').textContent = err.message || 'Unknown error occurred.';
        console.error('JaaS init error:', err);
    }
}

// Wait for the external API script to load
let attempts = 0;
const waitForJaas = setInterval(() => {
    attempts++;
    if (typeof JitsiMeetExternalAPI !== 'undefined') {
        clearInterval(waitForJaas);
        initJaas();
    } else if (attempts > 40) {
        clearInterval(waitForJaas);
        document.getElementById('loading-screen').style.display = 'none';
        document.getElementById('error-panel').style.display = 'flex';
        document.getElementById('error-msg').textContent =
            'Failed to load the JaaS API script. Please check your internet connection.';
    }
}, 250);

// 30-second overall timeout — if still on loading screen, show error
setTimeout(() => {
    const ls = document.getElementById('loading-screen');
    if (ls && ls.style.display !== 'none') {
        ls.style.display = 'none';
        const ep = document.getElementById('error-panel');
        ep.style.display = 'flex';
        document.getElementById('error-msg').innerHTML =
            'Connection timed out. This is usually caused by an invalid token or network issue.<br><br>' +
            '<small style="color:#666;">Check the browser console (F12) for details. ' +
            'JWT provided: <code>' + (JWT_TOKEN ? JWT_TOKEN.substring(0,40) + '…' : '<strong>EMPTY — JWT generation failed on the server!</strong>') + '</code></small>';
    }
}, 30000);

// Confirm before leaving page
window.addEventListener('beforeunload', (e) => {
    e.preventDefault();
    e.returnValue = '';
});
</script>
</body>
</html>
