{{> header}}
<style>
  .learn-section { min-height: calc(100vh - 80px); display: flex; background: var(--color-background); position: relative; }
  .learn-sidebar { width: 320px; background: var(--color-surface); border-right: 1px solid var(--color-border); display: flex; flex-direction: column; position: fixed; top: 70px; left: 0; bottom: 0; overflow-y: auto; z-index: 100; transition: transform 0.3s ease, width 0.3s ease; }
  .learn-sidebar.collapsed { width: 60px; }
  .sidebar-header { padding: 1.25rem; border-bottom: 1px solid var(--color-border); display: flex; align-items: center; gap: 1rem; }
  .sidebar-header h2 { font-size: 1rem; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; }
  .toggle-sidebar { background: none; border: none; color: var(--color-text-muted); cursor: pointer; padding: 0.5rem; border-radius: 4px; min-width: 44px; min-height: 44px; display: flex; align-items: center; justify-content: center; }
  .toggle-sidebar:hover { background: var(--color-background); color: var(--color-text); }
  .course-progress { padding: 1rem 1.25rem; border-bottom: 1px solid var(--color-border); }
  .progress-bar { height: 6px; background: var(--color-background); border-radius: 3px; overflow: hidden; margin-bottom: 0.5rem; }
  .progress-fill { height: 100%; background: var(--gradient-primary); border-radius: 3px; transition: width 0.3s ease; }
  .progress-text { font-size: 0.8rem; color: var(--color-text-muted); }
  .lessons-list { flex: 1; overflow-y: auto; padding: 0.5rem 0; -webkit-overflow-scrolling: touch; }
  .module-item { border-bottom: 1px solid var(--color-border); }
  .module-header { padding: 1rem 1.25rem; font-weight: 600; font-size: 0.9rem; color: var(--color-text-muted); text-transform: uppercase; letter-spacing: 0.5px; cursor: pointer; display: flex; align-items: center; justify-content: space-between; }
  .module-header:hover { background: var(--color-background); }
  .lesson-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.875rem 1.25rem; cursor: pointer; transition: all 0.2s; border-left: 3px solid transparent; min-height: 48px; }
  .lesson-item:hover { background: var(--color-background); }
  .lesson-item.active { background: rgba(99, 102, 241, 0.1); border-left-color: var(--color-primary); }
  .lesson-item.completed .lesson-status { background: var(--color-success); color: white; }
  .lesson-status { width: 28px; height: 28px; border-radius: 50%; border: 2px solid var(--color-border); display: flex; align-items: center; justify-content: center; font-size: 0.75rem; flex-shrink: 0; }
  .lesson-title { flex: 1; font-size: 0.9rem; line-height: 1.3; }
  .lesson-duration { font-size: 0.75rem; color: var(--color-text-muted); }

  .learn-content { flex: 1; margin-left: 320px; display: flex; flex-direction: column; transition: margin-left 0.3s ease; }
  .learn-sidebar.collapsed + .learn-content { margin-left: 60px; }
  .content-header { padding: 1rem 2rem; border-bottom: 1px solid var(--color-border); background: var(--color-surface); display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
  .content-header h1 { font-size: 1.25rem; margin: 0; flex: 1; min-width: 0; }
  .content-nav { display: flex; gap: 0.5rem; flex-wrap: wrap; }
  .nav-btn { padding: 0.5rem 1rem; border: 1px solid var(--color-border); background: var(--color-surface); border-radius: var(--border-radius-sm); cursor: pointer; color: var(--color-text); transition: all 0.2s; min-height: 44px; display: flex; align-items: center; justify-content: center; }
  .nav-btn:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
  .nav-btn:disabled { opacity: 0.5; cursor: not-allowed; }

  .video-container { background: #000; aspect-ratio: 16/9; max-height: 70vh; display: flex; align-items: center; justify-content: center; }
  .video-container video, .video-container iframe { width: 100%; height: 100%; }
  .video-placeholder { color: var(--color-text-muted); text-align: center; padding: 2rem; }

  .lesson-content { padding: 2rem; flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; }
  .lesson-content h2 { margin-bottom: 1rem; }
  .lesson-content p { line-height: 1.7; color: var(--color-text-muted); margin-bottom: 1rem; }

  .complete-btn { padding: 0.75rem 1.5rem; background: var(--gradient-primary); border: none; border-radius: var(--border-radius-sm); color: white; font-weight: 600; cursor: pointer; transition: all 0.2s; min-height: 44px; }
  .complete-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(99, 102, 241, 0.3); }
  .complete-btn.completed { background: var(--color-success); }

  .loading-state { display: flex; align-items: center; justify-content: center; height: 100%; color: var(--color-text-muted); }
  .error-state { text-align: center; padding: 4rem 2rem; }
  .error-state .icon { font-size: 4rem; margin-bottom: 1rem; }

  /* Mobile sidebar overlay */
  .sidebar-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 99; opacity: 0; transition: opacity 0.3s ease; }
  .sidebar-overlay.active { opacity: 1; }

  /* Mobile toggle button (floating) */
  .mobile-sidebar-toggle { display: none; position: fixed; bottom: 20px; left: 20px; width: 56px; height: 56px; border-radius: 50%; background: var(--gradient-primary); border: none; color: white; font-size: 1.5rem; cursor: pointer; z-index: 101; box-shadow: 0 4px 20px rgba(99, 102, 241, 0.4); }
  .mobile-sidebar-toggle:active { transform: scale(0.95); }

  /* Tablet/Mobile responsive */
  @media (max-width: 1024px) {
    .learn-sidebar { transform: translateX(-100%); width: 300px; top: 0; }
    .learn-sidebar.open { transform: translateX(0); }
    .learn-content { margin-left: 0; }
    .sidebar-overlay { display: block; }
    .mobile-sidebar-toggle { display: flex; align-items: center; justify-content: center; }
    .content-header { padding: 1rem; }
    .lesson-content { padding: 1.5rem; }
  }

  /* Mobile phones */
  @media (max-width: 480px) {
    .learn-sidebar { width: 100%; max-width: 320px; }
    .content-header { flex-direction: column; align-items: stretch; }
    .content-header h1 { font-size: 1.1rem; text-align: center; margin-bottom: 0.75rem; }
    .content-nav { justify-content: center; }
    .nav-btn { flex: 1; padding: 0.6rem 0.75rem; font-size: 0.85rem; }
    .complete-btn { width: 100%; margin-top: 0.5rem; }
    .video-container { aspect-ratio: 16/10; max-height: 50vh; }
    .lesson-content { padding: 1rem; }
    .lesson-content h2 { font-size: 1.25rem; }
    .mobile-sidebar-toggle { bottom: 16px; left: 16px; width: 50px; height: 50px; font-size: 1.25rem; }
    .lesson-item { padding: 1rem; }
    .sidebar-header { padding: 1rem; }
    .course-progress { padding: 0.875rem 1rem; }
  }

  /* Small phones */
  @media (max-width: 375px) {
    .learn-sidebar { max-width: 280px; }
    .content-header h1 { font-size: 1rem; }
    .nav-btn { padding: 0.5rem; font-size: 0.8rem; }
  }
