// VFM Student Dashboard + Lesson Viewer
// Requires vfm-api.js + auth.jsx loaded before this file.

// ---- Enroll / Checkout button ----
function EnrollButton({ courseId, price, onAuthRequired }) {
  const { user }                    = window.useAuth();
  const [enrolled, setEnrolled]     = React.useState(null);
  const [busy, setBusy]             = React.useState(false);
  const [error, setError]           = React.useState('');

  React.useEffect(() => {
    if (!user) { setEnrolled(false); return; }
    window.vfmEnrollments.isEnrolled(courseId).then(setEnrolled);
  }, [user, courseId]);

  async function handleClick() {
    if (!user) { onAuthRequired(); return; }
    setBusy(true); setError('');
    try {
      const { url } = await window.vfmEnrollments.startCheckout(courseId);
      window.location.href = url;
    } catch (err) {
      setError(err.message);
      setBusy(false);
    }
  }

  if (enrolled === null) return <div className="enroll-btn enroll-btn--loading">Checking…</div>;

  if (enrolled) {
    return (
      <div className="enroll-enrolled">
        <span className="enroll-enrolled-badge">✓ Enrolled</span>
        <p style={{ fontSize: '0.85rem', color: 'rgba(20,20,20,0.55)', marginTop: '0.35rem' }}>
          Access this course from My Courses.
        </p>
      </div>
    );
  }

  return (
    <div>
      <button className="enroll-btn" onClick={handleClick} disabled={busy}>
        {busy ? 'Redirecting to checkout…' : `Enroll — CA$${Number(price).toLocaleString('en-CA')}`}
      </button>
      {error && <p className="enroll-error">{error}</p>}
      <p className="enroll-guarantee">30-day money-back guarantee · Lifetime access</p>
    </div>
  );
}

// ---- Star rating display ----
function Stars({ rating }) {
  return (
    <span className="stars" aria-label={`${rating} stars`}>
      {[1,2,3,4,5].map(n => (
        <span key={n} style={{ color: n <= Math.round(rating) ? '#FFFFFF' : 'rgba(0,0,0,0.18)' }}>★</span>
      ))}
    </span>
  );
}

