Back to Dashboard
App Specification

CogniFlow Application Specification

1. Overview

1.1. Purpose

CogniFlow is an AI-Powered Course Creation and Learning tool designed to help users (educators, students, and lifelong learners) easily create, share, and consume educational content.

1.2. Core Features

  • AI-assisted course outline generation and modification.
  • AI-generated lesson content and quizzes.
  • AI-generated images, syllabi, and presentations for courses.
  • User authentication and profile management.
  • Tiered access (Free, Student, Teacher) with feature limitations/enhancements.
  • Public and private course sharing.
  • Class management for teachers to assign courses to students.
  • Course interaction tracking (lesson completion, quiz scores).
  • Social features: Liking courses, following users.
  • Administrative panel for user and content management.
  • Internationalization and Text-to-Speech (TTS) support.

1.3. Target Audience

  • Educators and content creators.
  • Students.
  • Lifelong learners.
  • Administrators managing the platform.

1.4. Technology Stack

  • Frontend: Next.js, React, ShadCN UI, Tailwind CSS.
  • Backend/AI: Genkit (Google Gemini models for text, Replicate for images).
  • Database: Firebase Firestore.
  • Authentication: Firebase Authentication.
  • Storage: Firebase Storage.

2. Global Components & Features

2.1. Application Header (<AppHeader />)

  • Logo & App Name: "CogniFlow" logo and text, links to / (Home/Activity Feed) or /dashboard if logged in.
  • Navigation Links: Dynamically displayed based on user authentication status and role.
    • Create Course: (/lessons/create)
      • Icon: PlusCircle
      • Visible: Logged-in users.
    • My Courses: (/lessons/my-plans)
      • Icon: BookOpenText
      • Visible: Logged-in users.
    • Public Courses: (/lessons/public-plans)
      • Icon: Globe
      • Visible: All users.
    • Class Courses: (/lessons/class-plans)
      • Icon: Library
      • Visible: Logged-in users who are students in any class or admins.
    • My Classes: (/classes/my-classes)
      • Icon: UsersIcon
      • Visible: Logged-in users who are Teachers or Admins.
    • Hall of Fame: (/hall-of-fame)
      • Icon: Trophy
      • Visible: All users.
  • Theme Toggle:
    • Icon: Sun (Light), Moon (Dark)
    • Options: Light, Dark, System.
    • Persists theme choice.
  • Language Selector:
    • Icon: LanguageIcon
    • Dropdown to select application language.
    • Persists language choice.
  • User Authentication Menu:
    • If Logged Out:
      • "Sign In" Button (/auth/signin): Icon LogIn.
      • "Sign Up" Button (/auth/signup).
    • If Logged In:
      • Avatar Dropdown:
        • Displays user's profile picture or initials.
        • User's display name and email.
      • Menu Items:
        • Dashboard (/dashboard): Icon LayoutDashboard.
        • Billing (/settings/billing): Icon CreditCard.
        • TTS Settings (/settings/tts): Icon Volume2.
        • Sign Out: Icon LogOut, triggers Firebase sign out.

2.2. Authentication

  • Sign Up Page (/auth/signup):
    • Email Input: email, placeholder m@example.com.
    • Password Input: password, placeholder ••••••••.
    • "Create Account" Button: Handles email/password sign-up.
    • "Sign Up with Google" Button: Handles Google OAuth sign-up.
    • Link to Sign In Page.
  • Sign In Page (/auth/signin):
    • Email Input: email.
    • Password Input: password.
    • "Sign In" Button: Handles email/password sign-in.
    • "Forgot Password?" Link: Opens Password Reset Dialog.
    • "Sign In with Google" Button: Handles Google OAuth sign-in.
    • Link to Sign Up Page.
  • Password Reset Dialog (on Sign In Page):
    • Email Input: resetEmail.
    • "Send Reset Link" Button.