</style>

<section class="learn-section">
  <!-- Mobile sidebar overlay -->
  <div class="sidebar-overlay" id="sidebarOverlay"></div>

  <!-- Mobile floating toggle button -->
  <button class="mobile-sidebar-toggle" id="mobileSidebarToggle" aria-label="Open course menu">📚</button>

  <aside class="learn-sidebar" id="learnSidebar">
    <div class="sidebar-header">
      <button class="toggle-sidebar" id="toggleSidebar" aria-label="Close sidebar">✕</button>
      <h2 id="courseTitle">Loading...</h2>
    </div>
    <div class="course-progress">
      <div class="progress-bar"><div class="progress-fill" id="progressFill" style="width: 0%"></div></div>
      <div class="progress-text"><span id="progressPercent">0</span>% complete</div>
    </div>
    <div class="lessons-list" id="lessonsList">
      <div class="loading-state">Loading lessons...</div>
    </div>
  </aside>

  <div class="learn-content">
    <div class="content-header">
      <h1 id="lessonTitle">Select a lesson</h1>
      <div class="content-nav">
        <button class="nav-btn" id="prevBtn" disabled>← Prev</button>
        <button class="complete-btn" id="completeBtn">✓ Complete</button>
        <button class="nav-btn" id="nextBtn" disabled>Next →</button>
      </div>
    </div>
    <div class="video-container" id="videoContainer">
      <div class="video-placeholder">
        <div style="font-size: 3rem; margin-bottom: 1rem;">📚</div>
        <p>Select a lesson to start learning</p>
      </div>
    </div>
    <div class="lesson-content" id="lessonContent"></div>
  </div>

  <div class="error-state" id="errorState" style="display: none;">
    <div class="icon">🔒</div>
    <h2>Access Denied</h2>
    <p id="errorMessage">You need to be enrolled in this course to access the content.</p>
    <a href="/my-courses" class="btn btn-primary" style="margin-top: 1rem;">Go to My Courses</a>
  </div>
