This commit is contained in:
Marcelo
2026-02-17 00:07:00 +00:00
parent b7a86a2d1c
commit be4ca2ed78
92 changed files with 6850 additions and 1188 deletions

2
.env.local.example Normal file → Executable file
View File

@@ -1,3 +1,5 @@
NEXT_PUBLIC_SUPABASE_URL=YOUR_URL NEXT_PUBLIC_SUPABASE_URL=YOUR_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_ANON_KEY NEXT_PUBLIC_SUPABASE_ANON_KEY=YOUR_ANON_KEY
TEACHER_EMAILS=teacher@example.com TEACHER_EMAILS=teacher@example.com
DATABASE_URL=
DIRECT_URL=

0
.eslintrc.json Normal file → Executable file
View File

3
.gitignore vendored Normal file → Executable file
View File

@@ -2,9 +2,12 @@ node_modules
.next .next
out out
dist dist
.env
.env.local .env.local
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
pnpm-debug.log* pnpm-debug.log*
/generated/prisma

0
app/(auth)/auth/callback/route.ts Normal file → Executable file
View File

8
app/(auth)/auth/login/page.tsx Normal file → Executable file
View File

@@ -3,6 +3,8 @@ import LoginForm from "@/components/auth/LoginForm";
type LoginPageProps = { type LoginPageProps = {
searchParams: Promise<{ searchParams: Promise<{
redirectTo?: string | string[]; redirectTo?: string | string[];
role?: string | string[];
forgot?: string | string[];
}>; }>;
}; };
@@ -10,6 +12,10 @@ export default async function LoginPage({ searchParams }: LoginPageProps) {
const params = await searchParams; const params = await searchParams;
const redirectValue = params.redirectTo; const redirectValue = params.redirectTo;
const redirectTo = Array.isArray(redirectValue) ? redirectValue[0] : redirectValue; const redirectTo = Array.isArray(redirectValue) ? redirectValue[0] : redirectValue;
const roleValue = params.role;
const role = Array.isArray(roleValue) ? roleValue[0] : roleValue;
const forgotValue = params.forgot;
const forgot = Array.isArray(forgotValue) ? forgotValue[0] : forgotValue;
return <LoginForm redirectTo={redirectTo ?? "/courses"} />; return <LoginForm redirectTo={redirectTo ?? "/courses"} role={role} showForgot={forgot === "1"} />;
} }

9
app/(auth)/auth/signup/page.tsx Normal file → Executable file
View File

@@ -81,6 +81,15 @@ export default function SignupPage() {
Login Login
</Link> </Link>
</p> </p>
<p className="mt-2 text-sm text-slate-600">
Are you a teacher?{" "}
<Link className="font-semibold text-brand" href="/auth/login?role=teacher">
Login here
</Link>
</p>
<p className="mt-2 text-xs text-slate-500">
Teacher accounts are invite-only. If you received an invite, use the email provided.
</p>
</div> </div>
); );
} }

View File

@@ -0,0 +1,92 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireUser } from "@/lib/auth/requireUser";
import { db } from "@/lib/prisma";
type ToggleLessonCompleteInput = {
courseSlug: string;
lessonId: string;
};
export async function toggleLessonComplete({ courseSlug, lessonId }: ToggleLessonCompleteInput) {
const user = await requireUser();
if (!user?.id) {
return { success: false, error: "Unauthorized" };
}
const lesson = await db.lesson.findUnique({
where: { id: lessonId },
select: {
id: true,
module: {
select: {
courseId: true,
course: {
select: {
slug: true,
},
},
},
},
},
});
if (!lesson || lesson.module.course.slug !== courseSlug) {
return { success: false, error: "Lesson not found" };
}
const enrollment = await db.enrollment.findUnique({
where: {
userId_courseId: {
userId: user.id,
courseId: lesson.module.courseId,
},
},
select: { id: true },
});
if (!enrollment) {
return { success: false, error: "Not enrolled in this course" };
}
const existingProgress = await db.userProgress.findUnique({
where: {
userId_lessonId: {
userId: user.id,
lessonId,
},
},
select: {
id: true,
isCompleted: true,
},
});
const nextCompleted = !existingProgress?.isCompleted;
if (existingProgress) {
await db.userProgress.update({
where: { id: existingProgress.id },
data: {
isCompleted: nextCompleted,
finishedAt: nextCompleted ? new Date() : null,
lastPlayedAt: new Date(),
},
});
} else {
await db.userProgress.create({
data: {
userId: user.id,
lessonId,
isCompleted: true,
finishedAt: new Date(),
},
});
}
revalidatePath(`/courses/${courseSlug}/learn`);
return { success: true, isCompleted: nextCompleted };
}

304
app/(protected)/courses/[slug]/learn/page.tsx Normal file → Executable file
View File

@@ -1,214 +1,130 @@
"use client"; import { notFound, redirect } from "next/navigation";
import { db } from "@/lib/prisma";
import { requireUser } from "@/lib/auth/requireUser";
import StudentClassroomClient from "@/components/courses/StudentClassroomClient";
import { useEffect, useState } from "react"; function getText(value: unknown): string {
import Link from "next/link"; if (!value) return "";
import { useParams } from "next/navigation"; if (typeof value === "string") return value;
import LessonRow from "@/components/LessonRow"; if (typeof value === "object") {
import ProgressBar from "@/components/ProgressBar"; const record = value as Record<string, unknown>;
import { getCourseBySlug } from "@/lib/data/courseCatalog"; if (typeof record.es === "string") return record.es;
import { if (typeof record.en === "string") return record.en;
getCourseProgress,
getCourseProgressPercent,
markLessonComplete,
setLastLesson,
} from "@/lib/progress/localProgress";
import { teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import { supabaseBrowser } from "@/lib/supabase/browser";
import type { Course, Lesson } from "@/types/course";
const lessonContent = (lesson: Lesson) => {
if (lesson.type === "video") {
return (
<div className="space-y-3">
<div className="aspect-video rounded-2xl border border-slate-300 bg-[#f6f6f7] p-4">
<div className="flex h-full items-center justify-center rounded-xl border-2 border-dashed border-slate-300 text-lg text-slate-500">
Video placeholder ({lesson.minutes} min)
</div>
</div>
{lesson.videoUrl ? (
<p className="text-sm text-slate-500">
Demo video URL: <span className="font-medium text-slate-700">{lesson.videoUrl}</span>
</p>
) : null}
</div>
);
} }
return "";
}
if (lesson.type === "reading") { type PageProps = {
return ( params: Promise<{ slug: string }>;
<div className="rounded-2xl border border-slate-300 bg-white p-5"> searchParams: Promise<{ lesson?: string }>;
<p className="text-lg leading-9 text-slate-700">
Reading placeholder content for lesson: {lesson.title}. Replace with full lesson text and references in Phase 2.
</p>
</div>
);
}
return (
<div className="rounded-2xl border border-slate-300 bg-white p-5">
<p className="text-lg text-slate-700">Interactive placeholder for lesson: {lesson.title}.</p>
<button className="acve-button-secondary mt-3 px-3 py-1.5 text-sm" type="button">
Start interactive
</button>
</div>
);
}; };
export default function CourseLearnPage() { export default async function CourseLearnPage({ params, searchParams }: PageProps) {
const params = useParams<{ slug: string }>(); const { slug } = await params;
const slug = params.slug; const { lesson: requestedLessonId } = await searchParams;
const [course, setCourse] = useState<Course | undefined>(() => getCourseBySlug(slug));
const [hasResolvedCourse, setHasResolvedCourse] = useState(false);
const [userId, setUserId] = useState("guest"); const user = await requireUser();
const [isAuthed, setIsAuthed] = useState(false); if (!user?.id) {
const [selectedLessonId, setSelectedLessonId] = useState<string | null>(null); redirect(`/courses/${slug}`);
const [completedLessonIds, setCompletedLessonIds] = useState<string[]>([]);
const [progress, setProgress] = useState(0);
useEffect(() => {
const loadCourse = () => {
setCourse(getCourseBySlug(slug));
setHasResolvedCourse(true);
};
loadCourse();
window.addEventListener(teacherCoursesUpdatedEventName, loadCourse);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, loadCourse);
}, [slug]);
useEffect(() => {
const client = supabaseBrowser();
if (!client) return;
client.auth.getUser().then(({ data }) => {
setUserId(data.user?.id ?? "guest");
setIsAuthed(Boolean(data.user));
});
const { data } = client.auth.onAuthStateChange((_event, session) => {
setUserId(session?.user?.id ?? "guest");
setIsAuthed(Boolean(session?.user));
});
return () => data.subscription.unsubscribe();
}, []);
useEffect(() => {
if (!course) return;
const progressState = getCourseProgress(userId, course.slug);
const fallback = course.lessons[0]?.id ?? null;
setSelectedLessonId(progressState.lastLessonId ?? fallback);
setCompletedLessonIds(progressState.completedLessonIds);
setProgress(getCourseProgressPercent(userId, course.slug, course.lessons.length));
}, [course, userId]);
const completionSet = new Set(completedLessonIds);
if (!course && !hasResolvedCourse) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<p className="text-slate-600">Loading course...</p>
</div>
);
} }
const course = await db.course.findUnique({
where: { slug },
select: {
id: true,
slug: true,
title: true,
price: true,
modules: {
orderBy: { orderIndex: "asc" },
select: {
id: true,
title: true,
lessons: {
orderBy: { orderIndex: "asc" },
select: {
id: true,
title: true,
description: true,
videoUrl: true,
estimatedDuration: true,
},
},
},
},
},
});
if (!course) { if (!course) {
return ( notFound();
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h1 className="text-2xl font-bold text-slate-900">Course not found</h1>
<p className="mt-2 text-slate-600">The requested course slug does not exist in mock data.</p>
<Link className="mt-4 inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href="/courses">
Back to courses
</Link>
</div>
);
} }
const selectedLesson = let enrollment = await db.enrollment.findUnique({
course.lessons.find((lesson) => lesson.id === selectedLessonId) ?? course.lessons[0]; where: {
userId_courseId: {
userId: user.id,
courseId: course.id,
},
},
select: { id: true },
});
if (!selectedLesson) { if (!enrollment) {
return ( const isFree = Number(course.price) === 0;
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm"> if (isFree) {
<h1 className="text-2xl font-bold text-slate-900">No lessons available</h1> enrollment = await db.enrollment.create({
<p className="mt-2 text-slate-600">This course currently has no lessons configured.</p> data: {
<Link className="mt-4 inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href={`/courses/${course.slug}`}> userId: user.id,
Back to course courseId: course.id,
</Link> amountPaid: 0,
</div> },
); select: { id: true },
});
} else {
redirect(`/courses/${slug}`);
}
} }
const isLocked = (lesson: Lesson) => !lesson.isPreview && !isAuthed; const completedProgress = await db.userProgress.findMany({
where: {
userId: user.id,
isCompleted: true,
lesson: {
module: {
courseId: course.id,
},
},
},
select: {
lessonId: true,
},
});
const onSelectLesson = (lesson: Lesson) => { const modules = course.modules.map((module) => ({
if (isLocked(lesson)) return; id: module.id,
setSelectedLessonId(lesson.id); title: getText(module.title) || "Untitled module",
setLastLesson(userId, course.slug, lesson.id); lessons: module.lessons.map((lesson) => ({
}; id: lesson.id,
title: getText(lesson.title) || "Untitled lesson",
description: getText(lesson.description),
videoUrl: lesson.videoUrl,
estimatedDuration: lesson.estimatedDuration,
})),
}));
const onMarkComplete = () => { const flattenedLessonIds = modules.flatMap((module) => module.lessons.map((lesson) => lesson.id));
if (!selectedLesson) return; const initialSelectedLessonId =
markLessonComplete(userId, course.slug, selectedLesson.id); requestedLessonId && flattenedLessonIds.includes(requestedLessonId)
const progressState = getCourseProgress(userId, course.slug); ? requestedLessonId
setCompletedLessonIds(progressState.completedLessonIds); : flattenedLessonIds[0] ?? "";
setProgress(getCourseProgressPercent(userId, course.slug, course.lessons.length));
};
return ( return (
<div className="space-y-6"> <StudentClassroomClient
<header className="acve-panel p-6"> courseSlug={course.slug}
<div className="flex flex-wrap items-center justify-between gap-4"> courseTitle={getText(course.title) || "Untitled course"}
<div> modules={modules}
<Link className="inline-flex items-center gap-2 text-base text-slate-600 hover:text-brand md:text-xl" href={`/courses/${course.slug}`}> initialSelectedLessonId={initialSelectedLessonId}
<span className="text-base">{"<-"}</span> initialCompletedLessonIds={completedProgress.map((progress) => progress.lessonId)}
Back to Course />
</Link>
<h1 className="mt-2 text-3xl text-[#222b39] md:text-5xl">Course Content</h1>
</div>
<div className="min-w-[240px]">
<ProgressBar value={progress} label={`${progress}% complete`} />
</div>
</div>
</header>
<section className="space-y-3">
{course.lessons.map((lesson, index) => (
<div key={lesson.id} className="space-y-1">
<LessonRow
index={index}
isActive={lesson.id === selectedLesson?.id}
isLocked={isLocked(lesson)}
lesson={lesson}
onSelect={() => onSelectLesson(lesson)}
/>
{completionSet.has(lesson.id) ? (
<p className="pl-2 text-sm font-medium text-[#2f9d73]">Completed</p>
) : null}
</div>
))}
</section>
<section className="acve-panel space-y-4 p-6">
<div className="flex items-start justify-between gap-4">
<div>
<h2 className="text-2xl text-[#222b39] md:text-4xl">{selectedLesson.title}</h2>
<p className="mt-1 text-base text-slate-600">
{selectedLesson.type} | {selectedLesson.minutes} min
</p>
</div>
<button
className="acve-button-primary px-4 py-2 text-sm font-semibold hover:brightness-105"
onClick={onMarkComplete}
type="button"
>
Mark complete
</button>
</div>
{lessonContent(selectedLesson)}
</section>
</div>
); );
} }

View File

@@ -0,0 +1,47 @@
import Link from "next/link";
import { requireUser } from "@/lib/auth/requireUser";
export default async function OrgDashboardPage() {
await requireUser();
return (
<div className="space-y-6">
<header className="acve-panel p-6">
<h1 className="text-3xl font-bold text-slate-900">Organization Dashboard (Placeholder)</h1>
<p className="mt-2 text-slate-600">
Org admin tools are frontend placeholders for seat management, usage analytics, and assignment flows.
</p>
<p className="mt-3 inline-flex rounded-md border border-amber-300 bg-amber-50 px-3 py-1 text-sm font-semibold text-amber-900">
Org admin only (access model pending backend)
</p>
</header>
<section className="grid gap-4 md:grid-cols-3">
<article className="acve-panel p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Seats</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">12 / 20 used</p>
</article>
<article className="acve-panel p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Active learners</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">9</p>
</article>
<article className="acve-panel p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Courses assigned</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">4</p>
</article>
</section>
<section className="acve-panel p-6">
<h2 className="text-xl font-semibold text-slate-900">Assignment Queue (Placeholder)</h2>
<ul className="mt-3 space-y-2 text-sm text-slate-700">
<li className="rounded-md border border-slate-200 px-3 py-2">Assign &quot;Contract Analysis Practice&quot; to Team A (disabled)</li>
<li className="rounded-md border border-slate-200 px-3 py-2">Invite 3 learners to &quot;Legal English Foundations&quot; (disabled)</li>
<li className="rounded-md border border-slate-200 px-3 py-2">Export monthly progress report (disabled)</li>
</ul>
<Link className="mt-4 inline-flex rounded-md border border-slate-300 px-3 py-2 text-sm hover:bg-slate-50" href="/">
Back to home
</Link>
</section>
</div>
);
}

194
app/(protected)/practice/[slug]/page.tsx Normal file → Executable file
View File

@@ -1,19 +1,49 @@
"use client"; "use client";
import { useState } from "react"; import { useEffect, useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import ProgressBar from "@/components/ProgressBar"; import ProgressBar from "@/components/ProgressBar";
import { getPracticeBySlug, mockPracticeModules } from "@/lib/data/mockPractice"; import { getPracticeBySlug, mockPracticeModules } from "@/lib/data/mockPractice";
const attemptsKey = (slug: string) => `acve.practice-attempts.${slug}`;
type AttemptRecord = {
completedAt: string;
score: number;
total: number;
};
export default function PracticeExercisePage() { export default function PracticeExercisePage() {
const params = useParams<{ slug: string }>(); const params = useParams<{ slug: string }>();
const practiceModule = getPracticeBySlug(params.slug); const practiceModule = getPracticeBySlug(params.slug);
const [started, setStarted] = useState(false);
const [index, setIndex] = useState(0); const [index, setIndex] = useState(0);
const [score, setScore] = useState(0); const [score, setScore] = useState(0);
const [finished, setFinished] = useState(false); const [finished, setFinished] = useState(false);
const [selected, setSelected] = useState<number | null>(null); const [selected, setSelected] = useState<number | null>(null);
const [attempts, setAttempts] = useState<AttemptRecord[]>([]);
const loadAttempts = () => {
if (!practiceModule) return;
if (typeof window === "undefined") return;
const raw = window.localStorage.getItem(attemptsKey(practiceModule.slug));
if (!raw) {
setAttempts([]);
return;
}
try {
setAttempts(JSON.parse(raw) as AttemptRecord[]);
} catch {
setAttempts([]);
}
};
useEffect(() => {
loadAttempts();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [practiceModule?.slug]);
if (!practiceModule) { if (!practiceModule) {
return ( return (
@@ -50,6 +80,20 @@ export default function PracticeExercisePage() {
const next = () => { const next = () => {
if (index + 1 >= total) { if (index + 1 >= total) {
if (typeof window !== "undefined") {
const raw = window.localStorage.getItem(attemptsKey(practiceModule.slug));
const parsed = raw ? ((JSON.parse(raw) as AttemptRecord[]) ?? []) : [];
const nextAttempts = [
{
completedAt: new Date().toISOString(),
score,
total,
},
...parsed,
].slice(0, 5);
window.localStorage.setItem(attemptsKey(practiceModule.slug), JSON.stringify(nextAttempts));
setAttempts(nextAttempts);
}
setFinished(true); setFinished(true);
return; return;
} }
@@ -58,31 +102,120 @@ export default function PracticeExercisePage() {
}; };
const restart = () => { const restart = () => {
setStarted(true);
setIndex(0); setIndex(0);
setScore(0); setScore(0);
setSelected(null); setSelected(null);
setFinished(false); setFinished(false);
}; };
const start = () => {
setStarted(true);
setFinished(false);
setIndex(0);
setScore(0);
setSelected(null);
};
if (finished) { if (finished) {
return ( return (
<div className="mx-auto max-w-3xl rounded-2xl border border-slate-300 bg-white p-8 text-center shadow-sm"> <div className="acve-page">
<h1 className="acve-heading text-5xl">Exercise complete</h1> <section className="acve-panel p-6 text-center md:p-8">
<p className="mt-2 text-3xl text-slate-700"> <p className="acve-pill mx-auto mb-3 w-fit">Practice Results</p>
Final score: {score}/{total} <h1 className="text-3xl font-semibold text-[#222a38] md:text-4xl">Exercise complete</h1>
</p> <p className="mt-2 text-xl text-slate-700 md:text-2xl">
<button className="acve-button-primary mt-6 px-6 py-2 text-lg font-semibold hover:brightness-105" onClick={restart} type="button"> Final score: {score}/{total}
Restart </p>
</button> <div className="mt-5 flex flex-wrap items-center justify-center gap-2">
<button className="acve-button-primary px-5 py-2 text-sm font-semibold hover:brightness-105" onClick={restart} type="button">
Retake quiz
</button>
<button className="rounded-md border border-slate-300 px-5 py-2 text-sm font-semibold text-slate-700" type="button">
Review answers (placeholder)
</button>
<Link className="rounded-md border border-slate-300 px-5 py-2 text-sm font-semibold text-slate-700" href="/practice">
Back to modules
</Link>
</div>
</section>
<section className="acve-panel p-4">
<h2 className="text-base font-semibold text-slate-800">Attempt History (Mock)</h2>
{attempts.length === 0 ? (
<p className="mt-2 text-sm text-slate-600">No attempts recorded yet.</p>
) : (
<ul className="mt-2 space-y-2">
{attempts.map((attempt) => (
<li key={attempt.completedAt} className="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
Score {attempt.score}/{attempt.total} on {new Date(attempt.completedAt).toLocaleString()}
</li>
))}
</ul>
)}
</section>
</div>
);
}
if (!started) {
return (
<div className="acve-page">
<section className="acve-panel acve-section-base">
<p className="acve-pill mb-3 w-fit">Practice Session</p>
<h1 className="text-3xl font-semibold leading-tight text-[#222a38] md:text-4xl">{practiceModule.title}</h1>
<p className="mt-2 max-w-3xl text-base leading-relaxed text-slate-600">{practiceModule.description}</p>
<div className="mt-4 grid gap-3 sm:grid-cols-3">
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Questions</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">{total}</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Estimated time</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">{Math.max(3, total * 2)} min</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Difficulty</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">Intermediate</p>
</div>
</div>
<div className="mt-5 flex flex-wrap items-center gap-2">
<button className="acve-button-primary px-5 py-2 text-sm font-semibold hover:brightness-105" onClick={start} type="button">
Start practice
</button>
<Link className="rounded-md border border-slate-300 px-5 py-2 text-sm font-semibold text-slate-700" href="/practice">
Back to modules
</Link>
</div>
</section>
<section className="acve-panel p-4">
<h2 className="text-base font-semibold text-slate-800">Attempt History (Mock)</h2>
{attempts.length === 0 ? (
<p className="mt-2 text-sm text-slate-600">No attempts recorded yet for this module.</p>
) : (
<ul className="mt-2 space-y-2">
{attempts.map((attempt) => (
<li key={attempt.completedAt} className="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
Score {attempt.score}/{attempt.total} on {new Date(attempt.completedAt).toLocaleString()}
</li>
))}
</ul>
)}
</section>
</div> </div>
); );
} }
return ( return (
<div className="space-y-6"> <div className="acve-page">
<section className="text-center"> <section className="acve-panel p-4">
<p className="acve-pill mx-auto mb-4 w-fit">Practice and Exercises</p> <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
<h1 className="acve-heading text-4xl md:text-6xl">Master Your Skills</h1> <p className="text-base font-semibold text-slate-700">
{practiceModule.title} | Question {index + 1} / {total}
</p>
<p className="text-base font-semibold text-[#222a38]">Score: {score}/{total}</p>
</div>
<ProgressBar value={progress} />
</section> </section>
<section className="grid gap-4 md:grid-cols-3"> <section className="grid gap-4 md:grid-cols-3">
@@ -95,28 +228,33 @@ export default function PracticeExercisePage() {
isActive ? "border-brand bg-white shadow-sm" : "border-slate-300 bg-white" isActive ? "border-brand bg-white shadow-sm" : "border-slate-300 bg-white"
}`} }`}
> >
<div className="mb-2 text-3xl text-brand md:text-4xl">{moduleIndex === 0 ? "A/" : moduleIndex === 1 ? "[]" : "O"}</div> <div className="mb-2 text-3xl text-brand">{moduleIndex === 0 ? "A/" : moduleIndex === 1 ? "[]" : "O"}</div>
<h2 className="text-2xl text-[#222a38] md:text-4xl">{module.title}</h2> <h2 className="text-xl text-[#222a38]">{module.title}</h2>
<p className="mt-2 text-lg text-slate-600 md:text-2xl">{module.description}</p> <p className="mt-2 text-sm text-slate-600">{module.description}</p>
</div> </div>
); );
})} })}
</section> </section>
<section className="acve-panel p-4"> <section className="acve-panel p-4">
<div className="mb-3 flex items-center justify-between gap-4"> <h2 className="text-lg font-semibold text-slate-800">Attempt History (Mock)</h2>
<p className="text-xl font-semibold text-slate-700"> {attempts.length === 0 ? (
Question {index + 1} / {total} <p className="mt-2 text-sm text-slate-600">No attempts recorded yet.</p>
</p> ) : (
<p className="text-xl font-semibold text-[#222a38] md:text-2xl">Score: {score}/{total}</p> <ul className="mt-2 space-y-2">
</div> {attempts.map((attempt) => (
<ProgressBar value={progress} /> <li key={attempt.completedAt} className="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
Score {attempt.score}/{attempt.total} on {new Date(attempt.completedAt).toLocaleString()}
</li>
))}
</ul>
)}
</section> </section>
<section className="acve-panel p-6"> <section className="acve-panel p-6">
<div className="rounded-2xl bg-[#f6f6f8] px-6 py-10 text-center"> <div className="rounded-2xl bg-[#f6f6f8] px-6 py-8 text-center">
<p className="text-lg text-slate-500 md:text-2xl">Spanish Term</p> <p className="text-sm font-semibold uppercase tracking-wide text-slate-500">Prompt</p>
<h2 className="acve-heading mt-2 text-3xl md:text-6xl">{current.prompt.replace("Spanish term: ", "")}</h2> <h2 className="mt-2 text-3xl font-semibold text-[#222a38] md:text-4xl">{current.prompt.replace("Spanish term: ", "")}</h2>
</div> </div>
<div className="mt-6 grid gap-3"> <div className="mt-6 grid gap-3">
@@ -135,7 +273,7 @@ export default function PracticeExercisePage() {
return ( return (
<button <button
key={choice} key={choice}
className={`rounded-xl border px-4 py-3 text-left text-base text-slate-800 md:text-xl ${stateClass}`} className={`rounded-xl border px-4 py-3 text-left text-base text-slate-800 ${stateClass}`}
onClick={() => pick(choiceIndex)} onClick={() => pick(choiceIndex)}
type="button" type="button"
> >
@@ -146,7 +284,7 @@ export default function PracticeExercisePage() {
</div> </div>
<button <button
className="acve-button-primary mt-6 px-6 py-2 text-lg font-semibold hover:brightness-105 disabled:opacity-50" className="acve-button-primary mt-6 px-6 py-2 text-sm font-semibold hover:brightness-105 disabled:opacity-50"
disabled={selected === null} disabled={selected === null}
onClick={next} onClick={next}
type="button" type="button"

View File

@@ -0,0 +1,386 @@
"use server";
import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import { z } from "zod";
import { revalidatePath } from "next/cache";
import { ContentStatus, Prisma, ProficiencyLevel } from "@prisma/client";
// --- VALIDATION SCHEMAS (Zod) ---
const createCourseSchema = z.object({
title: z.string().min(3, "El título debe tener al menos 3 caracteres"),
});
// --- ACTIONS ---
/**
* 1. LIST COURSES
* Used by: app/(protected)/teacher/page.tsx (Dashboard)
*/
export async function getTeacherCourses() {
const user = await requireTeacher();
if (!user) {
return { success: false, error: "No autorizado" };
}
try {
const courses = await db.course.findMany({
where: {
authorId: user.id,
},
orderBy: {
updatedAt: "desc",
},
select: {
id: true,
title: true,
slug: true,
price: true,
status: true,
level: true,
_count: {
select: {
modules: true,
enrollments: true,
}
}
}
});
return { success: true, data: courses };
} catch (error) {
console.error("Error fetching courses:", error);
return { success: false, error: "Error al cargar los cursos" };
}
}
/**
* 2. CREATE COURSE (Draft) */
export async function createCourse(formData: FormData) {
const user = await requireTeacher();
if (!user) {
return { success: false, error: "No autorizado" };
}
// 1. Extract & Validate
const rawTitle = formData.get("title");
const validated = createCourseSchema.safeParse({ title: rawTitle });
if (!validated.success) {
return { success: false, error: validated.error.flatten().fieldErrors.title?.[0] || "Error en el título" };
}
const title = validated.data.title;
// 2. Generate basic slug
const slug = `${title.toLowerCase().replace(/ /g, "-").replace(/[^\w-]/g, "")}-${Math.floor(Math.random() * 10000)}`;
try {
// 3. Create DB Record
const course = await db.course.create({
data: {
title: title,
slug: slug,
authorId: user.id,
description: "Descripción pendiente...",
status: "DRAFT",
},
});
// 4. Revalidate & Return
revalidatePath("/teacher/courses");
return { success: true, data: course };
} catch (error) {
console.error("Create course error:", error);
return { success: false, error: "No se pudo crear el curso." };
}
}
/**
* 3. DELETE COURSE */
export async function deleteCourse(courseId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "No autorizado" };
try {
const course = await db.course.findUnique({
where: { id: courseId },
select: { authorId: true }
});
if (!course || course.authorId !== user.id) {
return { success: false, error: "No tienes permiso para eliminar este curso." };
}
await db.course.delete({
where: { id: courseId },
});
revalidatePath("/teacher/courses");
return { success: true, data: "Curso eliminado" };
} catch {
return { success: false, error: "Error al eliminar el curso" };
}
}
export async function updateCourse(courseId: string, courseSlug: string, formData: FormData) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
const title = formData.get("title") as string;
const summary = formData.get("summary") as string;
// Direct cast is okay if you trust the select/input values
const level = formData.get("level") as ProficiencyLevel;
const status = formData.get("status") as ContentStatus;
const price = parseFloat(formData.get("price") as string) || 0;
await db.course.update({
where: { id: courseId, authorId: user.id },
data: {
title,
description: summary,
level,
status,
price,
},
});
// Revalidate both the list and the editor (edit route uses slug, not id)
revalidatePath("/teacher/courses");
revalidatePath(`/teacher/courses/${courseSlug}/edit`, "page");
return { success: true };
} catch {
return { success: false, error: "Failed to update" };
}
}
export async function updateLesson(lessonId: string, data: {
title?: string;
description?: Prisma.InputJsonValue | null;
videoUrl?: string;
isPublished?: boolean; // optional: for later
}) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
const updateData: Prisma.LessonUpdateInput = { updatedAt: new Date() };
if (data.title !== undefined) updateData.title = data.title;
if (data.description !== undefined) updateData.description = data.description === null ? Prisma.JsonNull : data.description;
if (data.videoUrl !== undefined) updateData.videoUrl = data.videoUrl;
await db.lesson.update({
where: { id: lessonId },
data: updateData,
});
// 2. Revalidate to show changes immediately
revalidatePath("/teacher/courses");
return { success: true };
} catch (error) {
console.error("Update Lesson Error:", error);
return { success: false, error: "Failed to update lesson" };
}
}
export async function createModule(courseId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
// Find the highest orderIndex so we can put the new one at the end
const lastModule = await db.module.findFirst({
where: { courseId },
orderBy: { orderIndex: "desc" },
});
const newOrder = lastModule ? lastModule.orderIndex + 1 : 0;
await db.module.create({
data: {
courseId,
title: "Nuevo Módulo", // Default title
orderIndex: newOrder,
},
});
revalidatePath(`/teacher/courses/${courseId}/edit`, "page");
return { success: true };
} catch (error) {
console.error("Create Module Error:", error);
return { success: false, error: "Failed to create module" };
}
}
// 2. CREATE LESSON
export async function createLesson(moduleId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
// Find the highest orderIndex for lessons in this module
const lastLesson = await db.lesson.findFirst({
where: { moduleId },
orderBy: { orderIndex: "desc" },
});
const newOrder = lastLesson ? lastLesson.orderIndex + 1 : 0;
// Create the lesson with default values
const lesson = await db.lesson.create({
data: {
moduleId,
title: "Nueva Lección",
orderIndex: newOrder,
estimatedDuration: 0,
version: 1,
// The type field is required in your schema (based on previous context)
// If you have a 'type' enum, set a default like 'VIDEO' or 'TEXT'
// type: "VIDEO",
},
});
revalidatePath(`/teacher/courses/${moduleId}/edit`, "page");
return { success: true, lessonId: lesson.id };
} catch (error) {
console.error("Create Lesson Error:", error);
return { success: false, error: "Failed to create lesson" };
}
}
/**
* DELETE MODULE
* Also deletes all lessons inside it due to Prisma cascade or manual cleanup
*/
export async function deleteModule(moduleId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
await db.module.delete({
where: {
id: moduleId,
course: { authorId: user.id } // Security: ownership check
},
});
revalidatePath("/teacher/courses");
return { success: true };
} catch {
return { success: false, error: "No se pudo eliminar el módulo" };
}
}
/**
* DELETE LESSON
*/
export async function deleteLesson(lessonId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
await db.lesson.delete({
where: {
id: lessonId,
module: { course: { authorId: user.id } } // Deep ownership check
},
});
revalidatePath("/teacher/courses");
return { success: true };
} catch {
return { success: false, error: "No se pudo eliminar la lección" };
}
}
export async function reorderModules(moduleId: string, direction: 'up' | 'down') {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
const currentModule = await db.module.findUnique({
where: { id: moduleId },
include: { course: true }
});
if (!currentModule || currentModule.course.authorId !== user.id) {
return { success: false, error: "Module not found" };
}
const siblingModule = await db.module.findFirst({
where: {
courseId: currentModule.courseId,
orderIndex: direction === 'up'
? { lt: currentModule.orderIndex }
: { gt: currentModule.orderIndex }
},
orderBy: { orderIndex: direction === 'up' ? 'desc' : 'asc' }
});
if (!siblingModule) return { success: true }; // Already at the top/bottom
// Swap orderIndex values
await db.$transaction([
db.module.update({
where: { id: currentModule.id },
data: { orderIndex: siblingModule.orderIndex }
}),
db.module.update({
where: { id: siblingModule.id },
data: { orderIndex: currentModule.orderIndex }
})
]);
revalidatePath(`/teacher/courses/${currentModule.course.slug}/edit`, "page");
return { success: true };
}
/**
* Reorder lessons within the same module (swap orderIndex with sibling)
*/
export async function reorderLessons(lessonId: string, direction: "up" | "down") {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
const currentLesson = await db.lesson.findUnique({
where: { id: lessonId },
include: { module: { include: { course: true } } },
});
if (!currentLesson || currentLesson.module.course.authorId !== user.id) {
return { success: false, error: "Lesson not found" };
}
const siblingLesson = await db.lesson.findFirst({
where: {
moduleId: currentLesson.moduleId,
orderIndex:
direction === "up"
? { lt: currentLesson.orderIndex }
: { gt: currentLesson.orderIndex },
},
orderBy: { orderIndex: direction === "up" ? "desc" : "asc" },
});
if (!siblingLesson) return { success: true }; // Already at top/bottom
await db.$transaction([
db.lesson.update({
where: { id: currentLesson.id },
data: { orderIndex: siblingLesson.orderIndex },
}),
db.lesson.update({
where: { id: siblingLesson.id },
data: { orderIndex: currentLesson.orderIndex },
}),
]);
revalidatePath(`/teacher/courses/${currentLesson.module.course.slug}/edit`, "page");
return { success: true };
}

