import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'; import { Course } from '../types'; import { getCourses, getLearningPaths, PublicLearningPath } from '../services/db'; import { courseApi, InstructorSummary, profileApi } from '../services/api'; import { useAuth } from './AuthContext'; /** The three area tones from the design; every category is shown in one of them. */ export type AreaTone = 'midia' | 'conv' | 'oper'; const TONES: AreaTone[] = ['midia', 'conv', 'oper']; export interface Professor { id: string; name: string; courses: Course[]; headline?: string; avatarImageUrl?: string | null; } interface CatalogContextType { courses: Course[]; paths: PublicLearningPath[]; /** Categories that have published courses, in the admin-defined order. */ areas: string[]; professors: Professor[]; isLoading: boolean; failed: boolean; reload: () => Promise; courseById: (courseId: string) => Course | undefined; toneOf: (category: string) => AreaTone; pathTone: (path: PublicLearningPath) => AreaTone; } const CatalogContext = createContext(undefined); export const CatalogProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const { user, isLoading: authLoading } = useAuth(); const [courses, setCourses] = useState([]); const [paths, setPaths] = useState([]); const [instructorProfiles, setInstructorProfiles] = useState([]); const [categoryOrder, setCategoryOrder] = useState([]); const [isLoading, setIsLoading] = useState(true); const [failed, setFailed] = useState(false); const reload = useCallback(async () => { setFailed(false); try { const [loadedCourses, loadedPaths, categories, instructors] = await Promise.all([ getCourses(), getLearningPaths().catch(() => [] as PublicLearningPath[]), courseApi.categories().then((response) => response.data).catch(() => [] as string[]), profileApi.instructors().then((response) => response.data).catch(() => [] as InstructorSummary[]), ]); setCourses(loadedCourses); setPaths(loadedPaths); setCategoryOrder(categories); setInstructorProfiles(instructors); } catch { // Never replace a failed API with fake catalogue data: the screens use the // `failed` flag to show an honest loading error instead. setFailed(true); } finally { setIsLoading(false); } }, []); // Progress on each course belongs to the signed-in learner, so reload when the session changes. useEffect(() => { if (authLoading) return; void reload(); }, [authLoading, reload, user?.id]); const value = useMemo(() => { const present: string[] = Array.from(new Set(courses.map((course) => course.category).filter(Boolean))); const ordered = [ ...categoryOrder.filter((category) => present.includes(category)), ...present.filter((category) => !categoryOrder.includes(category)).sort((a, b) => a.localeCompare(b, 'pt-BR')), ]; const toneIndex = new Map(ordered.map((category, index) => [category, index])); const toneOf = (category: string): AreaTone => TONES[(toneIndex.get(category) ?? 0) % TONES.length]; const byId = new Map(courses.map((course) => [course.id, course])); const professorMap = new Map(); instructorProfiles.forEach((professor) => { professorMap.set(professor.id, { id: professor.id, name: professor.name, headline: professor.headline || undefined, avatarImageUrl: professor.avatarImageUrl, courses: [], }); }); courses.forEach((course) => { if (!course.instructorId) return; const entry = professorMap.get(course.instructorId) || { id: course.instructorId, name: course.instructor || 'Professor', headline: undefined, avatarImageUrl: null, courses: [], }; entry.courses.push(course); professorMap.set(course.instructorId, entry); }); return { courses, paths, areas: ordered, professors: Array.from(professorMap.values()).sort((a, b) => a.name.localeCompare(b.name, 'pt-BR')), isLoading, failed, reload, courseById: (courseId: string) => byId.get(courseId), toneOf, pathTone: (path: PublicLearningPath) => { const counts = new Map(); path.courses.forEach((course) => counts.set(course.category, (counts.get(course.category) || 0) + 1)); const main = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; return main ? toneOf(main) : 'midia'; }, }; }, [categoryOrder, courses, failed, isLoading, instructorProfiles, paths, reload]); return {children}; }; export const useCatalog = () => { const context = useContext(CatalogContext); if (!context) throw new Error('useCatalog must be used within CatalogProvider'); return context; };