</section>

<script>
(function() {
  var courseId = '{{courseId}}';
  var API = '/api';
  var currentLessonIndex = 0;
  var lessons = [];
  var progress = {};
  
  function getAuthHeaders() {
    var token = localStorage.getItem('access_token');
    return token ? { 'Authorization': 'Bearer ' + token } : {};
  }
  
  async function loadCourse() {
    try {
      var r = await fetch(API + '/lms/learn/' + courseId, { credentials: 'include', headers: getAuthHeaders() });
      if (!r.ok) {
        if (r.status === 401) {
          window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
          return;
        }
        throw new Error('Not enrolled');
      }
      var data = await r.json();
      renderCourse(data.course, data.progress);
    } catch (e) {
      document.querySelector('.learn-sidebar').style.display = 'none';
      document.querySelector('.learn-content').style.display = 'none';
      document.getElementById('errorState').style.display = 'block';
    }
  }
  
  function renderCourse(course, prog) {
    progress = prog || {};
    document.getElementById('courseTitle').textContent = course.title;
    updateProgress();

    // Get lessons directly from course (no modules structure)
    lessons = [];
    var html = '';
    var courseLessons = course.lessons || [];

    if (courseLessons.length > 0) {
      html += '<div class="module-item"><div class="module-header">Course Content</div>';
      courseLessons.forEach(function(lesson, li) {
        var isCompleted = progress.completedLessons?.includes(lesson.id);
        lessons.push({ ...lesson, lessonIndex: li, completed: isCompleted });
        var duration = lesson.estimatedMinutes ? lesson.estimatedMinutes + ' min' : '';
        html += '<div class="lesson-item' + (isCompleted ? ' completed' : '') + '" data-lesson-id="' + lesson.id + '" data-index="' + li + '">' +
          '<span class="lesson-status">' + (isCompleted ? '✓' : (li + 1)) + '</span>' +
          '<span class="lesson-title">' + lesson.title + '</span>' +
          '<span class="lesson-duration">' + duration + '</span>' +
        '</div>';
      });
      html += '</div>';
    }
    document.getElementById('lessonsList').innerHTML = html || '<div class="loading-state">No lessons available</div>';
    
    // Add click handlers
    document.querySelectorAll('.lesson-item').forEach(function(item) {
      item.addEventListener('click', function() { loadLesson(parseInt(this.dataset.index)); });
    });
    
    // Load first incomplete lesson or first lesson
    var firstIncomplete = lessons.findIndex(function(l) { return !l.completed; });
    loadLesson(firstIncomplete >= 0 ? firstIncomplete : 0);
  }
  
  function updateProgress() {
    var percent = progress.percent || 0;
    document.getElementById('progressFill').style.width = percent + '%';
    document.getElementById('progressPercent').textContent = Math.round(percent);
  }
  
  async function loadLesson(index) {
    if (index < 0 || index >= lessons.length) return;
    currentLessonIndex = index;
    var lesson = lessons[index];
    
    document.querySelectorAll('.lesson-item').forEach(function(item, i) {
      item.classList.toggle('active', i === index);
    });
    
    document.getElementById('lessonTitle').textContent = lesson.title;
    document.getElementById('prevBtn').disabled = index === 0;
    document.getElementById('nextBtn').disabled = index === lessons.length - 1;
    
    var completeBtn = document.getElementById('completeBtn');
    completeBtn.textContent = lesson.completed ? '✓ Completed' : 'Mark Complete';
    completeBtn.classList.toggle('completed', lesson.completed);
    
    // Load lesson content
    try {
      var r = await fetch(API + '/lms/learn/' + courseId + '/lessons/' + lesson.id, { credentials: 'include', headers: getAuthHeaders() });
      if (!r.ok) throw new Error('Failed to load lesson');
      var data = await r.json();
      renderLessonContent(data);
    } catch (e) {
      document.getElementById('videoContainer').innerHTML = '<div class="video-placeholder"><div style="font-size: 4rem;">❌</div><p>Failed to load lesson</p></div>';
    }
  }
  
  function renderLessonContent(lesson) {
    var videoHtml = '';
    if (lesson.videoUrl) {
      if (lesson.videoUrl.includes('youtube') || lesson.videoUrl.includes('youtu.be')) {
        var videoId = lesson.videoUrl.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&]+)/)?.[1];
        videoHtml = '<iframe src="https://www.youtube.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>';
      } else if (lesson.videoUrl.includes('vimeo')) {
        var vimeoId = lesson.videoUrl.match(/vimeo\.com\/(\d+)/)?.[1];
        videoHtml = '<iframe src="https://player.vimeo.com/video/' + vimeoId + '" frameborder="0" allowfullscreen></iframe>';
      } else {
        videoHtml = '<video controls src="' + lesson.videoUrl + '"></video>';
      }
    } else {
      videoHtml = '<div class="video-placeholder"><div style="font-size: 4rem;">📖</div><p>This is a text-based lesson</p></div>';
    }
    document.getElementById('videoContainer').innerHTML = videoHtml;
    document.getElementById('lessonContent').innerHTML = lesson.content || '';
  }
  
  async function markComplete() {
    var lesson = lessons[currentLessonIndex];
    if (lesson.completed) return;
    
    try {
      var r = await fetch(API + '/lms/learn/' + courseId + '/lessons/' + lesson.id + '/complete', {
        method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }
      });
      if (r.ok) {
        lesson.completed = true;
        progress.completedLessons = progress.completedLessons || [];
        progress.completedLessons.push(lesson.id);
        progress.percent = (progress.completedLessons.length / lessons.length) * 100;
        updateProgress();
        document.querySelector('.lesson-item[data-index="' + currentLessonIndex + '"]').classList.add('completed');
        document.querySelector('.lesson-item[data-index="' + currentLessonIndex + '"] .lesson-status').textContent = '✓';
        var btn = document.getElementById('completeBtn');
        btn.textContent = '✓ Completed';
        btn.classList.add('completed');
        if (currentLessonIndex < lessons.length - 1) loadLesson(currentLessonIndex + 1);
      }
    } catch (e) { console.error('Failed to mark complete:', e); }
  }
  
  document.getElementById('prevBtn').addEventListener('click', function() { loadLesson(currentLessonIndex - 1); });
  document.getElementById('nextBtn').addEventListener('click', function() { loadLesson(currentLessonIndex + 1); });
  document.getElementById('completeBtn').addEventListener('click', markComplete);

  // Mobile sidebar functionality
  var sidebar = document.getElementById('learnSidebar');
  var overlay = document.getElementById('sidebarOverlay');
  var mobileToggle = document.getElementById('mobileSidebarToggle');
  var closeBtn = document.getElementById('toggleSidebar');

  function openSidebar() {
    sidebar.classList.add('open');
    overlay.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  function closeSidebar() {
    sidebar.classList.remove('open');
    overlay.classList.remove('active');
    document.body.style.overflow = '';
  }

  // Check if mobile view
  function isMobile() {
    return window.innerWidth <= 1024;
  }

  mobileToggle.addEventListener('click', openSidebar);
  closeBtn.addEventListener('click', function() {
    if (isMobile()) {
      closeSidebar();
    } else {
      sidebar.classList.toggle('collapsed');
    }
  });
  overlay.addEventListener('click', closeSidebar);

  // Close sidebar when lesson is selected on mobile
  document.getElementById('lessonsList').addEventListener('click', function(e) {
    if (e.target.closest('.lesson-item') && isMobile()) {
      closeSidebar();
    }
  });

  // Handle resize
  window.addEventListener('resize', function() {
    if (!isMobile()) {
      closeSidebar();
    }
  });

  loadCourse();
})();
</script>
{{> footer}}

