import React, { useEffect, useRef, useState } from 'react'; import { Link, Navigate, useNavigate, useParams } from 'react-router-dom'; import { CaretRightIcon, CheckIcon, CircleNotchIcon, PlayIcon } from '@phosphor-icons/react'; import { Comment, Course, Lesson } from '../types'; import { getComments, getLessonNote, incrementViews, saveComment, saveLessonNote, saveLessonProgress } from '../services/db'; import { useCourse, useLessonProgress } from '../hooks/useCourse'; import { useAuth } from '../context/AuthContext'; import { useToast } from '../context/ToastContext'; import { LessonVideo } from '../components/course/LessonVideo'; import { MaterialRow, useMaterialAction } from '../components/course/Materials'; import { Avatar } from '../components/ui/Avatar'; import { lessonDuration } from '../lib/format'; import { paths } from '../lib/routes'; import { signUpState } from './CoursePage'; import { useIsMobile } from '../hooks/useMediaQuery'; import { attachmentIcon, MaterialButton } from '../components/course/Materials'; export type LessonTab = 'aulas' | 'materiais' | 'discussao'; /** Everything the lesson screen does, shared by the desktop and mobile layouts. */ export const useLessonScreen = (course: Course | undefined, lesson: Lesson | undefined) => { const { user } = useAuth(); const { showToast } = useToast(); const navigate = useNavigate(); const progress = useLessonProgress(course); const [comments, setComments] = useState([]); const [draft, setDraft] = useState(''); const [posting, setPosting] = useState(false); const [note, setNote] = useState(''); const [noteSaving, setNoteSaving] = useState(false); const advanceTimer = useRef(); const trackedView = useRef(''); useEffect(() => { if (!user || !lesson) { setNote(''); return; } let cancelled = false; getLessonNote(lesson.id) .then((data) => { if (!cancelled) setNote(data.body); }) .catch(() => { if (!cancelled) setNote(''); }); return () => { cancelled = true; }; }, [lesson?.id, user?.id]); const saveNote = async () => { if (!lesson) return; setNoteSaving(true); try { const saved = await saveLessonNote(lesson.id, note); setNote(saved.body); showToast('Anotação salva.', 'success'); } catch { showToast('Não foi possível salvar a anotação.', 'error'); } finally { setNoteSaving(false); } }; useEffect(() => { if (!user || !course || !lesson) return; const key = `${course.id}:${lesson.id}`; if (trackedView.current === key) return; trackedView.current = key; void incrementViews(course.id); }, [course?.id, lesson?.id, user?.id]); useEffect(() => { if (!course || !user) { setComments([]); return; } getComments(course.id).then(setComments).catch(() => setComments([])); }, [course?.id, user?.id]); useEffect(() => () => window.clearTimeout(advanceTimer.current), []); const index = course && lesson ? course.lessons.indexOf(lesson) : -1; const nextLesson = course && index >= 0 ? course.lessons[index + 1] : undefined; const onTime = (seconds: number, duration?: number) => { if (!user || !lesson) return; const lessonId = lesson.id; const watchedSeconds = Math.floor(seconds); if (watchedSeconds > 0 && watchedSeconds - (progress.lastSaved.current[lessonId] || 0) >= 30) { progress.lastSaved.current[lessonId] = watchedSeconds; progress.setWatched((current) => ({ ...current, [lessonId]: watchedSeconds })); saveLessonProgress(lessonId, watchedSeconds).catch(() => undefined); } // Automatically mark as complete when reaching 95%+. if (duration && duration > 0 && Math.round((seconds / duration) * 100) >= 95) progress.markCompleted(lessonId, Math.round(seconds)); }; const onEnded = (seconds: number, autoAdvance: boolean) => { if (!lesson) return; progress.markCompleted(lesson.id, seconds); if (autoAdvance && nextLesson && course && user) { advanceTimer.current = window.setTimeout(() => navigate(paths.lesson(course.id, nextLesson.id)), 1000); } }; const postComment = async (event?: React.FormEvent) => { event?.preventDefault(); if (!draft.trim() || !course) return; setPosting(true); try { const saved = await saveComment({ courseId: course.id, lessonId: lesson?.id, text: draft }); setComments((current) => [saved, ...current]); setDraft(''); } catch { // The server remains the source of truth; keep the text for a retry. showToast('Não foi possível publicar agora. Tente de novo.', 'error'); } finally { setPosting(false); } }; const materials = lesson?.attachments || []; const courseLevel = course?.attachments || []; return { progress, comments, draft, setDraft, posting, postComment, onTime, onEnded, index, nextLesson, materials, courseLevel, note, setNote, noteSaving, saveNote }; }; export const CommentItem: React.FC<{ comment: Comment; lessonNumber?: number }> = ({ comment, lessonNumber }) => (
{comment.user}{[lessonNumber ? `Aula ${lessonNumber}` : '', comment.date].filter(Boolean).join(' · ')}

{comment.text}

{comment.reply && (
RespostaProfessor{comment.replyDate ? ` ${comment.replyDate}` : ''}

{comment.reply}

)}
); export const LessonPage: React.FC = () => { const { courseId, lessonId } = useParams<{ courseId: string; lessonId: string }>(); const { user, isLoading: authLoading } = useAuth(); const { course, isLoading, missing } = useCourse(courseId); const lesson = course?.lessons.find((item) => item.id === lessonId); const screen = useLessonScreen(course, lesson); const action = useMaterialAction(); const [tab, setTab] = useState('aulas'); const isMobile = useIsMobile(); if (authLoading || isLoading) return
; if (!user) return ; if (missing || !course) return ; if (!lesson) return ; const { progress, comments, index, nextLesson } = screen; const lessonNumber = (comment: Comment) => (comment.lessonId ? course.lessons.findIndex((item) => item.id === comment.lessonId) + 1 : 0); const done = progress.completed.has(lesson.id); const pct = course.lessons.length ? Math.round((progress.doneCount / course.lessons.length) * 100) : 0; if (isMobile) return

{lesson.title}

Aula {index + 1} de {course.lessons.length}{course.instructor ? ` · ${course.instructor}` : ''}

{([['aulas', 'Aulas'], ['materiais', 'Materiais'], ['discussao', 'Discussão']] as const).map(([key, label]) => )}
{tab === 'aulas' &&
{course.lessons.map((item, itemIndex) => {progress.completed.has(item.id) ? : item.id === lesson.id ? : itemIndex + 1}{item.title}{lessonDuration(item)})}
} {tab === 'materiais' &&
{[...screen.materials, ...screen.courseLevel].map((attachment) =>
{attachmentIcon(attachment.type)}{attachment.name}{attachment.size}
)}
{screen.materials.length + screen.courseLevel.length === 0 &&

Esta aula não tem materiais.

}
} {tab === 'discussao' && <>