42
app/(protected)/teacher/courses/[slug]/edit/page.tsx Normal file → Executable file
View File

@@ -1,13 +1,41 @@
import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher"; import { requireTeacher } from "@/lib/auth/requireTeacher";
import { notFound, redirect } from "next/navigation";
import TeacherEditCourseForm from "@/components/teacher/TeacherEditCourseForm"; import TeacherEditCourseForm from "@/components/teacher/TeacherEditCourseForm";
type TeacherEditCoursePageProps = { export default async function CourseEditPage({ params }: { params: Promise<{ slug: string }> }) {
params: Promise<{ slug: string }>; const user = await requireTeacher();
}; if (!user) redirect("/auth/login");
export default async function TeacherEditCoursePage({ params }: TeacherEditCoursePageProps) {
await requireTeacher();
const { slug } = await params; const { slug } = await params;
return <TeacherEditCourseForm slug={slug} />; // Fetch Course + Modules + Lessons
} const course = await db.course.findUnique({
where: { slug: slug },
include: {
modules: {
orderBy: { orderIndex: "asc" },
include: {
lessons: {
orderBy: { orderIndex: "asc" },
},
},
},
},
});
if (!course) notFound();
// Security Check
if (course.authorId !== user.id && user.role !== "SUPER_ADMIN") {
return <div>No autorizado</div>;
}
// Transform Decimal to number for the UI component
const courseData = {
...course,
price: course.price.toNumber(),
};
return <TeacherEditCourseForm course={courseData} />;
}

View File