// ---- Dashboard: My Courses ----
function DashboardPage({ onPageChange }) {
  const { user }                      = window.useAuth();
  const [enrollments, setEnrollments] = React.useState(null);
  const [progress, setProgress]       = React.useState({});

  React.useEffect(() => {
    if (!user) return;
    window.vfmEnrollments.mine().then(({ data }) => setEnrollments(data || []));
  }, [user]);

  if (!user) return (
    <div className="dash-empty">
      <div style={{ fontSize: '3rem', marginBottom: '1rem' }}>🎬</div>
      <h2>Sign in to see your courses</h2>
    </div>
  );

  if (enrollments === null) return <div className="dash-loading">Loading your courses…</div>;

  if (!enrollments.length) return (
    <div className="dash-empty">
      <div style={{ fontSize: '3.5rem', marginBottom: '1rem' }}>📽️</div>
      <h2 style={{ marginBottom: '0.5rem' }}>No courses yet</h2>
      <p style={{ marginBottom: '1.5rem', color: 'var(--text-secondary)' }}>Browse our filmmaking courses and start your journey.</p>
      <button className="enroll-btn" style={{ display: 'inline-block', width: 'auto', padding: '0.75rem 2rem' }}
        onClick={() => onPageChange('courses')}>
        Browse Courses
      </button>
    </div>
  );

  const SLUG_TO_PAGE = {
    'beginner-filmmaking':      'courses-beginner',
    'intermediate-filmmaking':  'courses-intermediate',
    'professional-filmmaking':  'courses-professional',
  };

  return (
    <div className="section" style={{ paddingTop: '9rem' }}>
      <div className="container">
        <h1 style={{ marginBottom: '0.5rem' }}>My Courses</h1>
        <p style={{ color: 'var(--text-secondary)', marginBottom: '3rem' }}>
          {enrollments.length} course{enrollments.length !== 1 ? 's' : ''} · Lifetime access
        </p>

        <div className="dash-grid">
          {enrollments.map(({ courses: course, enrolled_at }) => (
            <div key={course.id} className="dash-card">
              <div className="dash-card-thumb">
                <span style={{ fontSize: '3.5rem' }}>
                  {course.level === 'beginner' ? '🎬' : course.level === 'intermediate' ? '🎥' : '🏆'}
                </span>
                <span className="dash-level-pill">{course.level}</span>
              </div>
              <div className="dash-card-body">
                <h3 className="dash-card-title">{course.title}</h3>
                <p className="dash-card-sub">{course.subtitle}</p>
                <p className="dash-card-date">
                  Enrolled {new Date(enrolled_at).toLocaleDateString('en-CA', { year: 'numeric', month: 'short', day: 'numeric' })}
                </p>
                <button
                  className="dash-card-btn"
                  onClick={() => onPageChange(SLUG_TO_PAGE[course.slug] || 'courses')}
                >
                  Continue Learning →
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---- Lesson Viewer (sidebar + YouTube) ----
function LessonViewerPage({ courseSlug, lessonId: initialLessonId, onPageChange }) {
  const { user }                              = window.useAuth();
  const [course, setCourse]                   = React.useState(null);
  const [activeLessonId, setActiveLessonId]   = React.useState(initialLessonId || null);
  const [progressMap, setProgressMap]         = React.useState({});
  const [enrolled, setEnrolled]               = React.useState(null);
  const [sidebarOpen, setSidebarOpen]         = React.useState(true);

  React.useEffect(() => {
    window.vfmCourses.bySlug(courseSlug).then(({ data }) => {
      if (!data) return;
      setCourse(data);
      if (!activeLessonId) {
        const firstLesson = data.modules?.[0]?.lessons?.[0];
        if (firstLesson) setActiveLessonId(firstLesson.id);
      }
    });
  }, [courseSlug]);

  React.useEffect(() => {
    if (!user || !course) return;
    window.vfmEnrollments.isEnrolled(course.id).then(setEnrolled);
  }, [user, course]);

  React.useEffect(() => {
    if (!course) return;
    const allIds = course.modules.flatMap(m => m.lessons.map(l => l.id));
    if (!allIds.length) return;
    window.vfmProgress.forLessons(allIds).then(({ data }) => {
      const map = {};
      (data || []).forEach(p => { map[p.lesson_id] = p; });
      setProgressMap(map);
    });
  }, [course]);

  const activeLesson = React.useMemo(() => {
    if (!course || !activeLessonId) return null;
    for (const mod of course.modules) {
      for (const lesson of mod.lessons) {
        if (lesson.id === activeLessonId) return lesson;
      }
    }
    return null;
  }, [course, activeLessonId]);

  async function markComplete() {
    if (!user || !activeLessonId) return;
    await window.vfmProgress.markComplete(activeLessonId);
    setProgressMap(prev => ({ ...prev, [activeLessonId]: { ...prev[activeLessonId], completed: true } }));
  }

  const canWatch = (lesson) =>
    lesson.is_preview || enrolled || !user;

  if (!course) return <div className="lesson-loading">Loading course…</div>;

  const totalLessons    = course.modules.flatMap(m => m.lessons).length;
  const completedCount  = Object.values(progressMap).filter(p => p.completed).length;
  const progressPercent = totalLessons ? Math.round((completedCount / totalLessons) * 100) : 0;

  return (
    <div className="lesson-shell">
      {/* Top bar */}
      <div className="lesson-topbar">
        <button className="lesson-back-btn" onClick={() => onPageChange('dashboard')}>
          ← My Courses
        </button>
        <h2 className="lesson-course-title">{course.title}</h2>
        <div className="lesson-progress-pill">
          <div className="lesson-progress-bar">
            <div className="lesson-progress-fill" style={{ width: `${progressPercent}%` }} />
          </div>
          <span>{progressPercent}%</span>
        </div>
        <button className="lesson-sidebar-toggle" onClick={() => setSidebarOpen(o => !o)} aria-label="Toggle sidebar">
          ☰
        </button>
      </div>

      <div className="lesson-body">
        {/* Video area */}
        <div className="lesson-main">
          {activeLesson ? (
            <>
              <div className="lesson-video-wrap">
                {activeLesson.youtube_video_id ? (
                  <iframe
                    className="lesson-video"
                    src={`https://www.youtube.com/embed/${activeLesson.youtube_video_id}?rel=0&modestbranding=1`}
                    title={activeLesson.title}
                    frameBorder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                  />
                ) : (
                  <div className="lesson-video-placeholder">
                    <span style={{ fontSize: '3rem' }}>🎬</span>
                    <p>Video coming soon</p>
                  </div>
                )}
              </div>
              <div className="lesson-info">
                <div className="lesson-info-top">
                  <h1 className="lesson-title">{activeLesson.title}</h1>
                  {progressMap[activeLessonId]?.completed ? (
                    <span className="lesson-done-badge">✓ Completed</span>
                  ) : (
                    <button className="lesson-complete-btn" onClick={markComplete} disabled={!user}>
                      Mark Complete
                    </button>
                  )}
                </div>
                {activeLesson.description && (
                  <p className="lesson-desc">{activeLesson.description}</p>
                )}
              </div>
            </>
          ) : (
            <div className="lesson-video-placeholder">
              <span style={{ fontSize: '3rem' }}>👈</span>
              <p>Select a lesson from the sidebar</p>
            </div>
          )}
        </div>

        {/* Sidebar */}
        {sidebarOpen && (
          <aside className="lesson-sidebar">
            <div className="lesson-sidebar-head">Course Content</div>
            {course.modules.map((mod) => (
              <div key={mod.id} className="lesson-module">
                <div className="lesson-module-title">{mod.title}</div>
                <ul className="lesson-list">
                  {mod.lessons.map((lesson) => {
                    const isActive    = lesson.id === activeLessonId;
                    const isCompleted = progressMap[lesson.id]?.completed;
                    const canView     = lesson.is_preview || enrolled;
                    return (
                      <li
                        key={lesson.id}
                        className={`lesson-item${isActive ? ' lesson-item--active' : ''}${isCompleted ? ' lesson-item--done' : ''}${!canView ? ' lesson-item--locked' : ''}`}
                        onClick={() => canView && setActiveLessonId(lesson.id)}
                        role="button"
                        tabIndex={canView ? 0 : -1}
                        onKeyDown={e => e.key === 'Enter' && canView && setActiveLessonId(lesson.id)}
                        aria-label={`${lesson.title}${!canView ? ' — enroll to unlock' : ''}`}
                      >
                        <span className="lesson-item-icon">
                          {isCompleted ? '✓' : !canView ? '🔒' : '▶'}
                        </span>
                        <span className="lesson-item-title">{lesson.title}</span>
                        {lesson.is_preview && !enrolled && (
                          <span className="lesson-preview-badge">Preview</span>
                        )}
                        {lesson.duration_seconds > 0 && (
                          <span className="lesson-dur">
                            {Math.floor(lesson.duration_seconds / 60)}m
                          </span>
                        )}
                      </li>
                    );
                  })}
                </ul>
              </div>
            ))}
          </aside>
        )}
      </div>
    </div>
  );
}

window.EnrollButton      = EnrollButton;
window.Stars             = Stars;
window.DashboardPage     = DashboardPage;
window.LessonViewerPage  = LessonViewerPage;