2.3. Internationalization (i18n)

  • Mechanism: LanguageContext and translation files in src/lib/i18n/locales/.
  • Supported Languages: English (default), Polish, Spanish, French, German, Ukrainian, Russian, Portuguese, Czech, Slovak, Italian, Chinese (Simplified), Korean, Japanese, Croatian, Slovenian.
  • Selection: Via Language Selector in App Header. Persisted in localStorage.

2.4. Text-to-Speech (TTS)

  • Global Listen Button (<ListenButton />):
    • Appears on pages with substantial readable content (e.g., Lesson Content View).
    • Uses browser's SpeechSynthesis API.
    • Sanitizes Markdown for better speech output.
    • Controls: Play, Pause, Resume, Stop.
  • TTS Settings Page (/settings/tts):
    • Enable/Disable TTS Switch.
    • Voice Selector Dropdown (populates with system voices).
    • Speech Rate Slider.
    • Settings persisted in localStorage.

3. Core User Flows & Pages

3.1. Dashboard (/dashboard)

  • User Welcome & Avatar:
    • Greeting: "Welcome, [User's Display Name]!"
    • Avatar: Displays profile picture or initials. Clickable to open file input for photo change.
      • Hidden File Input: For image/*.
    • Followers Count: Displayed.
    • Following Count: Displayed.
  • Account Status Card:
    • Current Tier Display: Badge (e.g., "Free Tier", "Student Tier", "Teacher Tier").
    • Admin Badge: If user is admin.
    • Plan Creation Limits: Text indicating current usage vs. limit (e.g., "Courses created (this month): X / Y").
    • Lesson Solved Limits: Text indicating current usage vs. limit.
    • "Upgrade Plan" Button: Visible if not on highest tier or admin. Links to /upgrade.
    • "Manage Subscription" Button: Visible for paid tiers (not admin on free). Links to Stripe placeholder or actual Stripe portal.
  • Edit Profile Details Card:
    • Form Fields:
      • First Name Input: firstName, placeholder "Your first name".
      • Last Name Input: lastName, placeholder "Your last name".
      • Bio Textarea: bio, placeholder "Tell us a bit about yourself...". Max 200 chars.
      • Website URL Input: websiteUrl, placeholder "https://example.com". Type url.
    • "Save Profile Details" Button: Icon Save. Submits profile updates via updateExtendedUserProfileAction.
  • Quick Links/Actions:
    • "Create Course" Button (/lessons/create).
    • "My Courses" Button (/lessons/my-plans).
    • "Public Courses" Button (/lessons/public-plans).
  • Liked Courses Section:
    • Title: "Liked Courses". Icon Heart.
    • Scrollable list of courses the user has liked.
    • Each item shows course title and links to /lessons/run/[courseId].
    • Shows "No liked courses yet" if empty.
  • Following Users Section:
    • Title: "Following". Icon UserFollowIcon.
    • Scrollable list of users the current user is following.
    • Each item shows user avatar, display name, and links to /profile/[userId].
    • Shows "You are not following anyone yet" if empty.
  • Teacher Dashboard Section (<TeacherDashboardSection />) (Conditional: Teachers/Admins):
    • Title: "Teacher Dashboard".
    • "Create New Class" Button (/classes/create).
    • "Manage My Classes" Button (/classes/my-classes).
    • "View Student Progress" Button (Placeholder, disabled).
  • Admin Section (<AdminSection />) (Conditional: Admins):
    • Title: "Admin Panel - User Management".
    • See section 3.11 for details.

3.2. Create/Edit Course Page (/lessons/create, /lessons/edit/[planId]) (<CourseForm />)

  • Page Title: "Create New Course" or "Edit Course".
  • Form Fields & Controls:
    • Course Title Input: title. Max 150 chars. Placeholder "Enter a title for the course".
    • Course Topic Textarea: topic. Min 10 chars. Placeholder "e.g., Introduction to Jazz Music Theory...".
      • Detects YouTube URLs for transcript fetching.
    • YouTube URL & Transcript:
      • Displays detected YouTube URL if found in topic.
      • Shows status of transcript fetching (fetching, fetched, will fetch).
      • Fetched transcript displayed in a read-only scrollable area if plan outline exists.
    • File Attachment:
      • "Attach File" Button: Icon Paperclip. Opens file dialog. Accepts text, image, PDF, Word, CSV. Max 5MB.
      • Display of attached file name and type icon.
      • "Remove Attached File" Button (X icon).
      • File error display area.
    • Teaching Style Selector:
      • Row of avatar-like buttons for predefined styles (Sage, Spark, Storyteller, Innovator, Comedian, Explorer) and two custom styles (Custom 1, Custom 2).
        • Icons represent each style.
        • Tooltip shows style name.
        • Clicking selects/deselects a style. Selected style has a primary color ring.
      • Conditional Display Area Below Avatars:
        • If a predefined style is selected: Displays the style's name (e.g., "The Sage") and its descriptive AI prompt in a read-only card.
        • If "Custom Style 1" or "Custom Style 2" is selected: A Textarea appears.
          • Value bound to form.watch('teachingStylePrompt').
          • onChange updates form.setValue('teachingStylePrompt', ...).
          • onBlur saves the content to userProfile.customTeachingStylePrompt1 or customTeachingStylePrompt2 via action.
          • Placeholder: "Enter your detailed custom teaching style prompt here..."
    • Course Parameters:
      • Difficulty Select: difficulty. Options: Beginner, Intermediate, Advanced, Mixed.
      • Number of Lessons Input: numLessons. Type number, min 1, max 20.
      • Quiz Questions per Lesson Input: numQuizQuestions. Type number, min 1, max 10, default 3.
      • Language Select: language (for AI content generation). Dropdown of supportedLanguages.
    • Class Assignment (Teachers/Admins only):
      • classIds field.
      • Multi-select DropdownMenu with checkboxes for available teacher's classes.
      • Placeholder "Select classes". Description about assignment.
    • Public Toggle Switch: isPublic.
      • Label: "Make Publicly Visible".
      • Description varies for Free vs. Pro users.
      • Disabled for Free tier users (defaults to true).
    • "Generate Outline" Button:
      • Icon: Sparkles.
      • Visible if no planOutline exists.
      • Disabled if topic is empty, or while generating/fetching transcript.
      • Triggers handleInitialGeneratePlan which calls generateCourse AI flow.
    • Course Outline Display/Editor:
      • Visible if planOutline exists or is being generated.
      • Title Input: title (editable if outline exists).
      • Topic Textarea: topic (editable if outline exists, smaller).
      • "View Outline" / "Edit Outline" Toggle Button: Icons EyeOff / Edit.
      • If isEditingOutline is false: <MarkdownDisplay /> of form.watch('planOutline').
      • If isEditingOutline is true: <Textarea /> for planOutline.
      • Listen Button (<ListenButton />): TTS for the outline.
    • Modification Request Textarea: modificationRequest.
      • Placeholder "e.g., Make lesson 3 more focused on practical examples...".
      • Visible if planOutline exists.
    • Tags Input Area:
      • currentTags displayed as Badges with remove (X) buttons.
      • "Add Tag" Button: Icon PlusCircle. Toggles visibility of tag input.
      • If isAddingTag is true:
        • <Input /> for tagInput. Placeholder "Type tag & press Enter...".
        • Inline "Add" Button (Check icon).
        • Inline "Cancel" Button (X icon).
    • Action Buttons (Contextual):
      • Main Submit Button:
        • Text changes: "Generate Outline", "Save New Course", "Regenerate and Save", "Save Course Changes".
        • Icon: Sparkles or Save.
        • Disabled based on form state, generation status, etc.
        • Calls handleInitialGeneratePlan or onSubmitMainForm.
      • "Modify & Save" Button (if outline exists and modificationRequest or parameters changed):
        • Icon: Sparkles or RefreshCw.
        • Calls handleModifyPlan. (Note: onSubmitMainForm logic now determines if modify/generate is needed).
      • "Run Course" Button: Visible if currentPlanIdForRunButton exists. Links to /lessons/run/[id]. Icon Eye.
      • "Generate Syllabus" Button: Visible if course is saved. Icon FileBadge. Calls generateCourseSyllabus.
      • "Generate Presentation" Button: Visible if course is saved. Icon Presentation. Calls generateCoursePresentation.
  • Error Display: Alerts for AI errors, save errors, file errors.
  • Example Prompts: Clickable text examples to populate the topic field.

3.3. My Courses Page (/lessons/my-plans)

  • Page Title: "My Courses".
  • Search Input: Filters courses by title, topic, tags. Icon Search.
  • Class Filter Dropdown (Teachers/Admins only): Filters courses by assigned class.
  • Course Card List: Grid of <Card> components for each course owned by the user.
    • Card Content:
      • Title, Topic Snippet.
      • Number of Lessons, Difficulty Badge, Language.
      • Public/Private Badge.
      • Author Avatar & Name (links to user's own profile, usually not emphasized here as it's "My Courses").
      • Assigned Classes Badges (if any).
      • Tags (clickable to filter search).
    • Card Footer Actions:
      • Like Button (<LikeButton />): Shows like count, allows liking (though typically one doesn't like their own course, UI might allow it).
      • Star Rating Button (<StarButton />): Shows average rating and total ratings. Allows rating (disabled for own course).
      • "Generate Presentation" Button: Icon Presentation.
      • "Generate Syllabus" Button: Icon FileBadge.
      • "Run Course" Button: Icon Eye. Links to /lessons/run/[id].
      • "Edit Course" Button: Icon Edit. Links to /lessons/edit/[id].
      • "Delete Course" Button: Icon Trash2. Opens AlertDialog for confirmation.
  • Empty State: Message if user has no courses, with a link to "Create Course".
  • Loading State: Skeletons for course cards.
  • Error State: Alert for data loading errors.

3.4. Public Courses Page (/lessons/public-plans)

  • Page Title: "Public Courses".
  • Search Input: Filters public courses.
  • Course Card List: Grid of public courses.
    • Similar card content to "My Courses".
    • Author Avatar & Name: Links to the course creator's profile (/profile/[userId]).
    • Card Footer Actions:
      • Like Button (<LikeButton />).
      • Star Rating Button (<StarButton />).
      • Follow Button (<FollowButton />) for the course author (if not current user).
      • "Generate Presentation" Button.
      • "Run Course" Button.
  • Empty State: Message if no public courses are available.

3.5. Class Courses Page (/lessons/class-plans) (Students enrolled in classes / Admins)

  • Page Title: "Class Courses".
  • Search Input.
  • Course Card List: Courses assigned to classes the student is part of.
    • Similar card content and actions to "Public Courses" (Run, Like, Rate, Follow Author, Generate Presentation).
  • Empty State: If not enrolled or no courses assigned to their classes.

3.6. Run Course Page (/lessons/run/[planId])

  • Dynamic Page Title: "[Course Title]" or "[Course Title] - [Lesson Title]".
  • Back to List Button: Icon ArrowLeft. Navigates back to LessonListView.
  • Header Area (when in list view):
    • Course Title.
    • Author Info: Avatar, Name (link to profile), Follow Button.
  • Main View Area (switches between LessonListView, LessonContentView, QuizView, QuizResultsView):
    • LessonListView (Default View):
      • Card with title "Lessons".
      • List of lessons:
        • Icon (CheckCircle for completed, Radio for not).
        • Lesson Number and Title (clickable to select lesson).
        • Completion Status Badge.
      • Course Like Button & Star Rating in footer.
    • LessonContentView:
      • Lesson Title.
      • Teacher Actions (if canEditCurrentCourse):
        • "Edit Lesson Content" Button (Edit icon): Opens dialog.
        • "Add Media to Lesson" Button (UploadCloud icon): Opens dialog.
      • Image Display Area:
        • Shows generated imageDataUri (Replicate image) if available.
        • Shows loading state if generatingLessonImage is true.
        • Shows error message if imageError exists.
        • Shows "Generate Image" button if lesson.imagePrompt exists but no imageDataUri.
        • Placeholder if no image/prompt.
      • Attached Media Display: Iterates lesson.mediaItems.
        • Renders <img> for images, <video> for videos, <audio> for audio.
      • Markdown Content Display (<MarkdownDisplay />): Shows lesson.content.
      • Listen Button (<ListenButton />): For TTS of lesson content.
      • "Next: Quiz" Button:
        • Icon ArrowRight.
        • Enabled if content exists and user is logged in (or course is public).
        • Triggers handleStartQuiz.
      • Retry Content/Image Buttons: If errors occurred.
    • QuizView:
      • Title: "Quiz: [Lesson Title]".
      • Question Counter: "Question X of Y".
      • Question Text.
      • Question Media Display (if question.mediaItem exists).
      • Teacher Actions (if canEditCurrentCourse):
        • "Edit Question" Button: Opens dialog.
        • "Add Media to Question" Button: Opens dialog.
      • Multiple Choice Options: <RadioGroup> with <RadioGroupItem> for each option.
      • "Next" / "Submit" Button:
        • Icon ArrowRight for "Next".
        • Disabled if no answer selected.
        • Calls handleNextQuestion (or handleSubmitQuiz if last question).
    • QuizResultsView:
      • Title: "Quiz: [Lesson Title] - Results".
      • Score Display: "Your Score: X / Y". Icon Trophy.
      • Review Area: For each question:
        • Question Text & Media.
        • User's Answer (highlighted correct/incorrect with CheckCircle or XCircle).
        • Correct Answer (if user was wrong).
        • Explanation (if available).
        • Teacher Actions (if canEditCurrentCourse): Edit/Add Media buttons.
      • Course Star Rating Button (if not owner and conditions met).
      • "Next Lesson" / "Finish Course" Button: Icon ArrowRight. Calls handleFinishLesson.
  • Dialogs:
    • Edit Lesson Content Dialog:
      • Title: "Refine Lesson Content: [Lesson Title]".
      • Read-only display of current Markdown content.
      • Textarea for editableLessonContent.
      • Textarea for editModificationPrompt (AI refinement).
      • "Save Content" / "Refine with AI & Save" Button.
      • "Cancel" Button.
    • Edit Quiz Question Dialog (quizQuestionForm):
      • Title: "Edit Quiz Question".
      • Question Text Textarea.
      • Input fields for each Option (up to 5).
      • Correct Answer Index Input (number).
      • Explanation Textarea.
      • "Save Question" / "Cancel" Buttons.
    • Add Media Dialog (mediaForm):
      • Title: "Add Media to Lesson Content" / "Add Media to Quiz Question".
      • Media Type Select: Image, Video, Audio.
      • Media File Input (for Image/Audio): accept attribute based on type.
      • Media URL Input (for Video or as alternative).
      • Media Name Input (optional).
      • "Add Media" / "Cancel" Buttons.
  • Loading States: Skeletons and loaders for various parts.
  • Error States: Alerts for course loading, content generation, quiz errors.

3.7. User Profile Page (/profile/[userId])

  • User Avatar: photoURL or initials.
  • Display Name: User's displayName or derived name.
  • Followers Count / Following Count.
  • "Follow" / "Unfollow" Button (<FollowButton />): Visible if viewing another user's profile.
  • Bio Display: profile.bio.
  • Website Link: profile.websiteUrl (clickable).
  • Placeholder if no bio/website.
  • "Back" Button.
  • (Future: List of user's public courses).

3.8. Hall of Fame Page (/hall-of-fame)

  • Page Title: "Hall of Fame".
  • Top Creators Section Card:
    • Title: "Top Creators". Description.
    • Table:
      • Columns: Rank, Creator (Avatar, Name link), Score, Public Courses, Avg. Rating, Total Runs, Follow.
      • Follow Button (<FollowButton />) per creator.
    • Empty/Loading/Error states.
  • Top Students Section Card:
    • Title: "Top Students". Description.
    • Table:
      • Columns: Rank, Student (Avatar, Name link), Courses Completed (Badge), Follow.
      • Follow Button (<FollowButton />) per student.
    • Empty/Loading/Error states.

3.9. Settings

  • Billing Page (/settings/billing):
    • Page Title: "Billing Settings".
    • Card: "Subscription Status".
      • Displays current user tier (Badge). Admin badge if applicable.
      • Descriptive text based on tier.
      • "Manage Subscription" Button: If on a paid tier. Icon Settings, ExternalLink. Placeholder redirect.
      • "Upgrade Plan" Button: If on Free tier. Links to /upgrade.
      • Notes for Admins on Free/Paid tiers.
    • Error/Loading states.
  • Text-to-Speech Settings Page (/settings/tts):
    • Page Title: "Text-to-Speech Settings".
    • Card:
      • Title: "Text-to-Speech Settings". Icon Settings2. Description.
      • "Enable Text-to-Speech" Switch (isTTSEnabled).
      • If enabled:
        • Voice Selector Dropdown (selectedVoiceURI): Lists available browser voices (Name & Lang).
        • Speech Rate Slider (speechRate): 0.5x to 2x. Displays current value.
    • "Back" Button.
    • Handles TTS not supported/error states.

3.10. Classes (Teacher/Admin)

  • Layout (/classes/layout.tsx): Common sidebar navigation for class management.
    • Sidebar Title: "My Classes".
    • Sidebar Nav Links (<SidebarNav />):
      • Create New Class (/classes/create, Icon PlusCircle)
      • Manage My Classes (/classes/my-classes, Icon Users)
      • View Student Progress (Placeholder, Icon BarChart3, disabled)
  • Create Class Page (/classes/create):
    • Page Title: "Create New Class". Icon Users.
    • Form:
      • Class Name Input: className. Min 3 chars.
      • Student Emails Textarea: studentEmails. For inviting multiple students (newline/comma separated).
      • "Create Class" Button.
    • Error/Submitting states.
  • Edit Class Page (/classes/edit/[classId]):
    • Page Title: "Edit Class". Icon Users.
    • Form (pre-filled with class data):
      • Class Name Input.
      • Student Emails Textarea.
      • "Update Class" Button. Icon Save.
    • Error/Submitting/Loading states.
  • My Classes Page (/classes/my-classes):
    • Page Title: "My Classes".
    • "Create New Class" Button. Icon PlusCircle.
    • List of classes created by the teacher (Cards):
      • Card Title: Class Name.
      • Card Description: Student count.
      • Card Content: List of student emails (partial), Created Date.
      • Card Footer Actions:
        • Edit Button (Icon Edit, links to edit page).
        • Delete Button (Icon Trash2, opens AlertDialog confirmation).
    • Empty/Loading/Error states.

3.11. Admin Panel (Dashboard Section, for Admins) (<AdminSection />, <AdminUserActions />, <AdminUserCoursesDialog />)

  • Card Title: "Admin Panel - User Management".
  • User Search Input: Filters user table by name or email.
  • User Table:
    • Columns: Name, Email, Tier (Badge), Role (Admin/User Badge), Actions.
    • Actions per User Row (<AdminUserActions />):
      • Edit User Button: Icon Edit. Opens Dialog.
        • Dialog Title: "Edit User ([user.email])".
        • Tier Radio Group: Free, Student, Teacher.
        • Is Admin Switch.
        • "Save Changes" / "Cancel" Buttons.
        • Handles errors, cannot edit self/primary admin.
      • View User's Courses Button: Icon BookOpen. Opens Dialog (<AdminUserCoursesDialog />).
        • Dialog Title: "Courses by [user.displayName]".
        • Scrollable list of courses created by the target user.
        • Each course item shows: Title (link to edit course), Public/Private status, Lessons, Difficulty, Language, Tags.
        • Actions per course in dialog:
          • "Trash Course" Button: Icon Trash2. Confirmation dialog. Changes course status to 'trashed'.
          • "Permanently Delete Course" Button: Icon Trash2 (destructive). Confirmation dialog. Full deletion.
        • "Close" Button.
      • Delete User Profile Button (Full Data Deletion): Icon Trash2 (destructive). Opens AlertDialog.
        • Confirmation text about deleting Firestore data (profile, courses, progress, etc.) and reminder to delete Auth account manually.
        • Handles errors, cannot delete self/primary admin.
  • Empty/Loading/Error states for user list.

4. Core AI Flows (Server-Side - src/ai/flows/)

  • generate-course-flow.ts (generateCourse, modifyCourse):

    • generateCourse:
      • Input: GenerateCourseInput (topic, difficulty, numLessons, numQuizQuestions, language, optional teachingStylePrompt, optional attachment (data URI/text), optional YouTube transcript).
      • Output: CourseOutput (title, planOutline (Markdown), difficulty, numLessons, numQuizQuestions, tags).
    • modifyCourse:
      • Input: ModifyCourseInput (originalTopic, existingPlanTitle, existingPlan (outline), modificationRequest, difficulty, numLessons, numQuizQuestions, language, optional teachingStylePrompt).
      • Output: CourseOutput (revised title, planOutline, difficulty, numLessons, numQuizQuestions, tags).
  • generate-lesson-content-flow.ts (generateLessonContent):

    • Input: GenerateLessonContentInput (courseId, lessonIndex, lessonNumber, lessonTitle, courseTopic, courseOutline, language).
    • Output: GenerateLessonContentOutput (lesson content (Markdown), imagePrompt (for lesson display image)).
  • refine-lesson-content-flow.ts (refineLessonContent):

    • Input: RefineLessonContentInput (lessonTitle, currentContent (Markdown), modificationRequest, language).
    • Output: RefineLessonContentOutput (refinedContent (Markdown)).
  • generate-quiz-flow.ts (generateQuiz):

    • Input: GenerateQuizInput (lessonContent, numQuestions, language).
    • Output: GenerateQuizOutput (Array of QuizQuestion objects: questionText, options, correctAnswerIndex, explanation).
  • generate-image-flow.ts (generateImageAI):

    • Uses Replicate (black-forest-labs/flux-schnell model).
    • Input: GenerateImageInput (prompt, optional theme, optional Replicate model parameters).
    • Output: GenerateImageOutput ({ imageUrl: string }).
  • generate-syllabus-flow.ts (generateCourseSyllabus):

    • Input: GenerateCourseSyllabusInput (courseTitle, courseTopic, planOutline, numLessons, difficulty, language, tags, optional YouTube transcript).
    • Output: GenerateCourseSyllabusOutput (syllabusMarkdown (Markdown)).
  • generate-presentation-flow.ts (generateCoursePresentation):

    • Input: GenerateCoursePresentationInput (courseTitle, courseTopic, planOutline, numLessons, difficulty, language).
    • Output: GenerateCoursePresentationOutput (presentationMarkdown (Markdown)).

5. Data Models (Types - src/types/)

  • UserProfile (user.ts):

    • id, uid, email, displayName, photoURL?, createdAt, updatedAt, tier (free | student | teacher), isAdmin, firstName?, lastName?, bio?, websiteUrl?, customTeachingStylePrompt1?, customTeachingStylePrompt2?, createdPlanCount, solvedLessonCount, monthlyCreatedPlanCount, monthlySolvedLessonCount, countLastResetDate, ratedCourses?, following?, followersCount?, likedCourses?.
  • Course (lesson-plan.ts):

    • id, userId (owner), title, topic, difficulty (Beginner | ...), numLessons, numQuizQuestions, planOutline (Markdown), tags (array of LessonTag), isPublic, createdAt (ISO string), updatedAt (ISO string), language, classIds?, teacherName?, teacherPhotoURL?, youtubeUrl?, youtubeTranscriptContent?, ratings? ({ userId: rating }), averageRating?, totalRatings?, runCount?, likedBy? (string array of user IDs), likeCount?, status? (active | trashed).
  • Lesson (lesson-plan.ts):

    • id, courseId, lessonIndex, title, content? (Markdown), imagePrompt?, imageUrl? (Storage URL), mediaItems? (array of MediaItem), quizId?.
  • Quiz (lesson-plan.ts):

    • id, lessonId, questions (array of QuizQuestion).
  • QuizQuestion (lesson-plan.ts):

    • questionText, options (string array), correctAnswerIndex, explanation?, mediaItem? (MediaItem).
  • MediaItem (lesson-plan.ts):

    • type (image | video | audio), url, name?, uploadedAt? (ISO string).
  • LessonTag (lesson-plan.ts):

    • id, text.
  • ClassInfo (lesson-plan.ts):

    • id, className, teacherId, studentEmails (string array), createdAt (ISO string), updatedAt (ISO string).
  • UserCourseProgress (lesson-plan.ts):

    • userId, courseId, quizAttempts? ({ quizId: UserQuizAttemptDetails }).
    • UserQuizAttemptDetails: score, answers ({ qIndex: optionIndex }), submittedAt (ISO string).
  • UserLessonCompletion (lesson-plan.ts):

    • id?, userId, courseId, lessonId, completedAt (Timestamp/FieldValue).
  • ActivityFeedItem (activity-feed.ts):

    • Base: id, type, timestamp, actorId, actorDisplayName, actorPhotoURL?.
    • Types: NewCourseActivityItem (courseId, courseTitle, courseTopic), CourseLikeActivityItem, CourseRatingActivityItem, UserFollowActivityItem.
  • HallOfFameEntry (hall-of-fame.ts):

    • TopStudentEntry: rank, userId, displayName, photoURL?, completedCoursesCount.
    • TopCreatorEntry: rank, userId, displayName, photoURL?, creatorScore, numberOfPublicCourses, averageRating, totalRuns.

6. Error Handling & User Feedback

  • Toasts (<Toaster />, useToast): Used for non-blocking notifications (success, error, info, warning).
  • Inline Alerts (<Alert />): Used for displaying more prominent errors or warnings directly on pages/forms (e.g., AI generation errors, form validation issues).
  • Form Validation: Zod schemas for client-side validation on forms like Sign Up, Sign In, Course Form, Class Form, Profile Edit. Messages displayed via <FormMessage />.
  • Server Action Error Handling: Server actions (src/actions/) return structured error objects (e.g., { errorKey?: string, errorMessage?: string }) which are then translated and displayed on the client.
  • AI Flow Error Handling: Genkit flows include try...catch blocks. Errors are propagated to client-side calls and displayed.
  • Loading States: Spinners (Loader2), Skeletons (<Skeleton />) are used to indicate data fetching or processing.
  • Empty States: Informative messages when lists are empty (e.g., "No courses yet").

7. Key Dependencies

  • Firebase: Authentication, Firestore, Storage.
  • Next.js: Framework.
  • React: UI Library.
  • ShadCN UI: Component library (built on Radix UI & Tailwind CSS).
  • Tailwind CSS: Styling.
  • Genkit: AI flow orchestration.
    • @genkit-ai/googleai (for Gemini models).
  • Replicate: Image generation.
  • Zod: Schema validation.
  • React Hook Form: Form management.
  • Lucide React: Icons.
  • Date-fns: Date formatting.
  • react-markdown: Rendering Markdown content.
  • next-themes: Theme management.
  • i18n (custom): For internationalization.