@@ -0,0 +1,120 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { updateLesson } from "@/app/(protected)/teacher/actions";
import VideoUpload from "@/components/teacher/VideoUpload"; // The component you created earlier
interface LessonEditorFormProps {
lesson: {
id: string;
title: string;
description?: string | null;
videoUrl?: string | null;
};
courseSlug: string;
}
export function LessonEditorForm({ lesson, courseSlug }: LessonEditorFormProps) {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [title, setTitle] = useState(lesson.title);
const [description, setDescription] = useState(lesson.description ?? "");
// 1. Auto-save Video URL when upload finishes
const handleVideoUploaded = async (url: string) => {
toast.loading("Guardando video...");
const res = await updateLesson(lesson.id, { videoUrl: url });
if (res.success) {
toast.dismiss();
toast.success("Video guardado correctamente");
router.refresh(); // Update the UI to show the new video player
} else {
toast.error("Error al guardar el video en la base de datos");
}
};
// 2. Save Text Changes (Title/Desc)
const handleSave = async () => {
setLoading(true);
const res = await updateLesson(lesson.id, { title, description });
if (res.success) {
toast.success("Cambios guardados");
router.refresh();
} else {
toast.error("Error al guardar cambios");
}
setLoading(false);
};
return (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* LEFT: Video & Content */}
<div className="lg:col-span-2 space-y-6">
{/* Video Upload Section */}
<section className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
<div className="p-6 border-b border-slate-100">
<h2 className="font-semibold text-slate-900">Video del Curso</h2>
<p className="text-sm text-slate-500">Sube el video principal de esta lección.</p>
</div>
<div className="p-6 bg-slate-50/50">
<VideoUpload
lessonId={lesson.id}
currentVideoUrl={lesson.videoUrl}
onUploadComplete={handleVideoUploaded}
/>
</div>
</section>
{/* Text Content */}
<section className="bg-white rounded-xl border border-slate-200 shadow-sm p-6 space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Título de la Lección</label>
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Descripción / Notas</label>
<textarea
rows={6}
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
placeholder="Escribe aquí el contenido de la lección..."
/>
</div>
</section>
</div>
{/* RIGHT: Settings / Actions */}
<div className="space-y-6">
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
<h3 className="font-semibold text-slate-900 mb-4">Acciones</h3>
<button
onClick={handleSave}
disabled={loading}
className="w-full bg-black text-white rounded-lg py-2.5 font-medium hover:bg-slate-800 disabled:opacity-50 transition-colors"
>
{loading ? "Guardando..." : "Guardar Cambios"}
</button>
<button
onClick={() => router.push(`/teacher/courses/${courseSlug}/edit`)}
className="w-full mt-3 bg-white border border-slate-300 text-slate-700 rounded-lg py-2.5 font-medium hover:bg-slate-50 transition-colors"
>
Volver al Curso
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,73 @@
import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import { redirect, notFound } from "next/navigation";
import Link from "next/link";
import { LessonEditorForm } from "./LessonEditorForm";
function getText(value: unknown): string {
if (!value) return "";
if (typeof value === "string") return value;
if (typeof value === "object") {
const text = value as Record<string, string>;
return text.es || text.en || "";
}
return "";
}
interface PageProps {
params: Promise<{ slug: string; lessonId: string }>;
}
export default async function LessonPage({ params }: PageProps) {
const user = await requireTeacher();
if (!user) redirect("/auth/login");
const { slug, lessonId } = await params;
// 1. Fetch Lesson + Course Info (for breadcrumbs)
const lesson = await db.lesson.findUnique({
where: { id: lessonId },
include: {
module: {
include: {
course: {
select: { title: true, slug: true, authorId: true }
}
}
}
}
});
// 2. Security & Null Checks
if (!lesson) notFound();
if (lesson.module.course.authorId !== user.id) redirect("/teacher");
return (
<div className="max-w-4xl mx-auto p-6">
{/* Breadcrumbs */}
<div className="flex items-center gap-2 text-sm text-slate-500 mb-6">
<Link href="/teacher" className="hover:text-black">Cursos</Link>
<span>/</span>
<Link href={`/teacher/courses/${slug}/edit`} className="hover:text-black">
{getText(lesson.module.course.title)}
</Link>
<span>/</span>
<span className="text-slate-900 font-medium">{getText(lesson.title)}</span>
</div>
<div className="flex items-center justify-between mb-8">
<h1 className="text-3xl font-bold text-slate-900">Editar Lección</h1>
</div>
{/* The Client Form */}
<LessonEditorForm
lesson={{
...lesson,
title: getText(lesson.title),
description: getText(lesson.description),
}}
courseSlug={slug}
/>
</div>
);
}

View File

View File

@@ -0,0 +1,14 @@
import { redirect } from "next/navigation";
interface PageProps {
params: Promise<{ slug: string }>;
}
export default async function CourseDashboardPage({ params }: PageProps) {
// 1. Get the slug from the URL
const { slug } = await params;
// 2. Automatically redirect to the Edit page
// This saves us from building a separate "Stats" page for now
redirect(`/teacher/courses/${slug}/edit`);
}

0
app/(protected)/teacher/courses/new/page.tsx Normal file → Executable file
View File

108
app/(protected)/teacher/page.tsx Normal file → Executable file
View File

@@ -1,7 +1,107 @@
export const dynamic = 'force-dynamic';
import { getTeacherCourses } from "./actions"; // Import the server action
import Link from "next/link";
import { redirect } from "next/navigation";
import { requireTeacher } from "@/lib/auth/requireTeacher"; import { requireTeacher } from "@/lib/auth/requireTeacher";
import TeacherDashboardClient from "@/components/teacher/TeacherDashboardClient"; import { logger } from "@/lib/logger";
export default async function TeacherDashboardPage() { export default async function TeacherDashboardPage() {
await requireTeacher(); try {
return <TeacherDashboardClient />; // 1. Auth Check (Double protection)
} // We log the attempt
logger.info("Accessing Teacher Dashboard");
// We wrap requireTeacher to catch potential DB/Supabase connection errors
let user;
try {
user = await requireTeacher();
} catch (authError) {
logger.error("requireTeacher failed with exception", authError);
throw authError;
}
if (!user) {
logger.info("User not authorized as teacher, redirecting");
redirect("/login");
}
// 2. Fetch Data
const { success, data: courses, error } = await getTeacherCourses();
return (
<div className="p-6 max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-2xl font-bold tracking-tight">Panel del Profesor</h1>
<p className="text-gray-500">Gestiona tus cursos y contenidos.</p>
</div>
<Link
href="/teacher/courses/new"
className="bg-black text-white px-4 py-2 rounded-md hover:bg-gray-800 transition-colors"
>
+ Nuevo Curso
</Link>
</div>
{/* Error State */}
{!success && (
<div className="bg-red-50 text-red-600 p-4 rounded-md border border-red-100">
Error: {error}
</div>
)}
{/* List State */}
{success && courses && (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{courses.length === 0 ? (
// Empty State
<div className="col-span-full text-center py-12 border-2 border-dashed border-gray-200 rounded-lg">
<h3 className="mt-2 text-sm font-semibold text-gray-900">No hay cursos</h3>
<p className="mt-1 text-sm text-gray-500">Empieza creando tu primer curso de Inglés Jurídico.</p>
</div>
) : (
// Course Cards
courses.map((course) => (
<Link
key={course.id}
href={`/teacher/courses/${course.slug}`}
className="block group"
>
<div className="border border-gray-200 rounded-lg p-5 hover:border-black transition-all bg-white shadow-sm hover:shadow-md">
<div className="flex justify-between items-start mb-4">
<span className={`text-xs font-medium px-2 py-1 rounded-full ${course.status === 'PUBLISHED' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
}`}>
{course.status === 'PUBLISHED' ? 'Publicado' : 'Borrador'}
</span>
<span className="text-sm font-bold text-gray-900">
${course.price.toString()}
</span>
</div>
<h3 className="font-semibold text-lg text-gray-900 group-hover:text-blue-600 mb-1">
{course.title as string}
</h3>
<p className="text-sm text-gray-500 mb-4">
{course.level}
</p>
<div className="flex items-center gap-4 text-xs text-gray-500 border-t pt-4">
<span>📚 {course._count.modules} Módulos</span>
<span>👥 {course._count.enrollments} Alumnos</span>
</div>
</div>
</Link>
))
)}
</div>
)}
</div>
);
} catch (error) {
logger.error("Critical error in TeacherDashboardPage", error);
throw error;
}
}

View File

@@ -0,0 +1,7 @@
import { requireTeacher } from "@/lib/auth/requireTeacher";
import TeacherUploadsLibraryClient from "@/components/teacher/TeacherUploadsLibraryClient";
export default async function TeacherUploadsPage() {
await requireTeacher();
return <TeacherUploadsLibraryClient />;
}

18
app/(public)/assistant/page.tsx Normal file → Executable file
View File

@@ -2,9 +2,21 @@ import AssistantDrawer from "@/components/AssistantDrawer";
export default function AssistantPage() { export default function AssistantPage() {
return ( return (
<div className="space-y-4"> <div className="acve-page">
<h1 className="acve-heading text-4xl md:text-6xl">AI Assistant (Demo)</h1> <section className="acve-panel acve-section-base">
<p className="text-lg text-slate-600 md:text-2xl">This page renders the same assistant UI as the global drawer.</p> <p className="acve-pill mb-3 w-fit">AI Assistant (Demo)</p>
<h1 className="text-4xl font-semibold leading-tight text-[#222a38] md:text-5xl">Ask legal English questions in context</h1>
<p className="mt-2 max-w-3xl text-base leading-relaxed text-slate-600 md:text-lg">
This is a product preview. Responses are mock while backend retrieval and tutor logic are being integrated.
</p>
</section>
<section className="grid gap-3 md:grid-cols-3">
<article className="acve-panel p-4 text-sm text-slate-700">Use for clause terms, case-study guidance, and writing clarity tips.</article>
<article className="acve-panel p-4 text-sm text-slate-700">For legal advice or final authority, always verify with qualified counsel.</article>
<article className="acve-panel p-4 text-sm text-slate-700">Conversation persistence is placeholder-only in this MVP stage.</article>
</section>
<AssistantDrawer mode="page" /> <AssistantDrawer mode="page" />
</div> </div>
); );

61
app/(public)/case-studies/[slug]/page.tsx Normal file → Executable file
View File

@@ -3,6 +3,13 @@
import Link from "next/link"; import Link from "next/link";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import { getCaseStudyBySlug } from "@/lib/data/mockCaseStudies"; import { getCaseStudyBySlug } from "@/lib/data/mockCaseStudies";
import type { CourseLevel } from "@/types/course";
const levelBadgeClass = (level: CourseLevel) => {
if (level === "Beginner") return "bg-emerald-100 text-emerald-900 border border-emerald-200";
if (level === "Intermediate") return "bg-sky-100 text-sky-900 border border-sky-200";
return "bg-violet-100 text-violet-900 border border-violet-200";
};
export default function CaseStudyDetailPage() { export default function CaseStudyDetailPage() {
const params = useParams<{ slug: string }>(); const params = useParams<{ slug: string }>();
@@ -21,35 +28,43 @@ export default function CaseStudyDetailPage() {
} }
return ( return (
<article className="acve-panel space-y-6 p-6"> <article className="acve-page">
<header className="space-y-2"> <header className="acve-panel acve-section-base">
<p className="text-lg text-slate-500"> <p className="text-sm font-semibold uppercase tracking-wide text-slate-500">{caseStudy.citation} ({caseStudy.year})</p>
{caseStudy.citation} ({caseStudy.year}) <h1 className="mt-2 text-4xl font-semibold leading-tight text-[#1f2b3a] md:text-5xl">{caseStudy.title}</h1>
</p> <div className="mt-3 flex flex-wrap items-center gap-2">
<h1 className="acve-heading text-3xl md:text-6xl">{caseStudy.title}</h1> <span className="rounded-full border border-slate-300 bg-white px-3 py-1 text-xs font-semibold text-slate-700">Topic: {caseStudy.topic}</span>
<p className="text-base text-slate-600 md:text-2xl"> <span className={`rounded-full px-3 py-1 text-xs font-semibold ${levelBadgeClass(caseStudy.level)}`}>Level: {caseStudy.level}</span>
Topic: {caseStudy.topic} | Level: {caseStudy.level} </div>
</p>
</header> </header>
<section> <section className="grid gap-4 lg:grid-cols-[1.35fr_0.8fr]">
<h2 className="text-2xl text-[#232b39] md:text-4xl">Summary</h2> <div className="acve-panel p-5">
<p className="mt-2 text-lg leading-relaxed text-slate-700 md:text-3xl">{caseStudy.summary}</p> <h2 className="text-2xl font-semibold text-[#232b39]">Case Summary</h2>
</section> <p className="mt-2 text-base leading-relaxed text-slate-700 md:text-lg">{caseStudy.summary}</p>
<section> <h3 className="mt-5 text-lg font-semibold text-[#232b39]">Reading Guide (Placeholder)</h3>
<h2 className="text-2xl text-[#232b39] md:text-4xl">Key legal terms explained</h2> <ul className="mt-2 space-y-2 text-sm text-slate-700">
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3"> <li className="rounded-lg border border-slate-200 bg-white px-3 py-2">1. Identify the legal issue and the jurisdiction context.</li>
{caseStudy.keyTerms.map((term, index) => ( <li className="rounded-lg border border-slate-200 bg-white px-3 py-2">2. Highlight the key reasoning applied by the court.</li>
<div key={term} className="rounded-xl border-l-4 border-accent bg-[#faf8f8] p-4"> <li className="rounded-lg border border-slate-200 bg-white px-3 py-2">3. Extract practical implications for drafting or litigation.</li>
<p className="text-xl font-semibold text-brand md:text-3xl">{term}</p> </ul>
<p className="mt-1 text-base text-slate-600 md:text-xl">Legal explanation block {index + 1}</p>
</div>
))}
</div> </div>
<aside className="acve-panel p-5">
<h2 className="text-lg font-semibold text-[#232b39]">Key Legal Terms</h2>
<div className="mt-3 space-y-2">
{caseStudy.keyTerms.map((term, index) => (
<div key={term} className="rounded-xl border border-slate-200 bg-[#faf8f8] p-3">
<p className="text-base font-semibold text-brand">{term}</p>
<p className="mt-1 text-sm text-slate-600">Legal explanation block {index + 1}</p>
</div>
))}
</div>
</aside>
</section> </section>
<section className="border-t border-slate-200 pt-5"> <section className="border-t border-slate-200 pt-1">
<Link className="acve-button-secondary inline-flex px-4 py-2 text-sm font-semibold hover:bg-brand-soft" href="/case-studies"> <Link className="acve-button-secondary inline-flex px-4 py-2 text-sm font-semibold hover:bg-brand-soft" href="/case-studies">
Back to Case Library Back to Case Library
</Link> </Link>

82
app/(public)/case-studies/page.tsx Normal file → Executable file
View File

@@ -3,73 +3,91 @@
import Link from "next/link"; import Link from "next/link";
import { useState } from "react"; import { useState } from "react";
import { mockCaseStudies } from "@/lib/data/mockCaseStudies"; import { mockCaseStudies } from "@/lib/data/mockCaseStudies";
import type { CourseLevel } from "@/types/course";
const levelBadgeClass = (level: CourseLevel) => {
if (level === "Beginner") return "bg-emerald-100 text-emerald-900 border border-emerald-200";
if (level === "Intermediate") return "bg-sky-100 text-sky-900 border border-sky-200";
return "bg-violet-100 text-violet-900 border border-violet-200";
};
export default function CaseStudiesPage() { export default function CaseStudiesPage() {
const [activeSlug, setActiveSlug] = useState(mockCaseStudies[0]?.slug ?? ""); const [activeSlug, setActiveSlug] = useState(mockCaseStudies[0]?.slug ?? "");
const activeCase = mockCaseStudies.find((item) => item.slug === activeSlug) ?? mockCaseStudies[0]; const activeCase = mockCaseStudies.find((item) => item.slug === activeSlug) ?? mockCaseStudies[0];
return ( return (
<div className="space-y-7"> <div className="acve-page">
<section className="text-center"> <section className="acve-panel acve-section-base">
<p className="acve-pill mx-auto mb-4 w-fit">Case Studies</p> <div className="flex flex-wrap items-center justify-between gap-4">
<h1 className="acve-heading text-4xl md:text-6xl">Learn from Landmark Cases</h1> <div>
<p className="mx-auto mt-3 max-w-4xl text-lg text-slate-600 md:text-3xl"> <p className="acve-pill mb-3 w-fit">Case Studies</p>
Real English law cases explained with key legal terms and practical insights. <h1 className="text-3xl font-semibold leading-tight text-[#202936] md:text-4xl">Landmark Cases, distilled for learning</h1>
</p> <p className="mt-2 max-w-3xl text-base leading-relaxed text-slate-600 md:text-lg">
Review outcomes, legal terms, and practical context in a cleaner, high-density reading layout.
</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-600">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Library</p>
<p className="mt-1 text-xl font-semibold text-slate-900">{mockCaseStudies.length} cases</p>
</div>
</div>
</section> </section>
<section className="grid gap-5 lg:grid-cols-[0.9fr_1.8fr]"> <section className="grid gap-4 lg:grid-cols-[0.9fr_1.7fr]">
<div className="space-y-3"> <aside className="acve-panel p-3">
<p className="mb-3 px-2 text-xs font-semibold uppercase tracking-wide text-slate-500">Browse Cases</p>
<div className="space-y-2">
{mockCaseStudies.map((caseStudy) => { {mockCaseStudies.map((caseStudy) => {
const isActive = caseStudy.slug === activeCase.slug; const isActive = caseStudy.slug === activeCase.slug;
return ( return (
<button <button
key={caseStudy.slug} key={caseStudy.slug}
className={`w-full rounded-2xl border p-4 text-left transition ${ className={`w-full rounded-xl border p-3 text-left transition ${
isActive ? "border-brand bg-white shadow-sm" : "border-slate-300 bg-white hover:border-slate-400" isActive ? "border-brand bg-white shadow-sm" : "border-slate-200 bg-white hover:border-slate-400"
}`} }`}
onClick={() => setActiveSlug(caseStudy.slug)} onClick={() => setActiveSlug(caseStudy.slug)}
type="button" type="button"
> >
<h2 className="text-xl text-[#232b39] md:text-3xl">{caseStudy.title}</h2> <h2 className="text-lg font-semibold leading-tight text-[#232b39] md:text-xl">{caseStudy.title}</h2>
<p className="mt-1 text-base text-slate-500 md:text-2xl"> <p className="mt-1 text-sm text-slate-500 md:text-base">
[{caseStudy.year}] {caseStudy.citation} [{caseStudy.year}] {caseStudy.citation}
</p> </p>
<div className="mt-3 flex items-center gap-2 text-sm"> <div className="mt-2 flex items-center gap-2 text-xs">
<span className="rounded-full bg-slate-100 px-3 py-1 text-slate-700">{caseStudy.topic}</span> <span className="rounded-full bg-slate-100 px-2 py-1 text-slate-700">{caseStudy.topic}</span>
<span className="rounded-full bg-accent px-3 py-1 font-semibold text-white">{caseStudy.level}</span> <span className={`rounded-full px-2 py-1 font-semibold ${levelBadgeClass(caseStudy.level)}`}>{caseStudy.level}</span>
</div> </div>
</button> </button>
); );
})} })}
</div> </div>
</aside>
<article className="acve-panel p-6"> <article className="acve-panel p-5 md:p-6">
<div className="mb-5 flex flex-wrap items-start justify-between gap-3"> <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div> <div>
<h2 className="text-3xl text-[#202936] md:text-6xl">{activeCase.title}</h2> <h2 className="text-3xl font-semibold leading-tight text-[#202936] md:text-4xl">{activeCase.title}</h2>
<p className="mt-2 text-lg text-slate-500 md:text-3xl"> <p className="mt-2 text-base text-slate-500 md:text-xl">
{activeCase.citation} | {activeCase.year} {activeCase.citation} | {activeCase.year}
</p> </p>
</div> </div>
<div className="space-y-2 text-right text-sm"> <div className="space-y-2 text-right text-xs">
<p className="rounded-full bg-accent px-3 py-1 font-semibold text-white">{activeCase.level}</p> <p className={`rounded-full px-3 py-1 font-semibold ${levelBadgeClass(activeCase.level)}`}>{activeCase.level}</p>
<p className="rounded-full bg-slate-100 px-3 py-1 text-slate-700">{activeCase.topic}</p> <p className="rounded-full bg-slate-100 px-3 py-1 text-slate-700">{activeCase.topic}</p>
</div> </div>
</div> </div>
<section className="border-t border-slate-200 pt-5"> <section className="border-t border-slate-200 pt-4">
<h3 className="text-4xl text-[#232b39]">Case Summary</h3> <h3 className="text-2xl font-semibold text-[#232b39]">Case Summary</h3>
<p className="mt-3 text-lg leading-relaxed text-slate-700 md:text-3xl">{activeCase.summary}</p> <p className="mt-2 text-base leading-relaxed text-slate-700 md:text-lg">{activeCase.summary}</p>
</section> </section>
<section className="mt-6"> <section className="mt-5">
<h3 className="mb-3 text-4xl text-[#232b39]">Key Legal Terms Explained</h3> <h3 className="mb-3 text-2xl font-semibold text-[#232b39]">Key Legal Terms Explained</h3>
<div className="space-y-3"> <div className="grid gap-3 sm:grid-cols-2">
{activeCase.keyTerms.map((term) => ( {activeCase.keyTerms.map((term) => (
<div key={term} className="rounded-xl border-l-4 border-accent bg-[#faf8f8] p-4"> <div key={term} className="rounded-xl border border-slate-200 bg-[#faf8f8] p-4">
<p className="text-xl font-semibold text-brand md:text-3xl">{term}</p> <p className="text-lg font-semibold text-brand">{term}</p>
<p className="mt-1 text-base text-slate-600 md:text-2xl">Term explanation will be expanded in phase 2 content.</p> <p className="mt-1 text-sm text-slate-600">Detailed explanation will expand in phase 2 content.</p>
</div> </div>
))} ))}
</div> </div>

283
app/(public)/courses/[slug]/page.tsx Normal file → Executable file
View File

@@ -1,135 +1,184 @@
"use client";
import Link from "next/link"; import Link from "next/link";
import { useParams } from "next/navigation"; import { notFound } from "next/navigation";
import { useEffect, useState } from "react"; import { db } from "@/lib/prisma";
import ProgressBar from "@/components/ProgressBar"; import { requireUser } from "@/lib/auth/requireUser";
import { getCourseBySlug } from "@/lib/data/courseCatalog";
import { getCourseProgressPercent, progressUpdatedEventName } from "@/lib/progress/localProgress";
import { teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import { supabaseBrowser } from "@/lib/supabase/browser";
import type { Course } from "@/types/course";
export default function CourseDetailPage() { function getText(value: unknown): string {
const params = useParams<{ slug: string }>(); if (!value) return "";
const slug = params.slug; if (typeof value === "string") return value;
const [course, setCourse] = useState<Course | undefined>(() => getCourseBySlug(slug)); if (typeof value === "object") {
const [hasResolvedCourse, setHasResolvedCourse] = useState(false); const record = value as Record<string, unknown>;
if (typeof record.en === "string") return record.en;
const [userId, setUserId] = useState("guest"); if (typeof record.es === "string") return record.es;
const [isAuthed, setIsAuthed] = useState(false);
const [progress, setProgress] = useState(0);
useEffect(() => {
const loadCourse = () => {
setCourse(getCourseBySlug(slug));
setHasResolvedCourse(true);
};
loadCourse();
window.addEventListener(teacherCoursesUpdatedEventName, loadCourse);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, loadCourse);
}, [slug]);
useEffect(() => {
const client = supabaseBrowser();
if (!client) return;
client.auth.getUser().then(({ data }) => {
const nextId = data.user?.id ?? "guest";
setUserId(nextId);
setIsAuthed(Boolean(data.user));
});
const { data } = client.auth.onAuthStateChange((_event, session) => {
setUserId(session?.user?.id ?? "guest");
setIsAuthed(Boolean(session?.user));
});
return () => data.subscription.unsubscribe();
}, []);
useEffect(() => {
if (!course) return;
const load = () => setProgress(getCourseProgressPercent(userId, course.slug, course.lessons.length));
load();
window.addEventListener(progressUpdatedEventName, load);
return () => window.removeEventListener(progressUpdatedEventName, load);
}, [course, userId]);
if (!course && !hasResolvedCourse) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<p className="text-slate-600">Loading course...</p>
</div>
);
} }
return "";
}
if (!course) { const levelLabel = (level: string) => {
return ( if (level === "BEGINNER") return "Beginner";
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm"> if (level === "INTERMEDIATE") return "Intermediate";
<h1 className="text-2xl font-bold text-slate-900">Course not found</h1> if (level === "ADVANCED") return "Advanced";
<p className="mt-2 text-slate-600">The requested course slug does not exist in mock data.</p> return level;
<Link className="mt-4 inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href="/courses"> };
Back to courses
</Link> type PageProps = {
</div> params: Promise<{ slug: string }>;
); };
}
export default async function CourseDetailPage({ params }: PageProps) {
const { slug } = await params;
const course = await db.course.findFirst({
where: { slug, status: "PUBLISHED" },
include: {
author: { select: { fullName: true } },
modules: {
orderBy: { orderIndex: "asc" },
include: {
lessons: {
orderBy: { orderIndex: "asc" },
select: { id: true, title: true, estimatedDuration: true },
},
},
},
_count: { select: { enrollments: true } },
},
});
if (!course) notFound();
const user = await requireUser();
const isAuthed = Boolean(user?.id);
const title = getText(course.title) || "Untitled course";
const summary = getText(course.description) || "";
const lessons = course.modules.flatMap((m) =>
m.lessons.map((l) => ({
id: l.id,
title: getText(l.title) || "Untitled lesson",
minutes: Math.ceil((l.estimatedDuration ?? 0) / 60),
})),
);
const lessonsCount = lessons.length;
const redirect = `/courses/${course.slug}/learn`; const redirect = `/courses/${course.slug}/learn`;
const loginUrl = `/auth/login?redirectTo=${encodeURIComponent(redirect)}`; const loginUrl = `/auth/login?redirectTo=${encodeURIComponent(redirect)}`;
const learningOutcomes = [
"Understand key legal vocabulary in context",
"Apply contract and case analysis patterns",
"Improve professional written legal communication",
];
return ( return (
<div className="grid gap-7 lg:grid-cols-[1.9fr_0.9fr]"> <div className="acve-page">
<section className="pt-1"> <section className="acve-panel overflow-hidden p-0">
<Link className="inline-flex items-center gap-2 text-lg text-slate-600 hover:text-brand md:text-2xl" href="/courses"> <div className="grid gap-0 lg:grid-cols-[1.6fr_0.9fr]">
<span className="text-xl">{"<-"}</span> <div className="acve-section-base">
Back to Courses <Link className="inline-flex items-center gap-2 text-base text-slate-600 hover:text-brand" href="/courses">
</Link> <span>{"<-"}</span>
Back to Courses
</Link>
<div className="mt-6 flex items-center gap-3 text-base text-slate-600 md:text-lg"> <div className="mt-4 flex flex-wrap items-center gap-2 text-sm text-slate-600">
<span className="rounded-full bg-accent px-4 py-1 text-base font-semibold text-white">{course.level}</span> <span className="rounded-full bg-accent px-3 py-1 font-semibold text-white">
<span>Contract Law</span> {levelLabel(course.level)}
</div> </span>
<span className="rounded-full border border-slate-300 bg-white px-3 py-1 font-semibold">
{course.status.toLowerCase()}
</span>
<span className="rounded-full border border-slate-300 bg-white px-3 py-1">
{lessonsCount} lessons
</span>
</div>
<h1 className="acve-heading mt-5 text-4xl leading-tight md:text-7xl">{course.title}</h1> <h1 className="mt-4 text-4xl font-semibold leading-tight text-[#1f2a3a] md:text-5xl">{title}</h1>
<p className="mt-5 max-w-5xl text-xl leading-relaxed text-slate-600 md:text-4xl">{course.summary}</p> <p className="mt-3 max-w-3xl text-base leading-relaxed text-slate-600 md:text-lg">{summary}</p>
<div className="mt-7 flex flex-wrap items-center gap-5 text-lg text-slate-600 md:text-3xl"> <div className="mt-5 grid gap-3 sm:grid-cols-3">
<span className="font-semibold text-slate-800">Rating {course.rating.toFixed(1)}</span> <div className="rounded-xl border border-slate-200 bg-white p-3">
<span>{course.students.toLocaleString()} students</span> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Students</p>
<span>{course.weeks} weeks</span> <p className="mt-1 text-2xl font-semibold text-slate-900">
<span>{course.lessonsCount} lessons</span> {course._count.enrollments.toLocaleString()}
</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Lessons</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">{lessonsCount}</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Instructor</p>
<p className="mt-1 text-lg font-semibold text-slate-900">
{course.author.fullName || "ACVE Team"}
</p>
</div>
</div>
</div>
<aside className="border-t border-slate-200 bg-slate-50/80 p-6 lg:border-l lg:border-t-0">
<h2 className="text-sm font-semibold uppercase tracking-wide text-slate-500">What you will learn</h2>
<ul className="mt-3 space-y-2">
{learningOutcomes.map((item) => (
<li key={item} className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700">
{item}
</li>
))}
</ul>
</aside>
</div> </div>
</section> </section>
<aside className="acve-panel space-y-5 p-7"> <section className="grid gap-5 lg:grid-cols-[1.6fr_0.85fr]">
<h2 className="text-2xl text-slate-700 md:text-4xl">Your Progress</h2> <article className="acve-panel acve-section-base">
<div className="flex items-end justify-between"> <h2 className="text-2xl font-semibold text-slate-900">Course structure preview</h2>
<p className="text-4xl font-semibold text-brand md:text-6xl">{progress}%</p> <div className="mt-4 grid gap-2">
<p className="text-lg text-slate-600 md:text-3xl"> {lessons.slice(0, 5).map((lesson, index) => (
{Math.round((progress / 100) * course.lessonsCount)}/{course.lessonsCount} lessons <div
</p> key={lesson.id}
</div> className="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
<ProgressBar value={progress} /> >
<div className="border-t border-slate-200 pt-5 text-lg text-slate-700 md:text-3xl"> <span className="font-medium text-slate-800">
<p className="mb-1 text-base text-slate-500 md:text-2xl">Instructor</p> Lesson {index + 1}: {lesson.title}
<p className="mb-4 font-semibold text-slate-800">{course.instructor}</p> </span>
<p className="mb-1 text-base text-slate-500 md:text-2xl">Duration</p> <span className="text-slate-500">{lesson.minutes} min</span>
<p className="mb-4 font-semibold text-slate-800">{course.weeks} weeks</p> </div>
<p className="mb-1 text-base text-slate-500 md:text-2xl">Level</p> ))}
<p className="font-semibold text-slate-800">{course.level}</p> {lessons.length === 0 && (
</div> <p className="rounded-lg border border-dashed border-slate-200 bg-slate-50 px-3 py-4 text-sm text-slate-500">
{isAuthed ? ( No lessons yet. Check back soon.
<Link className="acve-button-primary mt-2 inline-flex w-full justify-center px-4 py-3 text-xl font-semibold md:text-2xl hover:brightness-105" href={redirect}> </p>
Start Course )}
</Link> </div>
) : ( </article>
<Link className="acve-button-primary mt-2 inline-flex w-full justify-center px-4 py-3 text-xl font-semibold md:text-2xl hover:brightness-105" href={loginUrl}>
Login to start <aside className="acve-panel space-y-5 p-6">
</Link> <h2 className="text-2xl text-slate-700 md:text-4xl">Course details</h2>
)} <div className="border-t border-slate-200 pt-5 text-lg text-slate-700 md:text-3xl">
</aside> <p className="mb-1 text-base text-slate-500 md:text-2xl">Instructor</p>
<p className="mb-4 font-semibold text-slate-800">{course.author.fullName || "ACVE Team"}</p>
<p className="mb-1 text-base text-slate-500 md:text-2xl">Level</p>
<p className="mb-4 font-semibold text-slate-800">{levelLabel(course.level)}</p>
<p className="mb-1 text-base text-slate-500 md:text-2xl">Lessons</p>
<p className="font-semibold text-slate-800">{lessonsCount}</p>
</div>
{isAuthed ? (
<Link
className="acve-button-primary mt-2 inline-flex w-full justify-center px-4 py-3 text-xl font-semibold md:text-2xl hover:brightness-105"
href={redirect}
>
Start Course
</Link>
) : (
<Link
className="acve-button-primary mt-2 inline-flex w-full justify-center px-4 py-3 text-xl font-semibold md:text-2xl hover:brightness-105"
href={loginUrl}
>
Login to start
</Link>
)}
</aside>
</section>
</div> </div>
); );
} }

178
app/(public)/courses/page.tsx Normal file → Executable file
View File

@@ -1,115 +1,93 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import CourseCard from "@/components/CourseCard"; import CourseCard from "@/components/CourseCard";
import Tabs from "@/components/Tabs"; import { db } from "@/lib/prisma";
import { getAllCourses } from "@/lib/data/courseCatalog";
import {
getCourseProgressPercent,
progressUpdatedEventName,
} from "@/lib/progress/localProgress";
import { teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import { supabaseBrowser } from "@/lib/supabase/browser";
import type { Course, CourseLevel } from "@/types/course";
const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"]; export default async function CoursesPage() {
const courses = await db.course.findMany({
export default function CoursesPage() { where: {
const [activeLevel, setActiveLevel] = useState<CourseLevel>("Beginner"); status: "PUBLISHED",
const [userId, setUserId] = useState("guest"); },
const [progressBySlug, setProgressBySlug] = useState<Record<string, number>>({}); include: {
const [courses, setCourses] = useState<Course[]>(() => getAllCourses()); author: {
select: {
const counts = useMemo( fullName: true,
() =>
levels.reduce(
(acc, level) => {
acc[level] = courses.filter((course) => course.level === level).length;
return acc;
}, },
{} as Record<CourseLevel, number>, },
), modules: {
[courses], select: {
); _count: {
select: {
lessons: true,
},
},
},
},
_count: {
select: {
enrollments: true,
},
},
},
orderBy: {
updatedAt: "desc",
},
});
useEffect(() => { const totalLessons = courses.reduce(
const loadCourses = () => { (total, course) => total + course.modules.reduce((courseTotal, module) => courseTotal + module._count.lessons, 0),
setCourses(getAllCourses()); 0,
};
loadCourses();
window.addEventListener(teacherCoursesUpdatedEventName, loadCourses);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, loadCourses);
}, []);
useEffect(() => {
const client = supabaseBrowser();
if (!client) return;
client.auth.getUser().then(({ data }) => {
setUserId(data.user?.id ?? "guest");
});
const { data } = client.auth.onAuthStateChange((_event, session) => {
setUserId(session?.user?.id ?? "guest");
});
return () => data.subscription.unsubscribe();
}, []);
useEffect(() => {
const load = () => {
const nextProgress: Record<string, number> = {};
for (const course of courses) {
nextProgress[course.slug] = getCourseProgressPercent(userId, course.slug, course.lessons.length);
}
setProgressBySlug(nextProgress);
};
load();
window.addEventListener(progressUpdatedEventName, load);
window.addEventListener(teacherCoursesUpdatedEventName, load);
return () => {
window.removeEventListener(progressUpdatedEventName, load);
window.removeEventListener(teacherCoursesUpdatedEventName, load);
};
}, [courses, userId]);
const filteredCourses = useMemo(
() => courses.filter((course) => course.level === activeLevel),
[activeLevel, courses],
); );
return ( return (
<div className="space-y-8"> <div className="acve-page">
<section className="acve-panel p-5"> <section className="acve-panel overflow-hidden p-0">
<div className="flex flex-wrap items-center gap-4"> <div className="grid gap-0 lg:grid-cols-[1.45fr_0.95fr]">
<Tabs active={activeLevel} onChange={setActiveLevel} options={levels} /> <div className="acve-section-base">
<span className="text-base font-semibold text-slate-600">{counts[activeLevel]} courses in this level</span> <p className="acve-pill mb-4 w-fit">Course Catalog</p>
</div> <h1 className="text-3xl font-semibold leading-tight text-[#202a39] md:text-4xl">Build your legal English learning path</h1>
</section> <p className="mt-3 max-w-2xl text-base leading-relaxed text-slate-600 md:text-lg">
Discover our published legal English courses and start with the path that matches your level.
<section className="acve-panel px-6 py-8">
<div className="flex items-start gap-4">
<div className="mt-1 flex h-12 w-12 items-center justify-center rounded-xl bg-accent text-2xl font-semibold text-white">C</div>
<div>
<h1 className="text-3xl text-[#202a39] md:text-5xl">{activeLevel} Level Courses</h1>
<p className="mt-2 text-base text-slate-600 md:text-2xl">
{activeLevel === "Beginner"
? "Perfect for those new to English law. Build a strong foundation with fundamental concepts and terminology."
: activeLevel === "Intermediate"
? "Deepen practical analysis skills with real-world drafting, contract review, and legal communication."
: "Master complex legal reasoning and advanced writing for high-impact legal practice."}
</p> </p>
<div className="mt-5 grid gap-3 sm:grid-cols-3">
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Total Courses</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">{courses.length}</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Published Lessons</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">{totalLessons}</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Instructors</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">
{new Set(courses.map((course) => course.author.fullName || "ACVE Team")).size}
</p>
</div>
</div>
</div> </div>
<aside className="border-t border-slate-200 bg-slate-50/80 p-5 lg:border-l lg:border-t-0">
<h2 className="text-base font-semibold text-slate-800">Open Access</h2>
<p className="mt-2 text-sm text-slate-600">
This catalog is public. Open any course card to visit the landing page and enroll.
</p>
</aside>
</div> </div>
</section> </section>
<div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3"> {courses.length === 0 ? (
{filteredCourses.map((course) => ( <section className="acve-panel acve-section-base">
<CourseCard key={course.slug} course={course} progress={progressBySlug[course.slug] ?? 0} /> <div className="rounded-xl border border-dashed border-slate-300 bg-slate-50 px-6 py-12 text-center">
))} <h2 className="text-2xl font-semibold text-slate-900">Coming Soon</h2>
</div> <p className="mt-2 text-slate-600">We are preparing new courses. Please check back shortly.</p>
</div>
</section>
) : (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{courses.map((course) => (
<CourseCard key={course.slug} course={course} />
))}
</div>
)}
</div> </div>
); );
} }

40
app/(public)/page.tsx Normal file → Executable file
View File

@@ -10,22 +10,22 @@ const highlights = [
export default function HomePage() { export default function HomePage() {
return ( return (
<div className="space-y-8"> <div className="acve-page">
<section className="acve-panel relative overflow-hidden p-6 md:p-10"> <section className="acve-panel relative overflow-hidden p-5 md:p-8">
<div className="grid items-start gap-8 lg:grid-cols-[1.1fr_0.9fr]"> <div className="grid items-start gap-6 lg:grid-cols-[1.15fr_0.85fr]">
<div> <div>
<p className="acve-pill mb-5 w-fit text-base"> <p className="acve-pill mb-4 w-fit text-sm">
<span className="mr-2 text-accent">*</span> <span className="mr-2 text-accent">*</span>
Professional Legal Education Professional Legal Education
</p> </p>
<h1 className="acve-heading text-4xl leading-[1.1] md:text-7xl">Learn English Law with Confidence</h1> <h1 className="acve-heading text-4xl leading-tight md:text-5xl">Learn English Law with Confidence</h1>
<p className="mt-5 max-w-2xl text-lg leading-relaxed text-slate-600 md:text-2xl"> <p className="mt-3 max-w-2xl text-base leading-relaxed text-slate-600 md:text-lg">
Courses, case studies, and guided practice designed for Latin American professionals and students. Courses, case studies, and guided practice designed for Latin American professionals and students.
</p> </p>
<ul className="mt-7 space-y-3"> <ul className="mt-5 grid gap-2 sm:grid-cols-2">
{highlights.map((item) => ( {highlights.map((item) => (
<li key={item} className="flex items-start gap-3 text-base text-slate-700 md:text-xl"> <li key={item} className="flex items-start gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700">
<span className="mt-1 flex h-7 w-7 items-center justify-center rounded-full border-2 border-accent text-base text-accent"> <span className="mt-0.5 flex h-5 w-5 items-center justify-center rounded-full border border-accent text-xs text-accent">
v v
</span> </span>
{item} {item}
@@ -33,11 +33,11 @@ export default function HomePage() {
))} ))}
</ul> </ul>
<div className="mt-8 flex flex-wrap gap-3"> <div className="mt-6 flex flex-wrap gap-2">
<Link className="acve-button-primary px-8 py-3 text-lg font-semibold transition hover:brightness-105" href="/courses"> <Link className="acve-button-primary px-6 py-2 text-sm font-semibold transition hover:brightness-105" href="/courses">
Start Learning Start Learning
</Link> </Link>
<Link className="acve-button-secondary px-8 py-3 text-lg font-semibold transition hover:bg-brand-soft" href="/courses"> <Link className="acve-button-secondary px-6 py-2 text-sm font-semibold transition hover:bg-brand-soft" href="/courses">
Explore Courses Explore Courses
</Link> </Link>
</div> </div>
@@ -47,29 +47,29 @@ export default function HomePage() {
<div className="overflow-hidden rounded-3xl border border-slate-300 bg-white shadow-sm"> <div className="overflow-hidden rounded-3xl border border-slate-300 bg-white shadow-sm">
<Image <Image
alt="ACVE legal library" alt="ACVE legal library"
className="h-[420px] w-full object-cover object-right md:h-[600px]" className="h-[360px] w-full object-cover object-right md:h-[460px]"
height={900} height={900}
priority priority
src="/images/hero-reference.png" src="/images/hero-reference.png"
width={700} width={700}
/> />
</div> </div>
<div className="absolute bottom-5 left-5 right-5 rounded-2xl border border-slate-300 bg-white px-5 py-4 shadow-sm"> <div className="absolute bottom-4 left-4 right-4 rounded-2xl border border-slate-300 bg-white px-4 py-3 shadow-sm">
<p className="text-sm font-semibold uppercase tracking-wide text-accent">AI</p> <p className="text-sm font-semibold uppercase tracking-wide text-accent">AI</p>
<p className="text-xl font-semibold text-slate-800">Legal Assistant Ready</p> <p className="text-lg font-semibold text-slate-800">Legal Assistant Ready</p>
<p className="text-base text-slate-500">Ask me anything about English Law</p> <p className="text-sm text-slate-500">Ask me anything about English Law</p>
</div> </div>
</div> </div>
</div> </div>
<div className="mt-10 grid gap-4 border-t border-slate-200 pt-7 text-center text-sm font-semibold uppercase tracking-wide text-slate-500 md:grid-cols-3"> <div className="mt-6 grid gap-3 border-t border-slate-200 pt-5 text-center text-xs font-semibold uppercase tracking-wide text-slate-500 md:grid-cols-3">
<Link className="rounded-xl border border-slate-300 bg-white px-3 py-4 hover:border-brand hover:text-brand" href="/courses"> <Link className="rounded-xl border border-slate-300 bg-white px-3 py-3 hover:border-brand hover:text-brand" href="/courses">
Browse courses Browse courses
</Link> </Link>
<Link className="rounded-xl border border-slate-300 bg-white px-3 py-4 hover:border-brand hover:text-brand" href="/case-studies"> <Link className="rounded-xl border border-slate-300 bg-white px-3 py-3 hover:border-brand hover:text-brand" href="/case-studies">
Read case studies Read case studies
</Link> </Link>
<Link className="rounded-xl border border-slate-300 bg-white px-3 py-4 hover:border-brand hover:text-brand" href="/practice"> <Link className="rounded-xl border border-slate-300 bg-white px-3 py-3 hover:border-brand hover:text-brand" href="/practice">
Practice and exercises Practice and exercises
</Link> </Link>
</div> </div>

45
app/(public)/practice/page.tsx Normal file → Executable file
View File

@@ -3,13 +3,23 @@ import { mockPracticeModules } from "@/lib/data/mockPractice";
export default function PracticePage() { export default function PracticePage() {
return ( return (
<div className="space-y-7"> <div className="acve-page">
<section className="text-center"> <section className="acve-panel acve-section-base">
<p className="acve-pill mx-auto mb-4 w-fit">Practice and Exercises</p> <div className="grid gap-4 md:grid-cols-[1.5fr_0.9fr]">
<h1 className="acve-heading text-4xl md:text-6xl">Master Your Skills</h1> <div>
<p className="mx-auto mt-3 max-w-4xl text-lg text-slate-600 md:text-3xl"> <p className="acve-pill mb-3 w-fit">Practice and Exercises</p>
Interactive exercises designed to reinforce your understanding of English law concepts. <h1 className="text-3xl font-semibold leading-tight text-[#222a38] md:text-4xl">Build confidence through short practice sessions</h1>
</p> <p className="mt-3 max-w-3xl text-base leading-relaxed text-slate-600 md:text-lg">
Train legal vocabulary, clause analysis, and case reasoning with quick modules you can complete in minutes.
</p>
</div>
<div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Practice Overview</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{mockPracticeModules.length} modules</p>
<p className="mt-2 text-sm text-slate-600">Interactive now: {mockPracticeModules.filter((item) => item.isInteractive).length}</p>
<p className="text-sm text-slate-600">Coming soon: {mockPracticeModules.filter((item) => !item.isInteractive).length}</p>
</div>
</div>
</section> </section>
<section className="grid gap-4 md:grid-cols-3"> <section className="grid gap-4 md:grid-cols-3">
@@ -17,22 +27,27 @@ export default function PracticePage() {
<Link <Link
key={module.slug} key={module.slug}
href={`/practice/${module.slug}`} href={`/practice/${module.slug}`}
className={`rounded-2xl border p-6 shadow-sm transition hover:-translate-y-0.5 ${ className={`rounded-2xl border p-5 shadow-sm transition hover:-translate-y-0.5 ${
index === 0 ? "border-brand bg-white" : "border-slate-300 bg-white" index === 0 ? "border-brand bg-white" : "border-slate-200 bg-white hover:border-slate-300"
}`} }`}
> >
<div className="mb-3 text-3xl text-brand md:text-4xl">{index === 0 ? "A/" : index === 1 ? "[]" : "O"}</div> <div className="mb-2 flex items-center justify-between">
<h2 className="text-2xl text-[#222a38] md:text-4xl">{module.title}</h2> <div className="text-2xl text-brand">{index === 0 ? "A/" : index === 1 ? "[]" : "O"}</div>
<p className="mt-2 text-lg text-slate-600 md:text-2xl">{module.description}</p> <span className="rounded-full border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-semibold text-slate-600">
<p className="mt-4 text-sm font-semibold uppercase tracking-wide text-slate-500"> {module.questions?.length ? `${module.questions.length} questions` : "Scaffolded"}
</span>
</div>
<h2 className="text-2xl leading-tight text-[#222a38]">{module.title}</h2>
<p className="mt-2 text-base leading-relaxed text-slate-600">{module.description}</p>
<p className="mt-4 text-xs font-semibold uppercase tracking-wide text-slate-500">
{module.isInteractive ? "Interactive now" : "Coming soon"} {module.isInteractive ? "Interactive now" : "Coming soon"}
</p> </p>
</Link> </Link>
))} ))}
</section> </section>
<section className="acve-panel p-5 text-center"> <section className="acve-panel p-4 text-center">
<p className="text-sm font-semibold uppercase tracking-wide text-slate-500"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
Open a module to start the full interactive flow Open a module to start the full interactive flow
</p> </p>
</section> </section>

154
app/globals copy.css Executable file
View File

@@ -0,0 +1,154 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
color-scheme: light;
--acve-bg: #f3f3f5;
--acve-panel: #ffffff;
--acve-ink: #273040;
--acve-muted: #667085;
--acve-line: #d8dbe2;
--acve-brand: #98143f;
--acve-brand-soft: #f8eef2;
--acve-gold: #d4af37;
--acve-heading-font: "Palatino Linotype", "Book Antiqua", "Times New Roman", serif;
--acve-body-font: "Segoe UI", "Trebuchet MS", "Verdana", sans-serif;
}
html,
body {
margin: 0;
min-height: 100%;
background: radial-gradient(circle at top right, #fcfcfd 0%, #f5f5f7 55%, #f0f0f2 100%);
color: var(--acve-ink);
font-family: var(--acve-body-font);
text-rendering: geometricPrecision;
}
a {
color: inherit;
text-decoration: none;
}
h1,
h2,
h3,
h4 {
font-family: var(--acve-heading-font);
}
::selection {
background: #f2d6df;
color: #421020;
}
.acve-shell {
background: linear-gradient(180deg, #f7f7f8 0%, #f2f3f5 100%);
}
.acve-panel {
border: 1px solid var(--acve-line);
background: var(--acve-panel);
border-radius: 16px;
}
.acve-heading {
color: var(--acve-brand);
font-family: var(--acve-heading-font);
letter-spacing: 0.01em;
}
.acve-pill {
display: inline-flex;
align-items: center;
border: 1px solid var(--acve-line);
border-radius: 9999px;
background: #fafafa;
color: #384253;
padding: 8px 14px;
font-size: 0.95rem;
}
.acve-button-primary {
background: var(--acve-brand);
color: #ffffff;
border-radius: 12px;
border: 1px solid var(--acve-brand);
}
.acve-button-secondary {
border: 1px solid var(--acve-brand);
color: var(--acve-brand);
background: #ffffff;
border-radius: 12px;
}
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--radius: 0.5rem;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

99
app/globals.css Normal file → Executable file
View File

@@ -3,17 +3,56 @@
@tailwind utilities; @tailwind utilities;
:root { :root {
color-scheme: light; /* ACVE core variables */
--acve-bg: #f3f3f5;
--acve-panel: #ffffff;
--acve-ink: #273040;
--acve-muted: #667085;
--acve-line: #d8dbe2;
--acve-brand: #98143f; --acve-brand: #98143f;
--acve-brand-soft: #f8eef2; --acve-ink: #253247;
--acve-gold: #d4af37; --acve-line: #d8dce3;
--acve-panel: #ffffff;
--acve-heading-font: "Palatino Linotype", "Book Antiqua", "Times New Roman", serif; --acve-heading-font: "Palatino Linotype", "Book Antiqua", "Times New Roman", serif;
--acve-body-font: "Segoe UI", "Trebuchet MS", "Verdana", sans-serif; --acve-body-font: "Segoe UI", "Trebuchet MS", "Verdana", sans-serif;
--acve-space-1: 4px;
--acve-space-2: 8px;
--acve-space-3: 12px;
--acve-space-4: 16px;
--acve-space-5: 24px;
--acve-space-6: 32px;
--acve-space-7: 48px;
/* SHADCN MAPPING */
--background: 0 0% 98%;
/* Matches your #f5f5f7 approx */
--foreground: 220 24% 20%;
/* Matches your --acve-ink */
--primary: 341 77% 34%;
/* Your Burgundy #98143f */
--primary-foreground: 0 0% 100%;
--card: 0 0% 100%;
--card-foreground: 220 24% 20%;
--border: 223 18% 87%;
/* Matches your --acve-line */
--input: 223 18% 87%;
--ring: 341 77% 34%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--radius: 0.75rem;
/* 12px to match your primary button */
} }
html, html,
@@ -23,6 +62,8 @@ body {
background: radial-gradient(circle at top right, #fcfcfd 0%, #f5f5f7 55%, #f0f0f2 100%); background: radial-gradient(circle at top right, #fcfcfd 0%, #f5f5f7 55%, #f0f0f2 100%);
color: var(--acve-ink); color: var(--acve-ink);
font-family: var(--acve-body-font); font-family: var(--acve-body-font);
font-size: 16px;
line-height: 1.45;
text-rendering: geometricPrecision; text-rendering: geometricPrecision;
} }
@@ -31,6 +72,25 @@ a {
text-decoration: none; text-decoration: none;
} }
a,
button,
input,
select,
textarea,
[role="button"] {
outline-color: transparent;
}
a:focus-visible,
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible,
[role="button"]:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
}
h1, h1,
h2, h2,
h3, h3,
@@ -57,6 +117,7 @@ h4 {
color: var(--acve-brand); color: var(--acve-brand);
font-family: var(--acve-heading-font); font-family: var(--acve-heading-font);
letter-spacing: 0.01em; letter-spacing: 0.01em;
line-height: 1.1;
} }
.acve-pill { .acve-pill {
@@ -75,6 +136,7 @@ h4 {
color: #ffffff; color: #ffffff;
border-radius: 12px; border-radius: 12px;
border: 1px solid var(--acve-brand); border: 1px solid var(--acve-brand);
min-height: 44px;
} }
.acve-button-secondary { .acve-button-secondary {
@@ -82,4 +144,25 @@ h4 {
color: var(--acve-brand); color: var(--acve-brand);
background: #ffffff; background: #ffffff;
border-radius: 12px; border-radius: 12px;
min-height: 44px;
}
.acve-page {
display: flex;
flex-direction: column;
gap: var(--acve-space-5);
}
.acve-section-tight {
padding: var(--acve-space-4);
}
.acve-section-base {
padding: var(--acve-space-5);
}
@media (min-width: 768px) {
.acve-page {
gap: var(--acve-space-6);
}
} }

2
app/layout.tsx Normal file → Executable file
View File

@@ -15,7 +15,7 @@ export default function RootLayout({ children }: Readonly<{ children: React.Reac
<body> <body>
<div className="acve-shell flex min-h-screen flex-col"> <div className="acve-shell flex min-h-screen flex-col">
<Navbar /> <Navbar />
<main className="mx-auto w-full max-w-[1300px] flex-1 px-4 py-6 md:py-8">{children}</main> <main className="mx-auto w-full max-w-[1200px] flex-1 px-4 py-5 md:px-5 md:py-7">{children}</main>
<Footer /> <Footer />
</div> </div>
<AssistantDrawer /> <AssistantDrawer />

23
components.json Executable file
View File

@@ -0,0 +1,23 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals copy.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}

127
components/AssistantDrawer.tsx Normal file → Executable file
View File

@@ -1,6 +1,11 @@
"use client"; "use client";
import { FormEvent, useEffect, useMemo, useState } from "react"; import { SubmitEvent, useEffect, useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter } from "@/components/ui/sheet";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
type AssistantMessage = { type AssistantMessage = {
id: string; id: string;
@@ -25,6 +30,14 @@ export default function AssistantDrawer({ mode = "global" }: AssistantDrawerProp
]); ]);
const [input, setInput] = useState(""); const [input, setInput] = useState("");
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [messages]);
useEffect(() => { useEffect(() => {
if (mode === "page") { if (mode === "page") {
return; return;
@@ -35,17 +48,7 @@ export default function AssistantDrawer({ mode = "global" }: AssistantDrawerProp
return () => window.removeEventListener(ASSISTANT_TOGGLE_EVENT, onToggle); return () => window.removeEventListener(ASSISTANT_TOGGLE_EVENT, onToggle);
}, [mode]); }, [mode]);
const panelClasses = useMemo(() => { const send = (event: SubmitEvent) => {
if (mode === "page") {
return "mx-auto flex h-[70vh] max-w-3xl flex-col rounded-2xl border border-slate-300 bg-white shadow-xl";
}
return `fixed right-0 top-0 z-50 h-screen w-full max-w-md border-l border-slate-300 bg-white shadow-2xl transition-transform ${
isOpen ? "translate-x-0" : "translate-x-full"
}`;
}, [isOpen, mode]);
const send = (event: FormEvent) => {
event.preventDefault(); event.preventDefault();
const trimmed = input.trim(); const trimmed = input.trim();
if (!trimmed) return; if (!trimmed) return;
@@ -59,57 +62,65 @@ export default function AssistantDrawer({ mode = "global" }: AssistantDrawerProp
setInput(""); setInput("");
}; };
if (mode === "global" && !isOpen) { const ChatContent = (
<div className="flex h-full flex-col">
<ScrollArea className="flex-1 p-4">
<div className="space-y-4">
{messages.map((message) => (
<div
key={message.id}
className={`max-w-[90%] rounded-lg px-3 py-2 text-sm ${message.role === "user"
? "ml-auto bg-primary text-primary-foreground"
: "mr-auto border border-border bg-muted text-foreground"
}`}
>
{message.content}
</div>
))}
<div ref={scrollRef} />
</div>
</ScrollArea>
<SheetFooter className="mt-auto border-t bg-background p-4 sm:flex-col">
<form className="w-full" onSubmit={send}>
<div className="flex gap-2">
<Input
className="flex-1"
onChange={(event) => setInput(event.target.value)}
placeholder="Type your message..."
value={input}
/>
<Button type="submit">Send</Button>
</div>
</form>
</SheetFooter>
</div>
);
if (mode === "page") {
return ( return (
<aside className={panelClasses}> <Card className="mx-auto flex h-[68vh] max-w-4xl flex-col shadow-xl">
<div /> <CardHeader className="border-b px-4 py-3">
</aside> <CardTitle className="text-2xl text-primary font-serif">AI Assistant</CardTitle>
</CardHeader>
<CardContent className="flex-1 p-0 overflow-hidden">
{ChatContent}
</CardContent>
</Card>
); );
} }
return ( return (
<aside className={panelClasses}> <Sheet open={isOpen} onOpenChange={setIsOpen}>
<div className="flex items-center justify-between border-b border-slate-200 px-4 py-3"> <SheetContent className="flex w-full flex-col p-0 sm:max-w-md">
<h2 className="acve-heading text-2xl">AI Assistant</h2> <SheetHeader className="px-4 py-3 border-b">
{mode === "global" ? ( <SheetTitle className="text-primary font-serif">AI Assistant</SheetTitle>
<button <SheetDescription className="sr-only">Chat with our AI assistant</SheetDescription>
className="rounded-md border border-slate-300 px-2 py-1 text-sm text-slate-600 hover:bg-slate-50" </SheetHeader>
onClick={() => setIsOpen(false)} <div className="flex-1 overflow-hidden">
type="button" {ChatContent}
>
Close
</button>
) : null}
</div>
<div className="flex-1 space-y-3 overflow-y-auto p-4">
{messages.map((message) => (
<div
key={message.id}
className={`max-w-[90%] rounded-lg px-3 py-2 text-sm ${
message.role === "user"
? "ml-auto bg-brand text-white"
: "mr-auto border border-slate-200 bg-slate-50 text-slate-800"
}`}
>
{message.content}
</div>
))}
</div>
<form className="border-t border-slate-200 p-3" onSubmit={send}>
<div className="flex gap-2">
<input
className="flex-1 rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
onChange={(event) => setInput(event.target.value)}
placeholder="Type your message..."
value={input}
/>
<button className="rounded-md bg-brand px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
Send
</button>
</div> </div>
</form> </SheetContent>
</aside> </Sheet>
); );
} }

123
components/CourseCard.tsx Normal file → Executable file
View File

@@ -1,43 +1,104 @@
import Link from "next/link"; import Link from "next/link";
import type { Course } from "@/types/course"; import type { Prisma } from "@prisma/client";
import ProgressBar from "@/components/ProgressBar"; import ProgressBar from "@/components/ProgressBar";
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
type PublicCourseCardCourse = Prisma.CourseGetPayload<{
include: {
author: {
select: {
fullName: true;
};
};
modules: {
select: {
_count: {
select: {
lessons: true;
};
};
};
};
_count: {
select: {
enrollments: true;
};
};
};
}>;
type CourseCardProps = { type CourseCardProps = {
course: Course; course: PublicCourseCardCourse;
progress?: number; progress?: number;
}; };
export default function CourseCard({ course, progress = 0 }: CourseCardProps) { const levelBadgeClass = (level: PublicCourseCardCourse["level"]) => {
return ( if (level === "BEGINNER") return "bg-emerald-100 text-emerald-900 border border-emerald-200";
<Link if (level === "INTERMEDIATE") return "bg-sky-100 text-sky-900 border border-sky-200";
href={`/courses/${course.slug}`} return "bg-violet-100 text-violet-900 border border-violet-200";
className="group flex h-full flex-col justify-between rounded-2xl border border-slate-300 bg-white p-6 shadow-sm transition hover:-translate-y-0.5 hover:border-brand/60" };
>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="rounded-full bg-[#ead7a0] px-3 py-1 text-xs font-semibold text-[#8a6b00]">{course.level}</span>
<span className="text-sm font-semibold text-slate-700">Rating {course.rating.toFixed(1)}</span>
</div>
<h3 className="text-2xl leading-tight text-[#212937] md:text-4xl">{course.title}</h3>
<p className="text-base text-slate-600 md:text-lg">{course.summary}</p>
</div>
<div className="mt-5 border-t border-slate-200 pt-4 text-base text-slate-600 md:text-lg"> const levelLabel = (level: PublicCourseCardCourse["level"]) => {
{progress > 0 ? ( if (level === "BEGINNER") return "Beginner";
<div className="mb-4"> if (level === "INTERMEDIATE") return "Intermediate";
<ProgressBar value={progress} label={`Progress ${progress}%`} /> return "Advanced";
};
const getText = (value: unknown): string => {
if (!value) return "";
if (typeof value === "string") return value;
if (typeof value === "object") {
const record = value as Record<string, unknown>;
if (typeof record.en === "string") return record.en;
if (typeof record.es === "string") return record.es;
}
return "";
};
export default function CourseCard({ course, progress = 0 }: CourseCardProps) {
const lessonsCount = course.modules.reduce((total, module) => total + module._count.lessons, 0);
const title = getText(course.title) || "Untitled course";
const summary = getText(course.description) || "Course details will be published soon.";
const instructor = course.author.fullName || "ACVE Team";
return (
<Link href={`/courses/${course.slug}`} className="group block h-full">
<Card className="h-full border-border hover:-translate-y-0.5 hover:border-primary/60 transition-all duration-200">
<CardHeader className="space-y-3 pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Badge variant="secondary" className={levelBadgeClass(course.level)}>
{levelLabel(course.level)}
</Badge>
<Badge variant="outline">{course.status.toLowerCase()}</Badge>
</div>
<span className="text-sm font-semibold text-muted-foreground">{lessonsCount} lessons</span>
</div> </div>
) : null} <CardTitle className="text-[1.85rem] leading-tight md:text-[2rem]">{title}</CardTitle>
<div className="mb-1 flex items-center justify-between"> <CardDescription className="text-base leading-relaxed">{summary}</CardDescription>
<span>{course.weeks} weeks</span> </CardHeader>
<span>{course.lessonsCount} lessons</span>
</div> <CardContent className="pt-4 text-base text-muted-foreground">
<div className="mb-3 flex items-center justify-between"> {progress > 0 ? (
<span>{course.students.toLocaleString()} students</span> <div className="mb-4">
<span className="text-brand transition-transform group-hover:translate-x-1">{">"}</span> <ProgressBar value={progress} label={`Progress ${progress}%`} />
</div> </div>
<div className="text-sm font-semibold text-slate-700 md:text-base">By {course.instructor}</div> ) : null}
</div> <div className="mb-1 flex items-center justify-between">
<span>{course._count.enrollments.toLocaleString()} enrolled</span>
<span>{lessonsCount} lessons</span>
</div>
</CardContent>
<CardFooter className="flex items-center justify-between border-t bg-muted/50 px-6 py-4 text-sm text-muted-foreground">
<span>By {instructor}</span>
<div className="flex items-center gap-2">
<span className="font-semibold text-primary">View Course</span>
<span className="text-primary opacity-0 transition-opacity group-hover:opacity-100">{">"}</span>
</div>
</CardFooter>
</Card>
</Link> </Link>
); );
} }

6
components/Footer.tsx Normal file → Executable file
View File

@@ -1,8 +1,8 @@
export default function Footer() { export default function Footer() {
return ( return (
<footer className="border-t border-slate-300 bg-[#f7f7f8]"> <footer className="border-t bg-muted/30">
<div className="mx-auto flex w-full max-w-[1300px] items-center justify-between px-4 py-5 text-sm text-slate-600"> <div className="mx-auto flex w-full max-w-[1300px] items-center justify-between px-4 py-6 text-sm text-muted-foreground">
<span>ACVE Centro de Estudios</span> <span className="font-medium">ACVE Centro de Estudios</span>
<span>Professional legal English learning</span> <span>Professional legal English learning</span>
</div> </div>
</footer> </footer>

52
components/LessonRow.tsx Normal file → Executable file
View File

@@ -1,4 +1,7 @@
import type { Lesson } from "@/types/course"; import type { Lesson } from "@/types/course";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
type LessonRowProps = { type LessonRowProps = {
index: number; index: number;
@@ -9,47 +12,54 @@ type LessonRowProps = {
}; };
const typeColors: Record<Lesson["type"], string> = { const typeColors: Record<Lesson["type"], string> = {
video: "bg-[#ffecee] text-[#ca4d6f]", video: "bg-red-50 text-red-600 dark:bg-red-900/20 dark:text-red-400",
reading: "bg-[#ecfbf4] text-[#2f9d73]", reading: "bg-green-50 text-green-600 dark:bg-green-900/20 dark:text-green-400",
interactive: "bg-[#eef4ff] text-[#6288da]", interactive: "bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400",
}; };
export default function LessonRow({ index, lesson, isActive, isLocked, onSelect }: LessonRowProps) { export default function LessonRow({ index, lesson, isActive, isLocked, onSelect }: LessonRowProps) {
return ( return (
<button <Button
className={`w-full rounded-2xl border p-5 text-left transition ${ variant="ghost"
isActive ? "border-brand/60 bg-white shadow-sm" : "border-slate-200 bg-white hover:border-slate-300" className={cn(
} ${isLocked ? "cursor-not-allowed opacity-60" : ""}`} "group h-auto w-full justify-start whitespace-normal rounded-2xl border p-5 text-left transition-all hover:bg-accent/50",
isActive
? "border-primary/60 bg-background shadow-sm ring-1 ring-primary/20"
: "border-border bg-background hover:border-border/80",
isLocked && "cursor-not-allowed opacity-60 hover:bg-transparent"
)}
onClick={isLocked ? undefined : onSelect} onClick={isLocked ? undefined : onSelect}
type="button" type="button"
disabled={isLocked && !isActive}
> >
<div className="flex items-center gap-4"> <div className="flex w-full items-center gap-4">
<div <div
className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border text-lg font-semibold ${ className={cn(
isActive ? "border-brand text-brand" : "border-slate-300 text-slate-500" "flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border text-lg font-semibold transition-colors",
}`} isActive ? "border-primary text-primary" : "border-input text-muted-foreground group-hover:border-primary/40 group-hover:text-foreground"
)}
> >
{isLocked ? "L" : index + 1} {isLocked ? "L" : index + 1}
</div> </div>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1 space-y-1">
<div className="mb-1 flex flex-wrap items-center gap-2 text-sm text-slate-500"> <div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<span className={`rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${typeColors[lesson.type]}`}> <Badge variant="outline" className={cn("rounded-full border-0 px-2.5 py-0.5 font-semibold capitalize", typeColors[lesson.type])}>
{lesson.type} {lesson.type}
</span> </Badge>
<span>{lesson.minutes} min</span> <span>{lesson.minutes} min</span>
{isLocked ? <span className="text-slate-400">Locked</span> : null} {isLocked ? <span className="text-muted-foreground/70">Locked</span> : null}
{lesson.isPreview ? <span className="text-[#8a6b00]">Preview</span> : null} {lesson.isPreview ? <span className="text-yellow-600 dark:text-yellow-400">Preview</span> : null}
</div> </div>
<p className="truncate text-lg text-[#222a38] md:text-2xl">{lesson.title}</p> <p className="truncate text-lg font-medium text-foreground md:text-2xl">{lesson.title}</p>
</div> </div>
{isActive ? ( {isActive ? (
<div className="hidden h-20 w-36 overflow-hidden rounded-xl border border-slate-200 bg-[#202020] md:block"> <div className="hidden h-20 w-36 overflow-hidden rounded-xl border border-border bg-muted md:block">
<div className="flex h-full items-center justify-center text-2xl text-white/80">Play</div> <div className="flex h-full items-center justify-center text-2xl text-muted-foreground/80">Play</div>
</div> </div>
) : null} ) : null}
</div> </div>
</button> </Button>
); );
} }

142
components/Navbar.tsx Normal file → Executable file
View File

@@ -2,10 +2,15 @@
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { ASSISTANT_TOGGLE_EVENT } from "@/components/AssistantDrawer"; import { ASSISTANT_TOGGLE_EVENT } from "@/components/AssistantDrawer";
import { DEMO_AUTH_EMAIL_COOKIE, DEMO_AUTH_ROLE_COOKIE } from "@/lib/auth/demoAuth";
import { isTeacherEmailAllowed, readTeacherEmailsBrowser } from "@/lib/auth/teacherAllowlist";
import { supabaseBrowser } from "@/lib/supabase/browser"; import { supabaseBrowser } from "@/lib/supabase/browser";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type NavLink = { type NavLink = {
href: string; href: string;
@@ -21,105 +26,162 @@ const navLinks: NavLink[] = [
export default function Navbar() { export default function Navbar() {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter();
const [userEmail, setUserEmail] = useState<string | null>(null); const [userEmail, setUserEmail] = useState<string | null>(null);
const [isTeacher, setIsTeacher] = useState(false);
const linkClass = (href: string) => const teacherEmails = useMemo(() => readTeacherEmailsBrowser(), []);
pathname === href || pathname?.startsWith(`${href}/`)
? "rounded-xl bg-brand px-5 py-3 text-sm font-semibold text-white shadow-sm"
: "rounded-xl px-5 py-3 text-sm font-semibold text-slate-700 transition-colors hover:text-brand";
useEffect(() => { useEffect(() => {
const client = supabaseBrowser(); const client = supabaseBrowser();
if (!client) return; if (!client) {
const cookieMap = new Map(
document.cookie
.split(";")
.map((entry) => entry.trim())
.filter(Boolean)
.map((entry) => {
const [key, ...rest] = entry.split("=");
return [key, decodeURIComponent(rest.join("="))] as const;
}),
);
const email = cookieMap.get(DEMO_AUTH_EMAIL_COOKIE) ?? null;
const role = cookieMap.get(DEMO_AUTH_ROLE_COOKIE) ?? "";
setUserEmail(email);
setIsTeacher(role === "teacher" || isTeacherEmailAllowed(email, teacherEmails));
return;
}
let mounted = true; let mounted = true;
client.auth.getUser().then(({ data }) => { client.auth.getUser().then(({ data }) => {
if (!mounted) return; if (!mounted) return;
setUserEmail(data.user?.email ?? null); const email = data.user?.email ?? null;
setUserEmail(email);
setIsTeacher(isTeacherEmailAllowed(email, teacherEmails));
}); });
const { data } = client.auth.onAuthStateChange((_event, session) => { const { data } = client.auth.onAuthStateChange((_event, session) => {
setUserEmail(session?.user?.email ?? null); const email = session?.user?.email ?? null;
setUserEmail(email);
setIsTeacher(isTeacherEmailAllowed(email, teacherEmails));
}); });
return () => { return () => {
mounted = false; mounted = false;
data.subscription.unsubscribe(); data.subscription.unsubscribe();
}; };
}, []); }, [teacherEmails]);
const links = useMemo(() => {
if (!isTeacher) return navLinks;
return [...navLinks, { href: "/teacher", label: "Teacher Dashboard" }];
}, [isTeacher]);
const authNode = useMemo(() => { const authNode = useMemo(() => {
if (!userEmail) { if (!userEmail) {
return ( return (
<div className="flex items-center gap-2 text-sm"> <div className="flex items-center gap-2">
<Link className="rounded-lg border border-slate-300 px-3 py-1.5 hover:bg-slate-50" href="/auth/login"> <Button variant="outline" size="sm" asChild>
Login <Link href="/auth/login">Login</Link>
</Link> </Button>
<Link className="rounded-lg bg-brand px-3 py-1.5 text-white hover:brightness-105" href="/auth/signup"> <Button size="sm" asChild>
Sign up <Link href="/auth/signup">Sign up</Link>
</Link> </Button>
</div> </div>
); );
} }
return ( return (
<div className="flex items-center gap-2 text-sm"> <div className="flex items-center gap-2 text-sm">
<span className="max-w-36 truncate text-slate-700">{userEmail}</span> <span className="hidden max-w-36 truncate text-muted-foreground sm:inline-block">{userEmail}</span>
<button {!isTeacher ? (
className="rounded-lg border border-slate-300 px-3 py-1.5 hover:bg-slate-50" <Link
className="inline-flex items-center rounded-md border border-amber-300 bg-amber-50 px-2 py-1 text-xs font-semibold text-amber-900"
href="/auth/login?role=teacher"
>
Teacher area (Teacher only)
</Link>
) : null}
<Button
variant="outline"
size="sm"
onClick={async () => { onClick={async () => {
const client = supabaseBrowser(); const client = supabaseBrowser();
if (!client) return; if (!client) {
document.cookie = `${DEMO_AUTH_EMAIL_COOKIE}=; path=/; max-age=0`;
document.cookie = `${DEMO_AUTH_ROLE_COOKIE}=; path=/; max-age=0`;
setUserEmail(null);
setIsTeacher(false);
router.refresh();
return;
}
await client.auth.signOut(); await client.auth.signOut();
}} }}
type="button"
> >
Logout Logout
</button> </Button>
</div> </div>
); );
}, [userEmail]); }, [isTeacher, router, userEmail]);
return ( return (
<header className="sticky top-0 z-40 border-b border-slate-300 bg-[#f7f7f8]/95 backdrop-blur"> <header className="sticky top-0 z-40 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="mx-auto flex w-full max-w-[1300px] items-center justify-between gap-4 px-4 py-3"> <div className="mx-auto flex w-full max-w-[1300px] items-center justify-between gap-4 px-4 py-3">
<div className="flex items-center gap-8"> <div className="flex items-center gap-8">
<Link className="flex items-center gap-3" href="/"> <Link className="flex items-center gap-3" href="/">
<div className="rounded-xl bg-[#edd7bc] p-1.5 shadow-sm"> <div className="rounded-xl bg-accent p-1.5 shadow-sm">
<Image alt="ACVE logo" className="h-10 w-10 rounded-lg object-cover" height={40} src="/images/logo.png" width={40} /> <Image alt="ACVE logo" className="h-10 w-10 rounded-lg object-cover" height={40} src="/images/logo.png" width={40} />
</div> </div>
<div> <div>
<div className="text-2xl font-bold leading-none tracking-tight text-brand md:text-4xl">ACVE</div> <div className="text-2xl font-bold leading-none tracking-tight text-primary md:text-4xl">ACVE</div>
<div className="-mt-1 text-xs text-slate-500 md:text-sm">Centro de Estudios</div> <div className="-mt-1 text-xs text-muted-foreground md:text-sm">Centro de Estudios</div>
</div> </div>
</Link> </Link>
<nav className="hidden items-center gap-1 text-sm lg:flex"> <nav className="hidden items-center gap-1 text-sm lg:flex">
{navLinks.map((link) => ( {links.map((link) => {
<Link key={link.href} className={linkClass(link.href)} href={link.href}> const isActive = pathname === link.href || pathname?.startsWith(`${link.href}/`);
{link.label} return (
</Link> <Button
))} key={link.href}
variant={isActive ? "default" : "ghost"}
asChild
className={cn("rounded-xl text-sm font-semibold", !isActive && "text-muted-foreground hover:text-primary")}
>
<Link href={link.href}>{link.label}</Link>
</Button>
);
})}
</nav> </nav>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <Button
className="rounded-xl border border-accent bg-white px-4 py-2.5 text-sm font-semibold text-accent hover:bg-amber-50" variant="outline"
className="border-primary/20 text-primary hover:bg-primary/5 hover:text-primary"
onClick={() => window.dispatchEvent(new Event(ASSISTANT_TOGGLE_EVENT))} onClick={() => window.dispatchEvent(new Event(ASSISTANT_TOGGLE_EVENT))}
type="button"
> >
AI Assistant AI Assistant
</button> </Button>
{authNode} {authNode}
</div> </div>
</div> </div>
<nav className="mx-auto flex w-full max-w-[1300px] gap-2 overflow-x-auto px-4 pb-3 text-sm lg:hidden"> <nav className="mx-auto flex w-full max-w-[1300px] gap-2 overflow-x-auto px-4 pb-3 text-sm lg:hidden">
{navLinks.map((link) => ( {links.map((link) => {
<Link key={link.href} className={linkClass(link.href)} href={link.href}> const isActive = pathname === link.href;
{link.label} return (
</Link> <Button
))} key={link.href}
variant={isActive ? "default" : "ghost"}
size="sm"
asChild
className="whitespace-nowrap rounded-xl"
>
<Link href={link.href}>{link.label}</Link>
</Button>
);
})}
</nav> </nav>
</header> </header>
); );

6
components/ProgressBar.tsx Normal file → Executable file
View File

@@ -8,9 +8,9 @@ export default function ProgressBar({ value, label }: ProgressBarProps) {
return ( return (
<div className="w-full"> <div className="w-full">
{label ? <div className="mb-1 text-xs font-semibold text-slate-600">{label}</div> : null} {label ? <div className="mb-1 text-xs font-semibold text-muted-foreground">{label}</div> : null}
<div className="h-2.5 w-full rounded-full bg-[#ececef]"> <div className="h-2.5 w-full rounded-full bg-secondary">
<div className="h-2.5 rounded-full bg-brand transition-all" style={{ width: `${clamped}%` }} /> <div className="h-2.5 rounded-full bg-primary transition-all" style={{ width: `${clamped}%` }} />
</div> </div>
</div> </div>
); );

31
components/Tabs.tsx Normal file → Executable file
View File

@@ -1,3 +1,5 @@
import { Tabs as TabsPrimitive, TabsList, TabsTrigger } from "@/components/ui/tabs";
type TabsProps<T extends string> = { type TabsProps<T extends string> = {
options: readonly T[]; options: readonly T[];
active: T; active: T;
@@ -6,21 +8,18 @@ type TabsProps<T extends string> = {
export default function Tabs<T extends string>({ options, active, onChange }: TabsProps<T>) { export default function Tabs<T extends string>({ options, active, onChange }: TabsProps<T>) {
return ( return (
<div className="inline-flex flex-wrap gap-2"> <TabsPrimitive value={active} onValueChange={(v) => onChange(v as T)}>
{options.map((option) => ( <TabsList className="h-auto gap-2 bg-transparent p-0">
<button {options.map((option) => (
key={option} <TabsTrigger
className={`rounded-xl border px-6 py-3 text-base font-semibold transition-colors ${ key={option}
option === active value={option}
? "border-accent bg-accent text-white shadow-sm" className="rounded-xl border border-input bg-background px-4 py-2 text-sm font-semibold text-slate-700 data-[state=active]:border-primary data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm md:px-5 md:py-2.5"
: "border-slate-300 bg-white text-slate-700 hover:border-slate-400" >
}`} {option}
onClick={() => onChange(option)} </TabsTrigger>
type="button" ))}
> </TabsList>
{option} </TabsPrimitive>
</button>
))}
</div>
); );
} }

123
components/auth/LoginForm.tsx Normal file → Executable file
View File

@@ -1,95 +1,152 @@
"use client"; "use client";
import { createBrowserClient } from "@supabase/ssr";
import { FormEvent, useState } from "react"; import { FormEvent, useState } from "react";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { supabaseBrowser } from "@/lib/supabase/browser";
type LoginFormProps = { type LoginFormProps = {
redirectTo: string; redirectTo: string;
role?: string;
showForgot?: boolean;
}; };
// Helper to prevent open redirect vulnerabilities
const normalizeRedirect = (redirectTo: string) => { const normalizeRedirect = (redirectTo: string) => {
if (!redirectTo.startsWith("/")) return "/courses"; if (redirectTo.startsWith("/") && !redirectTo.startsWith("//")) {
return redirectTo; return redirectTo;
}
return "/home"; // Default fallback
}; };
export default function LoginForm({ redirectTo }: LoginFormProps) { export default function LoginForm({ redirectTo, role, showForgot }: LoginFormProps) {
const router = useRouter(); const router = useRouter();
const safeRedirect = normalizeRedirect(redirectTo); const safeRedirect = normalizeRedirect(redirectTo);
const isTeacher = role === "teacher";
const showForgotNotice = Boolean(showForgot);
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
// Construct the "Forgot Password" link to preserve context
const forgotHref = `/auth/login?redirectTo=${encodeURIComponent(safeRedirect)}${isTeacher ? "&role=teacher" : ""
}&forgot=1`;
const onSubmit = async (event: FormEvent) => { const onSubmit = async (event: FormEvent) => {
event.preventDefault(); event.preventDefault();
setError(null); setError(null);
setLoading(true); setLoading(true);
const client = supabaseBrowser(); // 1. Initialize the Supabase Client (Browser side)
if (!client) { const supabase = createBrowserClient(
setLoading(false); process.env.NEXT_PUBLIC_SUPABASE_URL!,
setError("Supabase is not configured. Add NEXT_PUBLIC_SUPABASE_* to .env.local."); process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
return; );
}
const { error: signInError } = await client.auth.signInWithPassword({ email, password }); // 2. Attempt Real Login
setLoading(false); const { error: signInError } = await supabase.auth.signInWithPassword({
email,
password,
});
if (signInError) { if (signInError) {
setError(signInError.message); setLoading(false);
setError(signInError.message); // e.g. "Invalid login credentials"
return; return;
} }
// 3. CRITICAL: Refresh the Server Context
// This forces Next.js to re-run the Middleware and Server Components
// so they see the new cookie immediately.
router.refresh();
// 4. Navigate to the protected page
router.push(safeRedirect); router.push(safeRedirect);
}; };
return ( return (
<div className="acve-panel mx-auto w-full max-w-md p-6"> <div className="acve-panel mx-auto w-full max-w-md p-6 bg-white rounded-xl shadow-sm border border-slate-200">
<h1 className="acve-heading text-4xl">Login</h1> <h1 className="text-3xl font-bold text-slate-900 mb-2">
<p className="mt-1 text-base text-slate-600">Sign in to access protected learning routes.</p> {isTeacher ? "Acceso Profesores" : "Iniciar Sesión"}
</h1>
<p className="text-slate-600 mb-6">
{isTeacher
? "Gestiona tus cursos y estudiantes."
: "Ingresa para continuar aprendiendo."}
</p>
<form className="mt-5 space-y-4" onSubmit={onSubmit}> {showForgotNotice && (
<div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
El restablecimiento de contraseña no está disponible en este momento. Contacta a soporte.
</div>
)}
<form className="space-y-4" onSubmit={onSubmit}>
<label className="block"> <label className="block">
<span className="mb-1 block text-sm text-slate-700">Email</span> <span className="mb-1 block text-sm font-medium text-slate-700">Email</span>
<input <input
className="w-full rounded-xl border border-slate-300 px-3 py-2 outline-none focus:border-brand" className="w-full rounded-lg border border-slate-300 px-3 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all"
onChange={(event) => setEmail(event.target.value)} onChange={(e) => setEmail(e.target.value)}
required required
type="email" type="email"
value={email} value={email}
placeholder="tu@email.com"
/> />
</label> </label>
<label className="block"> <label className="block">
<span className="mb-1 block text-sm text-slate-700">Password</span> <span className="mb-1 block text-sm font-medium text-slate-700">Contraseña</span>
<input <input
className="w-full rounded-xl border border-slate-300 px-3 py-2 outline-none focus:border-brand" className="w-full rounded-lg border border-slate-300 px-3 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all"
onChange={(event) => setPassword(event.target.value)} onChange={(e) => setPassword(e.target.value)}
required required
type="password" type="password"
value={password} value={password}
placeholder="••••••••"
/> />
</label> </label>
{error ? <p className="text-sm text-red-600">{error}</p> : null} {error && (
<div className="rounded-md bg-red-50 p-3 text-sm text-red-600 border border-red-100">
{error}
</div>
)}
<button <button
className="acve-button-primary w-full px-4 py-2 font-semibold hover:brightness-105 disabled:opacity-60" className="w-full rounded-lg bg-black px-4 py-2.5 font-semibold text-white hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
disabled={loading} disabled={loading}
type="submit" type="submit"
> >
{loading ? "Signing in..." : "Login"} {loading ? "Entrando..." : "Entrar"}
</button> </button>
</form> </form>
<p className="mt-4 text-sm text-slate-600"> <div className="mt-6 space-y-2 text-center text-sm text-slate-600">
New here?{" "} <div>
<Link className="font-semibold text-brand" href="/auth/signup"> <Link className="font-semibold text-black hover:underline" href={forgotHref}>
Create an account ¿Olvidaste tu contraseña?
</Link> </Link>
</p> </div>
<div>
¿Nuevo aquí?{" "}
<Link className="font-semibold text-black hover:underline" href="/auth/signup">
Crear cuenta
</Link>
</div>
{!isTeacher && (
<div className="pt-2 border-t border-slate-100 mt-4">
¿Eres profesor?{" "}
<Link
className="font-semibold text-black hover:underline"
href={`/auth/login?role=teacher&redirectTo=${encodeURIComponent(safeRedirect)}`}
>
Ingresa aquí
</Link>
</div>
)}
</div>
</div> </div>
); );
} }

View File

@@ -0,0 +1,218 @@
"use client";
import { useEffect, useMemo, useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Check, Lock, PlayCircle } from "lucide-react";
import { toggleLessonComplete } from "@/app/(protected)/courses/[slug]/learn/actions";
import ProgressBar from "@/components/ProgressBar";
type ClassroomLesson = {
id: string;
title: string;
description: string;
videoUrl: string | null;
estimatedDuration: number;
};
type ClassroomModule = {
id: string;
title: string;
lessons: ClassroomLesson[];
};
type StudentClassroomClientProps = {
courseSlug: string;
courseTitle: string;
modules: ClassroomModule[];
initialSelectedLessonId: string;
initialCompletedLessonIds: string[];
};
export default function StudentClassroomClient({
courseSlug,
courseTitle,
modules,
initialSelectedLessonId,
initialCompletedLessonIds,
}: StudentClassroomClientProps) {
const router = useRouter();
const [isSaving, startTransition] = useTransition();
const [selectedLessonId, setSelectedLessonId] = useState(initialSelectedLessonId);
const [completedLessonIds, setCompletedLessonIds] = useState(initialCompletedLessonIds);
useEffect(() => {
setSelectedLessonId(initialSelectedLessonId);
}, [initialSelectedLessonId]);
useEffect(() => {
setCompletedLessonIds(initialCompletedLessonIds);
}, [initialCompletedLessonIds]);
const flatLessons = useMemo(() => modules.flatMap((module) => module.lessons), [modules]);
const completedSet = useMemo(() => new Set(completedLessonIds), [completedLessonIds]);
const totalLessons = flatLessons.length;
const completedCount = completedLessonIds.length;
const progressPercent = totalLessons > 0 ? Math.round((completedCount / totalLessons) * 100) : 0;
const selectedLesson =
flatLessons.find((lesson) => lesson.id === selectedLessonId) ?? flatLessons[0] ?? null;
const isRestricted = (lessonId: string) => {
const lessonIndex = flatLessons.findIndex((lesson) => lesson.id === lessonId);
if (lessonIndex <= 0) return false;
if (completedSet.has(lessonId)) return false;
const previousLesson = flatLessons[lessonIndex - 1];
return !completedSet.has(previousLesson.id);
};
const navigateToLesson = (lessonId: string) => {
if (isRestricted(lessonId)) return;
setSelectedLessonId(lessonId);
router.push(`/courses/${courseSlug}/learn?lesson=${lessonId}`, { scroll: false });
};
const handleToggleComplete = async () => {
if (!selectedLesson || isSaving) return;
const lessonId = selectedLesson.id;
const wasCompleted = completedSet.has(lessonId);
setCompletedLessonIds((prev) =>
wasCompleted ? prev.filter((id) => id !== lessonId) : [...prev, lessonId],
);
startTransition(async () => {
const result = await toggleLessonComplete({ courseSlug, lessonId });
if (!result.success) {
setCompletedLessonIds((prev) =>
wasCompleted ? [...prev, lessonId] : prev.filter((id) => id !== lessonId),
);
return;
}
setCompletedLessonIds((prev) => {
if (result.isCompleted) {
return prev.includes(lessonId) ? prev : [...prev, lessonId];
}
return prev.filter((id) => id !== lessonId);
});
router.refresh();
});
};
if (!selectedLesson) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6">
<h1 className="text-2xl font-semibold text-slate-900">No lessons available yet</h1>
<p className="mt-2 text-sm text-slate-600">This course does not have lessons configured.</p>
</div>
);
}
return (
<div className="grid gap-6 lg:grid-cols-[1.7fr_1fr]">
<section className="space-y-4 rounded-xl border border-slate-200 bg-white p-5">
<Link href={`/courses/${courseSlug}`} className="text-sm font-medium text-slate-600 hover:text-slate-900">
{"<-"} Back to Course
</Link>
<div className="aspect-video overflow-hidden rounded-xl border border-slate-200 bg-black">
{selectedLesson.videoUrl ? (
<video
key={`${selectedLesson.id}-${selectedLesson.videoUrl}`}
className="h-full w-full"
controls
onEnded={handleToggleComplete}
src={selectedLesson.videoUrl}
/>
) : (
<div className="flex h-full items-center justify-center text-sm text-slate-300">
Video not available for this lesson
</div>
)}
</div>
<div className="space-y-2 rounded-xl border border-slate-200 bg-white p-4">
<h1 className="text-2xl font-semibold text-slate-900">{selectedLesson.title}</h1>
{selectedLesson.description ? (
<p className="text-sm text-slate-600">{selectedLesson.description}</p>
) : null}
<p className="text-xs text-slate-500">
Duration: {Math.max(1, Math.ceil(selectedLesson.estimatedDuration / 60))} min
</p>
</div>
<button
type="button"
onClick={handleToggleComplete}
disabled={isSaving}
className="rounded-md border border-slate-300 bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-60"
>
{completedSet.has(selectedLesson.id) ? "Mark as Incomplete" : "Mark as Complete"}
</button>
</section>
<aside className="rounded-xl border border-slate-200 bg-white p-4">
<h2 className="mb-3 text-lg font-semibold text-slate-900">Course Content</h2>
<p className="mb-3 text-xs text-slate-500">{courseTitle}</p>
<div className="mb-4">
<ProgressBar
value={progressPercent}
label={`${completedCount}/${totalLessons} lessons (${progressPercent}%)`}
/>
</div>
<div className="max-h-[70vh] space-y-4 overflow-y-auto pr-1">
{modules.map((module, moduleIndex) => (
<div key={module.id} className="rounded-xl border border-slate-200 bg-slate-50/40">
<div className="border-b border-slate-200 px-3 py-2">
<p className="text-sm font-semibold text-slate-800">
Module {moduleIndex + 1}: {module.title}
</p>
</div>
<div className="space-y-1 p-2">
{module.lessons.map((lesson, lessonIndex) => {
const completed = completedSet.has(lesson.id);
const restricted = isRestricted(lesson.id);
const active = lesson.id === selectedLesson.id;
return (
<button
key={lesson.id}
type="button"
disabled={restricted}
onClick={() => navigateToLesson(lesson.id)}
className={`flex w-full items-center gap-2 rounded-lg border px-2 py-2 text-left text-sm transition-colors ${
active
? "border-slate-300 bg-white text-slate-900"
: "border-transparent bg-white/70 text-slate-700 hover:border-slate-200"
} ${restricted ? "cursor-not-allowed opacity-60 hover:border-transparent" : ""}`}
>
<span className="inline-flex h-5 w-5 items-center justify-center">
{completed ? (
<Check className="h-4 w-4 text-emerald-600" />
) : restricted ? (
<Lock className="h-4 w-4 text-slate-400" />
) : (
<PlayCircle className="h-4 w-4 text-slate-500" />
)}
</span>
<span className="line-clamp-1">
{lessonIndex + 1}. {lesson.title}
</span>
</button>
);
})}
</div>
</div>
))}
</div>
</aside>
</div>
);
}

45
components/teacher/TeacherDashboardClient.tsx Normal file → Executable file
View File

@@ -15,6 +15,13 @@ export default function TeacherDashboardClient() {
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load); return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, []); }, []);
const totalLessons = courses.reduce((sum, course) => sum + course.lessons.length, 0);
const totalStudents = courses.reduce((sum, course) => sum + course.students, 0);
const averageRating =
courses.length === 0 ? 0 : courses.reduce((sum, course) => sum + course.rating, 0) / courses.length;
const publishedCount = courses.filter((course) => course.status === "Published").length;
const draftCount = courses.filter((course) => course.status === "Draft").length;
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
@@ -22,14 +29,39 @@ export default function TeacherDashboardClient() {
<h1 className="text-3xl font-bold text-slate-900">Teacher Dashboard</h1> <h1 className="text-3xl font-bold text-slate-900">Teacher Dashboard</h1>
<p className="text-slate-600">Manage teacher-created courses stored locally for MVP.</p> <p className="text-slate-600">Manage teacher-created courses stored locally for MVP.</p>
</div> </div>
<Link <div className="flex gap-2">
className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" <Link
href="/teacher/courses/new" className="rounded-md border border-slate-300 px-4 py-2 text-sm font-semibold hover:bg-slate-50"
> href="/teacher/uploads"
Create course >
</Link> Upload library
</Link>
<Link
className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105"
href="/teacher/courses/new"
>
Create course
</Link>
</div>
</div> </div>
<section className="grid gap-4 sm:grid-cols-3">
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Courses</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{courses.length}</p>
<p className="mt-1 text-xs text-slate-500">Published: {publishedCount} | Draft: {draftCount}</p>
</article>
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Lessons</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{totalLessons}</p>
</article>
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Avg. rating</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{averageRating.toFixed(1)}</p>
<p className="mt-1 text-xs text-slate-500">Students tracked: {totalStudents}</p>
</article>
</section>
{courses.length === 0 ? ( {courses.length === 0 ? (
<div className="rounded-xl border border-dashed border-slate-300 bg-white p-6 text-sm text-slate-600"> <div className="rounded-xl border border-dashed border-slate-300 bg-white p-6 text-sm text-slate-600">
No teacher-created courses yet. No teacher-created courses yet.
@@ -41,6 +73,7 @@ export default function TeacherDashboardClient() {
<div className="flex flex-wrap items-start justify-between gap-3"> <div className="flex flex-wrap items-start justify-between gap-3">
<div> <div>
<p className="text-xs font-semibold uppercase tracking-wide text-brand">{course.level}</p> <p className="text-xs font-semibold uppercase tracking-wide text-brand">{course.level}</p>
<p className="mt-1 text-xs font-semibold uppercase tracking-wide text-slate-500">{course.status}</p>
<h2 className="text-xl font-semibold text-slate-900">{course.title}</h2> <h2 className="text-xl font-semibold text-slate-900">{course.title}</h2>
<p className="mt-1 text-sm text-slate-600">{course.summary}</p> <p className="mt-1 text-sm text-slate-600">{course.summary}</p>
</div> </div>

493
components/teacher/TeacherEditCourseForm.tsx Normal file → Executable file
View File

@@ -1,176 +1,373 @@
// components/teacher/TeacherEditCourseForm.tsx
"use client"; "use client";
import Link from "next/link"; import {
import { FormEvent, useEffect, useState } from "react"; updateCourse,
createModule,
createLesson,
reorderModules,
reorderLessons,
} from "@/app/(protected)/teacher/actions";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { getTeacherCourseBySlug, teacherCoursesUpdatedEventName, updateTeacherCourse } from "@/lib/data/teacherCourses"; import Link from "next/link";
import type { Course, CourseLevel } from "@/types/course"; import { toast } from "sonner";
const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"]; import { Prisma } from "@prisma/client";
type TeacherEditCourseFormProps = { type CourseData = {
id: string;
slug: string; slug: string;
title: Prisma.JsonValue;
description: Prisma.JsonValue;
level: string;
status: string;
price: number;
modules: {
id: string;
title: Prisma.JsonValue;
lessons: { id: string; title: Prisma.JsonValue }[];
}[];
}; };
export default function TeacherEditCourseForm({ slug }: TeacherEditCourseFormProps) { export default function TeacherEditCourseForm({ course }: { course: CourseData }) {
const router = useRouter(); const router = useRouter();
const [course, setCourse] = useState<Course | null>(null); const [loading, setLoading] = useState(false);
const [title, setTitle] = useState(""); const [optimisticModules, setOptimisticModules] = useState(course.modules);
const [level, setLevel] = useState<CourseLevel>("Beginner");
const [summary, setSummary] = useState("");
const [instructor, setInstructor] = useState("");
const [weeks, setWeeks] = useState(4);
const [rating, setRating] = useState(5);
const [saved, setSaved] = useState(false);
useEffect(() => { useEffect(() => {
const load = () => { setOptimisticModules(course.modules);
const found = getTeacherCourseBySlug(slug) ?? null; }, [course.modules]);
setCourse(found);
if (!found) return;
setTitle(found.title);
setLevel(found.level);
setSummary(found.summary);
setInstructor(found.instructor);
setWeeks(found.weeks);
setRating(found.rating);
};
load(); // Helper for JSON/String fields
window.addEventListener(teacherCoursesUpdatedEventName, load); const getStr = (val: Prisma.JsonValue) => {
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load); if (typeof val === "string") return val;
}, [slug]); if (val && typeof val === "object" && !Array.isArray(val)) {
const v = val as Record<string, unknown>;
const submit = (event: FormEvent) => { if (typeof v.en === "string") return v.en;
event.preventDefault(); if (typeof v.es === "string") return v.es;
if (!course) return; return "";
}
updateTeacherCourse(course.slug, { return "";
title: title.trim(),
level,
summary: summary.trim(),
instructor: instructor.trim(),
weeks: Math.max(1, weeks),
rating: Math.min(5, Math.max(0, rating)),
});
setSaved(true);
window.setTimeout(() => setSaved(false), 1200);
}; };
if (!course) { // 1. SAVE COURSE SETTINGS
return ( async function handleSubmit(formData: FormData) {
<div className="mx-auto max-w-2xl space-y-3 rounded-xl border border-slate-200 bg-white p-6 shadow-sm"> setLoading(true);
<h1 className="text-2xl font-bold text-slate-900">Teacher course not found</h1> const res = await updateCourse(course.id, course.slug, formData);
<p className="text-slate-600">This editor only works for courses created in the teacher area.</p>
<Link className="inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href="/teacher"> if (res.success) {
Back to dashboard toast.success("Curso actualizado");
</Link> router.refresh();
</div> } else {
); toast.error("Error al guardar");
}
setLoading(false);
} }
// 2. CREATE NEW MODULE
const handleAddModule = async () => {
setLoading(true); // Block UI while working
const res = await createModule(course.id);
if (res.success) {
toast.success("Módulo agregado");
router.refresh();
} else {
toast.error("Error al crear módulo");
}
setLoading(false);
};
// 3. CREATE NEW LESSON
const handleAddLesson = async (moduleId: string) => {
setLoading(true);
const res = await createLesson(moduleId);
if (res.success && res.lessonId) {
toast.success("Lección creada");
// Redirect immediately to the video upload page
router.push(`/teacher/courses/${course.slug}/lessons/${res.lessonId}`);
} else {
toast.error("Error al crear lección");
setLoading(false); // Only stop loading if we failed (otherwise we are redirecting)
}
};
// 4. REORDER MODULES (optimistic)
const handleReorderModule = async (moduleIndex: number, direction: "up" | "down") => {
const swapWith = direction === "up" ? moduleIndex - 1 : moduleIndex + 1;
if (swapWith < 0 || swapWith >= optimisticModules.length) return;
const next = [...optimisticModules];
[next[moduleIndex], next[swapWith]] = [next[swapWith], next[moduleIndex]];
setOptimisticModules(next);
const res = await reorderModules(optimisticModules[moduleIndex].id, direction);
if (res.success) {
router.refresh();
} else {
setOptimisticModules(course.modules);
toast.error(res.error ?? "Error al reordenar");
}
};
// 5. REORDER LESSONS (optimistic)
const handleReorderLesson = async (
moduleIndex: number,
lessonIndex: number,
direction: "up" | "down"
) => {
const lessons = optimisticModules[moduleIndex].lessons;
const swapWith = direction === "up" ? lessonIndex - 1 : lessonIndex + 1;
if (swapWith < 0 || swapWith >= lessons.length) return;
const nextModules = [...optimisticModules];
const nextLessons = [...lessons];
[nextLessons[lessonIndex], nextLessons[swapWith]] = [
nextLessons[swapWith],
nextLessons[lessonIndex],
];
nextModules[moduleIndex] = { ...nextModules[moduleIndex], lessons: nextLessons };
setOptimisticModules(nextModules);
const res = await reorderLessons(lessons[lessonIndex].id, direction);
if (res.success) {
router.refresh();
} else {
setOptimisticModules(course.modules);
toast.error(res.error ?? "Error al reordenar");
}
};
return ( return (
<div className="mx-auto max-w-3xl space-y-5"> <div className="mx-auto max-w-4xl space-y-6">
<form className="space-y-4 rounded-xl border border-slate-200 bg-white p-6 shadow-sm" onSubmit={submit}>
<h1 className="text-2xl font-bold text-slate-900">Edit Course</h1>
<label className="block"> {/* Header */}
<span className="mb-1 block text-sm text-slate-700">Title</span> <div className="flex items-center justify-between">
<input <h1 className="text-2xl font-bold text-slate-900">Editar Curso</h1>
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand" <div className="flex gap-2">
onChange={(event) => setTitle(event.target.value)} <Link
value={title} href={`/courses/${course.slug}`}
/> target="_blank"
</label> className="px-3 py-2 text-sm border border-slate-300 rounded-md hover:bg-slate-50 flex items-center gap-2"
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Level</span>
<select
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setLevel(event.target.value as CourseLevel)}
value={level}
> >
{levels.map((item) => ( <span>👁</span> Ver Vista Previa
<option key={item} value={item}> </Link>
{item}
</option>
))}
</select>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Summary</span>
<textarea
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setSummary(event.target.value)}
rows={3}
value={summary}
/>
</label>
<div className="grid gap-4 sm:grid-cols-2">
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Instructor</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setInstructor(event.target.value)}
value={instructor}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Weeks</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
min={1}
onChange={(event) => setWeeks(Number(event.target.value))}
type="number"
value={weeks}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Rating (0-5)</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
max={5}
min={0}
onChange={(event) => setRating(Number(event.target.value))}
step={0.1}
type="number"
value={rating}
/>
</label>
</div>
<div className="flex items-center gap-3">
<button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
Save changes
</button>
{saved ? <span className="text-sm font-medium text-emerald-700">Saved</span> : null}
<button <button
className="rounded-md border border-slate-300 px-4 py-2 text-sm hover:bg-slate-50" form="edit-form"
onClick={() => router.push(`/teacher/courses/${course.slug}/lessons/new`)} type="submit"
type="button" disabled={loading}
className="bg-black text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-slate-800 disabled:opacity-50"
> >
Add lesson {loading ? "Guardando..." : "Guardar Cambios"}
</button> </button>
</div> </div>
</form> </div>
<section className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm"> <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<h2 className="text-lg font-semibold text-slate-900">Lessons</h2>
<div className="mt-3 space-y-2"> {/* LEFT COLUMN: Main Info */}
{course.lessons.map((lesson) => ( <div className="lg:col-span-2 space-y-6">
<div key={lesson.id} className="rounded-md border border-slate-200 p-3 text-sm"> <form id="edit-form" action={handleSubmit} className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm space-y-4">
<p className="font-medium text-slate-900">{lesson.title}</p>
<p className="text-slate-600"> {/* Title */}
{lesson.type} | {lesson.minutes} min {lesson.isPreview ? "| Preview" : ""} <div>
</p> <label className="block text-sm font-medium text-slate-700 mb-1">Título</label>
<input
name="title"
defaultValue={getStr(course.title)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black transition-all"
/>
</div> </div>
))}
{/* Description */}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Resumen</label>
<textarea
name="summary"
rows={4}
defaultValue={getStr(course.description)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black transition-all"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Nivel</label>
<select
name="level"
defaultValue={course.level}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
>
<option value="BEGINNER">Principiante</option>
<option value="INTERMEDIATE">Intermedio</option>
<option value="ADVANCED">Avanzado</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Estado</label>
<select
name="status"
defaultValue={course.status}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
>
<option value="DRAFT">Borrador</option>
<option value="PUBLISHED">Publicado</option>
</select>
</div>
</div>
</form>
{/* MODULES & LESSONS SECTION */}
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">Plan de Estudios</h2>
<button
type="button"
onClick={handleAddModule}
disabled={loading}
className="text-sm text-blue-600 font-medium hover:underline disabled:opacity-50"
>
+ Nuevo Módulo
</button>
</div>
<div className="space-y-4">
{optimisticModules.length === 0 && (
<div className="text-center py-8 border border-dashed border-slate-200 rounded-lg bg-slate-50">
<p className="text-slate-500 text-sm mb-2">Tu curso está vacío.</p>
<button onClick={handleAddModule} className="text-black underline text-sm font-medium">
Agrega el primer módulo
</button>
</div>
)}
{optimisticModules.map((module, moduleIndex) => (
<div key={module.id} className="border border-slate-200 rounded-xl overflow-hidden bg-white shadow-sm">
{/* Module Header */}
<div className="bg-slate-50 px-4 py-2 border-b border-slate-200 flex justify-between items-center">
<div className="flex items-center gap-2">
<span className="font-medium text-sm text-slate-800">{getStr(module.title)}</span>
<div className="flex items-center">
<button
type="button"
onClick={() => handleReorderModule(moduleIndex, "up")}
disabled={moduleIndex === 0}
className="p-1.5 rounded-lg text-slate-500 hover:bg-slate-200 hover:text-slate-800 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover módulo arriba"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
</svg>
</button>
<button
type="button"
onClick={() => handleReorderModule(moduleIndex, "down")}
disabled={moduleIndex === optimisticModules.length - 1}
className="p-1.5 rounded-lg text-slate-500 hover:bg-slate-200 hover:text-slate-800 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover módulo abajo"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
</div>
<button className="text-xs text-slate-500 hover:text-black">Editar Título</button>
</div>
{/* Lessons List */}
<div className="divide-y divide-slate-100">
{module.lessons.map((lesson, lessonIndex) => (
<div
key={lesson.id}
className="px-4 py-3 flex items-center gap-2 hover:bg-slate-50 transition-colors group"
>
<div className="flex flex-col">
<button
type="button"
onClick={() => handleReorderLesson(moduleIndex, lessonIndex, "up")}
disabled={lessonIndex === 0}
className="p-0.5 rounded text-slate-400 hover:bg-slate-200 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover lección arriba"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
</svg>
</button>
<button
type="button"
onClick={() => handleReorderLesson(moduleIndex, lessonIndex, "down")}
disabled={lessonIndex === module.lessons.length - 1}
className="p-0.5 rounded text-slate-400 hover:bg-slate-200 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover lección abajo"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
<Link
href={`/teacher/courses/${course.slug}/lessons/${lesson.id}`}
className="flex items-center gap-3 flex-1 min-w-0"
>
<span className="text-slate-400 text-lg group-hover:text-blue-500 flex-shrink-0"></span>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-slate-700 group-hover:text-slate-900">
{getStr(lesson.title)}
</p>
</div>
<span className="text-xs text-slate-400 opacity-0 group-hover:opacity-100 border border-slate-200 rounded px-2 py-1 flex-shrink-0">
Editar Contenido
</span>
</Link>
</div>
))}
{/* Add Lesson Button */}
<button
type="button"
onClick={() => handleAddLesson(module.id)}
disabled={loading}
className="w-full text-left px-4 py-3 text-xs text-slate-500 hover:text-blue-600 hover:bg-slate-50 font-medium flex items-center gap-2 transition-colors"
>
<span className="text-lg leading-none">+</span> Agregar Lección
</button>
</div>
</div>
))}
</div>
</div>
</div> </div>
</section>
{/* RIGHT COLUMN: Price / Help */}
<div className="space-y-6">
<div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
<label className="block text-sm font-medium text-slate-700 mb-1">Precio (MXN)</label>
<input
form="edit-form"
name="price"
type="number"
step="0.01"
defaultValue={course.price}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
/>
<p className="mt-2 text-xs text-slate-500">
Si es 0, el curso será gratuito.
</p>
</div>
<div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
<h3 className="font-semibold text-slate-900 mb-2">💡 Tips</h3>
<ul className="text-sm text-slate-600 space-y-2 list-disc pl-4">
<li>Crea módulos para organizar tus temas.</li>
<li>Dentro de cada módulo, agrega lecciones.</li>
<li>Haz clic en una lección para <strong>subir el video</strong>.</li>
</ul>
</div>
</div>
</div>
</div> </div>
); );
} }

178
components/teacher/TeacherNewCourseForm.tsx Normal file → Executable file
View File

@@ -1,112 +1,108 @@
"use client"; "use client";
import { FormEvent, useState } from "react"; import { createCourse } from "@/app/(protected)/teacher/actions"; // Server Action
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { getAllCourseSlugs } from "@/lib/data/courseCatalog"; import { useState, FormEvent } from "react";
import { createTeacherCourse } from "@/lib/data/teacherCourses"; import Link from "next/link";
import type { CourseLevel } from "@/types/course";
const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"];
export default function TeacherNewCourseForm() { export default function TeacherNewCourseForm() {
const router = useRouter(); const router = useRouter();
const [title, setTitle] = useState(""); const [isLoading, setIsLoading] = useState(false);
const [level, setLevel] = useState<CourseLevel>("Beginner");
const [summary, setSummary] = useState("");
const [instructor, setInstructor] = useState("");
const [weeks, setWeeks] = useState(4);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const submit = (event: FormEvent) => { async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); event.preventDefault();
setIsLoading(true);
setError(null); setError(null);
const cleanTitle = title.trim(); const formData = new FormData(event.currentTarget);
const cleanSummary = summary.trim();
const cleanInstructor = instructor.trim();
if (!cleanTitle || !cleanSummary || !cleanInstructor) { try {
setError("Title, summary, and instructor are required."); // 1. Call the Server Action
return; const result = await createCourse(formData);
if (result.success && result.data) {
// 2. Redirect to the Course Editor
// We will build the [slug]/edit page next
router.push(`/teacher/courses/${result.data.slug}/edit`);
} else {
setError(result.error || "Algo salió mal al crear el curso.");
setIsLoading(false);
}
} catch {
setError("Error de conexión. Inténtalo de nuevo.");
setIsLoading(false);
} }
}
const created = createTeacherCourse(
{
title: cleanTitle,
level,
summary: cleanSummary,
instructor: cleanInstructor,
weeks: Math.max(1, weeks),
},
getAllCourseSlugs(),
);
router.push(`/teacher/courses/${created.slug}/edit`);
};
return ( return (
<form className="mx-auto max-w-2xl space-y-4 rounded-xl border border-slate-200 bg-white p-6 shadow-sm" onSubmit={submit}> <div className="mx-auto max-w-2xl">
<h1 className="text-2xl font-bold text-slate-900">Create Course</h1> {/* Breadcrumb / Back Link */}
<div className="mb-6">
<label className="block"> <Link
<span className="mb-1 block text-sm text-slate-700">Title</span> href="/teacher"
<input className="text-sm text-slate-500 hover:text-slate-900 transition-colors"
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setTitle(event.target.value)}
value={title}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Level</span>
<select
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setLevel(event.target.value as CourseLevel)}
value={level}
> >
{levels.map((item) => ( Volver al Panel
<option key={item} value={item}> </Link>
{item} </div>
</option>
))}
</select>
</label>
<label className="block"> <div className="rounded-xl border border-slate-200 bg-white p-8 shadow-sm">
<span className="mb-1 block text-sm text-slate-700">Summary</span> <h1 className="text-2xl font-bold text-slate-900 mb-2">Crear Nuevo Curso</h1>
<textarea <p className="text-slate-600 mb-8">
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand" Empieza con un título. Podrás agregar lecciones, cuestionarios y más detalles en la siguiente pantalla.
onChange={(event) => setSummary(event.target.value)} </p>
rows={3}
value={summary}
/>
</label>
<label className="block"> <form onSubmit={handleSubmit} className="space-y-6">
<span className="mb-1 block text-sm text-slate-700">Instructor</span> <div>
<input <label
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand" htmlFor="title"
onChange={(event) => setInstructor(event.target.value)} className="block text-sm font-medium text-slate-700 mb-1"
value={instructor} >
/> Título del Curso
</label> </label>
<input
id="title"
name="title"
type="text"
required
disabled={isLoading}
placeholder="Ej. Inglés Jurídico: Contratos Internacionales"
className="w-full rounded-lg border border-slate-300 px-4 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all disabled:opacity-50 disabled:bg-slate-50"
autoFocus
/>
<p className="mt-2 text-xs text-slate-500">
Esto generará la URL pública de tu curso.
</p>
</div>
<label className="block"> {error && (
<span className="mb-1 block text-sm text-slate-700">Weeks</span> <div className="bg-red-50 text-red-600 text-sm p-3 rounded-md border border-red-100">
<input {error}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand" </div>
min={1} )}
onChange={(event) => setWeeks(Number(event.target.value))}
type="number"
value={weeks}
/>
</label>
{error ? <p className="text-sm text-red-600">{error}</p> : null} <div className="flex items-center gap-4 pt-4">
<Link
<button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit"> href="/teacher"
Create course className="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900 transition-colors"
</button> >
</form> Cancelar
</Link>
<button
type="submit"
disabled={isLoading}
className="rounded-lg bg-black px-6 py-2 text-sm font-medium text-white hover:bg-slate-800 transition-colors disabled:opacity-50 flex items-center gap-2"
>
{isLoading ? (
<>Creating...</>
) : (
"Crear Curso & Continuar"
)}
</button>
</div>
</form>
</div>
</div>
); );
} }

0
components/teacher/TeacherNewLessonForm.tsx Normal file → Executable file
View File

View File

@@ -0,0 +1,140 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { getTeacherCourses, teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import type { Course } from "@/types/course";
type UploadAsset = {
id: string;
fileName: string;
type: "video" | "pdf" | "audio";
duration?: string;
size: string;
uploadedAt: string;
};
const mockAssets: UploadAsset[] = [
{ id: "asset-1", fileName: "contracts-intro-v1.mp4", type: "video", duration: "08:34", size: "48 MB", uploadedAt: "2026-02-01" },
{ id: "asset-2", fileName: "clause-red-flags.mp4", type: "video", duration: "12:12", size: "66 MB", uploadedAt: "2026-02-03" },
{ id: "asset-3", fileName: "brief-writing-reference.pdf", type: "pdf", size: "2.3 MB", uploadedAt: "2026-02-05" },
];
export default function TeacherUploadsLibraryClient() {
const [courses, setCourses] = useState<Course[]>([]);
const [selectedCourseByAsset, setSelectedCourseByAsset] = useState<Record<string, string>>({});
const [selectedLessonByAsset, setSelectedLessonByAsset] = useState<Record<string, string>>({});
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
const load = () => setCourses(getTeacherCourses());
load();
window.addEventListener(teacherCoursesUpdatedEventName, load);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, []);
const lessonOptionsByCourse = useMemo(() => {
const map: Record<string, Array<{ id: string; title: string }>> = {};
for (const course of courses) {
map[course.slug] = course.lessons.map((lesson) => ({ id: lesson.id, title: lesson.title }));
}
return map;
}, [courses]);
const attachAsset = (assetId: string) => {
const courseSlug = selectedCourseByAsset[assetId];
const lessonId = selectedLessonByAsset[assetId];
if (!courseSlug || !lessonId) {
setMessage("Select a course and lesson before attaching.");
return;
}
setMessage(`Placeholder only: asset attached to ${courseSlug} / ${lessonId}.`);
};
return (
<div className="space-y-6">
<header className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<h1 className="text-3xl font-bold text-slate-900">Upload Library</h1>
<p className="mt-1 text-sm text-slate-600">Central cloud-style asset library for reusing videos and files across courses.</p>
<p className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
Upload disabled in MVP. This is a placeholder for backend integration.
</p>
<div className="mt-4 flex gap-2">
<Link className="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50" href="/teacher">
Back to dashboard
</Link>
<button className="rounded-md bg-slate-200 px-3 py-1.5 text-sm font-semibold text-slate-700" type="button">
Upload file (disabled)
</button>
</div>
</header>
{message ? (
<p className="rounded-md border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700">{message}</p>
) : null}
<section className="grid gap-4">
{mockAssets.map((asset) => {
const selectedCourse = selectedCourseByAsset[asset.id] ?? "";
const lessonOptions = selectedCourse ? lessonOptionsByCourse[selectedCourse] ?? [] : [];
return (
<article key={asset.id} className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-brand">{asset.type}</p>
<h2 className="text-lg font-semibold text-slate-900">{asset.fileName}</h2>
<p className="mt-1 text-sm text-slate-600">
{asset.size} {asset.duration ? `| ${asset.duration}` : ""} | Uploaded {asset.uploadedAt}
</p>
</div>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
<select
className="rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
onChange={(event) => {
const slug = event.target.value;
setSelectedCourseByAsset((current) => ({ ...current, [asset.id]: slug }));
setSelectedLessonByAsset((current) => ({ ...current, [asset.id]: "" }));
}}
value={selectedCourse}
>
<option value="">Select course</option>
{courses.map((course) => (
<option key={course.slug} value={course.slug}>
{course.title}
</option>
))}
</select>
<select
className="rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
disabled={!selectedCourse}
onChange={(event) =>
setSelectedLessonByAsset((current) => ({ ...current, [asset.id]: event.target.value }))
}
value={selectedLessonByAsset[asset.id] ?? ""}
>
<option value="">Select lesson</option>
{lessonOptions.map((lesson) => (
<option key={lesson.id} value={lesson.id}>
{lesson.title}
</option>
))}
</select>
<button
className="rounded-md border border-slate-300 px-3 py-2 text-sm font-semibold hover:bg-slate-50"
onClick={() => attachAsset(asset.id)}
type="button"
>
Attach to lesson
</button>
</div>
</article>
);
})}
</section>
</div>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import { useState } from "react";
import { createBrowserClient } from "@supabase/ssr";
import { toast } from "sonner"; // or use alert()
interface VideoUploadProps {
lessonId: string;
currentVideoUrl?: string | null;
onUploadComplete: (url: string) => void; // Callback to save to DB
}
export default function VideoUpload({ lessonId, currentVideoUrl, onUploadComplete }: VideoUploadProps) {
const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0);
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
setProgress(0);
const supabase = createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
// Create a unique file path: lesson_id/timestamp_filename
const filePath = `${lessonId}/${Date.now()}_${file.name}`;
const { error } = await supabase.storage
.from("courses") // Make sure this bucket exists!
.upload(filePath, file, {
upsert: true,
});
if (error) {
toast.error("Upload failed: " + error.message);
setUploading(false);
return;
}
// Get Public URL
const { data: { publicUrl } } = supabase.storage
.from("courses")
.getPublicUrl(filePath);
onUploadComplete(publicUrl);
setUploading(false);
};
return (
<div className="border border-slate-200 rounded-lg p-6 bg-slate-50">
<h3 className="font-medium text-slate-900 mb-2">Video de la Lección</h3>
{currentVideoUrl ? (
<div className="mb-4 aspect-video bg-black rounded-md overflow-hidden relative group">
<video src={currentVideoUrl} controls className="w-full h-full" />
<div className="absolute inset-0 bg-black/50 hidden group-hover:flex items-center justify-center">
<p className="text-white text-sm">Subir otro para reemplazar</p>
</div>
</div>
) : (
<div className="mb-4 aspect-video bg-slate-200 rounded-md flex items-center justify-center text-slate-400">
Sin video
</div>
)}
<div className="flex flex-col gap-2">
<label className="block w-full">
<span className="sr-only">Choose video</span>
<input
type="file"
accept="video/*"
onChange={handleUpload}
disabled={uploading}
className="block w-full text-sm text-slate-500
file:mr-4 file:py-2 file:px-4
file:rounded-full file:border-0
file:text-sm file:font-semibold
file:bg-black file:text-white
hover:file:bg-slate-800
"
/>
</label>
{uploading && (
<div className="w-full bg-slate-200 rounded-full h-2 mt-2">
<div className="bg-black h-2 rounded-full transition-all" style={{ width: `${progress}%` }}></div>
</div>
)}
</div>
</div>
);
}

36
components/ui/badge.tsx Executable file
View File

@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }

57
components/ui/button.tsx Executable file
View File

@@ -0,0 +1,57 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

76
components/ui/card.tsx Executable file
View File

@@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

22
components/ui/input.tsx Executable file
View File

@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

48
components/ui/scroll-area.tsx Executable file
View File

@@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }

140
components/ui/sheet.tsx Executable file
View File

@@ -0,0 +1,140 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Sheet = SheetPrimitive.Root
const SheetTrigger = SheetPrimitive.Trigger
const SheetClose = SheetPrimitive.Close
const SheetPortal = SheetPrimitive.Portal
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
}
)
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
{children}
</SheetPrimitive.Content>
</SheetPortal>
))
SheetContent.displayName = SheetPrimitive.Content.displayName
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
SheetHeader.displayName = "SheetHeader"
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
SheetFooter.displayName = "SheetFooter"
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-foreground", className)}
{...props}
/>
))
SheetTitle.displayName = SheetPrimitive.Title.displayName
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
SheetDescription.displayName = SheetPrimitive.Description.displayName
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

31
components/ui/sonner.tsx Normal file
View File

@@ -0,0 +1,31 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }

55
components/ui/tabs.tsx Executable file
View File

@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }

252
frontend_plan.md Executable file
View File

@@ -0,0 +1,252 @@
# ACVE Frontend Product Plan (MVP-first, Fully Mapped UX)
## Purpose
Give a complete, navigable frontend experience (even if powered by mock data) that illustrates the full platform: learner flow, teacher flow, auth, course creation, uploads, and admin surfaces. This is intended to be the living blueprint for backend integration.
## Principles
- Every button leads somewhere (even if placeholder).
- Every flow is complete end-to-end, including empty states.
- Mock data must map to real schema terms to reduce backend mismatch.
- Logged-out and logged-in states are always distinct and testable.
- Teacher-only actions are visible only where appropriate, but teacher onboarding should be clear.
## Target Roles
- Visitor (logged out)
- Learner (logged in)
- Teacher (logged in, teacher role)
- Org Admin (future, placeholder-only)
- Super Admin (future, placeholder-only)
## Core Navigation Map
Top nav:
- Home
- Courses
- Case Studies
- Practice
- AI Assistant
- Auth (Login/Sign up or Account menu)
Global flows:
- Auth gating for: course player, practice modules, teacher dashboard.
- Visitor can browse marketing and course detail pages.
## User Journey: Visitor -> Learner
1. Home
- CTA: “Start Learning” -> /courses
- CTA: “Explore Courses” -> /courses
2. Courses list
- Filter by level
- Course cards show title, summary, instructor, rating, lessons, weeks
- CTA on card: “View Course” -> /courses/[slug]
3. Course detail
- Shows course description and “Start Course” button
- If logged out: CTA “Login to start” -> /auth/login?redirectTo=/courses/[slug]/learn
4. Login / Signup
- Email/password login
- “Are you a teacher? Login here” (teacher hint CTA)
5. After login
- Redirect back to requested page or /courses
6. Course player
- Lesson list with lock state for non-preview lessons if logged out
- Progress tracking
- “Mark complete” updates local progress
## User Journey: Teacher
1. Teacher login entry points
- Login page: “Are you a teacher? Login here” -> /auth/login?role=teacher (frontend-only)
- Navbar: “Teacher Dashboard” visible when role=teacher (or local mock toggle)
2. Teacher dashboard
- List teacher-created courses (mock/localStorage)
- CTA: “Create Course” -> /teacher/courses/new
3. Create course
- Title, level, summary, instructor, weeks
- Creates a local course stub with one intro lesson
- Redirect to edit course page
4. Edit course
- Update details
- List lessons
- CTA: “Add lesson” -> /teacher/courses/[slug]/lessons/new
5. Add lesson
- Title, type (video/reading/interactive), duration
- Video: field for placeholder URL or “Upload video” (mock)
- Save -> returns to edit page
6. Course publish flow (mock)
- Add “Status” selector (Draft/Published)
- Published courses appear in public catalog
## Planned Screens (Additions/Upgrades)
### Auth
- Login page
- Add teacher CTA
- Add “Forgot password” placeholder
- Signup page
- Add “I am a teacher” checkbox (frontend only)
- Show note: “Teacher accounts are approved by admin” (placeholder)
### Teacher Surfaces
- /teacher
- Add stats cards (mock)
- Add “Upload library” link (placeholder)
- /teacher/courses/[slug]/edit
- Add modules section (placeholder UI)
- Add reorder UI (drag handles, non-functional)
- /teacher/uploads
- Upload manager placeholder with file list
### Learner Surfaces
- /courses/[slug]/learn
- Add sidebar module grouping (placeholder)
- Add resource downloads section (placeholder)
- /practice/[slug]
- Add attempt history (mock)
### Org Admin (future placeholder)
- /org
- Team seats, usage, course assignments (placeholder only)
## Data Strategy (Frontend)
- Current:
- Course catalog: mockCourses + local teacher courses
- Practice: mock modules
- Case studies: mock
- Progress: localStorage (per userId or guest)
- Future API mapping (for backend):
- Courses -> Prisma `Course`, `Module`, `Lesson`
- Teachers -> `Profile` role=TEACHER
- Uploads -> `Resource` or `Lesson` video URL
- Progress -> `UserProgress`
## Page-by-Page Spec
### / (Home)
- Hero, highlights, CTA
- Quick links to courses/case studies/practice
### /courses
- Tabs for levels
- Grid of cards
- Badge for status (Draft/Published) for teacher
### /courses/[slug]
- Course overview
- “Start Course” button (auth-gated)
### /courses/[slug]/learn (Protected)
- Lesson list
- Lesson viewer with placeholders
- Progress bar
### /practice
- Modules list
### /practice/[slug] (Protected)
- Quiz flow
### /case-studies
- Case list + active preview
### /case-studies/[slug]
- Full case view
### /assistant
- Full page assistant UI
### /auth/login
- Login form
- CTA: teacher login
### /auth/signup
- Signup form
- Teacher checkbox (placeholder)
### /teacher (Protected)
- Dashboard
- Create course
### /teacher/courses/new (Protected)
- Create course form
### /teacher/courses/[slug]/edit (Protected)
- Edit course
- Lesson list
### /teacher/courses/[slug]/lessons/new (Protected)
- Add lesson
### /teacher/uploads (Protected)
- Placeholder upload UI
### /org (Protected)
- Placeholder org admin dashboard
## UX/Content Notes
- All teacher-only actions should be labeled “Teacher only” if role is not teacher.
- No real upload yet: use “Upload disabled in MVP” messaging.
- Show consistent empty states with CTA.
## Implementation Notes (Frontend)
- Use localStorage for teacher-created courses and uploads.
- Use event emitters to re-render lists when localStorage updates.
- Keep schema-aligned data shapes for easy backend swap.
## Milestones
1. Complete teacher login CTA + role hints
2. Teacher flows: create/edit/lessons + placeholder uploads
3. Course player: modules/resources placeholders
4. Org admin placeholder
5. UI polish & copy pass
## Implementation Checklist (Living)
Status key: TODO | IN PROGRESS | DONE
Auth & Entry Points
- DONE Add teacher CTA on `/auth/login` and `/auth/signup`
- DONE Add “Forgot password” placeholder link
- DONE Add teacher invite-only note on signup
- DONE Add role hint handling (`role=teacher`) for copy changes
Navigation & Role Visibility
- DONE Show “Teacher Dashboard” link when teacher role is detected (allowlist-based)
- DONE Add non-teacher “Teacher only” labels where relevant
Teacher Dashboard & Course Ops
- DONE Add stats cards (mock)
- DONE Add course publish status selector (Draft/Published)
- DONE Ensure published teacher courses appear in public catalog
- DONE Add lesson reordering UI (non-functional)
Teacher Upload Library
- DONE Create `/teacher/uploads` placeholder page
- DONE Add upload list with mock assets
- DONE Add “Attach to lesson” picker placeholder
- DONE Add “Upload disabled in MVP” messaging
Course Player Enhancements
- DONE Add module grouping sidebar (placeholder)
- DONE Add resources/downloads section (placeholder)
Practice Enhancements
- DONE Add attempt history block (mock)
Org Admin Placeholder
- DONE Create `/org` placeholder dashboard (seats, usage, assignments)
UI/Copy Polish
- DONE Empty state consistency pass
- DONE Microcopy alignment with schema terminology
## Progress Log
- 2026-02-10: Implementation checklist added.
- 2026-02-10: Added teacher CTA, invite-only copy, role-aware login copy, and forgot-password placeholder.
- 2026-02-10: Added Supabase config validation fallback so malformed env values do not crash frontend; app continues in placeholder mode.
- 2026-02-10: Added demo auth fallback credentials + cookie session for frontend-only development and allowlist-based teacher navbar visibility.
- 2026-02-10: Added teacher upload library placeholder flow (`/teacher/uploads`) with mock assets, attach picker, and dashboard link/stats.
- 2026-02-10: Added visible "Teacher only" label in navbar for logged-in non-teachers.
- 2026-02-10: Added teacher course status workflow (Draft/Published), public catalog filtering for teacher courses, and lesson reorder placeholder controls.
- 2026-02-10: Added course player module/resource placeholders, mock practice attempt history, and protected org placeholder dashboard.
- 2026-02-10: Completed UX/copy polish pass for status visibility and placeholder consistency.
## Open Questions
Resolved:
- Teacher approval is invite-only.
- Teacher roles are determined by email allowlist.
- Uploads go to a central library (“cloud”) and can be assigned to lessons/courses (reusable assets).

36
lib/auth/clientAuth.ts Normal file
View File

@@ -0,0 +1,36 @@
import { DEMO_AUTH_EMAIL_COOKIE, DEMO_AUTH_ROLE_COOKIE } from "@/lib/auth/demoAuth";
export type ClientAuthSnapshot = {
userId: string;
userEmail: string | null;
isAuthed: boolean;
isTeacher: boolean;
};
const readCookieMap = (): Map<string, string> =>
new Map(
document.cookie
.split(";")
.map((entry) => entry.trim())
.filter(Boolean)
.map((entry) => {
const [key, ...rest] = entry.split("=");
return [key, decodeURIComponent(rest.join("="))] as const;
}),
);
export const readDemoClientAuth = (): ClientAuthSnapshot => {
if (typeof document === "undefined") {
return { userId: "guest", userEmail: null, isAuthed: false, isTeacher: false };
}
const cookies = readCookieMap();
const userEmail = cookies.get(DEMO_AUTH_EMAIL_COOKIE) ?? null;
const role = cookies.get(DEMO_AUTH_ROLE_COOKIE) ?? "";
return {
userId: userEmail ?? "guest",
userEmail,
isAuthed: Boolean(userEmail),
isTeacher: role === "teacher",
};
};

34
lib/auth/demoAuth.ts Normal file
View File

@@ -0,0 +1,34 @@
export const DEMO_AUTH_EMAIL_COOKIE = "acve_demo_email";
export const DEMO_AUTH_ROLE_COOKIE = "acve_demo_role";
type DemoAccount = {
email: string;
password: string;
role: "teacher" | "learner";
};
const demoAccounts: DemoAccount[] = [
{
email: "teacher@acve.local",
password: "teacher123",
role: "teacher",
},
{
email: "learner@acve.local",
password: "learner123",
role: "learner",
},
];
export const demoCredentialsHint = demoAccounts
.map((account) => `${account.email} / ${account.password}`)
.join(" | ");
export const findDemoAccount = (email: string, password: string): DemoAccount | null => {
const cleanEmail = email.trim().toLowerCase();
return (
demoAccounts.find(
(account) => account.email.toLowerCase() === cleanEmail && account.password === password,
) ?? null
);
};

67
lib/auth/requireTeacher.ts Normal file → Executable file
View File

@@ -1,26 +1,53 @@
import { redirect } from "next/navigation"; import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { requireUser } from "@/lib/auth/requireUser"; import { cookies } from "next/headers";
import { db } from "@/lib/prisma";
import { UserRole } from "@prisma/client";
import { logger } from "@/lib/logger";
const readTeacherEmails = (): string[] => export async function requireTeacher() {
(process.env.TEACHER_EMAILS ?? "")
.split(",")
.map((email) => email.trim().toLowerCase())
.filter(Boolean);
export const requireTeacher = async () => { const cookieStore = await cookies();
const user = await requireUser("/teacher");
if (!user?.email) { // 1. Get Supabase Session
redirect("/"); const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() { return cookieStore.getAll() },
setAll(cookiesToSet: { name: string; value: string; options?: CookieOptions }[]) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
)
} catch (error) {
// This is expected in Server Components, but let's log it just in case
logger.warn("Failed to set cookies in Server Component context (expected behavior)", error);
}
},
},
}
);
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
return null; // Let the caller handle the redirect
} }
const allowed = readTeacherEmails(); // 2. Check Role in Database
if (allowed.length === 0) { const profile = await db.profile.findUnique({
redirect("/"); where: { id: user.id },
}
);
console.log("AUTH_USER_ID:", user.id);
console.log("DB_PROFILE:", profile);
if (!profile || (profile.role !== UserRole.TEACHER && profile.role !== UserRole.SUPER_ADMIN)) {
// You can decide to return null or throw an error here
return null;
} }
if (!allowed.includes(user.email.toLowerCase())) { return profile;
redirect("/"); }
}
return user;
};

28
lib/auth/requireUser.ts Normal file → Executable file
View File

@@ -1,16 +1,18 @@
import { redirect } from "next/navigation"; import { createServerClient } from "@supabase/ssr";
import { supabaseServer } from "@/lib/supabase/server"; import { cookies } from "next/headers";
import { db } from "@/lib/prisma";
export const requireUser = async (redirectTo: string) => { export async function requireUser() {
const supabase = await supabaseServer(); const cookieStore = await cookies();
if (!supabase) { const supabase = createServerClient(
return null; process.env.NEXT_PUBLIC_SUPABASE_URL!,
} process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookies: { getAll() { return cookieStore.getAll() } } }
);
const { data } = await supabase.auth.getUser(); const { data: { user } } = await supabase.auth.getUser();
if (!data.user) { if (!user) return null;
redirect(`/auth/login?redirectTo=${encodeURIComponent(redirectTo)}`);
}
return data.user; const profile = await db.profile.findUnique({ where: { id: user.id } });
}; return profile;
}

View File

@@ -0,0 +1,16 @@
const parseTeacherEmails = (source: string | undefined): string[] =>
(source ?? "")
.split(",")
.map((email) => email.trim().toLowerCase())
.filter(Boolean);
export const readTeacherEmailsServer = (): string[] => parseTeacherEmails(process.env.TEACHER_EMAILS);
export const readTeacherEmailsBrowser = (): string[] =>
parseTeacherEmails(process.env.NEXT_PUBLIC_TEACHER_EMAILS);
export const isTeacherEmailAllowed = (email: string | null, allowed: string[]): boolean => {
if (!email) return false;
if (allowed.length === 0) return false;
return allowed.includes(email.toLowerCase());
};

14
lib/data/courseCatalog.ts Normal file → Executable file
View File

@@ -2,12 +2,14 @@ import { mockCourses } from "@/lib/data/mockCourses";
import { getTeacherCourseBySlug, getTeacherCourses } from "@/lib/data/teacherCourses"; import { getTeacherCourseBySlug, getTeacherCourses } from "@/lib/data/teacherCourses";
import type { Course } from "@/types/course"; import type { Course } from "@/types/course";
const isPublished = (course: Course) => course.status === "Published";
export const getAllCourses = (): Course[] => { export const getAllCourses = (): Course[] => {
const teacherCourses = getTeacherCourses(); const teacherCourses = getTeacherCourses().filter(isPublished);
if (teacherCourses.length === 0) return mockCourses; if (teacherCourses.length === 0) return mockCourses.filter(isPublished);
const teacherSlugs = new Set(teacherCourses.map((course) => course.slug)); const teacherSlugs = new Set(teacherCourses.map((course) => course.slug));
const baseCourses = mockCourses.filter((course) => !teacherSlugs.has(course.slug)); const baseCourses = mockCourses.filter((course) => isPublished(course) && !teacherSlugs.has(course.slug));
return [...baseCourses, ...teacherCourses]; return [...baseCourses, ...teacherCourses];
}; };
@@ -17,4 +19,8 @@ export const getCourseBySlug = (slug: string): Course | undefined => {
return mockCourses.find((course) => course.slug === slug); return mockCourses.find((course) => course.slug === slug);
}; };
export const getAllCourseSlugs = (): string[] => getAllCourses().map((course) => course.slug); export const getAllCourseSlugs = (): string[] => {
const teacherCourses = getTeacherCourses();
const all = [...mockCourses, ...teacherCourses];
return all.map((course) => course.slug);
};

0
lib/data/mockCaseStudies.ts Normal file → Executable file
View File

4
lib/data/mockCourses.ts Normal file → Executable file
View File

@@ -5,6 +5,7 @@ export const mockCourses: Course[] = [
slug: "legal-english-foundations", slug: "legal-english-foundations",
title: "Legal English Foundations", title: "Legal English Foundations",
level: "Beginner", level: "Beginner",
status: "Published",
summary: "Build legal vocabulary, core writing patterns, and court terminology.", summary: "Build legal vocabulary, core writing patterns, and court terminology.",
rating: 4.8, rating: 4.8,
weeks: 4, weeks: 4,
@@ -24,6 +25,7 @@ export const mockCourses: Course[] = [
slug: "contract-analysis-practice", slug: "contract-analysis-practice",
title: "Contract Analysis Practice", title: "Contract Analysis Practice",
level: "Intermediate", level: "Intermediate",
status: "Published",
summary: "Analyze contract sections and identify risk-heavy clauses quickly.", summary: "Analyze contract sections and identify risk-heavy clauses quickly.",
rating: 4.7, rating: 4.7,
weeks: 5, weeks: 5,
@@ -44,6 +46,7 @@ export const mockCourses: Course[] = [
slug: "litigation-brief-writing", slug: "litigation-brief-writing",
title: "Litigation Brief Writing", title: "Litigation Brief Writing",
level: "Advanced", level: "Advanced",
status: "Published",
summary: "Craft persuasive briefs with strong authority usage and argument flow.", summary: "Craft persuasive briefs with strong authority usage and argument flow.",
rating: 4.9, rating: 4.9,
weeks: 6, weeks: 6,
@@ -65,6 +68,7 @@ export const mockCourses: Course[] = [
slug: "cross-border-ip-strategy", slug: "cross-border-ip-strategy",
title: "Cross-Border IP Strategy", title: "Cross-Border IP Strategy",
level: "Advanced", level: "Advanced",
status: "Published",
summary: "Understand IP enforcement strategy across multiple jurisdictions.", summary: "Understand IP enforcement strategy across multiple jurisdictions.",
rating: 4.6, rating: 4.6,
weeks: 4, weeks: 4,

0
lib/data/mockPractice.ts Normal file → Executable file
View File

1
lib/data/teacherCourses.ts Normal file → Executable file
View File

@@ -92,6 +92,7 @@ export const createTeacherCourse = (input: TeacherCourseInput, reservedSlugs: st
slug, slug,
title: input.title, title: input.title,
level: input.level, level: input.level,
status: "Draft",
summary: input.summary, summary: input.summary,
rating: 5, rating: 5,
weeks: Math.max(1, input.weeks), weeks: Math.max(1, input.weeks),

21
lib/logger.ts Normal file
View File

@@ -0,0 +1,21 @@
const getTimestamp = () => new Date().toISOString();
export const logger = {
info: (message: string, ...args: unknown[]) => {
console.log(`[INFO] [${getTimestamp()}] ${message}`, ...args);
},
warn: (message: string, ...args: unknown[]) => {
console.warn(`[WARN] [${getTimestamp()}] ${message}`, ...args);
},
error: (message: string, error?: unknown) => {
console.error(`[ERROR] [${getTimestamp()}] ${message}`, error);
if (error instanceof Error) {
console.error(error.stack);
}
},
debug: (message: string, ...args: unknown[]) => {
if (process.env.NODE_ENV === 'development') {
console.debug(`[DEBUG] [${getTimestamp()}] ${message}`, ...args);
}
}
};

24
lib/prisma.ts Executable file
View File

@@ -0,0 +1,24 @@
import { Pool } from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '@prisma/client'
// Use the POOLER URL (6543) for the app to handle high traffic
const connectionString = process.env.DATABASE_URL
const createPrismaClient = () => {
// 1. Create the Pool
const pool = new Pool({ connectionString })
// 2. Create the Adapter
const adapter = new PrismaPg(pool)
// 3. Init the Client
return new PrismaClient({ adapter })
}
// Prevent multiple instances during development hot-reloading
declare global {
var prisma: ReturnType<typeof createPrismaClient> | undefined
}
export const db = globalThis.prisma || createPrismaClient()
if (process.env.NODE_ENV !== 'production') globalThis.prisma = db

0
lib/progress/localProgress.ts Normal file → Executable file
View File

9
lib/supabase/browser.ts Normal file → Executable file
View File

@@ -1,17 +1,16 @@
import { createClient, type SupabaseClient } from "@supabase/supabase-js"; import { createClient, type SupabaseClient } from "@supabase/supabase-js";
import { readSupabasePublicConfig } from "@/lib/supabase/config";
let browserClient: SupabaseClient | null = null; let browserClient: SupabaseClient | null = null;
export const supabaseBrowser = (): SupabaseClient | null => { export const supabaseBrowser = (): SupabaseClient | null => {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL; const config = readSupabasePublicConfig();
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; if (!config) {
if (!url || !anonKey) {
return null; return null;
} }
if (!browserClient) { if (!browserClient) {
browserClient = createClient(url, anonKey); browserClient = createClient(config.url, config.anonKey);
} }
return browserClient; return browserClient;

28
lib/supabase/config.ts Normal file
View File

@@ -0,0 +1,28 @@
const isValidHttpUrl = (value: string): boolean => {
try {
const parsed = new URL(value);
return parsed.protocol === "http:" || parsed.protocol === "https:";
} catch {
return false;
}
};
export type SupabasePublicConfig = {
url: string;
anonKey: string;
};
export const readSupabasePublicConfig = (): SupabasePublicConfig | null => {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim();
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY?.trim();
if (!url || !anonKey) {
return null;
}
if (!isValidHttpUrl(url)) {
return null;
}
return { url, anonKey };
};

8
lib/supabase/middleware.ts Normal file → Executable file
View File

@@ -1,5 +1,6 @@
import { NextResponse, type NextRequest } from "next/server"; import { NextResponse, type NextRequest } from "next/server";
import { createServerClient, type CookieOptions } from "@supabase/ssr"; import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { readSupabasePublicConfig } from "@/lib/supabase/config";
export type SessionSnapshot = { export type SessionSnapshot = {
response: NextResponse; response: NextResponse;
@@ -11,9 +12,8 @@ export type SessionSnapshot = {
export const updateSession = async (req: NextRequest): Promise<SessionSnapshot> => { export const updateSession = async (req: NextRequest): Promise<SessionSnapshot> => {
const response = NextResponse.next({ request: req }); const response = NextResponse.next({ request: req });
const url = process.env.NEXT_PUBLIC_SUPABASE_URL; const config = readSupabasePublicConfig();
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; if (!config) {
if (!url || !anonKey) {
return { return {
response, response,
isAuthed: false, isAuthed: false,
@@ -22,7 +22,7 @@ export const updateSession = async (req: NextRequest): Promise<SessionSnapshot>
}; };
} }
const supabase = createServerClient(url, anonKey, { const supabase = createServerClient(config.url, config.anonKey, {
cookies: { cookies: {
getAll: () => req.cookies.getAll(), getAll: () => req.cookies.getAll(),
setAll: ( setAll: (

9
lib/supabase/server.ts Normal file → Executable file
View File

@@ -1,17 +1,16 @@
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { createServerClient, type CookieOptions } from "@supabase/ssr"; import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { readSupabasePublicConfig } from "@/lib/supabase/config";
export const supabaseServer = async () => { export const supabaseServer = async () => {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL; const config = readSupabasePublicConfig();
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; if (!config) {
if (!url || !anonKey) {
return null; return null;
} }
const cookieStore = await cookies(); const cookieStore = await cookies();
return createServerClient(url, anonKey, { return createServerClient(config.url, config.anonKey, {
cookies: { cookies: {
getAll() { getAll() {
return cookieStore.getAll(); return cookieStore.getAll();

6
lib/utils.ts Executable file
View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

12
lib/validations/course.ts Executable file
View File

@@ -0,0 +1,12 @@
import { z } from "zod";
const translationSchema = z.object({
en: z.string().min(1, "English version is required"),
es: z.string().min(1, "Spanish version is required"),
});
export const courseSchema = z.object({
title: translationSchema,
description: translationSchema,
tags: z.array(z.string()).default([]),
});

84
middleware.ts Normal file → Executable file
View File

@@ -1,45 +1,61 @@
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server"; import { NextResponse, type NextRequest } from "next/server";
import { updateSession } from "@/lib/supabase/middleware";
const isTeacherEmail = (email: string | null) => { export async function middleware(request: NextRequest) {
if (!email) return false; let supabaseResponse = NextResponse.next({
const allowed = (process.env.TEACHER_EMAILS ?? "") request,
.split(",") });
.map((value) => value.trim().toLowerCase())
.filter(Boolean);
if (allowed.length === 0) return false; const supabase = createServerClient(
return allowed.includes(email.toLowerCase()); process.env.NEXT_PUBLIC_SUPABASE_URL!,
}; process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet: any[]) {
cookiesToSet.forEach(({ name, value, options }) =>
request.cookies.set(name, value)
);
supabaseResponse = NextResponse.next({
request,
});
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options)
);
},
},
}
);
export async function middleware(req: NextRequest) { // IMPORTANT: This refreshes the session.
const pathname = req.nextUrl.pathname; // If the user is not logged in, 'user' will be null.
const { response, isAuthed, userEmail, isConfigured } = await updateSession(req); const { data: { user } } = await supabase.auth.getUser();
const isProtectedCoursePlayer = pathname.startsWith("/courses/") && pathname.includes("/learn"); const isTeacherRoute = request.nextUrl.pathname.startsWith("/teacher");
const isProtectedPractice = pathname.startsWith("/practice/"); const isProtectedRoute =
const isTeacherRoute = pathname.startsWith("/teacher"); request.nextUrl.pathname.startsWith("/courses") ||
request.nextUrl.pathname.startsWith("/practice") ||
isTeacherRoute;
if (!isConfigured) { const isLocalDev = process.env.NODE_ENV === 'development';
return response; const activeUser = isLocalDev ? { id: 'f3bbd600-4c58-45b0-855b-cc8f045117c6' } : user;
console.log("ACTIVE_USER:", activeUser);
// If they are trying to access a protected route and aren't logged in, redirect to login
if (isProtectedRoute && !user) {
const url = request.nextUrl.clone();
url.pathname = "/auth/login";
url.searchParams.set("redirectTo", request.nextUrl.pathname);
return NextResponse.redirect(url);
} }
if ((isProtectedCoursePlayer || isProtectedPractice || isTeacherRoute) && !isAuthed) { return supabaseResponse;
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = "/auth/login";
redirectUrl.searchParams.set("redirectTo", pathname);
return NextResponse.redirect(redirectUrl);
}
if (isTeacherRoute && !isTeacherEmail(userEmail)) {
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = "/";
return NextResponse.redirect(redirectUrl);
}
return response;
} }
export const config = { export const config = {
matcher: ["/courses/:path*", "/practice/:path*", "/teacher/:path*"], matcher: [
}; "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};

0
next-env.d.ts vendored Normal file → Executable file
View File

0
next.config.ts Normal file → Executable file
View File

2115
package-lock.json generated Normal file → Executable file

File diff suppressed because it is too large Load Diff

25
package.json Normal file → Executable file
View File

@@ -9,21 +9,42 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@prisma/adapter-pg": "^7.3.0",
"@prisma/client": "^7.3.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
"@supabase/ssr": "^0.5.2", "@supabase/ssr": "^0.5.2",
"@supabase/supabase-js": "^2.95.3", "@supabase/supabase-js": "^2.95.3",
"@types/pg": "^8.16.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.563.0",
"next": "^15.5.12", "next": "^15.5.12",
"next-themes": "^0.4.6",
"pg": "^8.18.0",
"react": "^19.2.4", "react": "^19.2.4",
"react-dom": "^19.2.4" "react-dom": "^19.2.4",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"tailwindcss-animate": "^1.0.7",
"zod": "^4.3.6"
},
"engines": {
"node": ">=24.0.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.19.9", "@types/node": "^25.2.2",
"@types/react": "^19.2.13", "@types/react": "^19.2.13",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"autoprefixer": "^10.4.24", "autoprefixer": "^10.4.24",
"eslint": "^9.39.2", "eslint": "^9.39.2",
"eslint-config-next": "^15.5.12", "eslint-config-next": "^15.5.12",
"postcss": "^8.5.6", "postcss": "^8.5.6",
"prisma": "^7.3.0",
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"ts-node": "^10.9.2",
"typescript": "^5.9.3" "typescript": "^5.9.3"
} }
} }

0
postcss.config.mjs Normal file → Executable file
View File

15
prisma.config.ts Executable file
View File

@@ -0,0 +1,15 @@
// This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
seed: 'npx tsx prisma/seed.ts',
},
datasource: {
url: process.env["DIRECT_URL"],
},
});

215
prisma/schema.prisma Executable file
View File

@@ -0,0 +1,215 @@
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
}
// --- ENUMS ---
enum UserRole {
SUPER_ADMIN // You (Full Access)
ORG_ADMIN // Law Firm Manager (View Team Progress, Manage Seats)
TEACHER // Content Creator (Create/Edit their own courses)
LEARNER // Student (View content, take quizzes)
}
enum ContentStatus {
DRAFT
PUBLISHED
ARCHIVED
}
enum ProficiencyLevel {
BEGINNER // A1-A2
INTERMEDIATE // B1-B2
ADVANCED // C1-C2
EXPERT // Legal Specific
}
enum ExerciseType {
MULTIPLE_CHOICE
FILL_IN_BLANK
TRANSLATION
MATCHING
}
// --- MODELS ---
model Profile {
id String @id @default(uuid()) // Links to Supabase Auth.uid()
email String @unique
fullName String?
avatarUrl String?
role UserRole @default(LEARNER)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relationships
memberships Membership[] // B2B Access
enrollments Enrollment[] // B2C Purchases (Mercado Pago)
progress UserProgress[]
certificates Certificate[]
authoredCourses Course[] @relation("CourseAuthor") // Teachers own courses
}
model Company {
id String @id @default(uuid())
name String
logoUrl String?
billingEmail String?
maxSeats Int @default(5) // Limit for B2B plans
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships Membership[]
certificates Certificate[]
}
model Membership {
id String @id @default(uuid())
userId String
companyId String
isActive Boolean @default(true)
role String @default("MEMBER") // Internal org role (Member/Admin)
joinedAt DateTime @default(now())
updatedAt DateTime @updatedAt
user Profile @relation(fields: [userId], references: [id], onDelete: Cascade)
company Company @relation(fields: [companyId], references: [id], onDelete: Cascade)
@@unique([userId, companyId]) // Prevent duplicate memberships
}
model Course {
id String @id @default(uuid())
title Json // { "en": "...", "es": "..." }
slug String @unique // Required for SEO URLs (e.g. /course/contract-law)
description Json // { "en": "...", "es": "..." }
level ProficiencyLevel @default(INTERMEDIATE)
tags String[]
status ContentStatus @default(DRAFT)
price Decimal @default(0.00) // Price in MXN
authorId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Prerequisites
prerequisiteId String?
prerequisite Course? @relation("CoursePrerequisites", fields: [prerequisiteId], references: [id])
dependents Course[] @relation("CoursePrerequisites")
author Profile @relation("CourseAuthor", fields: [authorId], references: [id])
modules Module[]
certificates Certificate[]
enrollments Enrollment[]
}
model Enrollment {
id String @id @default(uuid())
userId String
courseId String
// Payment Proof (Mercado Pago)
amountPaid Decimal // e.g. 500.00
currency String @default("MXN")
paymentMethod String @default("MERCADO_PAGO")
externalId String? // The Mercado Pago "payment_id" or "preference_id"
purchasedAt DateTime @default(now())
user Profile @relation(fields: [userId], references: [id], onDelete: Cascade)
course Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
@@unique([userId, courseId]) // Prevent buying the same course twice
}
model Module {
id String @id @default(uuid())
courseId String
title Json
orderIndex Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
course Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
lessons Lesson[]
}
model Lesson {
id String @id @default(uuid())
moduleId String
title Json
description Json?
slug String? // Optional for direct linking
orderIndex Int
videoUrl String?
estimatedDuration Int // Seconds
version Int @default(1)
isFreePreview Boolean @default(false) // Marketing hook
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
module Module @relation(fields: [moduleId], references: [id], onDelete: Cascade)
exercises Exercise[]
resources Resource[]
userProgress UserProgress[]
}
model Exercise {
id String @id @default(uuid())
lessonId String
type ExerciseType
content Json // { question: "...", options: [...], answer: "..." }
orderIndex Int @default(0)
lesson Lesson @relation(fields: [lessonId], references: [id], onDelete: Cascade)
}
model Resource {
id String @id @default(uuid())
lessonId String
fileUrl String
displayName Json
fileType String
lesson Lesson @relation(fields: [lessonId], references: [id], onDelete: Cascade)
}
model UserProgress {
id String @id @default(uuid())
userId String
lessonId String
isCompleted Boolean @default(false)
score Int? // For quiz results
startedAt DateTime @default(now())
finishedAt DateTime?
lastPlayedAt DateTime @default(now()) // For "Resume" feature
user Profile @relation(fields: [userId], references: [id], onDelete: Cascade)
lesson Lesson @relation(fields: [lessonId], references: [id], onDelete: Cascade)
@@unique([userId, lessonId]) // One progress record per lesson
}
model Certificate {
id String @id @default(uuid())
userId String
courseId String
companyId String? // Captured for co-branding (Nullable for B2C)
issuedAt DateTime @default(now())
metadataSnapshot Json // Burn the course name/version here
user Profile @relation(fields: [userId], references: [id])
course Course @relation(fields: [courseId], references: [id])
company Company? @relation(fields: [companyId], references: [id])
}

107
prisma/seed.ts Executable file
View File

@@ -0,0 +1,107 @@
// prisma/seed.ts
import { PrismaClient, UserRole, ContentStatus, ProficiencyLevel, ExerciseType } from '@prisma/client'
import { Pool } from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
const connectionString = process.env.DIRECT_URL
async function main() {
console.log('🌱 Starting seed...')
// 1. Setup the Adapter (Crucial for Prisma 7 + Serverless)
const pool = new Pool({ connectionString })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
try {
// 2. Create a Teacher/Super Admin
const teacher = await prisma.profile.upsert({
where: { email: 'admin@acve.com' },
update: {},
create: {
email: 'admin@acve.com',
fullName: 'ACVE Admin',
// ✅ CORRECT: Uses the strict Enum value
role: UserRole.SUPER_ADMIN,
avatarUrl: 'https://github.com/shadcn.png',
},
})
console.log(`👤 Created User: ${teacher.email}`)
// 3. Create a Law Firm (B2B)
const lawFirm = await prisma.company.create({
data: {
name: 'García & Partners',
billingEmail: 'billing@garcia.com',
maxSeats: 10,
memberships: {
create: {
userId: teacher.id,
// ✅ FIXED: Use 'ORG_ADMIN' to match your UserRole terminology
// Since this field is a String in schema, we use the string value explicitly.
role: 'ORG_ADMIN',
},
},
},
})
console.log(`🏢 Created Law Firm: ${lawFirm.name}`)
// 4. Create the Bilingual Course (Contract Law)
const course = await prisma.course.create({
data: {
title: {
en: "Legal English: Contract Basics",
es: "Inglés Jurídico: Fundamentos de Contratos"
},
slug: "contract-law-101",
description: {
en: "Master the terminology of international contracts.",
es: "Domina la terminología de contratos internacionales."
},
level: ProficiencyLevel.INTERMEDIATE,
status: ContentStatus.PUBLISHED,
price: 499.00,
authorId: teacher.id,
tags: ["contracts", "civil law", "compliance"],
modules: {
create: {
title: { en: "Module 1: Offer and Acceptance", es: "Módulo 1: Oferta y Aceptación" },
orderIndex: 1,
lessons: {
create: {
title: { en: "The Elements of a Contract", es: "Los Elementos de un Contrato" },
slug: "elements-of-contract",
orderIndex: 1,
estimatedDuration: 600,
isFreePreview: true,
exercises: {
create: {
type: ExerciseType.MULTIPLE_CHOICE,
orderIndex: 1,
content: {
question: "What is 'Consideration' in a contract?",
options: ["Payment", "Thoughtfulness", "A value exchange", "A signature"],
correctAnswer: "A value exchange"
}
}
}
}
}
}
}
},
})
console.log(`📚 Created Course: ${course.slug}`)
console.log('✅ Seed complete!')
} catch (e) {
console.error(e)
process.exit(1)
} finally {
await prisma.$disconnect()
}
}
main()

0
public/images/hero-reference.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

0
public/images/logo.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 391 KiB

After

Width:  |  Height:  |  Size: 391 KiB

View File

@@ -0,0 +1,197 @@
# ACVE Student Experience Plan (UX + Visual Quality)
## Objective
Upgrade the student-facing product so it feels intentional, modern, and trustworthy while staying MVP-compatible.
This plan focuses on:
- Better visual hierarchy (less oversized type, reduced empty space).
- Cleaner information density (more useful content per viewport).
- Consistent interaction patterns (cards, tabs, progress, actions).
- A polished learning flow from discovery to lesson completion.
## Current UX Problems (Observed)
- Excess whitespace on core pages (`/courses`, `/case-studies`, `/practice`) creates low information density.
- Heading/body type scale is too large in many sections, causing visual imbalance and "shouting" UI.
- Inconsistent card depth and spacing across pages.
- Weak content rhythm: sections do not form a predictable scan path.
- Placeholder areas appear disconnected from real actions (resources, modules, uploads).
## Experience Principles
- Dense, not crowded: every fold should provide clear options or useful context.
- Strong hierarchy: heading sizes and spacing should reflect importance.
- Familiar learning patterns: follow proven edtech structures (clear hero, category rails, progress surfaces, action clusters).
- Trust by consistency: repeated visual language for statuses, metadata, and actions.
- Mobile parity: same clarity and intent on small screens.
## Visual Direction
### Typography System
- Introduce a controlled type ramp:
- `Display`: 40-48px max (home hero only)
- `H1`: 32-36px
- `H2`: 24-28px
- `H3`: 18-22px
- `Body-lg`: 18px
- `Body`: 16px
- `Meta`: 13-14px
- Reduce line-length for long text blocks (`max-width` around 60-72ch).
- Reduce heading usage of very large serif text outside hero sections.
### Spacing & Layout
- Use a spacing scale (`4, 8, 12, 16, 24, 32, 48, 64`).
- Standard section padding:
- Desktop: 32-48px
- Mobile: 16-24px
- Enforce consistent card height and internal spacing.
- Reduce vertical gaps between filter bars and content grids.
### Components & Surfaces
- Standardize card anatomy:
- Header: title + level/status chips
- Body: summary + key stats
- Footer: instructor + primary action
- Unify chip styles:
- Level chip
- Status chip (`Draft`, `Published`)
- Access chip (`Preview`, `Locked`)
- Introduce one reusable "empty state" component with icon, message, CTA.
## Student Journey Improvements
## Discovery (`/`, `/courses`, `/case-studies`, `/practice`)
- Add compact "Quick Continue" strip at top for logged-in learners.
- Improve course list density:
- 3-column desktop, 2-column tablet, 1-column mobile.
- Show progress, lesson count, duration, rating without large gaps.
- Case studies:
- Left index list with tighter cards.
- Main detail panel with clearer section hierarchy and less oversized title.
- Practice:
- Show module status (`Available`, `Coming soon`) plus expected duration.
## Course Detail (`/courses/[slug]`)
- Improve hero balance:
- Course metadata row (level, status, rating, duration) in compact badges.
- Right side sticky panel for progress + CTA.
- Add "What you will learn" bullet block (placeholder content allowed).
- Add "Course structure" preview (module/lesson count summary).
## Learning Player (`/courses/[slug]/learn`)
- Keep two-column layout with stronger purpose:
- Left: module/lesson navigation.
- Right: lesson content, resources, completion action.
- Add lesson context strip:
- `Module X`, `Lesson Y`, estimated time, content type.
- Add "Next lesson" CTA after completion.
- Keep resources placeholder but place it in a consistent right-panel section.
## Practice Session (`/practice/[slug]`)
- Add pre-quiz panel:
- Difficulty, question count, expected time.
- During quiz:
- Fixed progress header.
- Cleaner answer state colors and spacing.
- Post-quiz:
- Score summary card + "Review answers" placeholder.
- Attempt history visible below summary.
## Navigation & Account Experience
- Navbar should remain compact and consistent across pages.
- Add contextual breadcrumbs on deep routes:
- `Courses > [Course] > Learn`
- `Practice > [Module]`
- Logged-in state:
- Show quick links (`Continue`, `My Courses`, `Practice`).
- Teacher-only controls remain isolated and clearly labeled.
## Motion & Feedback
- Add subtle page-enter animation (fade + 12px rise, 180-220ms).
- Card hover:
- slight elevation + border emphasis.
- Keep micro-interactions purposeful only (no decorative animation noise).
## Accessibility & Readability
- Minimum contrast ratio compliant for text and controls.
- 44px minimum hit targets for buttons/tabs.
- Keyboard focus ring visible on all actionable components.
- Avoid placing essential information by color only.
## Performance Constraints
- Avoid heavy media in above-the-fold learner screens.
- Use optimized image sizing and only essential shadows/blur.
- Keep layout shifts minimal (reserve card/media sizes).
## Implementation Phases
## Phase 1: Foundation (Design Tokens + Layout Baseline)
Status: DONE
- Create/update tokens in global styles:
- type scale
- spacing scale
- surface/elevation tokens
- badge/chip variants
- Normalize top-level content container widths and section paddings.
- Deliverable: consistent baseline on all public pages.
## Phase 2: Discovery Page Refresh
Status: DONE
- Refine `/courses`, `/case-studies`, `/practice` for density and hierarchy.
- Standardize card and metadata patterns.
- Deliverable: cleaner listing UX with less visual noise.
## Phase 3: Learning Flow Polish
Status: DONE
- Upgrade `/courses/[slug]` and `/courses/[slug]/learn`.
- Improve lesson progression and contextual guidance.
- Deliverable: student can move through lessons with clear momentum.
## Phase 4: Practice Flow Polish
Status: DONE
- Upgrade `/practice/[slug]` session flow and result state.
- Improve attempt history readability.
- Deliverable: practice looks structured and rewarding.
## Phase 5: Final QA + Consistency Pass
Status: DONE
- Accessibility checks (focus, contrast, tap targets).
- Mobile layout QA for all student routes.
- Copy and empty-state consistency.
## Route-by-Route Checklist
- `/` Home: DONE
- `/courses`: DONE
- `/courses/[slug]`: DONE
- `/courses/[slug]/learn`: DONE
- `/case-studies`: DONE
- `/case-studies/[slug]`: DONE
- `/practice`: DONE
- `/practice/[slug]`: DONE
- `/assistant`: DONE
## Progress Log
- 2026-02-11: Phase 1 baseline implemented with global spacing/type tokens and shared page spacing utilities in `app/globals.css`.
- 2026-02-11: Main content container tightened in `app/layout.tsx` to reduce visual spread.
- 2026-02-11: Discovery listings rebalanced for typography density in `app/(public)/courses/page.tsx`, `app/(public)/case-studies/page.tsx`, and `app/(public)/practice/page.tsx`.
- 2026-02-11: Shared card typography normalized in `components/CourseCard.tsx`.
- 2026-02-11: Strong discovery refresh shipped with denser hero bands, compact metadata surfaces, and clearer scan hierarchy on `/courses`, `/case-studies`, and `/practice`.
- 2026-02-11: Phase 3 update shipped for `/courses/[slug]` and `/courses/[slug]/learn` with clearer learning outcomes, structure preview, lesson context strip, and guided next-lesson progression.
- 2026-02-11: Demo auth persistence aligned across student pages by reading fallback cookies where Supabase is unavailable.
- 2026-02-11: Phase 4 shipped for `/practice/[slug]` with explicit pre-quiz briefing, cleaner in-quiz state, and results actions with persistent attempt history.
- 2026-02-11: Phase 5 completed with focus-visible accessibility baseline, hit-target reinforcement for primary/secondary buttons, and consistency pass on `/`, `/case-studies/[slug]`, and `/assistant`.
## Success Criteria
- Visual balance: no oversized heading blocks outside hero contexts.
- Density: key pages show actionable content above fold without clutter.
- Consistency: chips, cards, spacing, and metadata presentation are unified.
- Student flow: discovery -> course -> lesson -> completion feels continuous.
- QA: no major accessibility regressions; mobile parity achieved.
## Risks and Mitigation
- Risk: Over-designing before backend data.
- Mitigation: keep placeholders schema-aligned and componentized.
- Risk: Inconsistent execution across routes.
- Mitigation: enforce shared UI primitives and route checklist signoff.
- Risk: Rework after backend integration.
- Mitigation: keep layout and data contracts decoupled.
## Working Agreement
- Every UI change references this file and marks route checklist progress.
- No route is considered complete without desktop + mobile verification.
- Keep this as the source of truth for student-facing UX decisions.

65
tailwind.config.ts Normal file → Executable file
View File

@@ -1,22 +1,67 @@
import type { Config } from "tailwindcss"; import type { Config } from "tailwindcss";
const config: Config = { const config: Config = {
content: [ darkMode: ["class"],
content: [
"./app/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}",
"./lib/**/*.{js,ts,jsx,tsx,mdx}", "./lib/**/*.{js,ts,jsx,tsx,mdx}",
], ],
theme: { theme: {
extend: { extend: {
colors: { colors: {
surface: "#f3f3f5", surface: '#f3f3f5',
ink: "#273040", ink: '#273040',
brand: "#98143f", brand: '#98143f',
accent: "#d4af37", accent: {
}, DEFAULT: 'hsl(var(--accent))',
}, foreground: 'hsl(var(--accent-foreground))'
},
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))'
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))'
},
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))'
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))'
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))'
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))'
},
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
chart: {
'1': 'hsl(var(--chart-1))',
'2': 'hsl(var(--chart-2))',
'3': 'hsl(var(--chart-3))',
'4': 'hsl(var(--chart-4))',
'5': 'hsl(var(--chart-5))'
}
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
}
}
}, },
plugins: [], plugins: [require("tailwindcss-animate")],
}; };
export default config; export default config;

0
tsconfig.json Normal file → Executable file
View File

1
tsconfig.tsbuildinfo Normal file

File diff suppressed because one or more lines are too long

0
types/caseStudy.ts Normal file → Executable file
View File

2
types/course.ts Normal file → Executable file
View File

@@ -1,5 +1,6 @@
export type CourseLevel = "Beginner" | "Intermediate" | "Advanced"; export type CourseLevel = "Beginner" | "Intermediate" | "Advanced";
export type LessonType = "video" | "reading" | "interactive"; export type LessonType = "video" | "reading" | "interactive";
export type CourseStatus = "Draft" | "Published";
export type Lesson = { export type Lesson = {
id: string; id: string;
@@ -14,6 +15,7 @@ export type Course = {
slug: string; slug: string;
title: string; title: string;
level: CourseLevel; level: CourseLevel;
status: CourseStatus;
summary: string; summary: string;
rating: number; rating: number;
weeks: number; weeks: number;

5
types/index.ts Normal file
View File

@@ -0,0 +1,5 @@
export type ActionResponse<T = any> = {
success: boolean;
data?: T;
error?: string;
};

0
types/practice.ts Normal file → Executable file
View File