<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GenX Student Workspace — Dashboard</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Plus Jakarta Sans', 'sans-serif'],
                        outfit: ['Outfit', 'sans-serif'],
                    },
                    colors: {
                        brand: {
                            light: '#FFFFFF',
                            bg: '#F8FAFC',
                            indigo: '#4F46E5',
                            purple: '#7C3AED',
                            text: '#0F172A',
                            desc: '#475569',
                            muted: '#94A3B8',
                        }
                    },
                }
            }
        }
    </script>
    <style>
        body { background-color: #F8FAFC; color: #0F172A; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #F8FAFC; }
        ::-webkit-scrollbar-thumb { background: #E2E8F0; border-radius: 3px; }
        ::-webkit-scrollbar-thumb:hover { background: #CBD5E1; }

        .lesson-item { transition: all 0.2s ease; }
        .lesson-item.active { background: linear-gradient(to right, #EEF2FF, #F5F3FF); border-color: #C7D2FE; }
        .lesson-item.active .lesson-play-icon { background: #4F46E5; color: white; border-color: #4F46E5; }
        .lesson-item.active .lesson-title { color: #4F46E5; }

        .lesson-item.completed .lesson-play-icon { background: #ECFDF5; color: #059669; border-color: #6EE7B7; }
        .lesson-item.completed .lesson-title { text-decoration: line-through; opacity: 0.6; }

        #youtube-player { border: none; }

        @keyframes pulse-ring {
            0%   { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.35); }
            70%  { box-shadow: 0 0 0 12px rgba(79, 70, 229, 0); }
            100% { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0); }
        }
        .pulse-indigo { animation: pulse-ring 2.5s infinite; }
        @keyframes fadeSlideIn {
            from { opacity: 0; transform: translateY(6px); }
            to   { opacity: 1; transform: translateY(0); }
        }
        .fade-slide { animation: fadeSlideIn 0.3s ease forwards; }

        /* Fullscreen handling for custom player container */
        #player-area:fullscreen,
        #player-area:-webkit-full-screen,
        #player-area:-ms-fullscreen {
            width: 100vw !important;
            height: 100vh !important;
            background: #000;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        #player-area:fullscreen #youtube-player-container,
        #player-area:fullscreen #player-overlay,
        #player-area:-webkit-full-screen #youtube-player-container,
        #player-area:-webkit-full-screen #player-overlay,
        #player-area:-ms-fullscreen #youtube-player-container,
        #player-area:-ms-fullscreen #player-overlay {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body class="font-sans antialiased min-h-screen flex flex-col">

    <!-- Decorative blobs -->
    <div class="fixed top-0 right-1/4 w-[400px] h-[400px] bg-purple-50/30 rounded-full blur-[100px] pointer-events-none -translate-y-1/2 z-0"></div>
    <div class="fixed bottom-0 left-1/4 w-[400px] h-[400px] bg-indigo-50/20 rounded-full blur-[100px] pointer-events-none translate-y-1/3 z-0"></div>

    <?php
    $courseTitles = [
        'digital_marketing_foundational' => 'Digital Marketing Foundation',
        'web_development_foundational'   => 'Web Development Foundation',
        'ai_python_fullstack'            => 'AI & Python Full Stack',
        'digital_marketing_expert'       => 'Digital Marketing Expert',
    ];
    $currentCourseTitle = $courseTitles[$student_course] ?? 'Your Course';
    $hasContent = !empty($flat_lessons);

    // Pre-build a JS-safe data structure for all lessons
    $jsLessons = [];
    foreach ($flat_lessons as $lesson) {
        $ytId = \App\Models\CourseModel::extractYouTubeId($lesson['youtube_url']);
        $jsLessons[] = [
            'id'           => $lesson['id'],
            'title'        => $lesson['lesson_title'],
            'moduleName'   => $lesson['module_name'] ?? '',
            'duration'     => $lesson['duration'] ?? '',
            'notes'        => $lesson['notes'] ?? '',
            'youtubeId'    => $ytId,
            'youtubeUrl'   => $lesson['youtube_url'] ?? '',
            'moduleOrder'  => (int)($lesson['module_order'] ?? 1),
            'lessonOrder'  => (int)($lesson['lesson_order'] ?? 1),
            'courseType'   => $lesson['course_type'] ?? 'modular',
        ];
    }
    ?>

    <!-- Header -->
    <header class="border-b border-slate-200 bg-white/80 backdrop-blur-md sticky top-0 z-40">
        <div class="max-w-7xl mx-auto px-6 h-20 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <span class="font-outfit text-xl font-extrabold tracking-wider text-brand-text">
                    GEN<span class="text-brand-indigo">X</span>
                </span>
                <span class="text-[9px] tracking-widest font-bold uppercase text-brand-indigo border border-indigo-200 bg-indigo-50 px-2 py-0.5 rounded">Learning Workspace</span>
            </div>
            <div class="flex items-center gap-4">
                <span class="text-xs font-semibold text-brand-text hidden sm:inline">🎓 <?= esc($student_name) ?></span>
                <a href="<?= site_url('student/logout') ?>" class="text-xs font-bold text-red-500 hover:text-red-700 border border-red-100 bg-red-50/50 px-3 py-1.5 rounded-lg transition-colors">Sign Out</a>
            </div>
        </div>
    </header>

    <!-- Main -->
    <main class="max-w-7xl mx-auto px-6 py-10 flex-grow w-full relative z-10">

        <?php if (!$hasContent): ?>
        <!-- ───── No Content State ───── -->
        <div class="flex flex-col items-center justify-center min-h-[60vh] text-center space-y-6">
            <div class="w-24 h-24 rounded-3xl bg-indigo-50 border border-indigo-100 flex items-center justify-center text-4xl shadow-inner">🎬</div>
            <div>
                <h2 class="font-outfit text-2xl font-extrabold text-brand-text">Content Coming Soon</h2>
                <p class="text-brand-desc text-sm mt-2 max-w-md">
                    Your instructor is preparing lesson videos for <strong><?= esc($currentCourseTitle) ?></strong>. Check back soon!
                </p>
            </div>
            <div class="bg-white border border-slate-200 rounded-2xl p-6 max-w-sm w-full shadow-sm">
                <div class="text-[10px] font-bold uppercase tracking-widest text-brand-desc mb-1">Enrolled In</div>
                <div class="font-outfit font-extrabold text-brand-text"><?= esc($currentCourseTitle) ?></div>
                <div class="text-xs text-brand-desc mt-1"><?= esc($student_email) ?></div>
            </div>
        </div>

        <?php else: ?>
        <!-- ───── Main Dashboard Layout ───── -->
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">

            <!-- Left: Video Player + Tabs (8 cols) -->
            <div class="lg:col-span-8 space-y-5">

                <!-- Video Player Card -->
                <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm" id="player-card">
                    <!-- YouTube Iframe Area -->
                    <div class="relative aspect-video bg-slate-950" id="player-area">

                        <!-- Placeholder (shown when no video selected) -->
                        <div id="player-placeholder" class="absolute inset-0 flex flex-col items-center justify-center gap-4 text-white">
                            <div class="w-16 h-16 rounded-full bg-white/10 border border-white/20 flex items-center justify-center text-2xl pulse-indigo">▶</div>
                            <div class="text-center">
                                <div class="text-xs font-bold text-white/70 tracking-widest uppercase">Select a lesson to begin</div>
                                <div class="text-[10px] text-white/40 mt-1 font-mono" id="placeholder-course"><?= esc($currentCourseTitle) ?></div>
                            </div>
                        </div>

                        <!-- YouTube Player Wrapper (needed for API replacement) -->
                        <div id="youtube-player-container" class="absolute inset-0 w-full h-full hidden">
                            <div id="youtube-player"></div>
                        </div>

                        <!-- Click overlay (blocks links, handles toggle play/pause and double-click fullscreen) -->
                        <div id="player-overlay" class="absolute inset-0 bg-transparent z-10 hidden" onclick="handleOverlayClick()" ondblclick="toggleFullscreen()"></div>

                        <!-- Custom Premium Video Controls Bar -->
                        <div id="custom-controls" class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-slate-950/95 via-slate-950/70 to-transparent p-4 flex flex-col gap-2.5 z-20 opacity-0 group-hover:opacity-100 transition-opacity duration-300 hidden">
                            <!-- Scrub / Seekbar -->
                            <div class="flex items-center">
                                <input type="range" id="custom-seekbar" min="0" max="100" value="0" step="0.1" 
                                    class="w-full h-1 bg-white/20 rounded-lg appearance-none cursor-pointer accent-brand-indigo hover:h-1.5 transition-all outline-none" 
                                    oninput="onSeek(this.value)">
                            </div>
                            
                            <!-- Control Buttons -->
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-4">
                                    <button id="custom-play-btn" onclick="togglePlay()" class="text-white hover:text-brand-indigo transition-colors focus:outline-none w-5 h-5 flex items-center justify-center" title="Play/Pause">
                                        <svg class="w-3.5 h-3.5 fill-current" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
                                    </button>
                                    <span id="custom-time" class="text-[10px] font-mono text-slate-300">0:00 / 0:00</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <button onclick="toggleFullscreen()" class="text-white hover:text-brand-indigo transition-colors focus:outline-none w-5 h-5 flex items-center justify-center" title="Fullscreen">
                                        <svg class="w-4 h-4 fill-current" viewBox="0 0 24 24"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Info bar below player -->
                    <div class="px-6 py-4 border-b border-slate-100 bg-slate-50/50 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                        <div>
                            <span class="text-[9px] uppercase tracking-wider text-brand-indigo font-bold" id="playing-module-label">—</span>
                            <h2 id="playing-title" class="font-outfit text-base font-extrabold text-brand-text mt-0.5">Select a lesson to start</h2>
                        </div>
                        <div class="flex items-center gap-3 shrink-0">
                            <span id="playing-duration" class="text-xs text-brand-desc font-mono hidden"></span>
                            <label class="flex items-center gap-2 cursor-pointer">
                                <input type="checkbox" id="mark-complete-checkbox" class="w-4 h-4 rounded text-brand-indigo focus:ring-brand-indigo border-slate-300 cursor-pointer" onchange="toggleComplete()">
                                <span class="text-xs font-bold text-brand-text">Mark Complete</span>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Tabs: Notes / Resources / Sandbox -->
                <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
                    <div class="border-b border-slate-200 bg-slate-50/50 flex divide-x divide-slate-200">
                        <button onclick="switchTab('notes')" id="tab-btn-notes" class="px-6 py-4 text-xs font-bold text-brand-indigo border-b-2 border-brand-indigo bg-white focus:outline-none transition-all flex items-center gap-2">
                            📝 Lecture Notes
                        </button>
                        <button onclick="switchTab('resources')" id="tab-btn-resources" class="px-6 py-4 text-xs font-bold text-brand-desc hover:text-brand-text hover:bg-white focus:outline-none transition-all flex items-center gap-2">
                            📁 Resources
                        </button>
                        <button onclick="switchTab('sandbox')" id="tab-btn-sandbox" class="px-6 py-4 text-xs font-bold text-brand-desc hover:text-brand-text hover:bg-white focus:outline-none transition-all flex items-center gap-2">
                            ⚡ Sandbox
                        </button>
                    </div>
                    <div class="p-6">
                        <!-- Notes -->
                        <div id="tab-content-notes" class="space-y-4">
                            <h4 class="font-bold text-xs text-brand-text uppercase tracking-wider">Concept Summary</h4>
                            <p id="lecture-notes-display" class="text-brand-desc text-xs leading-relaxed italic text-slate-400">
                                Select a lesson from the sidebar to see its notes here.
                            </p>
                            <div class="p-4 border border-slate-100 rounded-xl bg-slate-50/50 mt-4 text-[11px] text-brand-desc">
                                💡 <strong>Tip:</strong> Take notes as you watch — revisit them during revision!
                            </div>
                        </div>
                        <!-- Resources -->
                        <div id="tab-content-resources" class="hidden space-y-4">
                            <h4 class="font-bold text-xs text-brand-text uppercase tracking-wider">Course Downloads</h4>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <a href="#" class="p-4 border border-slate-200 rounded-xl hover:border-brand-indigo/35 hover:bg-slate-50 transition-all flex items-center justify-between">
                                    <div class="flex items-center gap-3">
                                        <span class="text-xl">📄</span>
                                        <div>
                                            <div class="text-xs font-bold text-brand-text">Cheat Sheet PDF</div>
                                            <div class="text-[10px] text-brand-desc">Core definitions & variables</div>
                                        </div>
                                    </div>
                                    <span class="text-brand-indigo text-xs font-bold">Download</span>
                                </a>
                                <a href="#" class="p-4 border border-slate-200 rounded-xl hover:border-brand-indigo/35 hover:bg-slate-50 transition-all flex items-center justify-between">
                                    <div class="flex items-center gap-3">
                                        <span class="text-xl">💻</span>
                                        <div>
                                            <div class="text-xs font-bold text-brand-text">Practice Templates</div>
                                            <div class="text-[10px] text-brand-desc">Starter files for assignments</div>
                                        </div>
                                    </div>
                                    <span class="text-brand-indigo text-xs font-bold">Download</span>
                                </a>
                            </div>
                        </div>
                        <!-- Sandbox -->
                        <div id="tab-content-sandbox" class="hidden space-y-4">
                            <div class="flex justify-between items-center">
                                <h4 class="font-bold text-xs text-brand-text uppercase tracking-wider">Sandbox Terminal</h4>
                                <span class="text-[8px] uppercase tracking-widest bg-emerald-50 text-emerald-700 border border-emerald-200 px-2 py-0.5 rounded font-bold">active</span>
                            </div>
                            <div class="bg-slate-900 rounded-xl overflow-hidden border border-slate-800">
                                <div class="bg-slate-950 px-4 py-2 border-b border-slate-800 flex items-center justify-between">
                                    <span class="text-[10px] text-slate-400 font-mono">student@genx-sandbox:~$</span>
                                    <div class="flex gap-1.5">
                                        <span class="w-2.5 h-2.5 rounded-full bg-red-500/80"></span>
                                        <span class="w-2.5 h-2.5 rounded-full bg-yellow-500/80"></span>
                                        <span class="w-2.5 h-2.5 rounded-full bg-green-500/80"></span>
                                    </div>
                                </div>
                                <div class="p-4 font-mono text-xs text-slate-300 min-h-[140px] space-y-2">
                                    <div class="text-slate-500">// Type 'help' to see available commands</div>
                                    <div class="flex items-center gap-2">
                                        <span class="text-brand-indigo font-bold">$</span>
                                        <input type="text" id="sandbox-input" class="bg-transparent border-none outline-none text-white w-full font-mono text-xs" placeholder="Type here..." onkeydown="handleTerminalCommand(event)">
                                    </div>
                                    <div id="sandbox-output" class="text-slate-400 text-[11px] whitespace-pre-line leading-relaxed"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right: Progress + Syllabus (4 cols) -->
            <div class="lg:col-span-4 space-y-5">

                <!-- Progress Card -->
                <div class="bg-white border border-slate-200 p-6 rounded-2xl shadow-sm">
                    <h3 class="font-outfit text-sm font-extrabold text-brand-text mb-4">Your Progress</h3>
                    <div class="space-y-3">
                        <div class="flex justify-between items-center text-xs">
                            <span class="text-brand-desc font-medium">Completed Lectures</span>
                            <span class="font-bold text-brand-indigo" id="progress-text">0 / <?= count($flat_lessons) ?> Completed</span>
                        </div>
                        <div class="w-full bg-slate-100 rounded-full h-2 overflow-hidden">
                            <div id="progress-bar" class="bg-gradient-to-r from-brand-indigo to-brand-purple h-full rounded-full transition-all duration-500" style="width: 0%"></div>
                        </div>
                        <div class="text-[10px] text-brand-desc">
                            Course: <span class="font-bold text-brand-text"><?= esc($currentCourseTitle) ?></span>
                        </div>
                    </div>
                </div>

                <!-- Syllabus Sidebar -->
                <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
                    <div class="px-5 py-4 border-b border-slate-200 bg-slate-50/50">
                        <h3 class="font-outfit text-sm font-extrabold text-brand-text">Curriculum</h3>
                        <p class="text-[10px] text-brand-desc mt-0.5 font-semibold"><?= esc($currentCourseTitle) ?></p>
                    </div>

                    <div class="divide-y divide-slate-100 max-h-[70vh] overflow-y-auto" id="syllabus-container">
                        <?php if ($course_type === 'one_shot' || empty($syllabus)): ?>
                            <!-- Flat list (one-shot or no modules) -->
                            <div class="p-4 space-y-2">
                                <?php foreach ($flat_lessons as $lesson):
                                    $ytId = \App\Models\CourseModel::extractYouTubeId($lesson['youtube_url']);
                                ?>
                                    <button
                                        onclick="playLesson(<?= $lesson['id'] ?>)"
                                        id="lesson-btn-<?= $lesson['id'] ?>"
                                        class="lesson-item w-full text-left flex items-start gap-3 p-2.5 rounded-xl border border-transparent hover:bg-slate-50 transition-all group">
                                        <span class="lesson-play-icon w-6 h-6 rounded-full border border-slate-300 text-[10px] text-slate-400 flex items-center justify-center shrink-0 font-bold mt-0.5 transition-all">▶</span>
                                        <div class="flex-grow min-w-0">
                                            <div class="lesson-title text-xs font-bold text-brand-text truncate"><?= esc($lesson['lesson_title']) ?></div>
                                            <div class="flex items-center gap-2 mt-0.5">
                                                <?php if ($lesson['duration']): ?><span class="text-[10px] text-brand-desc">⏱ <?= esc($lesson['duration']) ?></span><?php endif; ?>
                                                <span class="text-[9px] font-bold text-emerald-600 uppercase tracking-widest hidden" id="badge-<?= $lesson['id'] ?>">✓ Done</span>
                                            </div>
                                        </div>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <!-- Modular layout -->
                            <?php foreach ($syllabus as $mod): ?>
                                <div class="p-4 space-y-2">
                                    <?php if (!empty($mod['module'])): ?>
                                        <h4 class="text-[10px] font-bold text-brand-indigo uppercase tracking-wider px-1 mb-3"><?= esc($mod['module']) ?></h4>
                                    <?php endif; ?>
                                    <?php foreach ($mod['lessons'] as $lesson):
                                        $ytId = \App\Models\CourseModel::extractYouTubeId($lesson['youtube_url']);
                                    ?>
                                        <button
                                            onclick="playLesson(<?= $lesson['id'] ?>)"
                                            id="lesson-btn-<?= $lesson['id'] ?>"
                                            class="lesson-item w-full text-left flex items-start gap-3 p-2.5 rounded-xl border border-transparent hover:bg-slate-50 transition-all group">
                                            <span class="lesson-play-icon w-6 h-6 rounded-full border border-slate-300 text-[10px] text-slate-400 flex items-center justify-center shrink-0 font-bold mt-0.5 transition-all">▶</span>
                                            <div class="flex-grow min-w-0">
                                                <div class="lesson-title text-xs font-bold text-brand-text truncate"><?= esc($lesson['lesson_title']) ?></div>
                                                <div class="flex items-center gap-2 mt-0.5">
                                                    <?php if ($lesson['duration']): ?><span class="text-[10px] text-brand-desc">⏱ <?= esc($lesson['duration']) ?></span><?php endif; ?>
                                                    <span class="text-[9px] font-bold text-emerald-600 uppercase tracking-widest hidden" id="badge-<?= $lesson['id'] ?>">✓ Done</span>
                                                </div>
                                            </div>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </div>
        <?php endif; ?>
    </main>

    <!-- Footer -->
    <footer class="border-t border-slate-200 bg-white py-8 text-center text-xs text-brand-desc mt-auto">
        <div class="max-w-7xl mx-auto px-6">
            &copy; 2026 GenX Institute Student Portal. Built with CodeIgniter 4.
        </div>
    </footer>

    <script>
    // ── Lesson data from PHP ──────────────────────────────
    const LESSONS = <?= json_encode($jsLessons) ?>;
    const TOTAL   = LESSONS.length;

    const completedSet = new Set();
    let currentLessonId = null;

    // ── YouTube Iframe Player API Integration ─────────────
    let ytPlayer = null;
    let ytApiReady = false;
    let progressInterval = null;
    let controlsTimeout = null;

    // Load YouTube Player API Script asynchronously
    (function() {
        const tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        const firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    })();

    // Required YouTube global callback
    window.onYouTubeIframeAPIReady = function() {
        ytApiReady = true;
    };

    // ── Play a lesson ─────────────────────────────────────
    function playLesson(id) {
        const lesson = LESSONS.find(l => l.id === id);
        if (!lesson) return;

        currentLessonId = id;

        const placeholder = document.getElementById('player-placeholder');
        const container   = document.getElementById('youtube-player-container');
        const overlay     = document.getElementById('player-overlay');
        const controls    = document.getElementById('custom-controls');

        if (lesson.youtubeId) {
            placeholder.classList.add('hidden');
            container.classList.remove('hidden');
            overlay.classList.remove('hidden');
            controls.classList.remove('hidden');

            if (!ytPlayer) {
                // Initialize the player
                ytPlayer = new YT.Player('youtube-player', {
                    height: '100%',
                    width: '100%',
                    videoId: lesson.youtubeId,
                    playerVars: {
                        autoplay: 1,
                        controls: 0,       // Hide native YouTube controls
                        rel: 0,            // Don't show related videos
                        showinfo: 0,
                        modestbranding: 1, // Minimize YouTube logo
                        disablekb: 1,      // Disable YouTube keyboard shortcuts to block shortcuts
                        enablejsapi: 1,
                        iv_load_policy: 3
                    },
                    events: {
                        'onReady': (event) => {
                            event.target.playVideo();
                            startProgressTracking();
                        },
                        'onStateChange': onPlayerStateChange
                    }
                });
            } else {
                // Player exists, swap video id
                ytPlayer.loadVideoById(lesson.youtubeId);
                ytPlayer.playVideo();
            }
        } else {
            container.classList.add('hidden');
            overlay.classList.add('hidden');
            controls.classList.add('hidden');
            placeholder.classList.remove('hidden');
            if (ytPlayer && typeof ytPlayer.stopVideo === 'function') {
                ytPlayer.stopVideo();
            }
        }

        // Info bar
        document.getElementById('playing-module-label').textContent = lesson.moduleName || 'Lesson';
        document.getElementById('playing-title').textContent = lesson.title;

        const durEl = document.getElementById('playing-duration');
        if (lesson.duration) {
            durEl.textContent = '⏱ ' + lesson.duration;
            durEl.classList.remove('hidden');
        } else {
            durEl.classList.add('hidden');
        }

        // Notes tab
        const notesEl = document.getElementById('lecture-notes-display');
        if (lesson.notes) {
            notesEl.textContent = lesson.notes;
            notesEl.classList.remove('italic', 'text-slate-400');
            notesEl.classList.add('text-brand-desc');
        } else {
            notesEl.textContent = 'No notes provided for this lesson.';
            notesEl.classList.add('italic', 'text-slate-400');
        }

        // Mark complete checkbox
        document.getElementById('mark-complete-checkbox').checked = completedSet.has(id);

        // Sidebar active state
        document.querySelectorAll('.lesson-item').forEach(el => {
            el.classList.remove('active');
        });
        const activeBtn = document.getElementById(`lesson-btn-${id}`);
        if (activeBtn) activeBtn.classList.add('active');
    }

    // ── Mark complete ─────────────────────────────────────
    function toggleComplete() {
        if (currentLessonId === null) return;
        const checkbox = document.getElementById('mark-complete-checkbox');
        const badge    = document.getElementById(`badge-${currentLessonId}`);
        const btn      = document.getElementById(`lesson-btn-${currentLessonId}`);

        if (checkbox.checked) {
            completedSet.add(currentLessonId);
            if (badge) badge.classList.remove('hidden');
            if (btn)   btn.classList.add('completed');
        } else {
            completedSet.delete(currentLessonId);
            if (badge) badge.classList.add('hidden');
            if (btn)   btn.classList.remove('completed');
        }
        updateProgress();
    }

    function updateProgress() {
        const count = completedSet.size;
        document.getElementById('progress-text').textContent = `${count} / ${TOTAL} Completed`;
        const pct = TOTAL > 0 ? (count / TOTAL) * 100 : 0;
        document.getElementById('progress-bar').style.width = `${pct}%`;
    }

    // ── Tab switching ─────────────────────────────────────
    function switchTab(tabId) {
        ['notes', 'resources', 'sandbox'].forEach(t => {
            const content = document.getElementById(`tab-content-${t}`);
            const btn     = document.getElementById(`tab-btn-${t}`);
            if (t === tabId) {
                content.classList.remove('hidden');
                btn.classList.add('text-brand-indigo', 'border-b-2', 'border-brand-indigo', 'bg-white');
                btn.classList.remove('text-brand-desc', 'hover:text-brand-text', 'hover:bg-white');
            } else {
                content.classList.add('hidden');
                btn.classList.remove('text-brand-indigo', 'border-b-2', 'border-brand-indigo', 'bg-white');
                btn.classList.add('text-brand-desc', 'hover:text-brand-text', 'hover:bg-white');
            }
        });
    }

    // ── Sandbox terminal ──────────────────────────────────
    function handleTerminalCommand(e) {
        if (e.key !== 'Enter') return;
        const val = e.target.value.trim().toLowerCase();
        const out = document.getElementById('sandbox-output');
        if (!val) return;

        let resp = '';
        if (val === 'help')       resp = `Available:\n  help      — show commands\n  run tests — run test suite\n  clear     — reset console`;
        else if (val === 'run tests') resp = `✓ Loading sandbox...\n✓ Running test suite...\n✓ ALL TESTS PASSED. Ready for placement!`;
        else if (val === 'clear') { out.textContent = ''; e.target.value = ''; return; }
        else                      resp = `bash: command not found: ${e.target.value}\nType 'help' for commands.`;

        out.textContent += `\n$ ${e.target.value}\n${resp}\n`;
        e.target.value = '';
    }

    // ── Auto-select first lesson on load ──────────────────
    document.addEventListener('DOMContentLoaded', () => {
        if (LESSONS.length > 0) {
            playLesson(LESSONS[0].id);
        }

        // Setup controls fadeout on mouse idle
        const playerArea = document.getElementById('player-area');
        if (playerArea) {
            playerArea.addEventListener('mousemove', () => {
                const controls = document.getElementById('custom-controls');
                if (controls && !controls.classList.contains('hidden')) {
                    controls.style.opacity = '1';
                    clearTimeout(controlsTimeout);
                    controlsTimeout = setTimeout(() => {
                        // Only hide controls if video is playing
                        if (ytPlayer && typeof ytPlayer.getPlayerState === 'function' && ytPlayer.getPlayerState() === YT.PlayerState.PLAYING) {
                            controls.style.opacity = '0';
                        }
                    }, 2500);
                }
            });
            playerArea.addEventListener('mouseleave', () => {
                const controls = document.getElementById('custom-controls');
                if (controls) {
                    controls.style.opacity = '0';
                }
            });
        }
    });

    // ── Custom Player Logic ────────────────────────────────
    function onPlayerStateChange(event) {
        const playBtn = document.getElementById('custom-play-btn');
        if (event.data === YT.PlayerState.PLAYING) {
            playBtn.innerHTML = `<svg class="w-3.5 h-3.5 fill-current" viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>`; // Pause SVG
            startProgressTracking();
        } else {
            playBtn.innerHTML = `<svg class="w-3.5 h-3.5 fill-current" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>`; // Play SVG
            stopProgressTracking();
        }
    }

    function togglePlay() {
        if (!ytPlayer || typeof ytPlayer.getPlayerState !== 'function') return;
        const state = ytPlayer.getPlayerState();
        if (state === YT.PlayerState.PLAYING) {
            ytPlayer.pauseVideo();
        } else {
            ytPlayer.playVideo();
        }
    }

    function handleOverlayClick() {
        togglePlay();
    }

    function startProgressTracking() {
        stopProgressTracking();
        progressInterval = setInterval(updateProgressBar, 250);
    }

    function stopProgressTracking() {
        if (progressInterval) {
            clearInterval(progressInterval);
            progressInterval = null;
        }
    }

    function formatTime(seconds) {
        if (isNaN(seconds) || seconds === Infinity) return '0:00';
        const m = Math.floor(seconds / 60);
        const s = Math.floor(seconds % 60);
        return `${m}:${s < 10 ? '0' : ''}${s}`;
    }

    function updateProgressBar() {
        if (!ytPlayer || typeof ytPlayer.getCurrentTime !== 'function') return;
        const current  = ytPlayer.getCurrentTime();
        const duration = ytPlayer.getDuration();
        if (duration > 0) {
            const pct = (current / duration) * 100;
            document.getElementById('custom-seekbar').value = pct;
            document.getElementById('custom-time').textContent = `${formatTime(current)} / ${formatTime(duration)}`;
        }
    }

    function onSeek(value) {
        if (!ytPlayer || typeof ytPlayer.getDuration !== 'function') return;
        const duration = ytPlayer.getDuration();
        const seekTo   = (value / 100) * duration;
        ytPlayer.seekTo(seekTo, true);
        // Force immediate seek indicator update
        document.getElementById('custom-time').textContent = `${formatTime(seekTo)} / ${formatTime(duration)}`;
    }

    function toggleFullscreen() {
        const area = document.getElementById('player-area');
        if (!document.fullscreenElement) {
            if (area.requestFullscreen) {
                area.requestFullscreen();
            } else if (area.webkitRequestFullscreen) { /* Safari */
                area.webkitRequestFullscreen();
            } else if (area.msRequestFullscreen) { /* IE11 */
                area.msRequestFullscreen();
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        }
    }
    </script>

</body>
</html>
