From 21085e887d66046c9935bc226eb7beb4cac732da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Thu, 5 Nov 2026 15:06:53 -0300 Subject: [PATCH] feat: finalize academy redesign and production readiness Align admin, community, search, library, learning and course management with the mockup. Add saved courses, download history, public community feed, instructor directory, backend search, course views, admin content tools and community moderation. Harden API and Nginx for production. --- App.tsx | 162 +- BACKEND.md | 10 +- components/CourseCard.tsx | 7 +- components/CourseGrid.tsx | 243 --- components/CoursePlayerModal.tsx | 682 ------- components/CourseRow.tsx | 176 -- components/Hero.tsx | 24 - components/LearningPathRow.tsx | 38 - components/LoginModal.tsx | 119 -- components/Logo.tsx | 92 +- components/MaterialCard.tsx | 24 +- components/MaterialsHubModal.tsx | 218 --- components/Navbar.tsx | 143 -- components/SearchModal.tsx | 175 -- components/UserManagementPanel.tsx | 15 +- components/admin/BannerManager.tsx | 115 ++ components/admin/CategoryManager.tsx | 66 + components/admin/TrailManager.tsx | 143 ++ components/catalog/Artwork.tsx | 140 ++ components/catalog/Hero.tsx | 173 ++ components/catalog/Shelf.tsx | 55 + components/course/LessonVideo.tsx | 129 ++ components/course/Materials.tsx | 86 + components/shell/AppShell.tsx | 26 + components/shell/MobileNavigation.tsx | 47 + components/shell/Sidebar.tsx | 197 ++ components/ui/Avatar.tsx | 15 + components/ui/ConfirmDialog.tsx | 33 + components/ui/MockupIcons.tsx | 58 + components/ui/Select.tsx | 77 + components/ui/Switch.tsx | 13 + context/CatalogContext.tsx | 131 ++ context/ThemeContext.tsx | 39 + context/ToastContext.tsx | 113 +- design/DESIGN.md | 135 ++ design/compor-academy-logo-dark.svg | 1 + design/compor-academy-logo-light.svg | 1 + ...ompor-academy-mobile-todas-as-paginas.html | 33 + design/compor-academy-mobile.png | Bin 0 -> 671779 bytes .../compor-academy-prototipo-ui-skills.html | 1632 +++++++++++++++++ design/compor-academy-prototipo.html | 1028 +++++++++++ design/prototype-reference.html | 1630 ++++++++++++++++ docker-compose.yml | 2 +- docker/nginx.conf | 15 + hooks/useCourse.ts | 81 + hooks/useMediaQuery.ts | 18 + hooks/useSavedCourses.ts | 63 + index.css | 99 - index.html | 87 +- index.tsx | 5 + lib/demoCatalog.ts | 139 ++ lib/downloads.ts | 14 + lib/format.ts | 50 + lib/navigation.ts | 19 + lib/routes.ts | 24 + lib/storage.ts | 17 + package-lock.json | 1009 +++++++++- package.json | 7 +- pages/AccessTokenPage.tsx | 2 +- pages/AuthPage.tsx | 82 + pages/CommunityPage.tsx | 61 + pages/CoursePage.tsx | 161 ++ pages/DownloadsPage.tsx | 51 + pages/ExplorePage.tsx | 48 + pages/InstructorProfile.tsx | 48 +- pages/LessonPage.tsx | 215 +++ pages/ManageCourses.tsx | 1571 ++++------------ pages/MaterialsPage.tsx | 113 +- pages/MyLearning.tsx | 80 +- pages/ProfessorsPage.tsx | 13 + pages/ProfilePage.tsx | 129 +- pages/SearchPage.tsx | 74 + pages/SuperAdmin.tsx | 459 ++++- pages/TrailDetail.tsx | 40 +- pages/TrailPage.tsx | 69 +- pages/TrailsPage.tsx | 11 + pages/YouPage.tsx | 29 + postcss.config.cjs | 1 + public/compor-academy-logo-dark.svg | 1 + public/compor-academy-logo-light.svg | 1 + public/favicon.svg | 13 +- .../016_views_saved_courses_downloads.sql | 24 + server/src/app.ts | 8 +- server/src/config.ts | 2 +- server/src/routes/admin.ts | 20 +- server/src/routes/courses.ts | 80 +- server/src/routes/downloads.ts | 52 + server/src/routes/learning.ts | 23 + server/src/routes/manage-courses.ts | 21 +- server/src/routes/profiles.ts | 21 + server/src/routes/saved-courses.ts | 40 + server/src/routes/search.ts | 76 + services/api.ts | 41 +- services/db.ts | 56 +- styles/app.css | 900 +++++++++ styles/legacy.css | 2 + styles/tokens.css | 130 ++ tailwind.config.cjs | 21 + types.ts | 2 + 99 files changed, 10749 insertions(+), 3935 deletions(-) delete mode 100644 components/CourseGrid.tsx delete mode 100644 components/CoursePlayerModal.tsx delete mode 100644 components/CourseRow.tsx delete mode 100644 components/Hero.tsx delete mode 100644 components/LearningPathRow.tsx delete mode 100644 components/LoginModal.tsx delete mode 100644 components/MaterialsHubModal.tsx delete mode 100644 components/Navbar.tsx delete mode 100644 components/SearchModal.tsx create mode 100644 components/admin/BannerManager.tsx create mode 100644 components/admin/CategoryManager.tsx create mode 100644 components/admin/TrailManager.tsx create mode 100644 components/catalog/Artwork.tsx create mode 100644 components/catalog/Hero.tsx create mode 100644 components/catalog/Shelf.tsx create mode 100644 components/course/LessonVideo.tsx create mode 100644 components/course/Materials.tsx create mode 100644 components/shell/AppShell.tsx create mode 100644 components/shell/MobileNavigation.tsx create mode 100644 components/shell/Sidebar.tsx create mode 100644 components/ui/Avatar.tsx create mode 100644 components/ui/ConfirmDialog.tsx create mode 100644 components/ui/MockupIcons.tsx create mode 100644 components/ui/Select.tsx create mode 100644 components/ui/Switch.tsx create mode 100644 context/CatalogContext.tsx create mode 100644 context/ThemeContext.tsx create mode 100644 design/DESIGN.md create mode 100644 design/compor-academy-logo-dark.svg create mode 100644 design/compor-academy-logo-light.svg create mode 100644 design/compor-academy-mobile-todas-as-paginas.html create mode 100644 design/compor-academy-mobile.png create mode 100644 design/compor-academy-prototipo-ui-skills.html create mode 100644 design/compor-academy-prototipo.html create mode 100644 design/prototype-reference.html create mode 100644 hooks/useCourse.ts create mode 100644 hooks/useMediaQuery.ts create mode 100644 hooks/useSavedCourses.ts delete mode 100644 index.css create mode 100644 lib/demoCatalog.ts create mode 100644 lib/downloads.ts create mode 100644 lib/format.ts create mode 100644 lib/navigation.ts create mode 100644 lib/routes.ts create mode 100644 lib/storage.ts create mode 100644 pages/AuthPage.tsx create mode 100644 pages/CommunityPage.tsx create mode 100644 pages/CoursePage.tsx create mode 100644 pages/DownloadsPage.tsx create mode 100644 pages/ExplorePage.tsx create mode 100644 pages/LessonPage.tsx create mode 100644 pages/ProfessorsPage.tsx create mode 100644 pages/SearchPage.tsx create mode 100644 pages/TrailsPage.tsx create mode 100644 pages/YouPage.tsx create mode 100644 postcss.config.cjs create mode 100644 public/compor-academy-logo-dark.svg create mode 100644 public/compor-academy-logo-light.svg create mode 100644 server/migrations/016_views_saved_courses_downloads.sql create mode 100644 server/src/routes/downloads.ts create mode 100644 server/src/routes/saved-courses.ts create mode 100644 server/src/routes/search.ts create mode 100644 styles/app.css create mode 100644 styles/legacy.css create mode 100644 styles/tokens.css create mode 100644 tailwind.config.cjs diff --git a/App.tsx b/App.tsx index 62bbe73..aeebc41 100644 --- a/App.tsx +++ b/App.tsx @@ -1,13 +1,12 @@ -import React, { useState } from 'react'; -import { HashRouter as Router, Routes, Route, Navigate } from 'react-router-dom'; -import { Navbar } from './components/Navbar'; -import { Hero } from './components/Hero'; -import { CourseGrid } from './components/CourseGrid'; +import React from 'react'; +import { BrowserRouter as Router, Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom'; import { ManageCourses } from './pages/ManageCourses'; import { MaterialsPage } from './pages/MaterialsPage'; -import { CoursePlayerModal } from './components/CoursePlayerModal'; import { AuthProvider, useAuth } from './context/AuthContext'; import { ToastProvider } from './context/ToastContext'; +import { ThemeProvider } from './context/ThemeContext'; +import { CatalogProvider } from './context/CatalogContext'; +import { AppShell } from './components/shell/AppShell'; import { Course, UserRole } from './types'; import { SuperAdmin } from './pages/SuperAdmin'; import { AccessTokenPage } from './pages/AccessTokenPage'; @@ -16,87 +15,63 @@ import { ProfilePage } from './pages/ProfilePage'; import { InstructorProfile } from './pages/InstructorProfile'; import { TrailDetail } from './pages/TrailDetail'; import { TrailPage } from './pages/TrailPage'; +import { AuthPage, homeFor } from './pages/AuthPage'; +import { paths } from './lib/routes'; +import { ExplorePage } from './pages/ExplorePage'; +import { SearchPage } from './pages/SearchPage'; +import { TrailsPage } from './pages/TrailsPage'; +import { ProfessorsPage } from './pages/ProfessorsPage'; +import { CommunityPage } from './pages/CommunityPage'; +import { DownloadsPage } from './pages/DownloadsPage'; +import { YouPage } from './pages/YouPage'; +import { ContinueCourse, CoursePage } from './pages/CoursePage'; +import { LessonPage } from './pages/LessonPage'; + +/** Keeps old /#/... links (invites, password resets, bookmarks) working after moving off HashRouter. */ +const LegacyHashRedirect: React.FC = () => { + const location = useLocation(); + const navigate = useNavigate(); + + React.useEffect(() => { + if (location.hash.startsWith('#/')) navigate(location.hash.slice(1), { replace: true }); + }, [location.hash, navigate]); + + return null; +}; -// Protected Route Component const ProtectedRoute: React.FC<{ children: React.ReactNode; allowedRoles?: UserRole[] }> = ({ children, allowedRoles }) => { const { user, isLoading } = useAuth(); if (isLoading) return null; - - if (!user) { - return ; - } - - if (allowedRoles && !allowedRoles.includes(user.role)) { - return ; - } + if (!user) return ; + if (allowedRoles && !allowedRoles.includes(user.role)) return ; return <>{children}; }; -// Home component -interface HomeProps { - onPlay: (course: Course) => void; -} - -const Home: React.FC = ({ onPlay }) => { - return ( -
- - -
- ); -}; - function AppContent() { - const [selectedCourse, setSelectedCourse] = useState(null); + const navigate = useNavigate(); + const setSelectedCourse = (course: Course) => navigate(paths.course(course.id)); return ( -
- {/* Navbar with Direct Materials Hub Trigger */} - - + - - } - /> - - {/* Full Dedicated Materials & Downloads Page */} - - - - } - /> - - {/* Professor Route - Protected */} - - - - } - /> - - - - - } - /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> +
} /> } /> } /> } /> @@ -104,42 +79,25 @@ function AppContent() { } /> } /> } /> - - {/* Catch all redirect */} } />
- - {/* Global Player Modal */} - setSelectedCourse(null)} - /> - - {/* Footer */} -
-
-
- Compor HUB - | - Portal de Cursos & Central de Downloads -
-
- © {new Date().getFullYear()} Compor HUB. Todos os direitos reservados. -
-
-
-
+ ); } function App() { return ( - - - - - + + + + + + + + + + ); } diff --git a/BACKEND.md b/BACKEND.md index 4c75144..ea3b3c3 100644 --- a/BACKEND.md +++ b/BACKEND.md @@ -14,10 +14,16 @@ The API health endpoint is available at `http://localhost:3001/api/v1/health` an ## Current API -- `GET /api/v1/courses` returns published courses. +- `GET /api/v1/courses` returns published courses and, for authenticated learners, their completion percentage and last activity. - `GET /api/v1/courses/:courseId` returns one published course. +- `POST /api/v1/courses/:courseId/view` records a course view for the “most watched” shelves. - `GET /api/v1/courses/me/learning` returns the authenticated learner's started courses, ordered by their last activity, with completion percentage. - `GET /api/v1/courses/:courseId/progress` and `PUT /api/v1/lessons/:lessonId/progress` persist completion and watch position. +- `GET /api/v1/community/comments` returns the public, paginated community feed. +- `GET/PUT/DELETE /api/v1/saved-courses` keeps the authenticated learner's saved-course list. +- `GET /api/v1/downloads` and `POST /api/v1/downloads/:assetId` keep the authenticated learner's download history. +- `GET /api/v1/profiles/instructors` lists public instructor profiles. +- `GET /api/v1/search?q=&area=` searches courses, paths and public instructors. - `GET /api/v1/admin/audit-log` exposes the last 50 administrative actions to superadmins. ## Accounts and instructor access @@ -34,7 +40,7 @@ To create the first local administrator, set `SUPERADMIN_EMAIL`, `SUPERADMIN_PAS For local demos, `npm run db:seed-demo-content` imports the original frontend catalogue into PostgreSQL. It requires the bootstrap administrator to exist and skips courses already present. -Anonymous visitors can browse course and lesson information, but media and download links are removed from their response. A signed-in account is required to play lessons, download materials, track progress, or participate in discussion. +Anonymous visitors can browse course, path, instructor and community information, but media and download links are removed from their response. A signed-in account is required to play lessons, download materials, track progress, or participate in discussion. ## Provider boundaries diff --git a/components/CourseCard.tsx b/components/CourseCard.tsx index 421151f..1b99979 100644 --- a/components/CourseCard.tsx +++ b/components/CourseCard.tsx @@ -1,5 +1,10 @@ import React from 'react'; -import { PlayCircle, Download, FileText, CheckCircle2 } from 'lucide-react'; +import { + PlayCircleIcon as PlayCircle, + DownloadSimpleIcon as Download, + FileTextIcon as FileText, + CheckCircleIcon as CheckCircle2 +} from '@phosphor-icons/react'; import { Course, SectionVariant } from '../types'; import { CourseCoverImage } from './CourseCoverImage'; import { useNavigate } from 'react-router-dom'; diff --git a/components/CourseGrid.tsx b/components/CourseGrid.tsx deleted file mode 100644 index e4114c5..0000000 --- a/components/CourseGrid.tsx +++ /dev/null @@ -1,243 +0,0 @@ -import React, { useState, useEffect, useRef, useCallback } from 'react'; -import { CourseRow } from './CourseRow'; -import { Section, Course } from '../types'; -import { getCourses, getLearningPaths, PublicLearningPath } from '../services/db'; -import { useAuth } from '../context/AuthContext'; -import { Loader2, ChevronLeft, ChevronRight } from 'lucide-react'; -import { LearningPathRow } from './LearningPathRow'; - -interface CourseGridProps { - onCourseSelect?: (course: Course) => void; - selectedCategoryFilter?: string; -} - -export const CourseGrid: React.FC = ({ - onCourseSelect, - selectedCategoryFilter -}) => { - const [courses, setCourses] = useState([]); - const [paths, setPaths] = useState([]); - const [loading, setLoading] = useState(true); - const [activeCategory, setActiveCategory] = useState('all'); - const { user } = useAuth(); - - // Slider State & Refs for Categories - const categoryScrollRef = useRef(null); - const isMouseDownRef = useRef(false); - const startXRef = useRef(0); - const scrollLeftRef = useRef(0); - const draggedDistanceRef = useRef(0); - const [isDraggingCategory, setIsDraggingCategory] = useState(false); - const [canScrollCatLeft, setCanScrollCatLeft] = useState(false); - const [canScrollCatRight, setCanScrollCatRight] = useState(false); - - const checkCategoryBoundaries = useCallback(() => { - if (!categoryScrollRef.current) return; - const { scrollLeft, scrollWidth, clientWidth } = categoryScrollRef.current; - setCanScrollCatLeft(scrollLeft > 10); - setCanScrollCatRight(scrollLeft + clientWidth < scrollWidth - 10); - }, []); - - useEffect(() => { - const loadData = async () => { - try { - const [loadedCourses, loadedPaths] = await Promise.all([getCourses(), getLearningPaths()]); - setCourses(loadedCourses); - setPaths(loadedPaths); - } finally { - setLoading(false); - } - }; - - loadData(); - }, [user]); - - useEffect(() => { - checkCategoryBoundaries(); - window.addEventListener('resize', checkCategoryBoundaries); - return () => window.removeEventListener('resize', checkCategoryBoundaries); - }, [checkCategoryBoundaries, courses]); - - const handleCategoryScroll = (direction: 'left' | 'right') => { - if (!categoryScrollRef.current) return; - const scrollAmount = 300; - categoryScrollRef.current.scrollBy({ - left: direction === 'left' ? -scrollAmount : scrollAmount, - behavior: 'smooth' - }); - }; - - const handleCatMouseDown = (e: React.MouseEvent) => { - if (!categoryScrollRef.current) return; - isMouseDownRef.current = true; - startXRef.current = e.pageX - categoryScrollRef.current.offsetLeft; - scrollLeftRef.current = categoryScrollRef.current.scrollLeft; - draggedDistanceRef.current = 0; - setIsDraggingCategory(false); - }; - - const handleCatMouseMove = (e: React.MouseEvent) => { - if (!isMouseDownRef.current || !categoryScrollRef.current) return; - e.preventDefault(); - const x = e.pageX - categoryScrollRef.current.offsetLeft; - const walk = (x - startXRef.current) * 1.4; - draggedDistanceRef.current = Math.abs(walk); - - if (draggedDistanceRef.current > 5) { - setIsDraggingCategory(true); - categoryScrollRef.current.scrollLeft = scrollLeftRef.current - walk; - } - }; - - const handleCatMouseUp = () => { - isMouseDownRef.current = false; - setTimeout(() => { - setIsDraggingCategory(false); - draggedDistanceRef.current = 0; - }, 50); - }; - - const handleCategoryClick = (cat: string) => { - if (draggedDistanceRef.current < 8) { - setActiveCategory(cat); - } - }; - - const categories = Array.from(new Set(courses.map((course) => course.category))) - .sort((left, right) => left.localeCompare(right, 'pt-BR')); - - if (loading) { - return ( -
- -
- ); - } - - if (courses.length === 0) { - return ( -
-
-

Cursos em breve

-

Ainda não há cursos publicados. Cadastre o primeiro curso no Painel do Instrutor.

-
-
- ); - } - - // Filter courses if a specific category is active - const filteredCourses = activeCategory === 'all' - ? courses - : courses.filter(c => c.category === activeCategory); - - // Group into curated sections for Netflix/Apple TV style layout - const sections: Section[] = [ - { - title: activeCategory === 'all' ? 'Cursos em Destaque' : activeCategory, - variant: 'landscape', - courses: filteredCourses - }, - { - title: 'Com Materiais & Planilhas para Download', - variant: 'landscape', - courses: courses.filter(c => (c.attachments && c.attachments.length > 0) || c.lessons.some(l => l.attachments && l.attachments.length > 0)) - }, - ]; - - return ( -
- - {/* Category Pills Slider Container */} -
-
- - {/* Scroll Button Left */} - {canScrollCatLeft && ( - - )} - - {/* Left Gradient Fade */} - {canScrollCatLeft && ( -
- )} - - {/* Scrollable Category Track */} -
- - - {categories.map(cat => { - const count = courses.filter(c => c.category === cat).length; - return ( - - ); - })} -
- - {/* Right Gradient Fade */} - {canScrollCatRight && ( -
- )} - - {/* Scroll Button Right */} - {canScrollCatRight && ( - - )} - -
-
- - {/* Sections Rows */} - {sections.map((section, index) => ( - section.courses.length > 0 && ( - - ) - ))} - {activeCategory === 'all' && paths.length > 0 && } -
- ); -}; diff --git a/components/CoursePlayerModal.tsx b/components/CoursePlayerModal.tsx deleted file mode 100644 index 5c668cd..0000000 --- a/components/CoursePlayerModal.tsx +++ /dev/null @@ -1,682 +0,0 @@ -import React, { useState, useEffect, useRef } from 'react'; -import { - X, - Send, - User as UserIcon, - Lightbulb, - Paperclip, - Lock, - Unlock, - ListVideo, - Play, - Download, - Sparkles, - MessageSquare, - CheckCircle2, - Check, - Share2, - FileText -} from 'lucide-react'; -import { Course, Comment, Lesson, Attachment } from '../types'; -import { useAuth } from '../context/AuthContext'; -import { getComments, getLessonProgress, saveComment, saveLessonCompletion, saveLessonProgress, incrementViews } from '../services/db'; -import { LoginModal } from './LoginModal'; -import { MaterialCard } from './MaterialCard'; -import { courseApi, LessonPlayback } from '../services/api'; - -declare global { - interface Window { - playerjs?: { - Player: new (element: HTMLIFrameElement) => { - on: (event: string, listener: (data?: { seconds?: number; duration?: number }) => void) => void; - }; - }; - } -} - -let bunnyPlayerJsPromise: Promise | null = null; - -const loadBunnyPlayerJs = () => { - if (window.playerjs) return Promise.resolve(); - if (bunnyPlayerJsPromise) return bunnyPlayerJsPromise; - bunnyPlayerJsPromise = new Promise((resolve, reject) => { - const script = document.createElement('script'); - script.src = 'https://assets.mediadelivery.net/playerjs/player-0.1.0.min.js'; - script.async = true; - script.onload = () => resolve(); - script.onerror = () => reject(new Error('Bunny player events could not be loaded')); - document.head.appendChild(script); - }); - return bunnyPlayerJsPromise; -}; - -interface CoursePlayerModalProps { - course: Course | null; - onClose: () => void; -} - -export const CoursePlayerModal: React.FC = ({ course, onClose }) => { - const { user } = useAuth(); - const [comments, setComments] = useState([]); - const [newComment, setNewComment] = useState(''); - const [currentLesson, setCurrentLesson] = useState(null); - const [completedLessonIds, setCompletedLessonIds] = useState([]); - const [watchedSecondsByLesson, setWatchedSecondsByLesson] = useState>({}); - const [showLoginPrompt, setShowLoginPrompt] = useState(false); - const [activeTab, setActiveTab] = useState<'playlist' | 'materials' | 'discussion'>('playlist'); - const [copiedLink, setCopiedLink] = useState(false); - const [playback, setPlayback] = useState(null); - const [playbackError, setPlaybackError] = useState(''); - - const videoRef = useRef(null); - const bunnyFrameRef = useRef(null); - const lastProgressSave = useRef>({}); - - // Load course data and this learner's saved state from PostgreSQL. - useEffect(() => { - if (course) { - incrementViews(course.id); - setCompletedLessonIds([]); - setWatchedSecondsByLesson({}); - lastProgressSave.current = {}; - if (user) { - getComments(course.id).then(setComments).catch(() => setComments([])); - getLessonProgress(course.id).then((progress) => { - const completed = progress.filter((item) => item.completedAt).map((item) => item.lessonId); - setCompletedLessonIds(completed); - setWatchedSecondsByLesson(Object.fromEntries(progress.map((item) => [item.lessonId, item.watchedSeconds]))); - lastProgressSave.current = Object.fromEntries(progress.map((item) => [item.lessonId, item.watchedSeconds])); - const nextIncomplete = course.lessons.find((lesson) => !completed.includes(lesson.id)); - if (nextIncomplete) setCurrentLesson(nextIncomplete); - }).catch(() => setCompletedLessonIds([])); - } else { - setComments([]); - } - - // Select first lesson by default - if (course.lessons && course.lessons.length > 0) { - setCurrentLesson(course.lessons[0]); - } - } - }, [course, user]); - - // The API verifies the session before returning a time-limited Bunny embed - // URL. A video provider key is never sent to the browser. - useEffect(() => { - if (!course || !user || !currentLesson) { - setPlayback(null); - setPlaybackError(''); - return; - } - let cancelled = false; - setPlayback(null); - setPlaybackError(''); - courseApi.playback(course.id, currentLesson.id) - .then((response) => { - if (!cancelled) setPlayback(response.data); - }) - .catch((error) => { - if (!cancelled) setPlaybackError(error instanceof Error ? error.message : 'Não foi possível carregar este vídeo.'); - }); - return () => { cancelled = true; }; - }, [course, user, currentLesson]); - - // Persist completed lessons and recalculate progress - const updateCompletedLessons = (newCompleted: string[]) => { - setCompletedLessonIds(newCompleted); - if (course) { - } - }; - - const toggleLessonCompleted = (lessonId: string) => { - if (!user) { - setShowLoginPrompt(true); - return; - } - if (completedLessonIds.includes(lessonId)) { - const updated = completedLessonIds.filter(id => id !== lessonId); - updateCompletedLessons(updated); - saveLessonCompletion(lessonId, false).catch(() => updateCompletedLessons(completedLessonIds)); - } else { - markLessonCompleted(lessonId); - } - }; - - const markLessonCompleted = (lessonId: string, watchedSeconds?: number) => { - if (!user || completedLessonIds.includes(lessonId)) return; - const previous = completedLessonIds; - updateCompletedLessons([...previous, lessonId]); - saveLessonCompletion(lessonId, true, watchedSeconds).catch(() => updateCompletedLessons(previous)); - }; - - // Video finished automatically -> mark lesson as completed - const handleVideoEnded = () => { - if (currentLesson && !completedLessonIds.includes(currentLesson.id)) { - markLessonCompleted(currentLesson.id, Math.round(videoRef.current?.duration || 0)); - } - - // Auto-advance to next lesson if available - if (course?.lessons && currentLesson) { - const currentIndex = course.lessons.findIndex(l => l.id === currentLesson.id); - if (currentIndex >= 0 && currentIndex < course.lessons.length - 1) { - const nextLesson = course.lessons[currentIndex + 1]; - if (user) { - setTimeout(() => { - setCurrentLesson(nextLesson); - }, 1000); - } - } - } - }; - - // Track video progress - const handleTimeUpdate = () => { - if (videoRef.current) { - const { currentTime, duration } = videoRef.current; - if (duration > 0) { - if (user && currentLesson && currentTime - (lastProgressSave.current[currentLesson.id] || 0) >= 30) { - const watchedSeconds = Math.floor(currentTime); - lastProgressSave.current[currentLesson.id] = watchedSeconds; - setWatchedSecondsByLesson((current) => ({ ...current, [currentLesson.id]: watchedSeconds })); - saveLessonProgress(currentLesson.id, watchedSeconds).catch(() => undefined); - } - const percent = Math.round((currentTime / duration) * 100); - // Automatically mark as complete when reaching 95%+ - if (percent >= 95 && currentLesson && !completedLessonIds.includes(currentLesson.id)) { - markLessonCompleted(currentLesson.id, Math.round(currentTime)); - } - } - } - }; - - // Bunny's iframe does not expose an HTMLVideoElement. Player.js receives - // Bunny's trusted playback events and sends the same progress updates used - // for external video providers. - useEffect(() => { - if (!playback || playback.kind !== 'embed' || !currentLesson || !user) return; - let disposed = false; - const lessonId = currentLesson.id; - void loadBunnyPlayerJs().then(() => { - if (disposed || !bunnyFrameRef.current || !window.playerjs) return; - const player = new window.playerjs.Player(bunnyFrameRef.current); - player.on('timeupdate', (data) => { - const watchedSeconds = Math.floor(data?.seconds || 0); - if (disposed || watchedSeconds <= 0 || watchedSeconds - (lastProgressSave.current[lessonId] || 0) < 30) return; - lastProgressSave.current[lessonId] = watchedSeconds; - setWatchedSecondsByLesson((current) => ({ ...current, [lessonId]: watchedSeconds })); - saveLessonProgress(lessonId, watchedSeconds).catch(() => undefined); - }); - player.on('ended', (data) => { - if (disposed) return; - markLessonCompleted(lessonId, Math.floor(data?.duration || data?.seconds || 0)); - }); - }).catch(() => undefined); - return () => { disposed = true; }; - }, [playback, currentLesson, user, completedLessonIds]); - - const restoreWatchPosition = () => { - if (!currentLesson || !videoRef.current) return; - const watchedSeconds = watchedSecondsByLesson[currentLesson.id] || 0; - if (watchedSeconds > 0 && watchedSeconds < videoRef.current.duration - 5) videoRef.current.currentTime = watchedSeconds; - }; - - const handleAddComment = async (e: React.FormEvent) => { - e.preventDefault(); - if (!newComment.trim() || !course) return; - - const comment = { - courseId: course.id, - lessonId: currentLesson?.id, - text: newComment, - }; - - try { - const savedComment = await saveComment(comment); - setComments([savedComment, ...comments]); - setNewComment(''); - } catch { - // The server remains the source of truth; leave the text intact for a retry. - } - }; - - const changeLesson = (lesson: Lesson) => { - setCurrentLesson(lesson); - }; - - const handleShare = () => { - navigator.clipboard.writeText(window.location.href); - setCopiedLink(true); - setTimeout(() => setCopiedLink(false), 2500); - }; - - // Collect all downloadable materials for this course (Global + All Lessons) - const allCourseAttachments: Array<{ attachment: Attachment; source: string }> = []; - - if (course?.attachments) { - course.attachments.forEach(att => { - allCourseAttachments.push({ attachment: att, source: 'Material Geral do Curso' }); - }); - } - - if (course?.lessons) { - course.lessons.forEach(l => { - if (l.attachments) { - l.attachments.forEach(att => { - allCourseAttachments.push({ attachment: att, source: l.title }); - }); - } - }); - } - - const currentLessonAttachments = currentLesson?.attachments || []; - - // Access Control Logic - const canWatch = currentLesson && Boolean(user); - - if (!course) return null; - - return ( -
- {/* Top Bar Floating Controls */} -
-
- - - {course.title} - -
- -
- - - -
-
- -
-
- - {/* Main Left Column: Video & Lesson Details */} -
- - {/* Video Player Section */} -
- {canWatch ? ( - playback ? ( - playback.kind === 'embed' && playback.embedUrl ? ( -