merge new_starr_app@qas history into apps/web

git-subtree-dir: apps/web
git-subtree-mainline: eaa6d2276a
git-subtree-split: 459af9d46a
This commit is contained in:
2026-08-24 12:21:16 +08:00
699 changed files with 103969 additions and 0 deletions
@@ -0,0 +1,65 @@
// CourseUpsellModal — shown when a learner reaches a locked Course's primary
// action button (Proceed/Start Learning). Offers plan upgrade, or buying the
// course individually when it has an active product. Shared by CourseList,
// Dashboard, and CourseDetails.
import { useNavigate } from "react-router-dom";
import { LockIcon, Check, ShoppingCart } from "lucide-react";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { resolveTierBadge } from "@/utils/tierBadge.util";
import { useDateFormat } from "@/hooks/useDateFormat";
export default function CourseUpsellModal({ open, onOpenChange, course, tierMap = {} }) {
const navigate = useNavigate();
const { fmtCurrency } = useDateFormat();
const slug = course?.subscription ?? "free";
const { rank, label, cls, panel } = resolveTierBadge(slug, tierMap);
return (
<ResponsiveModal
open={open}
onOpenChange={onOpenChange}
title={course?.title ?? "Course Details"}
description={course?.product ? "Purchase this course or upgrade your plan." : "Upgrade your plan to access this course."}
footer={
<>
<Button variant="outline" onClick={() => onOpenChange(false)}>Close</Button>
{course?.product?.is_active && (
<Button
variant="outline"
onClick={() => { onOpenChange(false); navigate(`/course/${course.course_id}/checkout`); }}
>
<ShoppingCart className="size-4" />
Buy {fmtCurrency(course.product.price ?? 0, course.product.currency ?? "USD")}
</Button>
)}
<Button onClick={() => { onOpenChange(false); navigate("/subscriptions"); }}>
<LockIcon /> View Plans
</Button>
</>
}
>
<div className="space-y-6 py-2">
{rank > 0 && (
<div className={`p-5 rounded-2xl border ${panel.bg} ${panel.border}`}>
<div className="flex items-center gap-3 mb-3">
<Badge className={cls}>
<LockIcon className="size-3" /> {label}
</Badge>
</div>
<ul className="space-y-2 text-sm [&_svg]:size-4 mb-4">
<li className="flex items-center gap-2"><Check /> Access to {label} content</li>
<li className="flex items-center gap-2"><Check /> Certificates & achievements</li>
</ul>
<p className="text-sm text-muted-foreground">
Upgrade to a <span className="font-medium">{label}</span> plan to unlock this course.
</p>
</div>
)}
</div>
</ResponsiveModal>
);
}
@@ -0,0 +1,277 @@
/***********************************************************************************************************************************************************************
* File Name : FilePreview.jsx
* Type : Component (Client)
* Description : Dialog-based file preview for task completion attachments.
* Renders by mime type:
* image/jpeg, image/png → FileZoomViewer (zoom/pan/fit)
* application/pdf → FileZoomViewer (pdf.js zoom/pan/fit)
* video/* → <video controls> (mp4, mov, webm, etc.)
* audio/* → centered audio player card (mp3, wav, etc.)
* other (incl. docx) → generic file card with download prompt
*
* Inline preview uses the blob-fetch pattern (same as
* VideoBlock/AudioBlock): authenticated GET via `api` →
* responseType 'blob' → URL.createObjectURL → set as src.
* This is required because <img>/<video>/<audio>/<iframe> src
* are native browser requests that don't carry the Authorization
* header attached by the axios interceptor.
*
* Props:
* file {object} – { file_id, file_url, file_name, file_size, mime_type, createdAt }
* open {boolean}
* onOpenChange {function}
* streamUrl {string} – proxy stream URL (inline preview, authenticated)
* downloadUrl {string} – proxy download URL (Content-Disposition: attachment)
***********************************************************************************************************************************************************************/
import { useState, useEffect } from 'react';
import {
Dialog, DialogContent, DialogHeader, DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Spinner } from '@/components/ui/spinner';
import {
Image, Video, Music, FileText, File, Download,
} from 'lucide-react';
import { formatDate } from '@/utils/table.util';
import { formatBytes } from './blocks/FileUpload';
import api from '@/utils/api.util';
import { saveBlob } from '@/utils/media.util';
import FileZoomViewer from '@/components/generic/FileZoomViewer';
// ─── Resolve preview kind from mime type ──────────────────────────────────────
const resolveKind = (mimeType = '', fileName = '') => {
if (mimeType.startsWith('image/')) return 'image';
if (mimeType.startsWith('video/')) return 'video';
if (mimeType.startsWith('audio/')) return 'audio';
if (mimeType === 'application/pdf') return 'pdf';
const ext = (fileName.split('.').pop() ?? '').toLowerCase();
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(ext)) return 'image';
if (['mp4', 'mov', 'mkv', 'webm', 'avi'].includes(ext)) return 'video';
if (['mp3', 'wav', 'm4a', 'ogg'].includes(ext)) return 'audio';
if (ext === 'pdf') return 'pdf';
return 'other';
};
const KIND_ICON = {
image: Image,
video: Video,
audio: Music,
pdf: FileText,
other: File,
};
// ─── useBlobUrl — fetches streamUrl via authenticated api, returns blob URL ────
const useBlobUrl = (streamUrl, enabled) => {
const [blobUrl, setBlobUrl] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
if (!enabled || !streamUrl) return;
let currentUrl = null;
let cancelled = false;
setLoading(true);
setError(false);
setBlobUrl(null);
api.get(streamUrl, { responseType: 'blob' })
.then((res) => {
if (cancelled) return;
currentUrl = URL.createObjectURL(res.data);
setBlobUrl(currentUrl);
})
.catch(() => {
if (!cancelled) setError(true);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
if (currentUrl) URL.revokeObjectURL(currentUrl);
};
}, [streamUrl, enabled]);
return { blobUrl, loading, error };
};
// ─── Loading / error placeholder ───────────────────────────────────────────────
const LoadingState = () => (
<div className="flex items-center justify-center py-16">
<Spinner className="size-6" />
</div>
);
const ErrorState = ({ onDownload, downloading, fileName }) => (
<div className="flex flex-col items-center gap-3 py-12 text-muted-foreground">
<File className="size-12" />
<p className="text-sm">Could not load preview.</p>
{onDownload && (
<Button variant="outline" size="sm" onClick={onDownload} disabled={downloading}>
<Download className="size-4" />
{downloading ? 'Downloading…' : 'Download file'}
</Button>
)}
</div>
);
// ─── Preview body per kind ─────────────────────────────────────────────────────
const PreviewBody = ({ file, kind, blobUrl, loading, error, downloadUrl, onDownload, downloading }) => {
if (kind === 'other') {
return (
<div className="flex flex-col items-center gap-3 py-12 text-muted-foreground">
<File className="size-12" />
<p className="text-sm">Preview not available for this file type.</p>
<Button variant="outline" size="sm" onClick={onDownload} disabled={downloading}>
<Download className="size-4" />
{downloading ? 'Downloading…' : 'Download file'}
</Button>
</div>
);
}
// ── Image / PDF — zoom/pan/fit viewer ───────────────────────────────────────
if (kind === 'image' || kind === 'pdf') {
if (error) return <ErrorState onDownload={onDownload} downloading={downloading} fileName={file.file_name} />;
return (
<FileZoomViewer
src={blobUrl}
mimeType={file.mime_type}
fileName={file.file_name}
loading={loading}
/>
);
}
if (loading) return <LoadingState />;
if (error || !blobUrl) return <ErrorState onDownload={onDownload} downloading={downloading} fileName={file.file_name} />;
switch (kind) {
case 'video':
return (
<div className="bg-black flex items-center justify-center aspect-video">
<video
src={blobUrl}
controls
controlsList="nodownload nofullscreen noremoteplayback"
disablePictureInPicture
onContextMenu={(e) => e.preventDefault()}
className="w-full h-full"
/>
</div>
);
case 'audio':
return (
<div className="flex flex-col items-center gap-4 py-8 px-6">
<div className="size-24 rounded-lg bg-muted flex items-center justify-center">
<Music className="size-9 text-muted-foreground" />
</div>
<div className="text-center">
<p className="text-sm font-medium truncate max-w-xs">{file.file_name}</p>
<p className="text-xs text-muted-foreground">Audio file</p>
</div>
<audio
src={blobUrl}
controls
controlsList="nodownload"
onContextMenu={(e) => e.preventDefault()}
className="w-full max-w-xs"
/>
</div>
);
default:
return null;
}
};
// ─── Main dialog ────────────────────────────────────────────────────────────────
const FilePreview = ({ file, open, onOpenChange, streamUrl, downloadUrl }) => {
const kind = file ? resolveKind(file.mime_type, file.file_name) : 'other';
const Icon = KIND_ICON[kind] ?? File;
// Only fetch the blob when the dialog is open and a previewable kind
const shouldFetch = open && !!file && kind !== 'other';
const { blobUrl, loading, error } = useBlobUrl(streamUrl, shouldFetch);
const [downloading, setDownloading] = useState(false);
if (!file) return null;
// ── Download handler — authenticated fetch via `api`, then save blob ──────
const handleDownload = async () => {
const url = downloadUrl || streamUrl;
if (!url) return;
setDownloading(true);
try {
const res = await api.get(url, { responseType: 'blob' });
saveBlob(res.data, file.file_name);
} catch {
// fall back to direct link if proxy fails (e.g. public file_url)
if (file.file_url) window.open(file.file_url, '_blank');
} finally {
setDownloading(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg lg:max-w-4xl p-0 gap-0 overflow-hidden">
<DialogHeader className="px-4 py-3 pr-12 border-b flex-row items-center justify-between gap-3 space-y-0">
<div className="flex items-center gap-2 min-w-0 select-none">
<Icon className="size-4.5 text-muted-foreground shrink-0" />
<DialogTitle className="text-sm font-medium truncate max-w-54">
{file.file_name}
</DialogTitle>
<Button
variant="outline" size="sm"
onClick={handleDownload}
disabled={downloading}
aria-label="Download"
>
{downloading ? <Spinner className="size-4" /> : <Download className="size-4" />} Download
</Button>
</div>
</DialogHeader>
<PreviewBody
file={file}
kind={kind}
blobUrl={blobUrl}
loading={loading}
error={error}
downloadUrl={downloadUrl}
onDownload={handleDownload}
downloading={downloading}
/>
<div className="px-4 py-2.5 border-t flex items-center justify-between text-xs text-muted-foreground">
<div className="flex items-center gap-2">
{file.mime_type && (
<Badge variant="secondary" className="text-xs font-normal select-none">
{file.mime_type}
</Badge>
)}
{file.file_size != null && (
<Badge variant="secondary" className="text-xs font-normal select-none">
{formatBytes(file.file_size)}
</Badge>
)}
</div>
{file.createdAt && (
<span>Uploaded {formatDate(file.createdAt)}</span>
)}
</div>
</DialogContent>
</Dialog>
);
};
export default FilePreview;
@@ -0,0 +1,55 @@
// components/LessonBlock.jsx
import { Skeleton } from "@/components/ui/skeleton";
import { PreviewChrome, PreviewContent } from "@/modules/admin/components/courses/LessonsPreview";
function LessonSkeleton() {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-2/3" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-5/6" />
<Skeleton className="w-full aspect-video rounded-xl" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/6" />
</div>
);
}
/**
* Props:
* lesson — { id, title, blocks[] }
* loading — true while fetch is in-flight
* showHeader — render the title/description/objectives block. Set false
* when the caller already renders its own lesson header
* above (e.g. LessonDetails), to avoid showing it twice.
*/
const LessonBlock = ({ lesson, loading = false, showHeader = true, onWatchProgress }) => {
if (!lesson && !loading) {
return (
<div className="h-full w-full flex items-center justify-center text-muted-foreground py-20">
<p className="text-sm">Select a lesson to get started.</p>
</div>
);
}
if (loading) {
return <LessonSkeleton />;
}
return (
<PreviewChrome showChrome={false}>
<div className="space-y-5">
<PreviewContent
lesson={lesson}
blocks={lesson.blocks ?? []}
empty="No content blocks yet."
showHeader={showHeader}
onWatchProgress={onWatchProgress}
/>
</div>
</PreviewChrome>
);
};
export default LessonBlock;
@@ -0,0 +1,89 @@
// LessonCard — grid card for a standalone Lesson. Shared by LessonsList.jsx and
// Dashboard.jsx's "Featured Lessons" section. Mirrors UnitCard.jsx; a Lesson has
// no lesson_count/quiz_id of its own — shows unit_count instead (how many Units
// it's attached to).
import { Timer, LockIcon, Layers, Tag } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { resolveTierBadge, cheapestTierSlug } from "@/utils/tierBadge.util";
function formatDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h && m) return `${h}h ${m}m`;
if (h) return `${h}h`;
return `${m}m`;
}
export const LessonCard = ({ lesson, tierMap = {}, onViewDetails }) => {
const locked = lesson.is_locked;
const duration = formatDuration(lesson.duration_seconds);
const unitCount = Number(lesson.unit_count ?? 0);
const courses = lesson.courses ?? [];
const slug = cheapestTierSlug(courses.map((c) => c.subscription), tierMap);
const { label, cls } = resolveTierBadge(slug, tierMap);
return (
<div
className={cn(
"bg-card rounded-2xl border p-4 flex flex-col gap-2.5 transition-all cursor-pointer group",
"hover:shadow-sm",
locked
? "opacity-80 hover:opacity-100 hover:border-muted-foreground/40"
: "hover:bg-muted/60 dark:hover:border-blue-500"
)}
onClick={() => onViewDetails(lesson)}
>
<div className="flex flex-wrap gap-1.5">
<Badge className={cls}>
{locked ? <LockIcon className="size-3" /> : <Tag className="size-3" />}
{label}
</Badge>
{locked && (
<Badge variant="secondary">
<LockIcon className="size-3" /> Locked
</Badge>
)}
</div>
<div className="flex flex-col gap-1">
<h1 className="text-lg font-medium leading-snug line-clamp-3 transition-colors group-hover:text-blue-700 dark:group-hover:text-blue-400">
{lesson.title}
</h1>
{lesson.description && (
<p className="text-sm leading-relaxed line-clamp-2 group-hover:text-blue-700 dark:group-hover:text-blue-400">
{lesson.description}
</p>
)}
</div>
<div className="flex items-center justify-between pt-2 mt-auto border-t">
<div className={`flex items-center gap-3 text-sm [&_svg]:size-4 ${locked ? "text-muted-foreground" : "text-card-foreground group-hover:text-blue-700 dark:group-hover:text-blue-400"}`}>
<div className="flex items-center gap-1">
<Timer /> {duration ?? "—"}
</div>
</div>
{locked && (
<span className="text-xs text-muted-foreground">Upgrade to unlock</span>
)}
</div>
</div>
);
};
export const LessonCardSkeleton = () => (
<div className="bg-card rounded-2xl border p-4 flex flex-col gap-2.5">
<div className="flex gap-1.5">
<Skeleton className="h-5 w-20 rounded-full" />
</div>
<Skeleton className="h-6 w-3/4" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
<div className="pt-2 mt-auto border-t">
<Skeleton className="h-4 w-24" />
</div>
</div>
);
@@ -0,0 +1,56 @@
// LessonUpsellModal — shown when a learner clicks a locked standalone Lesson.
// Mirrors UnitUpsellModal.jsx: unlocks via any course reachable through its
// attached Units (aggregated across all of them, since a Lesson can sit in
// more than one), plus a generic "View Plans" fallback.
// Shared by LessonsList and Dashboard.
import { useNavigate } from "react-router-dom";
import { LockIcon, Check } from "lucide-react";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { resolveTierBadge, cheapestTierSlug } from "@/utils/tierBadge.util";
export default function LessonUpsellModal({ open, onOpenChange, lesson, tierMap = {} }) {
const navigate = useNavigate();
const courses = lesson?.courses ?? [];
const slug = cheapestTierSlug([lesson?.subscription, ...courses.map((c) => c.subscription)], tierMap);
const { rank, label, cls, panel } = resolveTierBadge(slug, tierMap);
return (
<ResponsiveModal
open={open}
onOpenChange={onOpenChange}
title={lesson?.title ?? "Lesson Details"}
description="Upgrade your plan to access this lesson."
footer={
<>
<Button variant="outline" onClick={() => onOpenChange(false)}>Close</Button>
<Button onClick={() => { onOpenChange(false); navigate("/subscriptions"); }}>
<LockIcon /> View Plans
</Button>
</>
}
>
<div className="space-y-6 py-2">
{rank > 0 && (
<div className={`p-5 rounded-2xl border ${panel.bg} ${panel.border}`}>
<div className="flex items-center gap-3 mb-3">
<Badge className={cls}>
<LockIcon className="size-3" /> {label}
</Badge>
</div>
<ul className="space-y-2 text-sm [&_svg]:size-4 mb-4">
<li className="flex items-center gap-2"><Check /> Access to {label} content</li>
<li className="flex items-center gap-2"><Check /> Certificates & achievements</li>
</ul>
<p className="text-sm text-muted-foreground">
Upgrade to a <span className="font-medium">{label}</span> plan to unlock this lesson.
</p>
</div>
)}
</div>
</ResponsiveModal>
);
}
@@ -0,0 +1,47 @@
// LockedContentPanel — full-page inline panel shown when a deep-link lands on
// content the learner can't access (locked unit or a lesson under one).
// Distinct from UnitUpsellModal (a dialog triggered from card grids) — this
// renders in place of the page body itself. Shared by UnitDetails and
// LessonDetails.
//
// `item` (optional) is the unit/lesson's own subscription info, from the 403
// body's `item` field — lets a deep-link show the same own-tier badge the
// browse-list upsell modals already do, instead of only ever pointing at an
// attached course.
import { useNavigate } from "react-router-dom";
import { LockIcon, Zap } from "lucide-react";
import { Button } from "@/components/ui/button";
import { resolveTierBadge } from "@/utils/tierBadge.util";
export default function LockedContentPanel({ course, item, tierMap = {} }) {
const navigate = useNavigate();
const tier = course?.subscription ? tierMap[course.subscription] : null;
const ownTier = item?.subscription ? resolveTierBadge(item.subscription, tierMap) : null;
return (
<div className="flex flex-col items-center gap-6 py-32 text-center px-4">
<div className="h-16 w-16 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
<LockIcon className="size-7 text-amber-500" />
</div>
<div className="space-y-2 max-w-sm">
<h2 className="text-xl font-semibold">Premium / Exclusive Content</h2>
<p className="text-sm text-muted-foreground leading-relaxed">
{ownTier
? `This content requires the ${ownTier.label} plan.`
: course
? `This content is part of "${course.title}"${tier?.name ? ` (${tier.name} plan)` : ""}. Upgrade your plan or view the course to unlock it.`
: "Upgrade your plan to access this content."}
</p>
</div>
<div className="flex flex-col items-center gap-2">
<div className="flex items-center gap-2">
<Button onClick={() => navigate('/subscriptions')} className="gap-1.5">
<Zap className="size-4" /> View Available Plans
</Button>
</div>
<p className="text-xs text-muted-foreground">Already subscribed? Your plan may not cover this subscription.</p>
</div>
</div>
);
}
@@ -0,0 +1,35 @@
import { useState } from "react";
import { CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
/**
* Explicit self-report completion button, backing the manual_complete
* completion requirement type. Renders as already-completed (disabled,
* checkmark) once the lesson is marked done.
*/
export default function MarkCompleteButton({ label, completed, onMarkComplete }) {
const [saving, setSaving] = useState(false);
const handleClick = async () => {
if (completed || saving) return;
setSaving(true);
await onMarkComplete?.();
setSaving(false);
};
return (
<div className="flex justify-center py-6">
<Button
type="button"
size="lg"
variant={completed ? "outline" : "default"}
disabled={completed || saving}
onClick={handleClick}
className="gap-2"
>
<CheckCircle2 className="size-4" />
{completed ? "Completed" : saving ? "Marking complete…" : (label || "Mark Complete")}
</Button>
</div>
);
}
@@ -0,0 +1,107 @@
// PlanComparisonTable — side-by-side feature matrix, an alternate view next to
// the card grid on PlanList.jsx. Rows are the union of every active plan's
// admin-authored `features` list; a plan gets a checkmark for a row if that
// exact feature text is present in its own list.
import * as LucideIcons from "lucide-react";
import { Check, Minus, Tag, Lock } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { resolveTierBadge } from "@/utils/tierBadge.util";
import { getBundleContent, overlapsExistingAccess, isPlanCurrent } from "@/utils/planBundle.util";
export default function PlanComparisonTable({ plans, myTier, tierMap, fmtCurrency, onSelect }) {
const featureRows = [...new Set(
plans.flatMap((p) => (p.features ?? []).map((f) => f.text))
)];
return (
<div className="overflow-x-auto rounded-xl border bg-card">
<table className="w-full text-sm border-collapse min-w-[640px]">
<thead>
<tr className="border-b">
<th className="text-left p-4 w-48 align-bottom text-muted-foreground font-medium">Plan</th>
{plans.map((plan) => {
const { label, cls } = resolveTierBadge(plan.tier, tierMap);
const Icon = LucideIcons[tierMap[plan.tier]?.badge_icon] ?? Tag;
const isCurrent = isPlanCurrent(plan, myTier);
const isBlockedByOverlap = !isCurrent && overlapsExistingAccess(plan, myTier?.my_grants);
return (
<th key={plan.plan_id} className="p-4 text-center align-bottom min-w-[160px]">
<div className="flex flex-col items-center gap-2">
<Badge className={cls}><Icon className="size-3" />{label}</Badge>
<span className="font-semibold text-foreground">{plan.label}</span>
<span className="text-lg font-bold">{fmtCurrency(plan.price, plan.currency)}</span>
{isCurrent && <Badge variant="secondary" className="text-xs">Current Plan</Badge>}
{isBlockedByOverlap && (
<Badge variant="secondary" className="text-xs gap-1">
<Lock className="size-3" /> Already Included
</Badge>
)}
</div>
</th>
);
})}
</tr>
</thead>
<tbody>
<tr className="border-b bg-muted/30">
<td className="p-3 font-medium text-muted-foreground">Items included</td>
{plans.map((plan) => {
const bundle = getBundleContent(plan);
return (
<td key={plan.plan_id} className="p-3 text-center">
{bundle ? `${bundle.items.length} ${bundle.noun.toLowerCase()}${bundle.items.length !== 1 ? "s" : ""}` : "—"}
</td>
);
})}
</tr>
{featureRows.map((text, i) => (
<tr key={text} className={`border-b ${i % 2 === 1 ? "bg-muted/30" : ""}`}>
<td className="p-3 text-muted-foreground">{text}</td>
{plans.map((plan) => {
const included = (plan.features ?? []).some((f) => f.text === text);
return (
<td key={plan.plan_id} className="p-3 text-center">
{included
? <Check className="size-4 mx-auto text-green-500" />
: <Minus className="size-4 mx-auto text-muted-foreground/30" />
}
</td>
);
})}
</tr>
))}
{featureRows.length === 0 && (
<tr>
<td colSpan={plans.length + 1} className="p-6 text-center text-muted-foreground">
No features have been added to these plans yet.
</td>
</tr>
)}
</tbody>
<tfoot>
<tr>
<td className="p-4" />
{plans.map((plan) => {
const isCurrent = isPlanCurrent(plan, myTier);
const isBlockedByOverlap = !isCurrent && overlapsExistingAccess(plan, myTier?.my_grants);
return (
<td key={plan.plan_id} className="p-4 text-center">
<Button
size="sm"
variant={isCurrent || isBlockedByOverlap ? "secondary" : "default"}
disabled={isCurrent || isBlockedByOverlap || !plan.is_active}
onClick={() => onSelect(plan)}
>
{isCurrent ? "Current" : isBlockedByOverlap ? "Included" : !plan.is_active ? "Not Available" : "Select"}
</Button>
</td>
);
})}
</tr>
</tfoot>
</table>
</div>
);
}
@@ -0,0 +1,248 @@
/***********************************************************************************************************************************************************************
* File Name : TaskListTable.jsx
* Type : Component (Client)
* Description : Lightweight, read-only DataTable for the GroupList "List" view.
* Client-side search + pagination over the currently-fetched
* taskLists array (no admin DataTable dependency, no row actions,
* no selection/bulk actions).
*
* Props:
* taskLists {array} – array of TaskList objects (with .tasks[0])
* loading {boolean} – show skeleton rows
* onRefresh {function} – called when refresh button is clicked
* onRowClick {function} – (taskList) => void, navigates to task list view
* statusLabel {string} – 'ongoing' | 'completed' | 'overdue' — drives badge style
***********************************************************************************************************************************************************************/
import { useState, useMemo } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import {
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import {
Search, RefreshCw, ChevronsLeft, ChevronLeft, ChevronRight, ChevronsRight,
ArrowRight, Check, AlertTriangle, Circle,
} from 'lucide-react';
import { formatDateTime } from '@/utils/table.util';
const PAGE_SIZES = [50, 100, 1000];
// ─── Status badge per bucket ───────────────────────────────────────────────────
const StatusBadge = ({ status }) => {
const map = {
ongoing: { label: 'Ongoing', icon: Circle, className: 'bg-muted text-muted-foreground' },
completed: { label: 'Completed', icon: Check, className: 'bg-green-500/10 text-green-700 dark:text-green-400' },
overdue: { label: 'Overdue', icon: AlertTriangle, className: 'bg-destructive/10 text-destructive' },
};
const { label, icon: Icon, className } = map[status] ?? map.ongoing;
return (
<span className={`inline-flex items-center gap-1 text-xs font-medium rounded-full px-2.5 py-1 ${className}`}>
<Icon className="size-3.5" />
{label}
</span>
);
};
// ─── Skeleton rows ──────────────────────────────────────────────────────────────
const SkeletonRows = ({ rows = 5 }) => (
<>
{Array.from({ length: rows }).map((_, i) => (
<TableRow key={i}>
<TableCell><Skeleton className="h-4 w-32" /></TableCell>
<TableCell><Skeleton className="h-4 w-48" /></TableCell>
<TableCell><Skeleton className="h-4 w-24" /></TableCell>
<TableCell><Skeleton className="h-5 w-20 rounded-full" /></TableCell>
<TableCell><Skeleton className="h-4 w-4" /></TableCell>
</TableRow>
))}
</>
);
// ─── Main component ──────────────────────────────────────────────────────────────
export default function ClientTaskListTable({
taskLists = [],
loading = false,
onRefresh,
onRowClick,
statusLabel = 'ongoing',
}) {
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(50);
// ── Client-side search filter ─────────────────────────────────────────────
const filtered = useMemo(() => {
if (!search.trim()) return taskLists;
const q = search.trim().toLowerCase();
return taskLists.filter((tl) =>
tl.name?.toLowerCase().includes(q) ||
tl.description?.toLowerCase().includes(q)
);
}, [taskLists, search]);
// ── Pagination ─────────────────────────────────────────────────────────────
const totalRecords = filtered.length;
const totalPages = Math.max(1, Math.ceil(totalRecords / pageSize));
const clampedPage = Math.min(page, totalPages);
const pageRows = useMemo(() => {
const start = (clampedPage - 1) * pageSize;
return filtered.slice(start, start + pageSize);
}, [filtered, clampedPage, pageSize]);
const handleSearchChange = (val) => {
setSearch(val);
setPage(1);
};
const handlePageSizeChange = (val) => {
setPageSize(Number(val));
setPage(1);
};
const rangeStart = totalRecords === 0 ? 0 : (clampedPage - 1) * pageSize + 1;
const rangeEnd = Math.min(clampedPage * pageSize, totalRecords);
return (
<div className="flex flex-col gap-3">
{/* ── Toolbar: search + refresh ──────────────────────────────────── */}
<div className="flex items-center justify-between gap-2 flex-wrap">
<div className="relative max-w-xs flex-1">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<Input
placeholder="Search task lists..."
value={search}
onChange={(e) => handleSearchChange(e.target.value)}
className="pl-8"
/>
</div>
<Button
variant="outline"
onClick={onRefresh}
disabled={loading}
aria-label="Refresh"
>
<RefreshCw className={loading ? 'animate-spin' : ''} /> Refresh
</Button>
</div>
{/* ── Table ──────────────────────────────────────────────────────── */}
<div className="rounded-lg border overflow-hidden">
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableHead className="pl-6">Name</TableHead>
<TableHead>Description</TableHead>
<TableHead>Deadline</TableHead>
<TableHead>Status</TableHead>
<TableHead className="w-8" />
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<SkeletonRows />
) : pageRows.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-center py-12 text-sm text-muted-foreground">
No task lists match your search.
</TableCell>
</TableRow>
) : (
pageRows.map((tl) => {
const task = tl.tasks?.[0];
return (
<TableRow
key={tl.task_list_id}
className="hover:bg-muted/30 cursor-pointer transition-colors"
onClick={() => onRowClick?.(tl)}
>
<TableCell className="font-medium pl-6">{tl.name}</TableCell>
<TableCell className="text-muted-foreground text-sm max-w-xs truncate">
{tl.description || '—'}
</TableCell>
<TableCell className="text-sm whitespace-nowrap">
{task?.deadline ? formatDateTime(task.deadline) : '—'}
</TableCell>
<TableCell>
<StatusBadge status={statusLabel} />
</TableCell>
<TableCell className="pr-6">
<ArrowRight className="size-4 text-muted-foreground/60" />
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
</div>
{/* ── Pagination ─────────────────────────────────────────────────── */}
{!loading && totalRecords > 0 && (
<div className="flex items-center justify-between gap-2 flex-wrap">
<p className="text-sm text-muted-foreground">
Showing {rangeStart}-{rangeEnd} of {totalRecords}
</p>
<div className="flex items-center gap-1">
<Select value={String(pageSize)} onValueChange={handlePageSizeChange}>
<SelectTrigger className="h-8 w-[110px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{PAGE_SIZES.map((size) => (
<SelectItem key={size} value={String(size)}>
{size} / page
</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant="outline" size="icon" className="size-8"
onClick={() => setPage(1)}
disabled={clampedPage === 1}
aria-label="First page"
>
<ChevronsLeft className="size-4" />
</Button>
<Button
variant="outline" size="icon" className="size-8"
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={clampedPage === 1}
aria-label="Previous page"
>
<ChevronLeft className="size-4" />
</Button>
<span className="text-sm px-2 whitespace-nowrap">
{clampedPage} / {totalPages}
</span>
<Button
variant="outline" size="icon" className="size-8"
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
disabled={clampedPage === totalPages}
aria-label="Next page"
>
<ChevronRight className="size-4" />
</Button>
<Button
variant="outline" size="icon" className="size-8"
onClick={() => setPage(totalPages)}
disabled={clampedPage === totalPages}
aria-label="Last page"
>
<ChevronsRight className="size-4" />
</Button>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,43 @@
import { Sun, Moon, Monitor } from 'lucide-react'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { useTheme } from '@/contexts/ThemeContext'
export function ThemeSwitcher() {
const { theme, setTheme } = useTheme()
const themeConfig = {
light: { label: 'Light', icon: Sun },
dark: { label: 'Dark', icon: Moon },
system: { label: 'System', icon: Monitor },
}
return (
<div className="flex items-center gap-1 bg-card rounded-full border">
{Object.entries(themeConfig).map(([key, { label, icon: Icon }]) => (
<Tooltip key={key}>
<TooltipTrigger asChild>
<button
onClick={() => setTheme(key)}
aria-label={`Set theme to ${key}`}
className={`p-1 rounded-full transition-colors ${
theme === key ? 'border' : 'text-foreground'
}`}
>
<Icon
className="size-3.5"
style={theme === key ? { fill: 'currentColor' } : { fill: 'none' }}
/>
</button>
</TooltipTrigger>
<TooltipContent side="top">
<p>{label}</p>
</TooltipContent>
</Tooltip>
))}
</div>
)
}
@@ -0,0 +1,90 @@
// UnitCard — grid card for a standalone Unit. Shared by UnitsList.jsx and
// Dashboard.jsx's "Featured Units" section.
import { Timer, LockIcon, Layers, Tag } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { resolveTierBadge, cheapestTierSlug } from "@/utils/tierBadge.util";
function formatDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h && m) return `${h}h ${m}m`;
if (h) return `${h}h`;
return `${m}m`;
}
export const UnitCard = ({ unit, tierMap = {}, onViewDetails }) => {
const locked = unit.is_locked;
const duration = formatDuration(unit.duration_seconds);
const lessonCount = Number(unit.lesson_count ?? 0);
const courses = unit.courses ?? [];
const slug = cheapestTierSlug([unit.subscription, ...courses.map((c) => c.subscription)], tierMap);
const { label, cls } = resolveTierBadge(slug, tierMap);
return (
<div
className={cn(
"bg-card rounded-2xl border p-4 flex flex-col gap-2.5 transition-all cursor-pointer group",
"hover:shadow-sm",
locked
? "opacity-80 hover:opacity-100 hover:border-muted-foreground/40"
: "hover:bg-muted/60 dark:hover:border-blue-500"
)}
onClick={() => onViewDetails(unit)}
>
<div className="flex flex-wrap gap-1.5">
<Badge className={cls}>
{locked ? <LockIcon className="size-3" /> : <Tag className="size-3" />}
{label}
</Badge>
{locked && (
<Badge variant="secondary">
<LockIcon className="size-3" /> Locked
</Badge>
)}
</div>
<div className="flex flex-col gap-1">
<h1 className="text-lg font-medium leading-snug line-clamp-3 transition-colors group-hover:text-blue-700 dark:group-hover:text-blue-400">
{unit.title}
</h1>
{unit.description && (
<p className="text-sm leading-relaxed line-clamp-2 group-hover:text-blue-700 dark:group-hover:text-blue-400">
{unit.description}
</p>
)}
</div>
<div className="flex items-center justify-between pt-2 mt-auto border-t">
<div className={`flex items-center gap-3 text-sm [&_svg]:size-4 ${locked ? "text-muted-foreground" : "text-card-foreground group-hover:text-blue-700 dark:group-hover:text-blue-400"}`}>
<div className="flex items-center gap-1">
<Layers /> {lessonCount} {lessonCount === 1 ? "Lesson" : "Lessons"}
</div>
<div className="flex items-center gap-1">
<Timer /> {duration ?? "—"}
</div>
</div>
{locked && (
<span className="text-xs text-muted-foreground">Upgrade to unlock</span>
)}
</div>
</div>
);
};
export const UnitCardSkeleton = () => (
<div className="bg-card rounded-2xl border p-4 flex flex-col gap-2.5">
<div className="flex gap-1.5">
<Skeleton className="h-5 w-20 rounded-full" />
</div>
<Skeleton className="h-6 w-3/4" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
<div className="pt-2 mt-auto border-t">
<Skeleton className="h-4 w-24" />
</div>
</div>
);
@@ -0,0 +1,54 @@
// UnitUpsellModal — shown when a learner clicks a locked standalone Unit.
// Unlocks via any course it's attached to (links to view/buy the course).
// Shared by UnitsList, UnitDetails, and Dashboard.
import { useNavigate } from "react-router-dom";
import { LockIcon, Check } from "lucide-react";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { resolveTierBadge, cheapestTierSlug } from "@/utils/tierBadge.util";
export default function UnitUpsellModal({ open, onOpenChange, unit, tierMap = {} }) {
const navigate = useNavigate();
const courses = unit?.courses ?? [];
const slug = cheapestTierSlug([unit?.subscription, ...courses.map((c) => c.subscription)], tierMap);
const { rank, label, cls, panel } = resolveTierBadge(slug, tierMap);
return (
<ResponsiveModal
open={open}
onOpenChange={onOpenChange}
title={unit?.title ?? "Unit Details"}
description="Upgrade your plan to access this unit."
footer={
<>
<Button variant="outline" onClick={() => onOpenChange(false)}>Close</Button>
<Button onClick={() => { onOpenChange(false); navigate("/subscriptions"); }}>
<LockIcon /> View Plans
</Button>
</>
}
>
<div className="space-y-6 py-2">
{rank > 0 && (
<div className={`p-5 rounded-2xl border ${panel.bg} ${panel.border}`}>
<div className="flex items-center gap-3 mb-3">
<Badge className={cls}>
<LockIcon className="size-3" /> {label}
</Badge>
</div>
<ul className="space-y-2 text-sm [&_svg]:size-4 mb-4">
<li className="flex items-center gap-2"><Check /> Access to {label} content</li>
<li className="flex items-center gap-2"><Check /> Certificates & achievements</li>
</ul>
<p className="text-sm text-muted-foreground">
Upgrade to a <span className="font-medium">{label}</span> plan to unlock this unit.
</p>
</div>
)}
</div>
</ResponsiveModal>
);
}
@@ -0,0 +1,65 @@
import { Trophy, Clock, CheckCircle2 } from "lucide-react";
import { useDateFormat } from "@/hooks/useDateFormat";
/**
* Props:
* course — { title, pending_certificate, certificate, ... } the completed course
*/
const CourseCompleteBlock = ({ course }) => {
const { fmtDate } = useDateFormat();
const certificate = course?.certificate ?? null;
const pendingCert = course?.pending_certificate ?? null;
const isIssued = !!certificate;
const isPending = !isIssued && !!pendingCert;
return (
<div className="max-w-2xl mx-auto">
<div className="rounded-xl border bg-card p-6 space-y-6 text-center sm:p-10">
<div className="flex justify-center">
<div className="rounded-full bg-amber-500/10 p-4">
<Trophy className="size-10 text-amber-500" />
</div>
</div>
<div className="space-y-1.5">
<h2 className="text-2xl font-semibold sm:text-3xl">Congratulations!</h2>
<p className="text-sm text-muted-foreground sm:text-base">
You've successfully completed <span className="font-medium text-foreground">{course?.title}</span>.
</p>
</div>
<div className="rounded-lg border border-green-500/30 bg-green-500/5 px-4 py-3">
<p className="text-sm font-medium text-green-700 dark:text-green-400">Course Complete</p>
<p className="text-xs text-muted-foreground">
You've passed all required units and the final assessment for this course.
</p>
</div>
{isIssued ? (
<div className="flex items-start gap-2.5 rounded-lg border border-green-500/30 bg-green-500/5 px-4 py-3 text-left">
<CheckCircle2 className="size-4 text-green-500 shrink-0 mt-0.5" />
<div>
<p className="text-sm font-medium text-green-700 dark:text-green-400">Certificate Issued</p>
<p className="text-xs text-muted-foreground">
Issued on {fmtDate(certificate.issued_at)}. View and download it from your Certificates page.
</p>
</div>
</div>
) : (
<div className="flex items-start gap-2.5 rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3 text-left">
<Clock className="size-4 text-amber-500 shrink-0 mt-0.5" />
<div>
<p className="text-sm font-medium text-amber-700 dark:text-amber-400">Certificate Pending</p>
<p className="text-xs text-muted-foreground">
{isPending
? `Certificates are issued automatically every hour. Yours will be ready by ${fmtDate(pendingCert.issue_at)} — check your notifications.`
: "Certificates are issued automatically every hour. Yours will be ready within the next hour — check your notifications."}
</p>
</div>
</div>
)}
</div>
</div>
);
};
export default CourseCompleteBlock;
@@ -0,0 +1,333 @@
import { useState, useCallback, useRef } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import {
CloudUpload,
FileText,
Image,
Video,
Paperclip,
Plus,
X,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { isQasEnv, QAS_UPLOAD_LIMIT_MB } from "@/utils/environment.util";
// ── Helpers ───────────────────────────────────────────────────────────────────
function formatBytes(b) {
if (b >= 1024 * 1024 * 1024) return (b / 1024 / 1024 / 1024).toFixed(1) + " GB";
if (b >= 1024 * 1024) return (b / 1024 / 1024).toFixed(1) + " MB";
return (b / 1024).toFixed(0) + " KB";
}
function iconForFile(name) {
const ext = name.split(".").pop().toLowerCase();
if (["mp4", "mov", "avi", "webm"].includes(ext)) return "vid";
if (["pdf", "doc", "docx", "pptx", "txt"].includes(ext)) return "doc";
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext)) return "img";
return "def";
}
const FILE_ICON_MAP = {
vid: { icon: Video, bg: "bg-amber-100 dark:bg-amber-900", text: "text-amber-700 dark:text-amber-300" },
doc: { icon: FileText, bg: "bg-blue-100 dark:bg-blue-900", text: "text-blue-700 dark:text-blue-300" },
img: { icon: Image, bg: "bg-green-100 dark:bg-green-900", text: "text-green-700 dark:text-green-300" },
def: { icon: Paperclip, bg: "bg-muted", text: "text-muted-foreground" },
};
// ── FileIcon ──────────────────────────────────────────────────────────────────
const FileIcon = ({ type }) => {
const { icon: Icon, bg, text } = FILE_ICON_MAP[type] ?? FILE_ICON_MAP.def;
return (
<div className={cn("w-8 h-8 rounded-md flex items-center justify-center shrink-0", bg)}>
<Icon className={cn("size-4", text)} />
</div>
);
};
// ── FileItem ──────────────────────────────────────────────────────────────────
const FileItem = ({ file, onRemove }) => {
const isUploading = file.status === "uploading";
const isError = file.status === "error";
const isDone = file.status === "done";
return (
<div className="border rounded-md px-3 py-2.5 bg-muted/50 flex flex-col gap-1.5">
<div className="flex items-center gap-2.5">
<FileIcon type={file.type} />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{file.name}</p>
<p className="text-xs text-muted-foreground">{file.size}</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{isDone && <span className="text-xs text-green-600 dark:text-green-400 font-medium">Uploaded</span>}
{isError && <span className="text-xs text-destructive font-medium">Failed</span>}
{isUploading && <span className="text-xs text-blue-600 dark:text-blue-400">{file.progress}%</span>}
<button
onClick={onRemove}
className="text-muted-foreground hover:text-destructive transition-colors p-0.5 rounded"
aria-label={`Remove ${file.name}`}
>
<X className="size-3.5" />
</button>
</div>
</div>
{isUploading && <Progress value={file.progress} className="h-1" />}
{isError && <Progress value={100} className="h-1 [&>div]:bg-destructive" />}
</div>
);
};
// ── FileUpload ────────────────────────────────────────────────────────────────
/**
* Standalone file upload UI — no modal, no footer buttons.
* Compose inside <ResponsiveModal> or any container.
*
* Props:
* accept {string} – native <input accept> string (fallback if
* allowedFileTypes not provided)
* hint {string} – dropzone helper text (fallback if
* allowedFileTypes/maxFileCount not provided)
* allowedFileTypes {string[]} – e.g. ["PDF","DOCX","PNG","JPG","MP4"], from the
* task's upload_file requirement. Drives both
* the displayed hint and the <input accept>,
* and is enforced client-side on file add.
* maxFileCount {number} – max number of files allowed. Displayed in
* the hint and enforced client-side on file add.
* onChange {function} – fires on every file list change:
* ({ files, isUploading }) => void
* onUploadDone {function} – fires when all uploads finish:
* ({ files }) => void
*/
const FileUpload = ({
accept,
hint = "PDF, DOCX, MP4, PNG, JPG",
allowedFileTypes,
maxFileCount,
onChange,
onUploadDone,
}) => {
const [files, setFiles] = useState([]);
const [isDragging, setIsDragging] = useState(false);
const fileInputRef = useRef(null);
const isUploading = files.some((f) => f.status === "uploading");
// ── Derived accept string ───────────────────────────────────────────────────
const derivedAccept = allowedFileTypes?.length
? allowedFileTypes.map((ext) => `.${ext.toLowerCase()}`).join(",")
: accept;
// ── Derived hint text ────────────────────────────────────────────────────────
const derivedHint = (() => {
if (!allowedFileTypes?.length && !maxFileCount) return hint;
const parts = [];
if (allowedFileTypes?.length) {
parts.push(allowedFileTypes.map((e) => e.toUpperCase()).join(", "));
}
if (maxFileCount) {
parts.push(`Max ${maxFileCount} file${maxFileCount !== 1 ? "s" : ""}`);
}
return parts.join(" · ");
})();
// Notify parent with full state
const notify = (next) => {
const uploading = next.some((f) => f.status === "uploading");
onChange?.({ files: next, isUploading: uploading });
};
// ── simulate upload progress ──────────────────────────────────────────────
const simulateUpload = useCallback((id) => {
const tick = () => {
setFiles((prev) => {
const idx = prev.findIndex((f) => f.id === id);
if (idx === -1) return prev;
const next = [...prev];
const entry = { ...next[idx] };
entry.progress = Math.min(100, entry.progress + Math.floor(Math.random() * 18 + 8));
if (entry.progress >= 100) { entry.progress = 100; entry.status = "done"; }
next[idx] = entry;
notify(next);
const allDone = next.every((f) => f.status !== "uploading");
if (allDone) onUploadDone?.({ files: next });
return next;
});
setFiles((prev) => {
const f = prev.find((f) => f.id === id);
if (f && f.status === "uploading") setTimeout(tick, 250 + Math.random() * 200);
return prev;
});
};
setTimeout(tick, 300);
}, [onChange, onUploadDone]);
// ── add files ─────────────────────────────────────────────────────────────
const addFiles = useCallback((rawFiles) => {
let incoming = Array.from(rawFiles);
// ── Validate allowed file types ─────────────────────────────────────────
if (allowedFileTypes?.length) {
const allowed = allowedFileTypes.map((e) => e.toUpperCase());
const rejected = [];
incoming = incoming.filter((f) => {
const ext = (f.name.split(".").pop() ?? "").toUpperCase();
const ok = allowed.includes(ext);
if (!ok) rejected.push(f.name);
return ok;
});
if (rejected.length > 0) {
setTimeout(() => toast(
`${rejected.length === 1 ? `"${rejected[0]}" is` : `${rejected.length} files are`} not allowed. ` +
`Accepted types: ${allowed.join(", ")}.`
), 0);
}
}
setFiles((prev) => {
// ── Validate max file count ───────────────────────────────────────────
if (maxFileCount) {
const availableSlots = maxFileCount - prev.length;
if (availableSlots <= 0) {
setTimeout(() => toast(
`You can only attach up to ${maxFileCount} file${maxFileCount !== 1 ? "s" : ""}.`
), 0);
incoming = [];
} else if (incoming.length > availableSlots) {
setTimeout(() => toast(
`Only ${availableSlots} more file${availableSlots !== 1 ? "s" : ""} can be added ` +
`(max ${maxFileCount}).`
), 0);
incoming = incoming.slice(0, availableSlots);
}
}
const duplicates = [];
const toAdd = [];
incoming.forEach((f) => {
if (prev.some((e) => e.name === f.name)) {
duplicates.push(f.name);
} else {
toAdd.push({
id: crypto.randomUUID(),
name: f.name,
size: formatBytes(f.size),
bytes: f.size,
type: iconForFile(f.name),
progress: 0,
status: "uploading",
rawFile: f,
});
}
});
if (duplicates.length > 0) {
setTimeout(() => toast(duplicates.length === 1
? `"${duplicates[0]}" is already attached.`
: `${duplicates.length} files are already attached.`), 0);
}
const next = prev.concat(toAdd);
toAdd.forEach((e) => simulateUpload(e.id));
notify(next);
return next;
});
if (fileInputRef.current) fileInputRef.current.value = "";
}, [simulateUpload, onChange, allowedFileTypes, maxFileCount]);
// ── remove ────────────────────────────────────────────────────────────────
const removeFile = (id) => {
setFiles((prev) => {
const next = prev.filter((f) => f.id !== id);
notify(next);
return next;
});
};
// ── drag & drop ───────────────────────────────────────────────────────────
const onDragOver = (e) => { e.preventDefault(); setIsDragging(true); };
const onDragLeave = () => setIsDragging(false);
const onDrop = (e) => { e.preventDefault(); setIsDragging(false); addFiles(e.dataTransfer.files); };
const canAttachMore = !maxFileCount || files.length < maxFileCount;
return (
<div className="flex flex-col gap-0">
{/* Dropzone */}
{files.length === 0 && (
<div
onClick={() => fileInputRef.current?.click()}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
className={cn(
"border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors",
isDragging
? "border-blue-400 bg-blue-50 dark:bg-blue-950/30"
: "border-border hover:border-blue-400 hover:bg-muted/40"
)}
>
<CloudUpload className={cn("size-8 mx-auto mb-3", isDragging ? "text-blue-500" : "text-muted-foreground")} />
<p className="text-sm font-medium">Drop files here or click to browse</p>
<p className="text-sm text-muted-foreground mt-1">Upload your work to submit with this task</p>
<p className="text-sm mt-2">{derivedHint}</p>
{isQasEnv && (
<p className="text-xs text-amber-600 mt-1">
Self-hosted staging environment — uploads over {QAS_UPLOAD_LIMIT_MB}MB may fail (Cloudflare limit).
</p>
)}
</div>
)}
{/* File list */}
{files.length > 0 && (
<div>
<div className="flex items-center justify-between mb-4">
<span className="text-sm font-medium text-muted-foreground">Attached files</span>
{canAttachMore && (
<Button onClick={() => fileInputRef.current?.click()} variant="outline">
<Plus /> Attach
</Button>
)}
</div>
{files.length >= 2 ? (
<ScrollArea className="h-[210px]">
<div className="flex flex-col gap-2">
{files.map((f) => (
<FileItem key={f.id} file={f} onRemove={() => removeFile(f.id)} />
))}
</div>
</ScrollArea>
) : (
<div className="flex flex-col gap-2">
{files.map((f) => (
<FileItem key={f.id} file={f} onRemove={() => removeFile(f.id)} />
))}
</div>
)}
<p className="text-xs text-muted-foreground mt-2">{derivedHint}</p>
{isQasEnv && (
<p className="text-xs text-amber-600 mt-1">
Self-hosted staging environment — uploads over {QAS_UPLOAD_LIMIT_MB}MB may fail (Cloudflare limit).
</p>
)}
</div>
)}
<input
ref={fileInputRef}
type="file"
multiple
accept={derivedAccept}
className="hidden"
onChange={(e) => addFiles(e.target.files)}
/>
</div>
);
};
export default FileUpload;
export { FileUpload, FileItem, FileIcon, formatBytes, iconForFile };
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,300 @@
import { useNavigate } from "react-router-dom";
import { useState, useEffect, useRef } from "react";
import { Badge } from "@/components/ui/badge";
import { BookOpen, Tag, CheckCheck, RefreshCcw, Lock, Zap, Info } from "lucide-react";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { Progress } from "@/components/ui/progress";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { Button } from "@/components/ui/button";
import { SendHorizonal } from "lucide-react";
import { toast } from "sonner";
import api from "@/utils/api.util";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { resolveTierBadge } from "@/utils/tierBadge.util";
const LVL_LABEL = { beginner: 'Beginner', intermediate: 'Intermediate', advanced: 'Advanced' };
function TierBadge({ tier, locked = false }) {
const { tierMap } = useClientTiers();
const { rank, label, cls } = resolveTierBadge(tier ?? 'free', tierMap);
if (rank === 0 && !locked) return null;
return (
<Badge className={`gap-1 ${cls} w-fit shrink-0`}>
{rank > 0 ? <Lock className="size-3" /> : <Tag className="size-3" />}
{label}
</Badge>
);
}
const ReadCourse = ({ title = "Read Course", courses = [], groupId, taskListId, taskId }) => {
const navigate = useNavigate();
const [selected, setSelected] = useState(null);
const [details, setDetails] = useState({});
const [summaries, setSummaries] = useState({});
const [locked, setLocked] = useState({});
const [lockedInfo, setLockedInfo] = useState({});
const [fetching, setFetching] = useState({});
const prevCompletedRef = useRef({});
useEffect(() => {
courses.forEach((course) => {
const prev = prevCompletedRef.current[course.id];
if (course.completed && prev === false) {
toast(`"${course.title}" has been automatically turned in!`);
}
prevCompletedRef.current[course.id] = !!course.completed;
});
}, [courses]);
useEffect(() => {
courses.forEach(async (course) => {
if (!course.reference_id) return;
setFetching((prev) => ({ ...prev, [course.reference_id]: true }));
try {
const res = await api.get(`/client/courses/uuid/${course.reference_id}`);
const d = res.data?.data;
if (!d) return;
setDetails((prev) => ({ ...prev, [course.reference_id]: d }));
const progRes = await api.get(`/client/courses/${d.course_id}/progress/summary`);
const summary = progRes.data?.data;
if (summary) setSummaries((prev) => ({ ...prev, [course.reference_id]: summary }));
} catch (err) {
if (err?.response?.status === 403) {
setLocked((prev) => ({ ...prev, [course.reference_id]: true }));
const courseData = err.response?.data?.course;
if (courseData) setLockedInfo((prev) => ({ ...prev, [course.reference_id]: courseData }));
} else {
console.error('[ReadCourse] fetch failed:', err?.response?.status, err?.message);
}
} finally {
setFetching((prev) => ({ ...prev, [course.reference_id]: false }));
}
});
}, []);
const getReadingPercent = (course) => {
const summary = summaries[course.reference_id];
return summary ? summary.percent : (course.progress ?? 0);
};
const hasLocked = Object.values(locked).some(Boolean);
return (
<div className="border rounded-lg bg-card overflow-hidden">
{/* Header */}
<div className="px-6 py-4 border-b flex items-center gap-2">
<BookOpen className="size-4 text-muted-foreground" />
<h2 className="font-semibold text-sm">{title}</h2>
<Badge variant="secondary" className="ml-auto">{courses.length}</Badge>
</div>
{/* Subscription advisory */}
{hasLocked && (
<div className="flex items-start gap-3 px-5 py-3.5 border-b bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300">
<Info className="size-4 mt-0.5 shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium leading-snug">Subscription Required</p>
<p className="text-xs mt-0.5 text-amber-700 dark:text-amber-400 leading-relaxed">
To complete this activity, subscribe to one of our available tier plans.
</p>
</div>
<Button size="sm" variant="outline" className="shrink-0 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/40" onClick={() => navigate('/subscriptions')}>
<Zap className="size-3.5" /> View Plans
</Button>
</div>
)}
<ScrollArea className="w-full bg-muted overflow-hidden">
<div className="flex gap-4 p-4">
{courses.map((course) => {
const info = details[course.reference_id];
const courseInfo = lockedInfo[course.reference_id];
const percent = getReadingPercent(course);
const done = !!course.completed;
const allRead = !done && percent >= 100;
const isLocked = locked[course.reference_id];
const isFetching = fetching[course.reference_id];
// ── Locked card ───────────────────────────────────────────────────
// Skipped when already completed — a completion recorded while the
// content was accessible still counts even if it re-locks later
// (task_progress/reading-progress rows are never revoked on a tier
// change), so it must keep showing as Completed, not Locked.
if (isLocked && !done) {
return (
<div
key={course.id}
onClick={() => navigate('/subscriptions')}
className="bg-card rounded-2xl border border-dashed p-4 flex flex-col gap-3 hover:bg-muted/60 hover:shadow-sm transition-all cursor-pointer group w-96 shrink-0 opacity-80"
>
<div className="flex items-center gap-1.5">
<BookOpen className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Course</span>
<div className="ml-auto">
<TierBadge tier={courseInfo?.subscription} locked />
</div>
</div>
<div>
<h1 className="text-base font-semibold leading-snug line-clamp-2 text-muted-foreground">
{course.title}
</h1>
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">
This course requires a higher subscription plan.
</p>
</div>
<div className="mt-auto">
<Button size="sm" className="w-full gap-1.5" onClick={(e) => { e.stopPropagation(); navigate('/subscriptions'); }}>
<Zap className="size-3.5" /> Upgrade to unlock
</Button>
</div>
</div>
);
}
// ── Normal card ───────────────────────────────────────────────────
return (
<div
key={course.id}
onClick={() => !isFetching && setSelected(course)}
className={`bg-card rounded-2xl border p-4 flex flex-col gap-3 transition-all w-96 shrink-0 ${
isFetching
? 'opacity-60 cursor-wait'
: 'hover:bg-muted/60 hover:shadow-sm cursor-pointer group'
}`}
>
{/* Card type row */}
<div className="flex items-center gap-1.5">
<BookOpen className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Course</span>
<div className="ml-auto flex items-center gap-1.5">
{info?.subscription && <TierBadge tier={info.subscription} />}
{info?.level && (
<Badge variant="outline" className="text-xs capitalize">
{LVL_LABEL[info.level] ?? info.level}
</Badge>
)}
{!info && course.reference_id && (
<Badge variant="secondary" className="opacity-40 text-xs">Loading…</Badge>
)}
</div>
</div>
<div>
<h1
onClick={(e) => {
if (!info?.course_id) return;
e.stopPropagation();
navigate(`/course/${info.course_id}/unit`, {
state: taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {},
});
}}
className="text-base font-semibold leading-snug line-clamp-2 transition-colors text-blue-600 dark:text-blue-400 hover:underline cursor-pointer"
>
{course.title}
</h1>
<p className="text-sm text-muted-foreground leading-relaxed line-clamp-2 mt-1">
{info?.description ?? ''}
</p>
</div>
<div className="flex flex-col gap-2 mt-auto pt-1 border-t">
<div className="flex items-center justify-between text-sm pt-1">
<span className="flex items-center gap-1.5 text-muted-foreground">
{done
? <><CheckCheck className="size-4 text-green-500" /><span className="text-green-600 dark:text-green-400 font-medium">Completed</span></>
: allRead
? <><CheckCheck className="size-4 text-amber-500" /><span className="text-amber-600 dark:text-amber-400 font-medium">Lessons Done</span></>
: <><RefreshCcw className="size-4" /> In Progress</>
}
</span>
<span className="font-semibold text-xs">{percent}%</span>
</div>
<Progress
value={percent}
className={`h-1.5 ${done ? "[&>div]:bg-green-500" : allRead ? "[&>div]:bg-amber-500" : ""}`}
/>
</div>
</div>
);
})}
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
{/* Detail modal */}
{selected && (() => {
const info = details[selected.reference_id];
const percent = getReadingPercent(selected);
const done = !!selected.completed;
const allRead = !done && percent >= 100;
return (
<ResponsiveModal
open={!!selected}
onOpenChange={(o) => !o && setSelected(null)}
title={selected.title}
description={done ? "Course Summary" : "Course Info"}
footer={
<>
<Button variant="outline" onClick={() => setSelected(null)}>Cancel</Button>
<Button
onClick={() => {
if (!info?.course_id) return;
navigate(`/course/${info.course_id}/unit`, {
state: {
...(allRead ? { seekFirstIncomplete: true } : {}),
...(taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {}),
},
});
}}
disabled={done || !info?.course_id}
>
<SendHorizonal /> Proceed
</Button>
</>
}
>
<div className="flex flex-col gap-5">
{done ? (
<div className="flex items-center gap-2 bg-green-500/10 text-green-600 dark:text-green-400 rounded-lg px-4 py-3 text-sm font-medium">
<CheckCheck className="size-4 shrink-0" /> Automatically Turned-in
</div>
) : allRead ? (
<div className="flex items-center gap-2 bg-amber-500/10 text-amber-600 dark:text-amber-400 rounded-lg px-4 py-3 text-sm font-medium">
<CheckCheck className="size-4 shrink-0" /> Lessons complete — finish quizzes &amp; assessment to turn in
</div>
) : (
<div className="flex items-center gap-2 bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded-lg px-4 py-3 text-sm font-medium">
<RefreshCcw className="size-4 shrink-0" /> Currently in progress
</div>
)}
<div className="grid grid-cols-2 divide-x rounded-lg border text-center text-sm">
<div className="flex flex-col gap-1 py-4">
<span className="text-xl font-bold">
{info?.subscription ? (info.subscription.charAt(0).toUpperCase() + info.subscription.slice(1)) : '—'}
</span>
<span className="text-muted-foreground text-xs">Subscription</span>
</div>
<div className="flex flex-col gap-1 py-4">
<span className="text-xl font-bold">
{info?.level ? (LVL_LABEL[info.level] ?? info.level) : '—'}
</span>
<span className="text-muted-foreground text-xs">Level</span>
</div>
</div>
<div className="flex flex-col gap-1">
<p className="text-xs text-muted-foreground uppercase tracking-wide font-medium">About this course</p>
<p className="text-sm leading-relaxed">{info?.description ?? '—'}</p>
</div>
</div>
</ResponsiveModal>
);
})()}
</div>
);
};
export default ReadCourse;
@@ -0,0 +1,234 @@
import { useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { FileText, CheckCheck, Lock, Zap, Info, Tag } from "lucide-react";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import api from "@/utils/api.util";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { resolveTierBadge } from "@/utils/tierBadge.util";
function TierBadge({ tier }) {
const { tierMap } = useClientTiers();
const { rank, label, cls } = resolveTierBadge(tier ?? 'free', tierMap);
return (
<Badge className={`gap-1 ${cls} w-fit shrink-0`}>
{rank > 0 ? <Lock className="size-3" /> : <Tag className="size-3" />}
{label}
</Badge>
);
}
const ReadLesson = ({ title = "Read Lessons", lessons = [], groupId, taskListId, taskId }) => {
const navigate = useNavigate();
const [details, setDetails] = useState({});
const [locked, setLocked] = useState({});
const [lockedInfo, setLockedInfo] = useState({});
const [unavailable, setUnavailable] = useState({});
const [fetching, setFetching] = useState({});
useEffect(() => {
lessons.forEach(async (lesson) => {
if (!lesson.reference_id) return;
setFetching((prev) => ({ ...prev, [lesson.reference_id]: true }));
try {
const res = await api.get(`/client/courses/lesson/uuid/${lesson.reference_id}`);
const d = res.data?.data;
if (d) setDetails((prev) => ({ ...prev, [lesson.reference_id]: d }));
} catch (err) {
if (err?.response?.status === 403) {
setLocked((prev) => ({ ...prev, [lesson.reference_id]: true }));
const course = err.response?.data?.course;
if (course) setLockedInfo((prev) => ({ ...prev, [lesson.reference_id]: course }));
} else {
setUnavailable((prev) => ({ ...prev, [lesson.reference_id]: true }));
}
} finally {
setFetching((prev) => ({ ...prev, [lesson.reference_id]: false }));
}
});
}, []);
const hasLocked = Object.values(locked).some(Boolean);
return (
<div className="border rounded-lg bg-card overflow-hidden">
<div className="px-6 py-4 border-b flex items-center gap-2">
<FileText className="size-4 text-muted-foreground" />
<h2 className="font-semibold text-sm">{title}</h2>
<Badge variant="secondary" className="ml-auto">{lessons.length}</Badge>
</div>
{hasLocked && (
<div className="flex items-start gap-3 px-5 py-3.5 border-b bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300">
<Info className="size-4 mt-0.5 shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium leading-snug">Subscription Required</p>
<p className="text-xs mt-0.5 text-amber-700 dark:text-amber-400 leading-relaxed">
To complete this activity, subscribe to one of our available tier plans.
</p>
</div>
<Button size="sm" variant="outline" className="shrink-0 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/40" onClick={() => navigate('/subscriptions')}>
<Zap className="size-3.5" /> View Plans
</Button>
</div>
)}
<ScrollArea className="w-full bg-muted overflow-hidden">
<div className="flex gap-4 p-4">
{lessons.map((lesson) => {
const info = details[lesson.reference_id];
const courseInfo = lockedInfo[lesson.reference_id];
const isLocked = locked[lesson.reference_id];
const isUnavailable = unavailable[lesson.reference_id];
const isFetching = fetching[lesson.reference_id];
// ── Locked card ───────────────────────────────────────
// Skipped when already completed — a completion recorded
// while the lesson was accessible still counts even if it
// re-locks later (reading-progress rows are never revoked
// on a tier change), so it must keep showing as Completed.
if (isLocked && !lesson.completed) {
return (
<div
key={lesson.id}
onClick={() => navigate('/subscriptions')}
className="bg-card rounded-2xl border border-dashed p-4 flex flex-col gap-3 hover:bg-muted/60 hover:shadow-sm transition-all cursor-pointer group w-96 shrink-0 opacity-80"
>
<div className="flex items-center gap-1.5">
<FileText className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Lesson</span>
<div className="ml-auto">
<TierBadge tier={courseInfo?.subscription} />
</div>
</div>
{courseInfo?.title && (
<p className="text-xs text-muted-foreground font-medium truncate -mt-1">
from <span className="text-foreground/70">{courseInfo.title}</span>
</p>
)}
<div>
<h1 className="text-base font-semibold leading-snug line-clamp-2 text-muted-foreground">
{lesson.title}
</h1>
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">
Subscribe to <span className="font-medium">{courseInfo?.title ?? 'this course'}</span> to unlock this lesson.
</p>
</div>
<div className="mt-auto">
<Button size="sm" className="w-full gap-1.5" onClick={(e) => { e.stopPropagation(); navigate('/subscriptions'); }}>
<Zap className="size-3.5" /> Upgrade to unlock
</Button>
</div>
</div>
);
}
// ── Unavailable card ──────────────────────────────────
if (isUnavailable) {
return (
<div
key={lesson.id}
className="bg-card rounded-2xl border border-dashed p-4 flex flex-col gap-3 w-96 shrink-0 opacity-50 cursor-not-allowed"
>
<div className="flex items-center gap-1.5">
<FileText className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Lesson</span>
<Badge variant="secondary" className="ml-auto gap-1 text-muted-foreground text-xs">
<Lock className="size-3" /> Unavailable
</Badge>
</div>
<h1 className="text-base font-semibold leading-snug line-clamp-2 text-muted-foreground">
{lesson.title}
</h1>
<p className="text-sm text-muted-foreground">This lesson is no longer available.</p>
</div>
);
}
// ── Normal card ───────────────────────────────────────
return (
<div
key={lesson.id}
onClick={() => {
if (isFetching || !info) return;
// Course-attached lesson — jump straight to it within the
// course's unit reader (existing behavior).
if (info.unit?.course?.course_id) {
navigate(`/course/${info.unit.course.course_id}/unit`, {
state: {
lessonId: info.lesson_id,
unitId: info.unit.unit_id,
...(taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {}),
},
});
return;
}
// Standalone lesson (junction revamp — no parent course, or no
// parent unit at all) — the course-scoped route can't resolve,
// so fall back to the standalone lesson page instead.
navigate(`/lessons/${lesson.reference_id}`, {
state: taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {},
});
}}
className={`bg-card rounded-2xl border p-4 flex flex-col gap-3 transition-all w-96 shrink-0 ${
isFetching
? 'opacity-60 cursor-wait'
: 'hover:bg-muted/60 hover:shadow-sm cursor-pointer group'
}`}
>
{/* Card type row */}
<div className="flex items-center gap-1.5">
<FileText className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Lesson</span>
<div className="ml-auto">
{info?.unit?.course?.subscription
? <TierBadge tier={info.unit.course.subscription} />
: isFetching && <Badge variant="secondary" className="opacity-40 text-xs">Loading…</Badge>
}
</div>
</div>
{/* Course breadcrumb */}
{info?.unit?.course?.title && (
<p className="text-xs text-muted-foreground truncate -mt-1.5">
from <span className="text-foreground/70 font-medium">{info.unit.course.title}</span>
</p>
)}
<div>
<h1 className="text-base font-semibold leading-snug line-clamp-2 text-blue-600 dark:text-blue-400 hover:underline transition-colors cursor-pointer">
{lesson.title}
</h1>
<p className="text-sm text-muted-foreground leading-relaxed line-clamp-2 mt-1">
{info?.description ?? ''}
</p>
</div>
<div className="flex flex-col gap-2 mt-auto pt-1 border-t">
<div className="flex items-center justify-between text-sm pt-1">
{lesson.completed ? (
<span className="flex items-center gap-1.5 text-green-600 dark:text-green-400 font-medium">
<CheckCheck className="size-4" /> Completed
</span>
) : (
<span className="text-muted-foreground font-medium">Not Started</span>
)}
</div>
<Progress
value={lesson.completed ? 100 : 0}
className={`h-1.5 ${lesson.completed ? "[&>div]:bg-green-500" : ""}`}
/>
</div>
</div>
);
})}
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
);
};
export default ReadLesson;
@@ -0,0 +1,316 @@
import { useState, useEffect } from "react";
import { Badge } from "@/components/ui/badge";
import { Layers, CheckCheck, RefreshCw, SendHorizonal, Lock, Zap, Info, Tag } from "lucide-react";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { Progress } from "@/components/ui/progress";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { Button } from "@/components/ui/button";
import { useNavigate } from "react-router-dom";
import api from "@/utils/api.util";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { resolveTierBadge } from "@/utils/tierBadge.util";
function TierBadge({ tier }) {
const { tierMap } = useClientTiers();
const { rank, label, cls } = resolveTierBadge(tier ?? 'free', tierMap);
return (
<Badge className={`gap-1 ${cls} w-fit shrink-0`}>
{rank > 0 ? <Lock className="size-3" /> : <Tag className="size-3" />}
{label}
</Badge>
);
}
const ReadUnit = ({ title = "Read Units", units = [], groupId, taskListId, taskId }) => {
const navigate = useNavigate();
const [selected, setSelected] = useState(null);
const [details, setDetails] = useState({});
const [locked, setLocked] = useState({});
const [lockedInfo, setLockedInfo] = useState({});
const [unavailable, setUnavailable] = useState({});
const [fetching, setFetching] = useState({});
useEffect(() => {
units.forEach(async (unit) => {
if (!unit.reference_id) return;
setFetching((prev) => ({ ...prev, [unit.reference_id]: true }));
try {
const res = await api.get(`/client/courses/unit/uuid/${unit.reference_id}`);
const d = res.data?.data;
if (d) setDetails((prev) => ({ ...prev, [unit.reference_id]: d }));
} catch (err) {
if (err?.response?.status === 403) {
setLocked((prev) => ({ ...prev, [unit.reference_id]: true }));
const course = err.response?.data?.course;
if (course) setLockedInfo((prev) => ({ ...prev, [unit.reference_id]: course }));
} else {
setUnavailable((prev) => ({ ...prev, [unit.reference_id]: true }));
}
} finally {
setFetching((prev) => ({ ...prev, [unit.reference_id]: false }));
}
});
}, []);
const getProgress = (unit) => unit.completed ? 100 : (unit.progress ?? 0);
if (!units.length) {
return (
<div className="border rounded-lg bg-card overflow-hidden">
<div className="px-6 py-4 border-b flex items-center gap-2">
<Layers className="size-4 text-muted-foreground" />
<h2 className="font-semibold text-sm">{title}</h2>
<Badge variant="secondary" className="ml-auto">0</Badge>
</div>
<div className="p-4 text-center text-sm text-muted-foreground">No units available.</div>
</div>
);
}
const hasLocked = Object.values(locked).some(Boolean);
return (
<>
<div className="border rounded-lg bg-card overflow-hidden">
<div className="px-6 py-4 border-b flex items-center gap-2">
<Layers className="size-4 text-muted-foreground" />
<h2 className="font-semibold text-sm">{title}</h2>
<Badge variant="secondary" className="ml-auto">{units.length}</Badge>
</div>
{hasLocked && (
<div className="flex items-start gap-3 px-5 py-3.5 border-b bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300">
<Info className="size-4 mt-0.5 shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium leading-snug">Subscription Required</p>
<p className="text-xs mt-0.5 text-amber-700 dark:text-amber-400 leading-relaxed">
To complete this activity, subscribe to one of our available tier plans.
</p>
</div>
<Button size="sm" variant="outline" className="shrink-0 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/40" onClick={() => navigate('/subscriptions')}>
<Zap className="size-3.5" /> View Plans
</Button>
</div>
)}
<ScrollArea className="w-full bg-muted overflow-hidden">
<div className="flex gap-4 p-4">
{units.map((unit) => {
const info = details[unit.reference_id];
const courseInfo = lockedInfo[unit.reference_id];
const progress = getProgress(unit);
const isLocked = locked[unit.reference_id];
const isUnavailable = unavailable[unit.reference_id];
const isFetching = fetching[unit.reference_id];
// ── Locked card ───────────────────────────────────
// Skipped when already completed — a completion recorded
// while the unit was accessible still counts even if it
// re-locks later (reading-progress rows are never revoked
// on a tier change), so it must keep showing as Completed.
if (isLocked && !unit.completed) {
return (
<div
key={unit.id}
onClick={() => navigate('/subscriptions')}
className="bg-card rounded-2xl border border-dashed p-4 flex flex-col gap-3 hover:bg-muted/60 hover:shadow-sm transition-all cursor-pointer group w-96 shrink-0 opacity-80"
>
<div className="flex items-center gap-1.5">
<Layers className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Unit</span>
<div className="ml-auto">
<TierBadge tier={courseInfo?.subscription} />
</div>
</div>
{courseInfo?.title && (
<p className="text-xs text-muted-foreground font-medium truncate -mt-1">
from <span className="text-foreground/70">{courseInfo.title}</span>
</p>
)}
<div>
<h1 className="text-base font-semibold leading-snug line-clamp-2 text-muted-foreground">
{unit.title}
</h1>
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">
Subscribe to <span className="font-medium">{courseInfo?.title ?? 'this course'}</span> to unlock this unit.
</p>
</div>
<div className="mt-auto">
<Button size="sm" className="w-full gap-1.5" onClick={(e) => { e.stopPropagation(); navigate('/subscriptions'); }}>
<Zap className="size-3.5" /> Upgrade to unlock
</Button>
</div>
</div>
);
}
// ── Unavailable card ──────────────────────────────
if (isUnavailable) {
return (
<div
key={unit.id}
className="bg-card rounded-2xl border border-dashed p-4 flex flex-col gap-3 w-96 shrink-0 opacity-50 cursor-not-allowed"
>
<div className="flex items-center gap-1.5">
<Layers className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Unit</span>
<Badge variant="secondary" className="ml-auto gap-1 text-muted-foreground text-xs">
<Lock className="size-3" /> Unavailable
</Badge>
</div>
<h1 className="text-base font-semibold leading-snug line-clamp-2 text-muted-foreground">
{unit.title}
</h1>
<p className="text-sm text-muted-foreground">This unit is no longer available.</p>
</div>
);
}
// ── Normal card ───────────────────────────────────
return (
<div
key={unit.id}
onClick={() => !isFetching && setSelected(unit)}
className={`bg-card rounded-2xl border p-4 flex flex-col gap-3 transition-all w-96 shrink-0 ${
isFetching
? 'opacity-60 cursor-wait'
: 'hover:bg-muted/60 hover:shadow-sm cursor-pointer group'
}`}
>
{/* Card type row */}
<div className="flex items-center gap-1.5">
<Layers className="size-3.5 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground font-medium">Unit</span>
<div className="ml-auto">
{info?.course?.subscription
? <TierBadge tier={info.course.subscription} />
: isFetching && <Badge variant="secondary" className="opacity-40 text-xs">Loading…</Badge>
}
</div>
</div>
{info?.course?.title && (
<p className="text-xs text-muted-foreground truncate -mt-1">
from <span className="text-foreground/70 font-medium">{info.course.title}</span>
</p>
)}
<div>
<h1
onClick={(e) => {
if (!info) return;
e.stopPropagation();
if (info.course?.course_id) {
navigate(`/course/${info.course.course_id}/unit`, {
state: taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {},
});
return;
}
// Standalone unit (junction revamp — no parent course) —
// the course-scoped route can't resolve, fall back to
// the standalone unit reader instead.
navigate(`/units/${unit.reference_id}/read`, {
state: taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {},
});
}}
className="text-base font-semibold leading-snug line-clamp-2 transition-colors text-blue-600 dark:text-blue-400 hover:underline cursor-pointer"
>
{unit.title}
</h1>
<p className="text-sm text-muted-foreground leading-relaxed line-clamp-2 mt-1">
{info?.description ?? ''}
</p>
</div>
<div className="flex flex-col gap-2 mt-auto pt-1 border-t">
<div className="flex items-center justify-between text-sm pt-1">
{progress >= 100 ? (
<span className="flex items-center gap-1.5 text-green-600 dark:text-green-400 font-medium">
<CheckCheck className="size-4" /> Completed
</span>
) : progress > 0 ? (
<span className="flex items-center gap-1.5 text-muted-foreground font-medium">
<RefreshCw className="size-4" /> In Progress
</span>
) : (
<span className="text-muted-foreground font-medium">Not Started</span>
)}
{progress > 0 && <span className="text-xs font-semibold">{progress}%</span>}
</div>
<Progress
value={progress}
className={`h-1.5 ${progress >= 100 ? "[&>div]:bg-green-500" : ""}`}
/>
</div>
</div>
);
})}
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
<ResponsiveModal
open={!!selected}
onOpenChange={(v) => !v && setSelected(null)}
title={selected?.title}
description="Unit Info"
footer={
<>
<Button variant="outline" onClick={() => setSelected(null)}>Cancel</Button>
<Button
onClick={() => {
const info = details[selected?.reference_id];
if (!info) return;
if (info.course?.course_id) {
navigate(`/course/${info.course.course_id}/unit`, {
state: taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {},
});
return;
}
navigate(`/units/${selected.reference_id}/read`, {
state: taskId ? { taskCtx: { has_task: true, groupId, taskListId, taskId } } : {},
});
}}
disabled={
getProgress(selected ?? {}) >= 100 ||
locked[selected?.reference_id] ||
!details[selected?.reference_id]
}
>
<SendHorizonal /> Proceed
</Button>
</>
}
>
{selected && (() => {
const info = details[selected.reference_id];
const progress = getProgress(selected);
const done = progress >= 100;
return (
<div className="flex flex-col gap-4">
{done && (
<div className="flex items-center gap-2 bg-green-50 dark:bg-green-950/40 text-green-700 dark:text-green-400 text-sm font-medium rounded-lg px-4 py-3">
<CheckCheck className="size-4 shrink-0" /> Automatically Turned-in
</div>
)}
{info?.course?.title && (
<p className="text-sm">
<span className="text-muted-foreground">Course: </span>
<span className="font-medium">{info.course.title}</span>
</p>
)}
<div className="flex flex-col gap-1">
<p className="text-xs uppercase tracking-wide text-muted-foreground font-medium">About this unit</p>
<p className="text-sm leading-relaxed">{info?.description ?? '—'}</p>
</div>
</div>
);
})()}
</ResponsiveModal>
</>
);
};
export default ReadUnit;
@@ -0,0 +1,200 @@
import { ExternalLink, CheckCheck, RefreshCcw, Globe } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { useState } from "react";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { SendHorizonal } from "lucide-react";
// ── URL normalizer — ensures protocol is present so href is never treated as relative ──
const normalizeUrl = (url) => {
if (!url) return '#';
if (/^https?:\/\//i.test(url)) return url;
return `https://${url}`;
};
const getDomain = (url) => {
try { return new URL(normalizeUrl(url)).hostname.replace(/^www\./, ''); }
catch { return url; }
};
// ── Fallback banner — favicon over a gradient, no external preview fetch ──────
const LinkImageFallback = ({ domain, favicon, className = "h-40" }) => {
const [faviconFailed, setFaviconFailed] = useState(false);
return (
<div className={`w-full ${className} bg-gradient-to-br from-muted via-muted to-primary/10 flex flex-col items-center justify-center gap-2`}>
{!faviconFailed && favicon ? (
<img
src={favicon}
alt={domain}
className="w-12 h-12 rounded-xl"
onError={() => setFaviconFailed(true)}
/>
) : (
<Globe className="size-10 text-muted-foreground/50" />
)}
<span className="text-xs text-muted-foreground font-medium">{domain}</span>
</div>
);
};
// ── LinkCard ──────────────────────────────────────────────────────────────────
const LinkCard = ({ link, visited, onTurnIn, onUnvisit, submitting, unsubmitting }) => {
const [modalOpen, setModalOpen] = useState(false);
const [viewModalOpen, setViewModalOpen] = useState(false);
const domain = getDomain(link.url);
const displayFavicon = `https://www.google.com/s2/favicons?domain=${domain}&sz=128`;
const displayTitle = link.label ?? domain;
const displayDescription = link.url;
const handleTurnIn = async () => {
await onTurnIn(link.requirement_id);
setModalOpen(false);
};
const handleUnsubmit = async () => {
await onUnvisit(link.requirement_id);
setViewModalOpen(false);
};
return (
<>
<Card className="relative w-72 shrink-0 pt-0">
<LinkImageFallback domain={domain} favicon={displayFavicon} className="h-40 rounded-t-lg" />
<CardHeader>
<CardTitle className="line-clamp-1">{displayTitle}</CardTitle>
<CardDescription className="truncate text-xs">{displayDescription}</CardDescription>
</CardHeader>
<CardFooter>
{visited ? (
<Button variant="secondary" className="w-full" onClick={() => setViewModalOpen(true)}>
<CheckCheck /> Visited
</Button>
) : (
<Button className="w-full" onClick={() => setModalOpen(true)}>
Visit Link
</Button>
)}
</CardFooter>
</Card>
{/* Turn-in modal — first visit */}
<ResponsiveModal
open={modalOpen}
onOpenChange={setModalOpen}
title={`Visit Link: ${displayTitle}`}
description="By visiting a link, you are about to explore it then Turn-in after."
footer={
<>
<Button variant="outline" onClick={() => setModalOpen(false)}>Cancel</Button>
<Button onClick={handleTurnIn} disabled={submitting}>
<SendHorizonal /> {submitting ? "Submitting…" : "Turn In"}
</Button>
</>
}
>
<div className="flex flex-col gap-3 w-fit">
<Button asChild variant="link" className="text-blue-500">
<a href={normalizeUrl(link.url)} target="_blank" rel="noopener noreferrer">
<ExternalLink /> {link.url}
</a>
</Button>
</div>
</ResponsiveModal>
{/* View modal — after visited, with Resubmit */}
<ResponsiveModal
open={viewModalOpen}
onOpenChange={setViewModalOpen}
title={displayTitle}
description={displayDescription}
footer={
<>
<Button variant="outline" onClick={() => setViewModalOpen(false)}>Close</Button>
<Button onClick={handleUnsubmit} disabled={unsubmitting} variant="destructive">
<RefreshCcw className="size-4" /> {unsubmitting ? "Removing…" : "Unsubmit"}
</Button>
</>
}
>
<div className="flex flex-col gap-4">
<LinkImageFallback domain={domain} favicon={displayFavicon} className="h-40 rounded-lg" />
<div className="flex items-center gap-2 bg-green-500/10 text-green-600 dark:text-green-400 rounded-lg px-4 py-3 text-sm font-medium">
<CheckCheck className="size-4 shrink-0" /> Already submitted — you can unsubmit if needed.
</div>
<div>
<Button asChild variant="link" className="text-blue-500">
<a href={normalizeUrl(link.url)} target="_blank" rel="noopener noreferrer">
<ExternalLink /> {link.url}
</a>
</Button>
</div>
</div>
</ResponsiveModal>
</>
);
};
// ── VisitLink ─────────────────────────────────────────────────────────────────
/**
* Props:
* title {string} – section title
* links {array} – [{ requirement_id, label, url }]
* visitedMap {object} – { [requirement_id]: boolean }
* onVisit {function} – async (requirement_id) => void
* called when user confirms "Turn In"
*/
const VisitLink = ({ title = "Visit Links", links = [], visitedMap = {}, onVisit, onUnvisit }) => {
const [submittingId, setSubmittingId] = useState(null);
const [unsubmittingId, setUnsubmittingId] = useState(null);
const handleTurnIn = async (requirementId) => {
setSubmittingId(requirementId);
try { await onVisit?.(requirementId); }
finally { setSubmittingId(null); }
};
const handleUnvisit = async (requirementId) => {
setUnsubmittingId(requirementId);
try { await onUnvisit?.(requirementId); }
finally { setUnsubmittingId(null); }
};
return (
<div className="border rounded-lg bg-card overflow-hidden">
<div className="px-6 py-4 border-b flex items-center gap-2">
<ExternalLink className="size-4 text-muted-foreground" />
<h2 className="font-semibold text-md">{title}</h2>
<Badge className="ml-auto">{links.length}</Badge>
</div>
<ScrollArea className="w-full bg-muted overflow-hidden">
<div className="flex gap-4 p-4">
{links.map((link) => (
<LinkCard
key={link.requirement_id}
link={link}
visited={!!visitedMap[link.requirement_id]}
onTurnIn={handleTurnIn}
onUnvisit={handleUnvisit}
submitting={submittingId === link.requirement_id}
unsubmitting={unsubmittingId === link.requirement_id}
/>
))}
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
);
};
export default VisitLink;
@@ -0,0 +1,20 @@
// ScrollTrigger.jsx
import { useState, useEffect } from "react";
export function useScrollTrigger(elementRef) {
const [triggered, setTriggered] = useState(false);
useEffect(() => {
const handleScroll = () => {
if (!elementRef.current) return;
const { bottom } = elementRef.current.getBoundingClientRect();
setTriggered(bottom < 0);
};
window.addEventListener("scroll", handleScroll, { passive: true });
handleScroll();
return () => window.removeEventListener("scroll", handleScroll);
}, [elementRef]);
return triggered;
}
@@ -0,0 +1,466 @@
import { Outlet, useMatches, useNavigate } from "react-router-dom"
import { ThemeSwitcher } from "../components/ThemeSwitcher"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from "@/components/ui/dialog"
import {
User, Settings, LogOut, SquareArrowOutUpRight, TableOfContents,
CircleQuestionMark, Gift, Zap, Download, Copy, Check,
} from "lucide-react"
import * as LucideIcons from "lucide-react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Toaster } from "@/components/ui/sonner"
import { useAuth } from "@/contexts/AuthContext"
import api from "@/utils/api.util"
import { ClientProvider } from "@/contexts/provider/ClientProvider"
import { useProfile } from "@/contexts/ProfileProvider"
import { useClientTiers } from "@/contexts/ClientTiersProvider"
import { resolveTierBadge } from "@/utils/tierBadge.util"
import { useGroup } from "@/contexts/ClientGroupContext"
import { resolveAssetSrc } from "@/utils/media.util"
import { useEffect, useRef, useState } from "react"
import { useDateFormat } from "@/hooks/useDateFormat"
import { AVATAR_COLORS } from "@/data/profile.data"
import { Badge } from "@/components/ui/badge"
import ClientNotificationBell from "@/components/generic/ClientNotificationBell"
import StickyAnnouncementBar from "@/components/generic/StickyAnnouncementBar"
import EnvironmentBanner from "@/components/generic/EnvironmentBanner"
import { isQasEnv } from "@/utils/environment.util"
import { QRCodeCanvas } from "qrcode.react"
// ─── Refer / Invite dialog ────────────────────────────────────────────────────
function ReferDialog({ open, onOpenChange }) {
const { groups, fetchGroups, loading } = useGroup()
const [copiedLink, setCopiedLink] = useState(false)
useEffect(() => {
if (open) fetchGroups()
}, [open])
const group = groups[0] ?? null
const inviteUrl = group?.group_code
? `${window.location.origin}/signup?group_code=${group.group_code}`
: null
const handleCopyLink = async () => {
if (!inviteUrl) return
await navigator.clipboard.writeText(inviteUrl)
setCopiedLink(true)
setTimeout(() => setCopiedLink(false), 2000)
}
const handleDownload = () => {
const canvas = document.querySelector("[data-qr='refer-invite']")
if (!canvas) return
const url = canvas.toDataURL("image/png")
const link = document.createElement("a")
link.href = url
link.download = `QR_${group.group_code}.png`
link.click()
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>Invite link</DialogTitle>
</DialogHeader>
{loading ? (
<p className="py-8 text-center text-sm text-muted-foreground">Loading…</p>
) : !inviteUrl ? (
<p className="py-8 text-center text-sm text-muted-foreground">No group found.</p>
) : (
<div className="flex flex-col items-center gap-5 py-2">
{/* QR code */}
<div className="rounded-xl border bg-white p-4 shadow-sm">
<QRCodeCanvas
data-qr="refer-invite"
value={inviteUrl}
size={180}
includeMargin={false}
/>
</div>
{/* Download QR */}
<Button
variant="outline"
className="w-full gap-2"
onClick={handleDownload}
>
<Download className="size-4" />
Download QR code
</Button>
<div className="w-full flex items-center gap-2 text-xs text-muted-foreground">
<div className="flex-1 h-px bg-border" />
or share the link
<div className="flex-1 h-px bg-border" />
</div>
{/* Invite link */}
<div className="w-full flex flex-col gap-2">
<div className="flex items-center gap-2 rounded-lg border bg-muted px-3 py-2 min-w-0">
<p className="font-mono text-xs text-muted-foreground truncate w-64">
{inviteUrl}
</p>
</div>
<Button className="w-full gap-2" onClick={handleCopyLink}>
{copiedLink
? <><Check className="size-4" /> Copied!</>
: <><Copy className="size-4" /> Copy invite link</>
}
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
)
}
// ─── Extra active tiers dialog (stacked-tier "+N" badge) ──────────────────────
function ExtraTiersDialog({ open, onOpenChange, tiers, tierMap }) {
const { fmtDate } = useDateFormat()
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>Your active subscriptions</DialogTitle>
<DialogDescription>
You currently hold more than one active plan at the same time.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-2 py-2">
{tiers.map((t) => {
const badge = resolveTierBadge(t.tier, tierMap)
const TierIcon = LucideIcons[tierMap[t.tier]?.badge_icon] ?? null
return (
<div
key={t.tier_id ?? t.tier}
className="flex items-center justify-between rounded-lg border bg-muted/40 px-3 py-2.5"
>
<div className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold ${badge.cls}`}>
{TierIcon && <TierIcon className="size-3" />}
{badge.label}
</div>
<span className="text-xs text-muted-foreground">
{t.expires_at ? `Until ${fmtDate(t.expires_at)}` : "No expiry"}
</span>
</div>
)
})}
</div>
</DialogContent>
</Dialog>
)
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function getInitials(name = "") {
return name.trim().split(/\s+/).map((n) => n[0]?.toUpperCase() ?? "").slice(0, 2).join("")
}
// ─── Inner nav — uses contexts available inside ClientProvider ────────────────
function ClientNav() {
const navigate = useNavigate()
const { user, logout } = useAuth()
// Background fetches only — nav rendering never waits on these
const { achievements, getAchievements } = useProfile()
const { myTier, tierMap, tierCategories, getMyTier, getTierCategories } = useClientTiers()
const [referOpen, setReferOpen] = useState(false)
const [extraTiersOpen, setExtraTiersOpen] = useState(false)
const [badgeImgUrl, setBadgeImgUrl] = useState(null)
// Caches the resolved stream URL per asset_id — avoids re-hitting /media/token
// for the same asset on re-renders. Token TTL is 4h so safe within a session.
const badgeTokenCache = useRef({})
// Starts false on every mount (incl. full page reloads) so the tier badge
// shows a gray skeleton instead of flashing "Free" before /tiers/me resolves —
// myTier stays null for genuinely-free users too, so it can't be used as the signal.
const [tierReady, setTierReady] = useState(false)
useEffect(() => {
if (!user) return;
if (achievements.length === 0) getAchievements();
if (tierCategories.length === 0) getTierCategories();
if (!myTier) {
getMyTier().finally(() => setTierReady(true));
} else {
setTierReady(true);
}
}, [user]);
// ── Derive directly from auth user — same pattern as admin UserMenu ──────
// No extra fetch, no loading state, no flicker on reload.
const given = user?.personal_info?.name?.given_name ?? ""
const last = user?.personal_info?.name?.last_name ?? ""
const fullName = given && last ? `${given} ${last}` : (user?.email ?? "")
const avatarUrl = resolveAssetSrc(user?.personal_info?.avatar)
?? (typeof user?.personal_info?.avatar === 'string' ? user.personal_info.avatar : "")
const email = user?.email ?? ""
const avatarColor = AVATAR_COLORS[user?.acc_type] ?? 'bg-muted text-muted-foreground'
const tierSlug = myTier?.status === 'active' ? (myTier.tier ?? 'free') : 'free'
const tierBadge = resolveTierBadge(tierSlug, tierMap)
const TierIcon = LucideIcons[tierMap[tierSlug]?.badge_icon] ?? null
// A user can hold more than one active tier concurrently (e.g. premium +
// exclusive bought separately) — the pill above only ever shows the best
// one, so surface the rest as a "+N" trigger next to it.
const extraActiveTiers = (myTier?.active_tiers ?? []).filter((t) => t.tier !== tierSlug)
// Derive primitive deps — effect only fires when the actual asset changes,
// not on every tierMap/tierSlug reference churn.
const badgeAsset = tierMap[tierSlug]?.badgeAsset ?? null
const badgeAssetId = badgeAsset?.asset_id ?? null
const badgeProvider = badgeAsset?.storage_provider ?? null
const badgeFileUrl = badgeAsset?.file_url ?? null
useEffect(() => {
if (!badgeAssetId) { setBadgeImgUrl(null); return }
// Non-S3: use raw URL directly — no token needed
if (badgeProvider !== 's3') { setBadgeImgUrl(badgeFileUrl); return }
// Ref cache hit — reuse the URL without another POST
if (badgeTokenCache.current[badgeAssetId]) {
setBadgeImgUrl(badgeTokenCache.current[badgeAssetId])
return
}
let cancelled = false
const base = (import.meta.env.VITE_API_URL ?? '').replace(/\/$/, '')
api.post('/client/media/token', { asset_id: badgeAssetId })
.then(({ data }) => {
if (cancelled) return
const url = `${base}/client/media/stream/${data?.data?.token}`
badgeTokenCache.current[badgeAssetId] = url
setBadgeImgUrl(url)
})
.catch(() => { if (!cancelled) setBadgeImgUrl(null) })
return () => { cancelled = true }
}, [badgeAssetId, badgeProvider, badgeFileUrl])
const initials = given && last
? (given[0] + last[0]).toUpperCase()
: getInitials(fullName)
const handleLogout = async () => {
await logout()
navigate("/login")
}
// console.log("USER OBJECT:", JSON.stringify(user, null, 2))
return (
<>
<nav className="bg-card w-full border-b border-default">
<div className="flex flex-wrap items-center justify-between mx-auto py-3 px-6">
{/* Logo */}
<div className="flex gap-4 items-center">
<div className="w-40 cursor-pointer" onClick={() => navigate("/")}>
<img src="/philpro-white.png" alt="Philproperties" className="object-cover dark:hidden" />
<img src="/philpro-dark.png" alt="Philproperties" className="object-cover hidden dark:block" />
</div>
<div>
<svg
data-testid="geist-icon"
height="16"
width="16"
viewBox="0 0 16 16"
strokeLinejoin="round"
className="xs:hidden sm:block fill-slate-300"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4.01526 15.3939L4.3107 14.7046L10.3107 0.704556L10.6061 0.0151978L11.9849 0.606077L11.6894 1.29544L5.68942 15.2954L5.39398 15.9848L4.01526 15.3939Z"
/>
</svg>
</div>
<div id="name" className="lg:-ml-1 font-medium text-sm flex items-center gap-2">
{!tierReady ? (
<div className="xs:hidden md:inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-muted animate-pulse">
<div className="size-3 rounded-full bg-muted-foreground/30" />
<span className="text-transparent select-none">Loading</span>
</div>
) : tierBadge && (
<div className="xs:hidden md:inline-flex items-center gap-1.5">
<div className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold ${tierBadge.cls}`}>
{badgeImgUrl
? <img src={badgeImgUrl} className="size-3.5 rounded-full object-cover" />
: TierIcon && <TierIcon className="size-3" />
}
{tierBadge.label}
</div>
{extraActiveTiers.length > 0 && (
<button
type="button"
onClick={() => setExtraTiersOpen(true)}
className="inline-flex items-center justify-center px-1.5 py-0.5 rounded-full text-xs font-semibold bg-muted text-muted-foreground hover:bg-muted-foreground/20 transition-colors"
>
+{extraActiveTiers.length}
</button>
)}
</div>
)}
</div>
</div>
{/* Right — bell + user menu */}
<div className="flex items-center gap-3">
<ClientNotificationBell />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Avatar className="cursor-pointer">
<AvatarImage src={avatarUrl} />
<AvatarFallback className={`text-sm font-semibold ${avatarColor}`}>
{initials || "PH"}
</AvatarFallback>
</Avatar>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
{/* User info */}
<DropdownMenuGroup className="p-1.5">
<div className="w-full truncate text-start text-sm font-medium">
{fullName || "—"}
</div>
<div className="w-full truncate text-start text-[13px] font-medium text-muted-foreground">
{email}
</div>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem className="bg-gradient-to-r from-[#0e7490] via-[#3b82f6] to-[#4f46e5] text-white" onClick={() => navigate("/subscriptions")}>
<Zap /> Subscriptions
</DropdownMenuItem>
<DropdownMenuItem onClick={() => navigate("/profile")}>
<User /> Profile
</DropdownMenuItem>
<DropdownMenuItem onClick={() => navigate("/settings")}>
<Settings /> Account Settings
</DropdownMenuItem>
{/* <DropdownMenuItem>
<TableOfContents /> Documentation
<DropdownMenuShortcut>
<SquareArrowOutUpRight />
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem>
<CircleQuestionMark /> Feedback
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => setReferOpen(true)}>
<Gift /> Refer
</DropdownMenuItem> */}
<DropdownMenuItem onSelect={(e) => e.preventDefault()}>
Theme
<DropdownMenuShortcut>
<ThemeSwitcher />
</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem variant="destructive" onClick={handleLogout}>
<LogOut /> Log out
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</nav>
<ReferDialog open={referOpen} onOpenChange={setReferOpen} />
<ExtraTiersDialog
open={extraTiersOpen}
onOpenChange={setExtraTiersOpen}
tiers={extraActiveTiers}
tierMap={tierMap}
/>
</>
)
}
// ─── Layout ───────────────────────────────────────────────────────────────────
const ClientLayout = () => {
const matches = useMatches()
const currentHandle = matches.at(-1)?.handle ?? {}
const showFooter = currentHandle.showFooter ?? true
// Sticky announcement bar and nav stack inside one fixed header instead of
// each being independently `fixed top-0` (which made them overlap). Height
// is measured off this wrapper so --navbar-h always reflects the combined
// space, whether or not an announcement is currently showing.
const headerRef = useRef(null)
useEffect(() => {
if (!headerRef.current) return
const update = () => {
document.documentElement.style.setProperty('--navbar-h', `${headerRef.current.offsetHeight}px`)
}
update()
const ro = new ResizeObserver(update)
ro.observe(headerRef.current)
return () => ro.disconnect()
}, [])
return (
<ClientProvider>
<div className="min-h-screen flex flex-col">
<header ref={headerRef} className="fixed top-0 left-0 right-0 z-50 flex flex-col">
{isQasEnv && <EnvironmentBanner />}
<StickyAnnouncementBar />
<ClientNav />
</header>
<div className="flex-1 flex flex-col">
<Outlet />
</div>
<Toaster position="bottom-right" richColors />
{showFooter && (
<footer className="bg-muted border-t w-full py-4 px-5 text-right text-sm text-muted-foreground">
© Philproperties, 2026
</footer>
)}
</div>
</ClientProvider>
)
}
export default ClientLayout
@@ -0,0 +1,465 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { KeyRound, CreditCard, Megaphone, ChevronRight, Eye, EyeOff, ShieldAlert, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useAuth } from "@/contexts/AuthContext";
import { useProfile } from "@/contexts/ProfileProvider";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { useDateFormat } from "@/hooks/useDateFormat";
import api from "@/utils/api.util";
import { toast } from "sonner";
// ─── Section wrapper ──────────────────────────────────────────────────────────
function Section({ icon: Icon, title, description, children }) {
return (
<Card>
<CardHeader className="">
<CardTitle className="text-base font-semibold flex items-center gap-2">
<Icon className="size-4 text-muted-foreground" />
{title}
</CardTitle>
{description && <CardDescription>{description}</CardDescription>}
</CardHeader>
<Separator />
<CardContent className="space-y-4">
{children}
</CardContent>
</Card>
);
}
// ─── Security ─────────────────────────────────────────────────────────────────
function SecuritySection({ user, logout }) {
const navigate = useNavigate();
const isGoogle = user?.reg_type === "google";
const [form, setForm] = useState({ current_password: "", new_password: "", confirm: "" });
const [show, setShow] = useState({ current: false, new: false, confirm: false });
const [loading, setLoading] = useState(false);
const toggle = (field) => setShow((p) => ({ ...p, [field]: !p[field] }));
const set = (field, val) => setForm((p) => ({ ...p, [field]: val }));
const handleSubmit = async (e) => {
e.preventDefault();
if (form.new_password !== form.confirm) {
toast("New passwords do not match.");
return;
}
if (form.new_password.length < 8) {
toast("New password must be at least 8 characters.");
return;
}
setLoading(true);
try {
await api.post("/auth/change-password", {
current_password: form.current_password,
new_password: form.new_password,
});
toast("Password changed. Logging you out…");
setTimeout(async () => {
await logout();
navigate("/login");
}, 1500);
} catch (err) {
toast(err?.response?.data?.message ?? "Could not change password.");
} finally {
setLoading(false);
}
};
if (isGoogle) {
return (
<div className="flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-900/20 p-4">
<ShieldAlert className="size-4 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
<p className="text-sm text-amber-700 dark:text-amber-400">
Your account uses Google Sign-In. Password management is handled through Google.
</p>
</div>
);
}
return (
<form onSubmit={handleSubmit} className="space-y-4 max-w-sm">
{[
{ key: "current", label: "Current password", field: "current_password" },
{ key: "new", label: "New password", field: "new_password" },
{ key: "confirm", label: "Confirm new password", field: "confirm" },
].map(({ key, label, field }) => (
<div key={key} className="space-y-1.5">
<Label>{label}</Label>
<div className="relative">
<Input
type={show[key] ? "text" : "password"}
value={form[field]}
onChange={(e) => set(field, e.target.value)}
className="pr-10"
required
/>
<button
type="button"
onClick={() => toggle(key)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
>
{show[key] ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</button>
</div>
</div>
))}
<Button type="submit" disabled={loading}>
{loading ? "Saving…" : "Change password"}
</Button>
</form>
);
}
// ─── Subscription ─────────────────────────────────────────────────────────────
const TIER_COLORS = {
free: "bg-muted text-muted-foreground",
premium: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300",
exclusive: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400",
};
function SubscriptionSection() {
const navigate = useNavigate();
const { myTier, tierLoading, getMyTier, payments, paymentsLoading, getMyPayments } = useClientTiers();
const { fmtDate, fmtNumber } = useDateFormat();
useEffect(() => {
getMyTier();
getMyPayments();
}, []);
const tier = myTier?.tier ?? "free";
const expiresAt = myTier?.expires_at ? fmtDate(myTier.expires_at) : null;
return (
<div className="space-y-5">
{/* Current plan */}
<div>
<p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-2">Current plan</p>
{tierLoading ? (
<Skeleton className="h-9 w-40" />
) : (
<div className="flex items-center gap-3 flex-wrap">
<div className={`capitalize rounded-md border text-sm px-3 py-0.5 ${TIER_COLORS[tier]}`}>{tier}</div>
{expiresAt && (
<span className="text-sm text-muted-foreground">Expires {expiresAt}</span>
)}
{tier === "free" && (
<Button size="sm" variant="outline" onClick={() => navigate("/subscriptions")}>
Upgrade plan <ChevronRight className="size-3.5" />
</Button>
)}
</div>
)}
</div>
<Separator />
{/* Payment history */}
<div>
<p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-3">Payment history</p>
{paymentsLoading ? (
<div className="space-y-2">
{[...Array(3)].map((_, i) => <Skeleton key={i} className="h-10 w-full" />)}
</div>
) : payments.length === 0 ? (
<p className="text-sm text-muted-foreground">No payments yet.</p>
) : (
<div className="rounded-lg border overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-muted/50 sticky top-0 z-10">
<tr>
<th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">Date</th>
<th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">Plan</th>
<th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">Amount</th>
<th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">Status</th>
</tr>
</thead>
</table>
<ScrollArea className="h-[192px]">
<table className="w-full text-sm">
<tbody className="divide-y">
{payments.map((p) => (
<tr key={p.payment_id} className="hover:bg-muted/30 transition-colors">
<td className="px-4 py-3 text-muted-foreground">
{fmtDate(p.createdAt)}
</td>
<td className="px-4 py-3 capitalize">{p.plan?.tier ?? "—"}</td>
<td className="px-4 py-3">
{p.currency} {fmtNumber(p.amount ?? 0)}
</td>
<td className="px-4 py-3">
<Badge variant={p.status === "completed" ? "outline" : ""} className="capitalize text-xs">
{p.status}
</Badge>
</td>
</tr>
))}
</tbody>
</table>
</ScrollArea>
</div>
)}
</div>
</div>
);
}
// ─── Advertisements ───────────────────────────────────────────────────────────
const AD_OPTIONS = [
{
key: "show_popup_ads",
label: "Popup ads",
description: "Show promotional popups when you open pages like the dashboard.",
},
{
key: "show_other_ads",
label: "Other ads",
description: "Show banner, hero, and sidebar advertisements across the site.",
},
];
function AdvertisementsSection() {
const { profile, getProfile, updateProfile, profileLoading } = useProfile();
const [confirmPopupOff, setConfirmPopupOff] = useState(false);
useEffect(() => {
getProfile();
}, []);
const showPopupAds = profile?.personal_info?.show_popup_ads ?? true;
const showOtherAds = profile?.personal_info?.show_other_ads ?? true;
// No separate stored flag — "hidden" just means both underlying toggles are off,
// so it can never drift out of sync with them.
const hideAllAds = !showPopupAds && !showOtherAds;
const handleToggle = async (key, value) => {
// Turning popup ads off also turns off other ads — confirm first since
// it's a bigger change than the switch being flipped suggests.
if (key === "show_popup_ads" && value === false) {
setConfirmPopupOff(true);
return;
}
const result = await updateProfile({ [key]: value });
if (result?.success) {
toast("Preference saved.", {
description: "Reload the page for this to take effect."
});
}
};
const confirmTurnOffPopupAndOther = async () => {
setConfirmPopupOff(false);
const result = await updateProfile({ show_popup_ads: false, show_other_ads: false });
if (result?.success) {
toast("Preference saved.", {
description: "Reload the page for this to take effect."
});
}
};
const handleHideAllToggle = async (hide) => {
const result = await updateProfile({ show_popup_ads: !hide, show_other_ads: !hide });
if (result?.success) {
toast("Preference saved.", {
description: "Reload the page for this to take effect."
});
}
};
return (
<>
<div className="space-y-4">
<div>
<div className="flex items-center justify-between gap-4">
<div className="space-y-0.5">
<p className="text-sm font-medium">Hide all ads</p>
<p className="text-xs text-muted-foreground">
Turn off every advertisement across the platform, popups included.
</p>
</div>
{profileLoading ? (
<Skeleton className="h-6 w-11 rounded-full shrink-0" />
) : (
<Switch checked={hideAllAds} onCheckedChange={handleHideAllToggle} />
)}
</div>
<Separator className="mt-4" />
</div>
{AD_OPTIONS.map((opt, i) => (
<div key={opt.key}>
<div className="flex items-center justify-between gap-4">
<div className="space-y-0.5">
<p className="text-sm font-medium">{opt.label}</p>
<p className="text-xs text-muted-foreground">{opt.description}</p>
</div>
{profileLoading ? (
<Skeleton className="h-6 w-11 rounded-full shrink-0" />
) : (
<Switch
checked={profile?.personal_info?.[opt.key] ?? true}
onCheckedChange={(v) => handleToggle(opt.key, v)}
/>
)}
</div>
{i < AD_OPTIONS.length - 1 && <Separator className="mt-4" />}
</div>
))}
</div>
<AlertDialog open={confirmPopupOff} onOpenChange={setConfirmPopupOff}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Turn off popup ads?</AlertDialogTitle>
<AlertDialogDescription>
This will also turn off Other ads (banner, hero, and sidebar advertisements).
You can turn either back on here anytime.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={confirmTurnOffPopupAndOther}>
Turn off both
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
// ─── Delete Account ───────────────────────────────────────────────────────────
// Disabled while still in development — keep implemented for when we're ready
// to expose self-service account deletion.
//
// function DeleteAccountSection({ logout }) {
// const navigate = useNavigate();
// const [open, setOpen] = useState(false);
// const [loading, setLoading] = useState(false);
//
// const handleDelete = async () => {
// setLoading(true);
// try {
// await api.delete("/client/profile");
// toast("Account deleted. Goodbye!", {
// action: {
// label: "Close",
// onClick: () => {}
// }
// });
// await logout();
// navigate("/login");
// } catch (err) {
// toast(err?.response?.data?.message ?? "Could not delete account.", {
// action: {
// label: "Close",
// onClick: () => {}
// }
// });
// setLoading(false);
// }
// };
//
// return (
// <>
// <div className="flex items-start justify-between gap-4">
// <div className="space-y-1">
// <p className="text-sm font-medium text-destructive">Delete account</p>
// <p className="text-xs text-muted-foreground">
// Permanently remove your account and all associated data. This action cannot be undone.
// </p>
// </div>
// <Button
// variant="destructive"
// size="sm"
// className="shrink-0"
// onClick={() => setOpen(true)}
// >
// <Trash2 className="size-3.5 mr-1.5" />
// Delete account
// </Button>
// </div>
//
// <AlertDialog open={open} onOpenChange={setOpen}>
// <AlertDialogContent>
// <AlertDialogHeader>
// <AlertDialogTitle>Delete your account?</AlertDialogTitle>
// <AlertDialogDescription>
// This will permanently delete your account and sign you out of all sessions.
// Your data cannot be recovered after deletion.
// </AlertDialogDescription>
// </AlertDialogHeader>
// <AlertDialogFooter>
// <AlertDialogCancel disabled={loading}>Cancel</AlertDialogCancel>
// <AlertDialogAction
// onClick={handleDelete}
// disabled={loading}
// className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
// >
// {loading ? "Deleting…" : "Yes, delete my account"}
// </AlertDialogAction>
// </AlertDialogFooter>
// </AlertDialogContent>
// </AlertDialog>
// </>
// );
// }
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function AccountSettings() {
const { user, logout } = useAuth();
return (
<div className="mt-17 bg-muted min-h-screen">
<div className="p-6 lg:container lg:max-w-2xl lg:mx-auto space-y-6">
<div>
<h1 className="text-xl font-semibold tracking-tight">Account Settings</h1>
<p className="text-sm text-muted-foreground mt-0.5">Manage your security, subscription, and preferences.</p>
</div>
<Section icon={KeyRound} title="Security" description="Update your password. You'll be logged out of all sessions after changing.">
<SecuritySection user={user} logout={logout} />
</Section>
<Section icon={CreditCard} title="Subscription" description="Your current plan and billing history.">
<SubscriptionSection />
</Section>
<Section icon={Megaphone} title="Advertisements" description="Control which advertisements you see across the platform.">
<AdvertisementsSection />
</Section>
{/* <Section icon={Trash2} title="Danger Zone" description="Irreversible account actions.">
<DeleteAccountSection logout={logout} />
</Section> */}
</div>
</div>
);
}
@@ -0,0 +1,104 @@
// modules/client/pages/AdvertisementLandingPage.jsx
//
// Destination for an advertisement's own click-through when no redirect_link
// was set — the internal page authored in the "Page Builder" wizard step
// (Step 3 of Add Advertisement). Resolved by uuid via
// GET /api/client/advertisements/uuid/:uuid.
import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Megaphone, ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { PageMeta } from "@/contexts/MetadataContext";
import { resolveAssetSrc } from "@/utils/media.util";
import api from "@/utils/api.util";
export default function AdvertisementLandingPage() {
const { uuid } = useParams();
const navigate = useNavigate();
const [ad, setAd] = useState(null);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
useEffect(() => {
setLoading(true);
setNotFound(false);
api.get(`/client/advertisements/uuid/${uuid}`)
.then(({ data }) => setAd(data?.data?.data ?? null))
.catch(() => setNotFound(true))
.finally(() => setLoading(false));
}, [uuid]);
if (loading) {
return (
<div className="my-20 lg:container lg:mx-auto max-w-3xl px-4 space-y-4">
<Skeleton className="h-8 w-2/3" />
<Skeleton className="h-56 w-full rounded-lg" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-5/6" />
</div>
);
}
if (notFound || !ad) {
return (
<div className="my-20 lg:container lg:mx-auto max-w-3xl px-4 flex flex-col items-center text-center gap-3 py-16">
<Megaphone className="size-8 text-muted-foreground" />
<p className="font-medium">This advertisement is no longer available.</p>
<Button variant="outline" onClick={() => navigate("/dashboard")}>
<ArrowLeft className="size-4" /> Go back
</Button>
</div>
);
}
const page = ad.landing_page ?? {};
const imageSrc = resolveAssetSrc(ad.image) || ad.image_url || null;
const links = Array.isArray(page.links) ? page.links : [];
return (
<div className="my-20 lg:container lg:mx-auto max-w-3xl px-4 space-y-6 pb-16">
<PageMeta title={page.title ? `${page.title} - STARR` : undefined} description={page.description} />
<Button variant="ghost" size="sm" className="w-fit -ml-2" onClick={() => navigate("/dashboard")}>
<ArrowLeft className="size-4" /> Back
</Button>
{imageSrc && (
<div className="rounded-lg overflow-hidden border h-56 sm:h-72">
<img src={imageSrc} alt={page.title || ad.headline || "Advertisement"} className="w-full h-full object-cover" />
</div>
)}
<div className="space-y-2">
<h1 className="text-2xl sm:text-3xl font-bold tracking-tight">{page.title || ad.headline || "Advertisement"}</h1>
{page.description && <p className="text-muted-foreground text-lg">{page.description}</p>}
</div>
{page.body && (
<div className="prose prose-sm sm:prose max-w-none dark:prose-invert whitespace-pre-wrap">
{page.body}
</div>
)}
{links.length > 0 && (
<div className="flex flex-wrap gap-2 pt-2">
{links.map((l, i) => (
<Button
key={i}
variant={i === 0 ? "default" : "outline"}
onClick={() => {
if (!l.link) return;
if (/^https?:\/\//.test(l.link)) window.open(l.link, "_blank", "noopener,noreferrer");
else navigate(l.link);
}}
>
{l.label || l.link}
</Button>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,444 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { useAuth } from "@/contexts/AuthContext";
import { useProfile } from "@/contexts/ProfileProvider";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { PageMeta } from "@/contexts/MetadataContext";
import {
ArrowLeft, BookOpen, CalendarDays, Check,
House, Loader2, ShieldCheck, Tag, Zap, LockIcon,
} from "lucide-react";
import { useDateFormat } from "@/hooks/useDateFormat";
import api from "@/utils/api.util";
function formatDuration(days, unit) {
if (!days) return "Lifetime";
const UNIT_TO_DAYS = { minute: 1 / 1440, hour: 1 / 24, day: 1, month: 30, year: 365 };
const multiplier = UNIT_TO_DAYS[unit] ?? 1;
const value = Math.round((days / multiplier) * 1000) / 1000;
const label = unit ?? "day";
return `${value} ${label}${value !== 1 ? "s" : ""}`;
}
function formatCourseDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h && m) return `${h}h ${m}m`;
if (h) return `${h}h`;
return `${m}m`;
}
const TIER_STYLES = {
free: { badge: "bg-gradient-to-r from-lime-400 to-lime-600 text-white", icon: Tag, label: "Free" },
premium: { badge: "bg-gradient-to-r from-fuchsia-600 to-purple-600 text-white", icon: Zap, label: "Premium" },
exclusive: { badge: "bg-gradient-to-r from-rose-500 to-red-600 text-white", icon: LockIcon, label: "Exclusive" },
};
const CheckoutSkeleton = () => (
<div className="min-h-screen bg-muted pt-24">
<div className="max-w-6xl mx-auto px-6 pb-6">
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
<div className="lg:col-span-8 space-y-6">
<Skeleton className="h-5 w-48" />
<Skeleton className="h-48 w-full rounded-xl" />
<Skeleton className="h-52 w-full rounded-xl" />
</div>
<div className="lg:col-span-4">
<Skeleton className="h-80 w-full rounded-xl" />
</div>
</div>
</div>
</div>
);
const Checkout = () => {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { fmtCurrency } = useDateFormat();
const planId = searchParams.get("plan_id");
const returnToken = searchParams.get("token");
const wasCancelled = searchParams.get("cancelled") === "true";
const { user } = useAuth();
const { givenName, lastName: lastNameFromProfile, getProfile, profile } = useProfile();
const {
plans, plansLoading,
myTier, tierLoading,
checkoutLoading,
promoLoading,
getPlans, getMyTier,
validatePromo,
createOrder, captureOrder, cancelOrder,
} = useClientTiers();
const [promoCode, setPromoCode] = useState("");
const [promoResult, setPromoResult] = useState(null); // { valid, code, type, value, discount }
const [capturing, setCapturing] = useState(false);
const capturingRef = useRef(false);
useEffect(() => {
getProfile();
}, []);
useEffect(() => {
getMyTier();
if (!plans.length) getPlans();
}, [getMyTier, getPlans, plans.length]);
const plan = useMemo(
() => plans.find((p) => String(p.plan_id) === String(planId)) ?? null,
[plans, planId]
);
// Handle PayPal return after approval
useEffect(() => {
if (!returnToken || capturingRef.current) return;
capturingRef.current = true;
setCapturing(true);
captureOrder(returnToken).then((result) => {
if (result) {
navigate("/subscriptions", { replace: true });
} else {
setCapturing(false);
capturingRef.current = false;
}
});
}, [returnToken, captureOrder, navigate]);
// Handle PayPal return after cancellation
useEffect(() => {
if (!wasCancelled) return;
const orderId = searchParams.get("token");
if (orderId) cancelOrder(orderId);
toast("PayPal checkout was cancelled.");
navigate(`/subscriptions/checkout?plan_id=${planId}`, { replace: true });
}, [wasCancelled]); // eslint-disable-line react-hooks/exhaustive-deps
// const personalInfo = user?.personal_info ?? {};
const firstName = givenName || user?.personal_info?.name?.given_name || "";
const lastName = lastNameFromProfile || user?.personal_info?.name?.last_name || "";
const email = user?.email ?? "";
const isLoading = plansLoading || tierLoading;
// A user can hold more than one active tier concurrently — check membership
// in the full active set, not just the best one.
const isCurrent = !!plan && (myTier?.active_tiers ?? []).some((t) => t.tier === plan.tier);
const style = TIER_STYLES[plan?.tier] ?? TIER_STYLES.free;
const Icon = style.icon;
const effectivePrice = plan ? Number(plan.price) : 0;
const effectiveCurrency = plan?.currency ?? 'USD';
const subtotal = effectivePrice;
const discount = promoResult?.discount ?? 0;
const total = Math.max(subtotal - discount, 0);
const duration = formatDuration(plan?.duration_days, plan?.duration_unit);
const breadcrumbItems = [
{ label: "Home", icon: <House className="size-4" />, to: "/" },
{ label: "Subscriptions", to: "/subscriptions" },
{ label: "Checkout" },
];
const handleApplyPromo = async () => {
if (!plan) return;
const result = await validatePromo(plan.plan_id, promoCode.trim().toUpperCase());
if (result?.valid) {
setPromoResult(result);
toast("Promo code applied.");
} else {
toast(result?.reason ?? "Invalid promo code.");
}
};
const handleRemovePromo = () => {
setPromoResult(null);
setPromoCode("");
};
const handlePayPal = async () => {
const order = await createOrder(
plan.plan_id,
promoResult?.code ?? null,
);
if (!order) return;
const approvalUrl = order.approval_url;
if (!approvalUrl) { toast("Could not get PayPal approval URL."); return; }
window.location.href = approvalUrl;
};
if (capturing) {
return (
<div className="min-h-screen bg-muted flex items-center justify-center">
<div className="flex flex-col items-center gap-4">
<Loader2 className="size-10 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Confirming your payment…</p>
</div>
</div>
);
}
if (isLoading) return <CheckoutSkeleton />;
if (!planId || !plan) {
return (
<div className="min-h-screen bg-muted pt-24">
<div className="max-w-3xl mx-auto px-6 pb-6 space-y-4">
<AppBreadcrumb items={breadcrumbItems} />
<Card>
<CardContent className="py-10 text-center space-y-4">
<BookOpen className="size-10 mx-auto text-muted-foreground/50" />
<div>
<h1 className="text-xl font-semibold">No plan selected</h1>
<p className="text-sm text-muted-foreground mt-1">
Select a subscription plan before continuing to checkout.
</p>
</div>
<Button onClick={() => navigate("/subscriptions")}>
<ArrowLeft className="size-4" /> Back to Subscriptions
</Button>
</CardContent>
</Card>
</div>
</div>
);
}
if (!plan.is_active) {
return (
<div className="min-h-screen bg-muted pt-24">
<div className="max-w-3xl mx-auto px-6 pb-6 space-y-4">
<AppBreadcrumb items={breadcrumbItems} />
<Card>
<CardContent className="py-10 text-center space-y-4">
<LockIcon className="size-10 mx-auto text-muted-foreground/50" />
<div>
<h1 className="text-xl font-semibold">Plan Not Available</h1>
<p className="text-sm text-muted-foreground mt-1">
The <span className="font-medium text-foreground">{plan.label}</span> plan
is not available for purchase at the moment.
</p>
</div>
<Button onClick={() => navigate("/subscriptions")}>
<ArrowLeft className="size-4" /> Back to Subscriptions
</Button>
</CardContent>
</Card>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-muted pt-24">
<PageMeta title={plan ? `Checkout – ${plan.label} - STARR` : undefined} />
<div className="max-w-6xl mx-auto px-6 pb-6">
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
<div className="lg:col-span-8 space-y-6">
<AppBreadcrumb items={breadcrumbItems} />
<Card>
<CardHeader>
<CardTitle>Review Plan</CardTitle>
<CardDescription>Confirm the subscription you are about to purchase.</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<div className="flex items-start flex-col sm:flex-row gap-4">
<div className="w-full sm:w-32 h-32 bg-secondary rounded-xl flex items-center justify-center">
<Icon className="size-12 text-secondary-foreground" />
</div>
<div className="flex-1 space-y-3">
<div className="flex items-center gap-2 flex-wrap">
<Badge className={style.badge}>
<Icon className="size-3.5" /> {style.label}
</Badge>
<Badge variant="outline" className="gap-1">
<CalendarDays className="size-3.5" /> {duration}
</Badge>
</div>
<div>
<h1 className="text-2xl font-semibold">{plan.label}</h1>
<p className="text-sm text-muted-foreground mt-1">
{plan.course_count ?? plan.courses?.length ?? 0} course
{(plan.course_count ?? plan.courses?.length ?? 0) === 1 ? "" : "s"} included
</p>
</div>
<div className="flex items-center gap-3 flex-wrap">
<p className="text-2xl font-bold text-primary">
{fmtCurrency(effectivePrice, effectiveCurrency)}
</p>
</div>
</div>
</div>
<Separator />
<div className="space-y-3">
<p className="text-sm font-medium flex items-center gap-2">
<BookOpen className="size-4" /> Bundle
</p>
{plan.courses?.length > 0 ? (
<div className="space-y-3">
{plan.courses.map((course) => (
<div key={course.course_id} className="flex items-start gap-3">
<Check className="size-4 text-green-500 mt-0.5 shrink-0" />
<div className="min-w-0 flex-1">
<p className="text-sm font-medium line-clamp-1">{course.title}</p>
<div className="flex items-center gap-2 flex-wrap mt-1">
{course.level && (
<Badge variant="outline" className="h-5 text-xs capitalize">
{course.level}
</Badge>
)}
{formatCourseDuration(course.duration_seconds) && (
<span className="text-xs text-muted-foreground">
{formatCourseDuration(course.duration_seconds)}
</span>
)}
</div>
</div>
</div>
))}
</div>
) : (
<p className="text-sm text-muted-foreground">Access to free course content.</p>
)}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Billing Information</CardTitle>
<CardDescription>This uses the profile details on your account.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid lg:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="firstName">First Name</Label>
<Input id="firstName" value={firstName} disabled />
</div>
<div className="space-y-2">
<Label htmlFor="lastName">Last Name</Label>
<Input id="lastName" value={lastName} disabled />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email Address</Label>
<Input id="email" type="email" value={email} disabled />
</div>
</CardContent>
</Card>
</div>
<div className="lg:col-span-4">
<Card className="lg:sticky lg:top-24">
<CardHeader>
<CardTitle>Price Breakdown</CardTitle>
<CardDescription>Payment will be processed through PayPal.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<div className="flex justify-between gap-4">
<span className="text-muted-foreground">Plan Price</span>
<span className="font-medium">{fmtCurrency(subtotal, effectiveCurrency)}</span>
</div>
{promoResult?.valid && (
<div className="flex justify-between gap-4 text-green-600">
<span>Promo ({promoResult.code})</span>
<span>-{fmtCurrency(promoResult.discount, effectiveCurrency)}</span>
</div>
)}
</div>
<Separator />
<div className="space-y-2">
<Label htmlFor="promo">Promo Code</Label>
{promoResult?.valid ? (
<div className="flex items-center gap-2 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
<Check className="size-4 shrink-0" />
<span className="flex-1 font-medium">{promoResult.code}</span>
<button
onClick={handleRemovePromo}
className="text-green-500 hover:text-green-700 text-xs underline"
>
Remove
</button>
</div>
) : (
<div className="flex gap-2">
<Input
id="promo"
placeholder="Enter promo code"
value={promoCode}
onChange={(e) => setPromoCode(e.target.value)}
disabled={promoLoading || checkoutLoading}
onKeyDown={(e) => e.key === "Enter" && promoCode.trim() && handleApplyPromo()}
/>
<Button
variant="outline"
onClick={handleApplyPromo}
disabled={promoLoading || checkoutLoading || !promoCode.trim()}
>
{promoLoading ? <Loader2 className="size-4 animate-spin" /> : "Apply"}
</Button>
</div>
)}
</div>
<Separator />
<div className="flex justify-between items-center text-lg font-semibold">
<span>Total</span>
<span>{fmtCurrency(total, effectiveCurrency)}</span>
</div>
{isCurrent && (
<p className="text-xs text-muted-foreground rounded-md border bg-muted/50 px-3 py-2">
You already have an active {plan.tier} plan — this purchase will extend it by {duration}, instead of starting a new one.
</p>
)}
<Button
size="lg"
className="w-full"
onClick={handlePayPal}
disabled={checkoutLoading}
>
{checkoutLoading
? <Loader2 className="size-4 animate-spin" />
: <ShieldCheck className="size-4" />
}
{isCurrent
? `Extend for ${fmtCurrency(total, effectiveCurrency)} with PayPal`
: `Pay ${fmtCurrency(total, effectiveCurrency)} with PayPal`}
</Button>
<div className="text-center text-sm text-muted-foreground space-y-1">
<p className="inline-flex items-center justify-center gap-1">
<ShieldCheck className="size-4" />
Secure payment powered by PayPal
</p>
<p>Access starts after successful payment capture.</p>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</div>
);
};
export default Checkout;
@@ -0,0 +1,247 @@
import { useEffect, useRef, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import { ArrowLeft, BookOpen, CalendarDays, House, Loader2, ShieldCheck } from "lucide-react";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { useClientCourses } from "@/contexts/ClientCoursesContext";
import { useDateFormat } from "@/hooks/useDateFormat";
function formatAccess(days) {
if (!days) return "Lifetime access";
if (days % 365 === 0) return `${days / 365} year${days / 365 > 1 ? "s" : ""} access`;
if (days % 30 === 0) return `${days / 30} month${days / 30 > 1 ? "s" : ""} access`;
return `${days} day access`;
}
const PageSkeleton = () => (
<div className="min-h-screen bg-muted pt-24">
<div className="max-w-4xl mx-auto px-6 pb-6 space-y-4">
<Skeleton className="h-5 w-48" />
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
<div className="lg:col-span-8"><Skeleton className="h-64 w-full rounded-xl" /></div>
<div className="lg:col-span-4"><Skeleton className="h-48 w-full rounded-xl" /></div>
</div>
</div>
</div>
);
export default function CourseCheckout() {
const navigate = useNavigate();
const { id: courseId } = useParams();
const { fmtCurrency } = useDateFormat();
const [searchParams] = useSearchParams();
const returnToken = searchParams.get("token");
const wasCancelled = searchParams.get("cancelled") === "true";
const { course, courseLoading, getCourse, createCourseOrder, captureCourseOrder, cancelCourseOrder, purchaseLoading } = useClientCourses();
const [capturing, setCapturing] = useState(false);
const capturingRef = useRef(false);
useEffect(() => {
getCourse(courseId);
}, [courseId]);
// Handle PayPal return — capture
useEffect(() => {
// A real PayPal cancel redirect carries BOTH `cancelled=true` (our own
// cancelUrl) and `token=<order_id>` (PayPal always appends its own token
// to whatever return/cancel URL it's given) — without this guard, both
// this effect and the cancellation effect below fired on the same load,
// racing a capture call against the cancel and surfacing a confusing
// "Pending purchase not found" error toast instead of a clean
// cancellation message.
if (!returnToken || wasCancelled || capturingRef.current) return;
capturingRef.current = true;
setCapturing(true);
captureCourseOrder(returnToken).then((result) => {
if (result) {
navigate(`/course/${courseId}`, { replace: true });
} else {
setCapturing(false);
capturingRef.current = false;
}
});
}, [returnToken]); // eslint-disable-line react-hooks/exhaustive-deps
// Handle PayPal cancellation
useEffect(() => {
if (!wasCancelled) return;
const orderId = searchParams.get("token");
if (orderId) cancelCourseOrder(orderId);
// Deferred to a new macrotask: this page renders as an <Outlet /> child,
// which sits before <Toaster /> in ClientLayout's JSX — so a toast fired
// synchronously in this mount-time effect races the Toaster's own mount
// effect (which subscribes to sonner's store) and is silently dropped,
// since sonner only notifies subscribers already listening at publish
// time (no replay for late subscribers). setTimeout(0) pushes the call
// past the current effect-flush, after Toaster has subscribed.
setTimeout(() => toast("Payment was cancelled."), 0);
navigate(`/course/${courseId}/checkout`, { replace: true });
}, [wasCancelled]); // eslint-disable-line react-hooks/exhaustive-deps
const handlePayPal = async () => {
if (!course?.product?.id) return;
const order = await createCourseOrder(course.product.id);
if (!order) return;
if (!order.approval_url) { toast("Could not get PayPal approval URL."); return; }
window.location.href = order.approval_url;
};
if (capturing) {
return (
<div className="min-h-screen bg-muted flex items-center justify-center">
<div className="flex flex-col items-center gap-4">
<Loader2 className="size-10 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Confirming your payment…</p>
</div>
</div>
);
}
if (courseLoading) return <PageSkeleton />;
const product = course?.product ?? null;
if (!product) {
return (
<div className="min-h-screen bg-muted pt-24">
<div className="max-w-3xl mx-auto px-6 pb-6 space-y-4">
<Card>
<CardContent className="py-10 text-center space-y-4">
<BookOpen className="size-10 mx-auto text-muted-foreground/50" />
<div>
<h1 className="text-xl font-semibold">Not available for purchase</h1>
<p className="text-sm text-muted-foreground mt-1">
This course doesn't have an individual purchase option.
</p>
</div>
<Button onClick={() => navigate(`/course/${courseId}`)}>
<ArrowLeft className="size-4" /> Go Back
</Button>
</CardContent>
</Card>
</div>
</div>
);
}
const breadcrumbItems = [
{ label: "Home", icon: <House className="size-4" />, to: "/dashboard" },
{ label: "Courses", to: "/course" },
{ label: course?.title ?? "Course", to: `/course/${courseId}` },
{ label: "Checkout" },
];
return (
<div className="min-h-screen bg-muted pt-24">
<div className="max-w-5xl mx-auto px-6 pb-10">
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* ── Left ── */}
<div className="lg:col-span-8 space-y-6">
<AppBreadcrumb items={breadcrumbItems} />
<Card>
<CardHeader>
<CardTitle>Course Details</CardTitle>
<CardDescription>Review what you're about to purchase.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-start gap-4">
<div className="w-16 h-16 rounded-lg bg-secondary flex items-center justify-center shrink-0">
<BookOpen className="size-8 text-secondary-foreground" />
</div>
<div className="flex-1 min-w-0 space-y-1">
<h2 className="text-lg font-semibold leading-snug">{course?.title}</h2>
{course?.level && (
<Badge variant="outline" className="capitalize">{course.level}</Badge>
)}
{course?.description && (
<p className="text-sm text-muted-foreground line-clamp-2">{course.description}</p>
)}
</div>
</div>
<Separator />
<div className="space-y-2 text-sm">
<div className="flex items-center gap-2 text-muted-foreground">
<CalendarDays className="size-4 shrink-0" />
<span>{formatAccess(product.access_days)}</span>
</div>
</div>
</CardContent>
</Card>
</div>
{/* ── Right / Summary ── */}
<div className="lg:col-span-4">
<Card className="lg:sticky lg:top-24">
<CardHeader>
<CardTitle>Price Summary</CardTitle>
<CardDescription>Payment processed through PayPal.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex justify-between items-center">
<span className="text-muted-foreground">Course Price</span>
<span className="font-medium">{fmtCurrency(product.price, product.currency)}</span>
</div>
<Separator />
<div className="flex justify-between items-center text-lg font-semibold">
<span>Total</span>
<span>{fmtCurrency(product.price, product.currency)}</span>
</div>
{course?.has_purchased ? (
<Button size="lg" className="w-full" variant="outline" disabled>
Already Purchased
</Button>
) : course?.purchase_eligible === false ? (
<div className="space-y-2">
<Button size="lg" className="w-full" variant="outline" disabled>
Not Yet Available
</Button>
<p className="text-xs text-muted-foreground text-center">
Complete your plan's starter content to unlock this purchase.
</p>
</div>
) : (
<Button
size="lg"
className="w-full"
onClick={handlePayPal}
disabled={purchaseLoading}
>
{purchaseLoading
? <Loader2 className="size-4 animate-spin" />
: <ShieldCheck className="size-4" />
}
Pay {fmtCurrency(product.price, product.currency)} with PayPal
</Button>
)}
<div className="text-center text-xs text-muted-foreground space-y-1">
<p className="inline-flex items-center justify-center gap-1">
<ShieldCheck className="size-3.5" />
Secure payment powered by PayPal
</p>
<p>Access starts after successful payment capture.</p>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,911 @@
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { useDateFormat } from "@/hooks/useDateFormat";
import { useParams, useNavigate } from "react-router-dom";
import api from "@/utils/api.util";
import {
House, Timer, Layers, GitBranch, Medal, CircleStar, LockIcon,
SendHorizonal, CheckCheck, CheckCircle2, Clock, FileQuestion, ClipboardList,
Hourglass, Check, Megaphone
} from "lucide-react";
import { cn } from "@/lib/utils";
import CourseBadge from "@/modules/admin/components/courses/CourseBadge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Progress } from "@/components/ui/progress";
import { motion, AnimatePresence } from "framer-motion";
import { useRef, useEffect, useState } from "react";
import { useScrollTrigger } from "../hooks/ScrollTrigger";
import {
Accordion, AccordionContent, AccordionItem, AccordionTrigger,
} from "@/components/ui/accordion";
import {
Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription,
} from "@/components/ui/dialog";
import { useClientCourses } from "@/contexts/ClientCoursesContext";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { useCourseReadingProgress } from "@/contexts/ClientCourseReadingProgressContext";
import { PageMeta } from "@/contexts/MetadataContext";
import { resolveTierBadge } from "@/utils/tierBadge.util";
import { getTierColor } from "@/utils/tierColors";
import { useClientAdvertisements } from "@/contexts/ClientAdvertisementContext";
import { Banner, BannerSkeleton } from "@/components/generic/Blocks/Client/Advertisements/Banner";
import { Tags } from "lucide-react";
import CourseUpsellModal from "../components/CourseUpsellModal";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function formatDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) return `${h}hr ${m}min`;
return `${m}min`;
}
// ─── Spine / card helpers ──────────────────────────────────────────────────────
const useVisibleNodes = (refs, count) => {
const [visible, setVisible] = useState(new Set());
useEffect(() => {
setVisible(new Set());
const observers = [];
const id = setTimeout(() => {
refs.current.forEach((el, i) => {
if (!el) return;
const obs = new IntersectionObserver(
([entry]) => {
setVisible((prev) => {
const next = new Set(prev);
if (entry.isIntersecting) next.add(i);
return next;
});
},
{ threshold: 0.2 }
);
obs.observe(el);
observers.push(obs);
});
}, 50);
return () => { clearTimeout(id); observers.forEach((o) => o.disconnect()); };
}, [count]);
return visible;
};
// ─── Unit Accordion Block ─────────────────────────────────────────────────────
const UnitAccordionBlock = ({ unit, unitIndex, i, cardRefs, courseId, onToggle, isCompleted, locked, onLockedClick }) => {
const navigate = useNavigate();
const quiz = unit.quiz ?? null;
return (
<motion.div
ref={(el) => (cardRefs.current[i] = el)}
className="group rounded-xl border bg-card hover:bg-blue-400/10 hover:shadow-md hover:border-blue-400 transition-all"
initial={{ opacity: 0, y: 14 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.35, delay: i * 0.05, ease: "easeOut" }}
>
<Accordion
type="single"
collapsible
defaultValue={`unit-${unit.unit_id}`}
onValueChange={() => setTimeout(onToggle, 250)}
>
<AccordionItem value={`unit-${unit.unit_id}`} className="border-none">
<AccordionTrigger className="px-4 py-4 hover:no-underline">
<div className="flex flex-col items-start gap-3 w-full">
<div className="flex items-center justify-between w-full">
<span className="text-sm font-semibold uppercase tracking-widest text-muted-foreground">
Unit {unitIndex + 1}
</span>
</div>
<h1 className="text-2xl font-bold text-card-foreground group-hover:text-blue-600 dark:group-hover:text-blue-400">
{unit.title}
</h1>
<div className="[&_svg]:size-4 text-md text-muted-foreground flex items-center gap-4">
{unit.lessons?.length > 0 && (
<div className="flex items-center gap-1.5">
<Layers /> {unit.lessons.length} {unit.lessons.length === 1 ? "Lesson" : "Lessons"}
</div>
)}
{unit.duration_seconds > 0 && (
<div className="flex items-center gap-1.5">
<Timer /> {formatDuration(unit.duration_seconds)}
</div>
)}
{quiz && (
<div className="flex items-center gap-1.5">
<FileQuestion /> Quiz
</div>
)}
</div>
</div>
</AccordionTrigger>
<AccordionContent className="px-1.5 h-full">
<div className="flex flex-col gap-1 pt-0">
{(unit.lessons ?? []).map((lesson) => (
<div
key={lesson.lesson_id}
className="flex items-center justify-between py-2 px-3 rounded-lg hover:bg-slate-200 dark:hover:bg-blue-500 transition-colors cursor-pointer"
onClick={() => locked
? onLockedClick?.()
: navigate(`/course/${courseId}/unit`, { state: { lessonId: lesson.lesson_id, unitId: unit.unit_id } })}
>
<div className="flex items-center gap-3 select-none min-w-0">
{isCompleted(lesson.uuid)
? <CheckCircle2 className="size-4 text-emerald-500 shrink-0" />
: <div className="w-4 h-4 rounded-full border border-muted-foreground/40 flex items-center justify-center flex-shrink-0" />
}
<span className="text-md text-card-foreground truncate">{lesson.title}</span>
</div>
{lesson.duration_seconds > 0 && (
<span className="text-sm shrink-0 ml-2">{formatDuration(lesson.duration_seconds)}</span>
)}
</div>
))}
{/* Quiz row — shown after lessons if unit has a quiz */}
{quiz && (
<div
className="flex items-center justify-between py-2 px-3 mt-1 rounded-lg border border-dashed border-blue-300 dark:border-blue-700 bg-blue-50/60 dark:bg-blue-950/30 hover:bg-blue-100 dark:hover:bg-blue-900/40 transition-colors cursor-pointer"
onClick={() => locked
? onLockedClick?.()
: navigate(`/course/${courseId}/unit`, { state: { quizUnitId: unit.unit_id } })}
>
<div className="flex items-center gap-3 select-none min-w-0">
{quiz.has_passed
? <CheckCircle2 className="size-4 text-emerald-500 shrink-0" />
: <FileQuestion className="size-4 text-blue-500 shrink-0" />
}
<span className="text-sm font-medium text-blue-700 dark:text-blue-300 truncate">{quiz.title}</span>
</div>
<Badge className={cn(
"shrink-0 ml-2 text-[10px]",
quiz.has_passed
? "bg-green-100 text-green-700 border border-green-400 dark:bg-green-900/40 dark:text-green-400 dark:border-green-700"
: "bg-blue-100 text-blue-700 border border-blue-300 dark:bg-blue-900/40 dark:text-blue-400 dark:border-blue-700"
)}>
{quiz.has_passed ? "Passed" : "Quiz"}
</Badge>
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</motion.div>
);
};
// ─── Assessment Card ──────────────────────────────────────────────────────────
const AssessmentCard = ({ assessment, courseId, delay, nodeRef }) => {
const navigate = useNavigate();
const passed = assessment.has_passed;
return (
<motion.div
ref={nodeRef}
className="w-full rounded-2xl border bg-card p-5 flex flex-col gap-3 shadow-sm"
initial={{ opacity: 0, y: 14 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.35, delay, ease: "easeOut" }}
>
<div className="flex items-center w-full justify-between">
<div className="flex items-center gap-2.5">
<div className="h-9 w-9 rounded-lg bg-violet-100 dark:bg-violet-900/40 flex items-center justify-center shrink-0">
<ClipboardList className="h-4.5 w-4.5 text-violet-600 dark:text-violet-400" />
</div>
<div className="min-w-0">
<p className="text-[10px] uppercase tracking-widest text-muted-foreground font-semibold">Final Assessment</p>
<p className="text-sm font-semibold leading-tight truncate">{assessment.title}</p>
</div>
</div>
{(() => {
const count = assessment.max_questions ?? assessment.question_count;
if (!count) return null;
return (
<div className="text-sm text-muted-foreground shrink-0">
{count} {count === 1 ? "question" : "questions"}
</div>
);
})()}
</div>
<div className="flex items-center justify-between">
{passed ? (
<Badge className="bg-green-100 text-green-700 border border-green-400 dark:bg-green-900/40 dark:text-green-400 dark:border-green-700 gap-1">
<CheckCircle2 className="size-3" /> Passed
</Badge>
) : (
<Badge className="bg-muted text-muted-foreground border gap-1">
<Clock className="size-3" /> Not yet passed
</Badge>
)}
<Button
type="button"
size="sm"
variant={passed ? "outline" : "default"}
className="h-7 text-xs"
onClick={() => navigate(`/course/${courseId}/unit`, { state: { seekAssessment: true } })}
>
{passed ? "Review" : "Take Assessment"}
</Button>
</div>
</motion.div>
);
};
// ─── Certificate Card ─────────────────────────────────────────────────────────
const CertCard = ({ courseTitle, courseLevel, badgeColor, badgeImageUrl, pendingCert, certificate, delay, nodeRef }) => {
const { fmtDate } = useDateFormat();
const isIssued = !!certificate;
const isPending = !isIssued && !!pendingCert;
let issuedLabel = "Upon completion";
if (isIssued) issuedLabel = fmtDate(certificate.issued_at);
if (isPending) issuedLabel = fmtDate(pendingCert.issue_at);
return (
<Dialog>
<motion.div
ref={nodeRef}
className="w-full max-w-[320px] rounded-2xl border bg-card p-6 flex flex-col items-center gap-4 shadow-sm"
initial={{ opacity: 0, y: 14 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.35, delay, ease: "easeOut" }}
>
<CourseBadge
title={courseTitle}
level={courseLevel}
color={badgeColor ?? "purple"}
imageUrl={badgeImageUrl}
/>
<div className="w-full flex items-end justify-between">
<div>
<p className="text-[10px] uppercase tracking-widest text-muted-foreground font-semibold">
{isIssued ? "Issued" : "Available"}
</p>
<p className="text-sm text-foreground mt-0.5">{issuedLabel}</p>
</div>
{isIssued ? (
<DialogTrigger asChild>
<Badge className="bg-green-100 text-green-700 border border-green-400 dark:bg-green-900/40 dark:text-green-400 dark:border-green-700 gap-1 cursor-pointer">
<CheckCircle2 className="size-3" /> Issued
</Badge>
</DialogTrigger>
) : isPending ? (
<DialogTrigger asChild>
<Badge className="bg-amber-100 text-amber-700 border border-amber-400 dark:bg-amber-900/40 dark:text-amber-400 dark:border-amber-700 gap-1 cursor-pointer">
<Clock className="size-3" /> Pending
</Badge>
</DialogTrigger>
) : (
<DialogTrigger asChild>
<Badge className="bg-muted text-muted-foreground border gap-1 cursor-pointer">
<Clock className="size-3" /> Not yet earned
</Badge>
</DialogTrigger>
)}
</div>
</motion.div>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{isIssued
? <CheckCircle2 className="size-4 text-green-500" />
: <Clock className="size-4 text-muted-foreground" />}
{isIssued ? "Certificate Issued" : isPending ? "Certificate Pending" : "Certificate"}
</DialogTitle>
<DialogDescription asChild>
<div className="space-y-3 pt-1 text-sm text-muted-foreground">
{isIssued ? (
<>
<p>
Your certificate for this course was officially issued on{" "}
<span className="font-medium text-foreground">{fmtDate(certificate.issued_at)}</span>.
</p>
<div className="rounded-lg border bg-muted px-4 py-3">
<p className="text-sm font-semibold text-foreground">{courseTitle}</p>
</div>
<p>
You can view and download it from your <span className="font-medium text-foreground">Certificates</span> page.
</p>
</>
) : isPending ? (
<>
<p>
You passed the course assessment on{" "}
<span className="font-medium text-foreground">{fmtDate(pendingCert.passed_at)}</span>.
Your certificate is being processed and will be officially issued on:
</p>
<div className="rounded-lg border bg-muted px-4 py-3 text-center">
<p className="text-base font-semibold text-foreground">{fmtDate(pendingCert.issue_at)}</p>
</div>
<p>
Once issued, it will appear in your <span className="font-medium text-foreground">Certificates</span> page.
</p>
</>
) : (
<>
<p>
Complete all lessons and pass the course assessment to earn your certificate for:
</p>
<div className="rounded-lg border bg-muted px-4 py-3">
<p className="text-sm font-semibold text-foreground">{courseTitle}</p>
</div>
<p>
Your certificate will be issued within <span className="font-medium text-foreground">the hour</span> after passing and will appear in your <span className="font-medium text-foreground">Certificates</span> page.
</p>
</>
)}
</div>
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
);
};
// ─── Course Units (spine + cards) ─────────────────────────────────────────────
const CourseUnits = ({ units = [], courseId, courseTitle, courseLevel, badgeColor, badgeImageUrl, onToggle, isCompleted, pendingCert, certificate, assessment, contentNotReady, locked, onLockedClick }) => {
const wrapRef = useRef(null);
const cardRefs = useRef([]);
// Build a flat ordered list of nodes: [unit, unit, ..., assessment?, cert]
// Quiz is rendered inside each unit accordion, not as a separate spine node.
// While content isn't ready yet, no unit/lesson/assessment titles are shown —
// only the Rewards (cert) card, as a preview of what's to come.
const nodes = contentNotReady
? [{ type: "cert" }]
: [
...units.map((unit) => ({ type: "unit", unit })),
...(assessment ? [{ type: "assessment", assessment }] : []),
{ type: "cert" },
];
const totalNodes = nodes.length;
const visibleNodes = useVisibleNodes(cardRefs, totalNodes);
const [mids, setMids] = useState([]);
const maxVisible = visibleNodes.size ? Math.max(...visibleNodes) : -1;
const measure = () => {
if (!wrapRef.current) return;
const base = wrapRef.current.getBoundingClientRect().top;
setMids(
cardRefs.current.map((el) => {
const r = el?.getBoundingClientRect();
return r ? Math.round((r.top + r.bottom) / 2 - base) : 0;
})
);
};
useEffect(() => {
const id = setTimeout(measure, 60);
window.addEventListener("resize", measure);
return () => { clearTimeout(id); window.removeEventListener("resize", measure); };
}, [totalNodes]);
const lastMid = mids.length ? mids[mids.length - 1] : 0;
const svgH = lastMid + 40;
const drawnTo = maxVisible >= 0 && mids[maxVisible] ? mids[maxVisible] : 0;
const isIssued = !!certificate;
return (
<div ref={wrapRef} className="flex gap-0 lg:gap-5 lg:px-4">
{/* Spine */}
<div className="relative flex-shrink-0 w-0 lg:w-7" style={{ height: svgH }}>
{mids.length > 0 && (
<>
<svg
className="absolute top-0 left-1/2 -translate-x-1/2 overflow-visible text-border xs:hidden lg:block"
width={2}
height={svgH}
xmlns="http://www.w3.org/2000/svg"
>
<line x1={1} y1={0} x2={1} y2={svgH} stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
{Array.from({ length: 10 }).map((_, i) => {
const y1 = (mids[0] / 10) * i;
const y2 = (mids[0] / 10) * (i + 1);
const revealed = drawnTo >= y2;
return (
<motion.line
key={`intro-${i}`}
x1={1} y1={y1} x2={1} y2={y2}
stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"
animate={{ opacity: revealed ? 1 : 0.3 }}
transition={{ duration: 0.4, ease: "easeOut" }}
/>
);
})}
{mids[0] != null && drawnTo > mids[0] && (
<motion.line
x1={1} y1={mids[0]} x2={1} y2={drawnTo}
stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"
initial={{ opacity: 0.3 }} animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
/>
)}
</svg>
{mids.map((mid, i) => {
const visible = visibleNodes.has(i);
const isCert = i === totalNodes - 1;
return (
<motion.div
key={`node-${i}`}
className={cn(
"absolute left-1/2 top-0 -translate-x-1/2 -translate-y-1/2 w-7 h-7 rounded-full border bg-background flex items-center justify-center text-xs font-medium xs:hidden lg:flex",
isCert && isIssued ? "border-emerald-500 text-emerald-500" : "border-border text-muted-foreground"
)}
style={{ top: mid }}
initial={{ opacity: 0, scale: 0 }}
animate={{ opacity: visible ? 1 : 0, scale: visible ? 1 : 0 }}
transition={{ type: "spring", stiffness: 400, damping: 18, delay: 0.05 }}
>
{isCert ? <Check className="size-3.5" /> : i + 1}
</motion.div>
);
})}
</>
)}
</div>
{/* Cards */}
<div className="flex flex-col gap-6 flex-1 max-w-3xl min-w-0 xs:pt-0 lg:pt-[50px]">
{nodes.map((node, ni) => {
const delay = ni * 0.05;
const nodeRef = (el) => (cardRefs.current[ni] = el);
if (node.type === "unit") {
const unitIndex = units.indexOf(node.unit);
return (
<UnitAccordionBlock
key={node.unit.unit_id}
unit={node.unit}
unitIndex={unitIndex}
i={ni}
cardRefs={cardRefs}
courseId={courseId}
onToggle={measure}
isCompleted={isCompleted}
locked={locked}
onLockedClick={onLockedClick}
/>
);
}
if (node.type === "assessment") {
return (
<AssessmentCard
key="assessment"
assessment={node.assessment}
courseId={courseId}
delay={delay}
nodeRef={nodeRef}
/>
);
}
// cert
return (
<CertCard
key="cert"
nodeRef={nodeRef}
delay={delay}
courseTitle={courseTitle}
courseLevel={courseLevel}
badgeColor={badgeColor}
badgeImageUrl={badgeImageUrl}
pendingCert={pendingCert}
certificate={certificate}
/>
);
})}
</div>
</div>
);
};
// ─── Course Details ───────────────────────────────────────────────────────────
const CourseDetails = () => {
const CourseBreadcrumb = useRef(null);
const triggered = useScrollTrigger(CourseBreadcrumb);
const { id: courseId } = useParams();
const navigate = useNavigate();
const { getCourse, course, courseBlocked, courseLoading, resetCourse } = useClientCourses();
const { myTier, getMyTier } = useClientTiers();
const { fetchCourseProgress, fetchCourseProgressSummary, summary: progressSummary, isCompleted, resetProgress } = useCourseReadingProgress();
const { adLists, listLoading: adLoading, getActiveAdvertisementList, handleAdCtaClick } = useClientAdvertisements();
const [tierMap, setTierMap] = useState({});
const [badgeImageUrl, setBadgeImageUrl] = useState(null);
const [upsellOpen, setUpsellOpen] = useState(false);
useEffect(() => {
api.get("/client/tiers/categories")
.then(({ data }) => {
const m = {};
(data.data ?? []).forEach((c) => { m[c.slug] = c; });
setTierMap(m);
})
.catch(() => { });
}, []);
const hasCompleted = !!course?.is_completed;
// duration_seconds is derived from authored lesson content (see duration.util.js) —
// zero means no lesson content has been built yet, so the course isn't ready to take.
const contentNotReady = !course?.duration_seconds;
useEffect(() => {
if (!myTier) getMyTier();
}, []);
useEffect(() => {
getMyTier();
getCourse(courseId);
getActiveAdvertisementList("course_details.banner");
return () => { resetCourse(); resetProgress(); setBadgeImageUrl(null); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [courseId]);
// Progress is meaningless (and 403s) on a course the user can't access —
// only fetch it once getCourse has resolved to a real, unlocked course.
useEffect(() => {
if (!course || courseBlocked) return;
fetchCourseProgress(courseId);
fetchCourseProgressSummary(courseId);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [course, courseBlocked, courseId]);
const bannerAds = adLists["course_details.banner"] ?? [];
// Resolve badge image once course loads — issue a client stream token for
// private S3 assets so the badge preview works on this page.
useEffect(() => {
if (!course?.badge_asset_id) {
setBadgeImageUrl(course?.badge_image_url ?? null);
return;
}
const STREAM_BASE = `${import.meta.env.VITE_API_URL}/client/media/stream`;
api.post("/client/media/token", { asset_id: course.badge_asset_id })
.then(({ data }) => {
const token = data.data?.token;
setBadgeImageUrl(token ? `${STREAM_BASE}/${token}` : null);
})
.catch(() => setBadgeImageUrl(course.badge_image_url ?? null));
}, [course?.badge_asset_id, course?.badge_image_url]);
const items = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: "Courses", to: `/course` },
{ label: course?.title ?? "Course" },
];
if (courseLoading) {
return (
<div className="my-17 p-8 lg:container lg:mx-auto space-y-4">
<Skeleton className="h-4 w-48" />
<Skeleton className="h-10 w-2/3" />
<Skeleton className="h-5 w-full max-w-2xl" />
<Skeleton className="h-5 w-full max-w-xl" />
</div>
);
}
return (
<div>
<PageMeta title={course ? `${course.title} - STARR` : undefined} description={course?.description} />
<div className="my-17">
<AnimatePresence>
{triggered && (
<motion.div
key="sticky-bar"
initial={{ y: -20, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={{ y: -20, opacity: 0 }}
transition={{ duration: 0.2, ease: "easeOut" }}
className="fixed top-[67px] left-0 right-0 z-10 bg-card border-b py-3 xs:px-4 md:px-6"
>
<div className="w-full flex items-center justify-between">
<AppBreadcrumb items={items} />
<div id="call-to-action">
{contentNotReady ? (
<Badge variant="secondary" className="gap-1.5 text-xs">
<Hourglass className="size-3" /> Coming Soon
</Badge>
) : (
<div className="flex gap-2 items-center">
<Dialog>
<DialogTrigger asChild>
<Button variant="outline">
<Megaphone /> View Ads
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-5xl">
<DialogHeader>
<DialogTitle>Advertisements</DialogTitle>
</DialogHeader>
{adLoading["course_details.banner"] ? (
<BannerSkeleton />
) : (
<Banner ads={bannerAds} onCtaClick={handleAdCtaClick} />
)}
</DialogContent>
</Dialog>
<Button size="sm" className="lg:hidden" onClick={() => courseBlocked ? setUpsellOpen(true) : navigate(`/course/${courseId}/unit`)}>
{hasCompleted
? <><CheckCheck /> Start Again</>
: <><SendHorizonal /> Start Learning</>
}
</Button>
<Button size="default" className="hidden lg:inline-flex" onClick={() => courseBlocked ? setUpsellOpen(true) : navigate(`/course/${courseId}/unit`)}>
{hasCompleted
? <><CheckCheck /> Start Again</>
: <><SendHorizonal /> Start Learning</>
}
</Button>
</div>
)}
</div>
</div>
</motion.div>
)}
</AnimatePresence>
<div className="flex flex-col gap-8">
<div className="flex flex-col gap-6">
{/* Hero */}
<div className="bg-primary dark:bg-accent/50">
<div className="lg:container lg:mx-auto flex flex-col gap-6 xs:px-6 xs:py-6 lg:px-4 lg:py-16">
<div>
<AppBreadcrumb
color={
{
link: { color: "text-white" },
page: { color: "text-white" }
}
}
items={items}
/>
</div>
<div className="flex lg:flex-row items-start justify-between w-full text-white">
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2 flex-wrap">
{(() => {
const slug = course?.plan_tier ?? course?.subscription ?? "free";
const { label, cls } = resolveTierBadge(slug, tierMap);
return <Badge className={cls}>{label}</Badge>;
})()}
{(course?.categories ?? []).map((cat) => (
<Badge key={cat.id} className="bg-white/15 text-white border-white/30">
<Tags /> {cat.name}
</Badge>
))}
</div>
<h1 className="font-bold xs:text-2xl lg:text-4xl">{course?.title ?? "Course Title"}</h1>
<p className="max-w-2xl xs:text-sm lg:text-lg">{course?.description ?? ""}</p>
<div className="flex items-center gap-4 text-sm lg:text-base">
{course?.duration_seconds > 0 && (
<div className="[&_svg]:size-4 flex gap-1.5 items-center">
<Timer />
{formatDuration(course.duration_seconds)}
</div>
)}
{course?.level && (
<div className="[&_svg]:size-4 flex gap-1.5 items-center">
<GitBranch />
{course.level.charAt(0).toUpperCase() + course.level.slice(1)}
</div>
)}
</div>
{progressSummary && progressSummary.lessons_total > 0 && (
<div className="flex flex-col gap-1.5 max-w-xl">
<div className="flex items-center justify-between text-sm text-white mb-1">
<span>{progressSummary.lessons_completed} of {progressSummary.lessons_total} lessons complete</span>
<span>{progressSummary.percent}%</span>
</div>
<Progress value={progressSummary.percent} className="[&>div]:bg-blue-500" />
</div>
)}
<div ref={CourseBreadcrumb} className="w-fit">
{contentNotReady ? (
<div className="flex items-center gap-2 rounded-lg border bg-muted px-4 py-2.5 text-sm text-muted-foreground">
<Hourglass className="size-4 shrink-0" />
This course is currently being prepared. Please check back later.
</div>
) : (
<Button
className="w-fit bg-blue-500"
onClick={() => courseBlocked ? setUpsellOpen(true) : navigate(`/course/${courseId}/unit`)}
>
{hasCompleted
? <><CheckCheck /> Start Again</>
: <><SendHorizonal /> Proceed</>
}
</Button>
)}
</div>
</div>
</div>
</div>
</div>
{/* Body */}
<div className="lg:container lg:mx-auto flex flex-col gap-6 xs:p-6 xs:-mt-5 lg:-mt-0">
<div className="flex flex-col xs:gap-12 lg:gap-12 flex-1 min-w-0">
<div className="space-y-4">
<div className="font-bold text-2xl">About</div>
<div className="max-w-3xl space-y-4">
<p>{course?.description ?? ""}</p>
</div>
</div>
{/* Objectives — no wrapper rendered at all when empty, otherwise an
empty div still eats a gap-12 slot in the flex column below */}
{course?.objectives?.length > 0 && (
<div className="space-y-4">
<div className="font-bold text-2xl">Learning Outcomes</div>
<ul className="max-w-3xl list-disc list-inside space-y-1">
{course.objectives.map((obj) => (
<li key={obj.objective_id}>{obj.text}</li>
))}
</ul>
</div>
)}
{/* Roles + Prerequisites */}
<div className="max-w-3xl space-y-6">
{/* Roles */}
<div className=" space-y-4">
<div className="space-y-2">
<div className="font-bold text-xl">Roles</div>
<p className="text-sm text-muted-foreground">Job roles this course qualifies you for</p>
</div>
{course?.roles?.length > 0 ? (
<div className="flex flex-wrap gap-2">
{course.roles.map((r) => (
<Badge key={r.role_id} variant="secondary" className="text-sm">
{r.text}
</Badge>
))}
</div>
) : (
<div className="rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground">
No specific roles are required for this course.
</div>
)}
</div>
{/* Prerequisites */}
<div className="rounded-xl border bg-card p-6 space-y-4">
<div>
<div className="font-bold text-xl">Prerequisites</div>
<p className="text-sm text-muted-foreground">Complete these courses first</p>
</div>
{course?.prerequisites?.length > 0 ? (
<div className="space-y-2">
{course.prerequisites.map((p) => {
// Guarded = the prerequisite itself sits behind a paid tier —
// paint the whole row with that tier's actual admin-configured
// color (Tier Categories → Color). Reuses the exact same
// gradient classes the tier Badge renders with (tierColors.js
// #badge) instead of a flat swatch fill — those strings are
// hardcoded per color key in tierColors.js so they survive
// Tailwind's build-time purge, unlike a runtime-composed
// bg-{key}-500 class would.
const tierInfo = p.subscription ? tierMap[p.subscription] : null;
const guarded = (tierInfo?.rank ?? 0) > 0 && !p.completed;
const tierColor = guarded ? getTierColor(tierInfo.color) : null;
return (
<div
key={p.prereq_id}
className={cn(
"flex items-center justify-between gap-3 py-3 px-3 rounded-lg",
p.completed && "bg-emerald-50 dark:bg-emerald-950/20",
!p.completed && !guarded && "bg-muted/40",
guarded && tierColor.badge
)}
>
<div className="flex items-center gap-3 min-w-0">
{p.completed ? (
<div className="w-6 h-6 rounded-full bg-emerald-500 flex items-center justify-center shrink-0">
<Check className="w-3.5 h-3.5 text-white" />
</div>
) : (
<div
className={cn("size-4 rounded-full border-2 shrink-0", guarded && "border-white/70")}
/>
)}
<span
className={cn(
"font-medium truncate",
!p.completed && !guarded && "text-muted-foreground",
guarded && "text-white"
)}
>
{p.title ?? "—"}
</span>
</div>
<Badge
variant="secondary"
className={cn(
"shrink-0 border-0 gap-1",
p.completed
? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400"
: guarded
? "bg-white/15 text-white"
: "text-muted-foreground"
)}
>
{p.completed
? <><CheckCheck className="size-3.5" /> Completed</>
: <><LockIcon className="size-3.5" /> Locked</>}
</Badge>
</div>
);
})}
</div>
) : (
<div className="rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground">
No prerequisites — this is a great course to start with.
</div>
)}
</div>
</div>
{/* Units — while content isn't ready, only Rewards is shown */}
<div className="space-y-4">
{course?.units?.length > 0 && (
<>
<div className="font-bold text-2xl">
{contentNotReady ? "Rewards" : "Course content"}
</div>
<CourseUnits
units={course.units}
courseId={courseId}
courseTitle={course.title}
courseLevel={course.level}
badgeColor={course.badge_color ?? "purple"}
badgeImageUrl={badgeImageUrl}
isCompleted={isCompleted}
pendingCert={course.pending_certificate ?? null}
certificate={course.certificate ?? null}
assessment={course.assessment ?? null}
contentNotReady={contentNotReady}
locked={courseBlocked}
onLockedClick={() => setUpsellOpen(true)}
/>
</>
)}
</div>
</div>
</div>
</div>
</div>
</div>
<CourseUpsellModal
open={upsellOpen}
onOpenChange={setUpsellOpen}
course={course}
tierMap={tierMap}
/>
</div>
);
};
export default CourseDetails;
@@ -0,0 +1,345 @@
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { House, Timer, ChevronLeft, ChevronRight, LockIcon, Tag, Tags, Search } from "lucide-react";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { Input } from "@/components/ui/input";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { useClientCourses } from "@/contexts/ClientCoursesContext";
import { cn } from "@/lib/utils";
import { Fragment } from "react";
import { PageMeta } from "@/contexts/MetadataContext";
import api from "@/utils/api.util";
import { resolveTierBadge } from "@/utils/tierBadge.util";
import { Building2 } from "lucide-react";
import { GitBranch } from "lucide-react";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function formatDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h && m) return `${h}h ${m}m`;
if (h) return `${h}h`;
return `${m}m`;
}
const ITEMS_PER_PAGE = 10;
// ─── Course Card ──────────────────────────────────────────────────────────────
const CourseCard = ({ course, tierMap, onViewDetails }) => {
const slug = course.subscription ?? "free";
const locked = course.is_locked;
const duration = formatDuration(course.duration_seconds);
const { rank, label, cls } = resolveTierBadge(slug, tierMap);
return (
<div
className={cn(
"bg-card rounded-2xl border p-4 flex flex-col gap-2.5 transition-all cursor-pointer group",
"hover:shadow-sm",
locked
? "opacity-80 hover:opacity-100 hover:border-muted-foreground/40"
: "hover:bg-muted/60 dark:hover:border-blue-500"
)}
onClick={() => onViewDetails(course)}
>
<div className="flex flex-wrap gap-1.5">
<Badge className={cls}>
{locked ? <LockIcon className="size-3" /> : <Tag className="size-3" />}
{label}
</Badge>
{course.level && !locked && (
<Badge variant="outline"><GitBranch />{course.level.charAt(0).toUpperCase() + course.level.slice(1)}</Badge>
)}
{(course.categories ?? []).map((cat) => (
<Badge key={cat.id} variant="outline"><Tags /> {cat.name}</Badge>
))}
{locked && (
<Badge variant="secondary">
<LockIcon className="size-3" /> Locked
</Badge>
)}
</div>
<div className="flex flex-col gap-1">
<h1 className="text-lg font-medium leading-snug line-clamp-3 transition-colors group-hover:text-blue-700 dark:group-hover:text-blue-400">
{course.title}
</h1>
{course.description && (
<p className="text-sm leading-relaxed line-clamp-2 group-hover:text-blue-700 dark:group-hover:text-blue-400">
{course.description}
</p>
)}
</div>
<div className="flex items-center justify-between pt-2 mt-auto border-t">
<div className={`flex items-center gap-1 text-sm [&_svg]:size-4 ${locked ? "text-muted-foreground" : "text-card-foreground group-hover:text-blue-700 dark:group-hover:text-blue-400"}`}>
<Timer />
{duration ?? "—"}
</div>
{locked && (
<span className="text-xs text-muted-foreground">Upgrade to unlock</span>
)}
</div>
</div>
);
};
// ─── Skeleton Card ────────────────────────────────────────────────────────────
const CourseCardSkeleton = () => (
<div className="bg-card rounded-2xl border p-4 flex flex-col gap-2.5">
<div className="flex gap-1.5">
<Skeleton className="h-5 w-16 rounded-full" />
<Skeleton className="h-5 w-20 rounded-full" />
</div>
<Skeleton className="h-6 w-3/4" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
<div className="pt-2 mt-auto border-t">
<Skeleton className="h-4 w-16" />
</div>
</div>
);
// ─── Pagination ───────────────────────────────────────────────────────────────
const Pagination = ({ currentPage, totalPages, totalItems, itemsPerPage, onPageChange }) => {
const start = (currentPage - 1) * itemsPerPage + 1;
const end = Math.min(currentPage * itemsPerPage, totalItems);
const getPages = () => {
const pages = [];
if (totalPages <= 5) {
for (let i = 1; i <= totalPages; i++) pages.push(i);
} else {
pages.push(1);
if (currentPage > 3) pages.push("...");
for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) pages.push(i);
if (currentPage < totalPages - 2) pages.push("...");
pages.push(totalPages);
}
return pages;
};
return (
<div className="flex items-center justify-between w-full pt-4 border-t">
<div className="text-sm text-muted-foreground">
Showing <span className="font-medium text-foreground">{start}–{end}</span> of{" "}
<span className="font-medium text-foreground">{totalItems}</span> courses
</div>
<div className="flex items-center gap-1">
<Button onClick={() => onPageChange(currentPage - 1)} disabled={currentPage === 1} variant="ghost" size="sm">
<ChevronLeft />
</Button>
{getPages().map((page, i) =>
page === "..." ? (
<span key={`ellipsis-${i}`} className="w-7 h-7 flex items-center justify-center text-xs text-muted-foreground">···</span>
) : (
<Button key={page} size="sm" variant={currentPage === page ? "default" : "outline"} onClick={() => onPageChange(page)}>
{page}
</Button>
)
)}
<Button onClick={() => onPageChange(currentPage + 1)} disabled={currentPage === totalPages} variant="ghost" size="sm">
<ChevronRight />
</Button>
</div>
</div>
);
};
// ─── Main Page ────────────────────────────────────────────────────────────────
const CoursesList = () => {
const navigate = useNavigate();
const { courses, coursesLoading, getCourses } = useClientCourses();
const [tierCategories, setTierCategories] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
const [subFilter, setSubFilter] = useState("All");
const [categoryFilter, setCategoryFilter] = useState("All");
const [allCategories, setAllCategories] = useState([]);
useEffect(() => {
getCourses();
api.get("/client/tiers/categories")
.then(({ data }) => setTierCategories(data.data ?? []))
.catch(() => { });
api.get("/client/courses/categories")
.then(({ data }) => setAllCategories(data.data ?? []))
.catch(() => { });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// slug → category info map
const tierMap = useMemo(() => {
const m = {};
tierCategories.forEach((c) => { m[c.slug] = c; });
return m;
}, [tierCategories]);
const filtered = useMemo(() =>
courses
.filter((c) => {
const matchSearch = c.title.toLowerCase().includes(search.toLowerCase()) ||
(c.description ?? "").toLowerCase().includes(search.toLowerCase());
const matchSub = subFilter === "All" || c.subscription === subFilter;
const matchCategory = categoryFilter === "All" || (c.categories ?? []).some((cat) => String(cat.id) === categoryFilter);
return matchSearch && matchSub && matchCategory;
})
.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)),
[courses, search, subFilter, categoryFilter]
);
const totalPages = Math.max(1, Math.ceil(filtered.length / ITEMS_PER_PAGE));
const paginated = filtered.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE);
const runSearch = () => { setSearch(searchInput); setCurrentPage(1); };
const handleViewDetails = (course) => navigate(`/course/${course.course_id}`);
const items = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: "Courses" },
];
return (
<div>
<PageMeta title="Courses - STARR" description="Browse your available training courses." />
<div className="py-24 bg-accent/70 min-h-screen">
<div className="flex flex-col gap-4 justify-between lg:container lg:mx-auto pt-2">
<AppBreadcrumb items={items} />
{/* Search & Filters */}
<div className="fixed top-[67px] left-0 right-0 z-10 bg-card border-b lg:static lg:bg-transparent lg:border-none py-3 xs:px-4 md:px-6 lg:px-0">
<div className="flex items-center xs:flex-col lg:flex-row gap-4">
<div className="flex items-center gap-2 w-full lg:max-w-64">
<Input
placeholder="Search courses..."
className="w-full bg-card text-sm"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") runSearch(); }}
/>
<Button size="icon" variant="outline" className="shrink-0 bg-card" onClick={runSearch} aria-label="Search">
<Search />
</Button>
</div>
<div className="flex gap-4 items-start w-full">
<Select value={subFilter} onValueChange={(v) => { setSubFilter(v); setCurrentPage(1); }}>
<SelectTrigger className="w-full lg:w-48 bg-card">
<SelectValue placeholder="Subscription" />
</SelectTrigger>
<SelectContent>
<SelectItem value="All">All</SelectItem>
{tierCategories.map((cat) => (
<SelectItem key={cat.slug} value={cat.slug}>
{cat.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value="courses" onValueChange={(v) => {
if (v === "units") navigate("/units");
if (v === "lessons") navigate("/lessons");
}}>
<SelectTrigger className="w-full lg:w-48 bg-card">
<SelectValue placeholder="Browse" />
</SelectTrigger>
<SelectContent>
<SelectItem value="courses">Courses</SelectItem>
<SelectItem value="units">Units</SelectItem>
<SelectItem value="lessons">Lessons</SelectItem>
</SelectContent>
</Select>
{allCategories.length > 0 && (
<Select value={categoryFilter} onValueChange={(v) => { setCategoryFilter(v); setCurrentPage(1); }}>
<SelectTrigger className="w-full lg:w-48 bg-card">
<SelectValue placeholder="Category" />
</SelectTrigger>
<SelectContent>
<SelectItem value="All">All Categories</SelectItem>
{allCategories.map((cat) => (
<SelectItem key={cat.id} value={String(cat.id)}>
{cat.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
</div>
{categoryFilter !== "All" && (
<div className="flex items-center flex-wrap gap-2">
<span className="text-sm text-muted-foreground">Tags:</span>
{allCategories
.filter((cat) => String(cat.id) === categoryFilter)
.map((cat) => (
<Badge
key={cat.id}
variant="default"
className="cursor-pointer"
onClick={() => { setCategoryFilter("All"); setCurrentPage(1); }}
>
<Tags className="size-3" />
{cat.name}
</Badge>
))}
</div>
)}
{/* Course Grid */}
{coursesLoading ? (
<div className="xs:pt-12 lg:pt-0 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{Array.from({ length: 8 }).map((_, i) => <CourseCardSkeleton key={i} />)}
</div>
) : paginated.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20">
<Building2 className="size-40 text-primary" />
<p className="text-md">No courses found</p>
</div>
) : (
<div className="xs:pt-12 lg:pt-0 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-4 xs:px-4 lg:px-0">
{paginated.map((course) => (
<CourseCard
key={course.course_id}
course={course}
tierMap={tierMap}
onViewDetails={handleViewDetails}
/>
))}
</div>
)}
{!coursesLoading && filtered.length > ITEMS_PER_PAGE && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
totalItems={filtered.length}
itemsPerPage={ITEMS_PER_PAGE}
onPageChange={setCurrentPage}
/>
)}
</div>
</div>
</div>
);
};
export default CoursesList;
@@ -0,0 +1,402 @@
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Users, Timer,
Tag, LockIcon,
} from "lucide-react";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table, TableHeader, TableBody,
TableHead, TableRow, TableCell,
} from "@/components/ui/table";
import { useNavigate, useLocation } from "react-router-dom";
import { toast } from "sonner";
import { useClientCourses } from "@/contexts/ClientCoursesContext";
import { useLibrary } from "@/contexts/ClientLibraryContext";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { UnitCard, UnitCardSkeleton } from "../components/UnitCard";
import LessonUpsellModal from "../components/LessonUpsellModal";
import { LessonCard, LessonCardSkeleton } from "../components/LessonCard";
import { resolveTierBadge } from "@/utils/tierBadge.util";
import { cn } from "@/lib/utils";
import { useGroup } from "@/contexts/ClientGroupContext";
import { useClientAdvertisements } from "@/contexts/ClientAdvertisementContext";
import { Hero, HeroSkeleton } from "@/components/generic/Blocks/Client/Advertisements/Hero";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function formatDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h && m) return `${h}h ${m}m`;
if (h) return `${h}h`;
return `${m}m`;
}
// ── Course Card ──────────────────────────────────────────────────────────────
const CourseCard = ({ course, onViewDetails }) => {
const { tierMap } = useClientTiers();
const slug = course.subscription ?? "free";
const locked = course.is_locked;
const duration = formatDuration(course.duration_seconds);
const { rank, label, cls } = resolveTierBadge(slug, tierMap);
return (
<div
className={cn(
"bg-card rounded-2xl border p-4 flex flex-col gap-2.5 transition-all cursor-pointer group",
"hover:shadow-sm",
locked
? "opacity-80 hover:opacity-100 hover:border-muted-foreground/40"
: "hover:bg-muted/60 dark:hover:border-blue-500"
)}
onClick={() => onViewDetails(course)}
>
<div className="flex flex-wrap gap-1.5">
<Badge className={cls}>
{rank > 0 || locked ? <LockIcon className="size-3" /> : <Tag className="size-3" />}
{label}
</Badge>
{course.level && (
<Badge variant="outline">
{course.level.charAt(0).toUpperCase() + course.level.slice(1)}
</Badge>
)}
{locked && (
<Badge variant="secondary" className="ml-auto">
<LockIcon className="size-3" /> Locked
</Badge>
)}
</div>
<div className="flex flex-col gap-1">
<h1 className="text-lg font-medium leading-snug line-clamp-3 transition-colors group-hover:text-blue-700 dark:group-hover:text-blue-400">
{course.title}
</h1>
{course.description && (
<p className="text-sm leading-relaxed line-clamp-2 text-muted-foreground">
{course.description}
</p>
)}
</div>
<div className="flex items-center justify-between pt-2 mt-auto border-t">
<div className={`flex items-center gap-1 text-sm [&_svg]:size-4 ${locked ? "text-muted-foreground" : "text-card-foreground group-hover:text-blue-700 dark:group-hover:text-blue-400"}`}>
<Timer />
{duration ?? "—"}
</div>
{locked && (
<span className="text-xs text-muted-foreground">Upgrade to unlock</span>
)}
</div>
</div>
);
};
// ─── Course Card Skeleton ─────────────────────────────────────────────────────
const CourseCardSkeleton = () => (
<div className="bg-card rounded-2xl border p-4 flex flex-col gap-2.5">
<div className="flex gap-1.5">
<Skeleton className="h-5 w-16 rounded-full" />
<Skeleton className="h-5 w-20 rounded-full" />
</div>
<Skeleton className="h-6 w-3/4" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
<div className="pt-2 mt-auto border-t">
<Skeleton className="h-4 w-16" />
</div>
</div>
);
// ─── Groups Table ─────────────────────────────────────────────────────────────
const GroupsTable = ({ groups, onView }) => (
<div className="bg-card border rounded-xl overflow-hidden">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent">
<TableHead className="w-10 text-center px-4">#</TableHead>
<TableHead className="px-4">Group Name</TableHead>
<TableHead className="px-4">Code</TableHead>
<TableHead className="px-4">Task Lists</TableHead>
<TableHead className="px-4" />
</TableRow>
</TableHeader>
<TableBody>
{groups.map((g, i) => {
const taskListCount = Number(g.task_list_count ?? g.taskLists?.length ?? 0);
return (
<TableRow key={g.group_id}>
<TableCell className="text-center px-4 text-muted-foreground tabular-nums">
{i + 1}
</TableCell>
<TableCell className="px-4 font-medium">{g.name}</TableCell>
<TableCell className="px-4">
<Badge variant="outline" className="font-mono text-xs">{g.group_code}</Badge>
</TableCell>
<TableCell className="px-4">
{taskListCount}
</TableCell>
<TableCell className="px-4 text-right">
<Button size="sm" variant="outline" onClick={() => onView(g)}>
View
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
);
const GroupsTableSkeleton = () => (
<div className="bg-card border rounded-xl overflow-hidden">
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent">
<TableHead className="w-10 text-center px-4">#</TableHead>
<TableHead className="px-4">Group Name</TableHead>
<TableHead className="px-4">Code</TableHead>
<TableHead className="px-4 w-full text-center whitespace-nowrap">Task Lists</TableHead>
<TableHead className="px-4" />
</TableRow>
</TableHeader>
<TableBody>
{[1, 2].map((i) => (
<TableRow key={i}>
<TableCell className="text-center px-4"><Skeleton className="h-4 w-4 mx-auto" /></TableCell>
<TableCell className="px-4"><Skeleton className="h-4 w-32" /></TableCell>
<TableCell className="px-4"><Skeleton className="h-5 w-16 rounded-full" /></TableCell>
<TableCell className="px-4"><Skeleton className="h-4 w-8 mx-auto" /></TableCell>
<TableCell className="px-4 text-right"><Skeleton className="h-8 w-14 ml-auto" /></TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
// ─── Client Dashboard ─────────────────────────────────────────────────────────
const Client = () => {
const navigate = useNavigate();
const { state: navState } = useLocation();
const { courses, coursesLoading, getCourses } = useClientCourses();
const { units, unitsLoading, getUnits, lessons, lessonsLoading, getLessons } = useLibrary();
const { tierMap } = useClientTiers();
const { groups, fetchGroups, loading: groupLoading } = useGroup();
const {
adLists, listLoading, getActiveAdvertisementList,
handleAdCtaClick,
} = useClientAdvertisements();
const [lessonModalOpen, setLessonModalOpen] = useState(false);
const [selectedLesson, setSelectedLesson] = useState(null);
const heroAds = adLists["dashboard.hero"] ?? [];
// Show welcome toast on first registration
useEffect(() => {
if (!navState?.justRegistered) return;
toast('Welcome to Philproperties!', {
description: 'You earned the Early Access badge. Check your notifications for details.',
duration: 6000,
});
window.history.replaceState({}, '');
}, []);
// Show a one-time notice the first time a manually-registered account
// gets folded into a Google sign-in with the same email.
useEffect(() => {
if (!navState?.justLinkedGoogle) return;
toast('Your Google account is now affiliated with this account.', {
description: 'You can sign in with Google going forward.',
duration: 6000,
});
window.history.replaceState({}, '');
}, []);
useEffect(() => {
getCourses();
getUnits();
getLessons();
}, []);
useEffect(() => {
fetchGroups();
}, [])
// ── Resolve hero ad carousel once on mount ────────────────────────────────
useEffect(() => {
getActiveAdvertisementList("dashboard.hero");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Show only first 3
const featuredCourses = courses.slice(0, 3);
const featuredUnits = units.slice(0, 3);
const featuredLessons = lessons.slice(0, 3);
const breadcrumbItems = [
{ label: "My Groups", icon: <Users className="size-4" /> },
];
// ── Card click — always go to the detail page; locked items show their
// upgrade prompt there, on the primary action button ──────────────────────
const handleViewDetails = (course) => navigate(`/course/${course.course_id}`);
const handleViewUnitDetails = (unit) => navigate(`/units/${unit.uuid}`);
const handleViewLessonDetails = (lesson) => {
if (lesson.is_locked) {
setSelectedLesson(lesson);
setLessonModalOpen(true);
} else {
navigate(`/lessons/${lesson.uuid}`);
}
};
return (
<div>
<div className="my-20">
<div className="flex flex-col gap-8 justify-between lg:container lg:mx-auto xs:pt-2 lg:pt-8 lg:px-16 xs:px-4 sm:px-6">
{/* ── Hero Advertisement Carousel ── */}
{listLoading["dashboard.hero"] ? (
<HeroSkeleton />
) : (
<Hero ads={heroAds} onCtaClick={handleAdCtaClick} />
)}
{/* ── My Groups ── */}
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between">
<AppBreadcrumb items={breadcrumbItems} />
{!groupLoading && groups.length > 0 && (
<span className="text-sm text-muted-foreground">
{groups.length} group{groups.length !== 1 ? 's' : ''}
</span>
)}
</div>
{groupLoading ? (
<GroupsTableSkeleton />
) : groups.length === 0 ? (
<p className="text-sm text-muted-foreground">You are not assigned to any group.</p>
) : (
<GroupsTable
groups={groups}
onView={(g) => navigate(`/group/${g.group_id}`)}
/>
)}
</div>
{/* ── Featured Courses (first 3) ── */}
<div className="flex flex-col gap-4">
<div className="w-full flex items-center justify-between">
<h1 className="text-2xl font-medium">Courses</h1>
<Button onClick={() => navigate(`/course`)}>View All</Button>
</div>
{coursesLoading ? (
<div className="grid lg:grid-cols-3 gap-4">
{Array.from({ length: 3 }).map((_, i) => (
<CourseCardSkeleton key={i} />
))}
</div>
) : featuredCourses.length === 0 ? (
<p className="text-sm text-muted-foreground">No courses available yet.</p>
) : (
<div className="grid lg:grid-cols-3 gap-4">
{featuredCourses.map((course) => (
<CourseCard
key={course.course_id}
course={course}
onViewDetails={handleViewDetails}
/>
))}
</div>
)}
</div>
{/* ── Featured Units (first 3) ── */}
<div className="flex flex-col gap-4">
<div className="w-full flex items-center justify-between">
<h1 className="text-2xl font-medium">Units</h1>
<Button onClick={() => navigate(`/units`)}>View All</Button>
</div>
{unitsLoading ? (
<div className="grid lg:grid-cols-3 gap-4">
{Array.from({ length: 3 }).map((_, i) => (
<UnitCardSkeleton key={i} />
))}
</div>
) : featuredUnits.length === 0 ? (
<p className="text-sm text-muted-foreground">No units available yet.</p>
) : (
<div className="grid lg:grid-cols-3 gap-4">
{featuredUnits.map((unit) => (
<UnitCard
key={unit.unit_id}
unit={unit}
tierMap={tierMap}
onViewDetails={handleViewUnitDetails}
/>
))}
</div>
)}
</div>
{/* ── Featured Lessons (first 3) ── */}
<div className="flex flex-col gap-4">
<div className="w-full flex items-center justify-between">
<h1 className="text-2xl font-medium">Lessons</h1>
<Button onClick={() => navigate(`/lessons`)}>View All</Button>
</div>
{lessonsLoading ? (
<div className="grid lg:grid-cols-3 gap-4">
{Array.from({ length: 3 }).map((_, i) => (
<LessonCardSkeleton key={i} />
))}
</div>
) : featuredLessons.length === 0 ? (
<p className="text-sm text-muted-foreground">No lessons available yet.</p>
) : (
<div className="grid lg:grid-cols-3 gap-4">
{featuredLessons.map((lesson) => (
<LessonCard
key={lesson.lesson_id}
lesson={lesson}
tierMap={tierMap}
onViewDetails={handleViewLessonDetails}
/>
))}
</div>
)}
</div>
</div>
</div>
{/* ── Upsell Modal — only for locked lessons ── */}
<LessonUpsellModal
open={lessonModalOpen}
onOpenChange={setLessonModalOpen}
lesson={selectedLesson}
tierMap={tierMap}
/>
</div>
);
};
export default Client;
@@ -0,0 +1,422 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useProfile } from "@/contexts/ProfileProvider";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Camera, Loader2, Plus, Trash2, ArrowLeft } from "lucide-react";
import AvatarUploadDialog from "@/components/generic/AvatarUploadDialog";
import { resolveAssetSrc } from "@/utils/media.util";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function getInitials(name = "") {
return name
.trim()
.split(/\s+/)
.map((n) => n[0]?.toUpperCase() ?? "")
.slice(0, 2)
.join("");
}
function emptyPhone() {
return { number: "", country_code: "+63", phone_type: "mobile", full_number: "" };
}
function emptyAddress() {
return {
address_type: "home",
street: "",
city: "",
state: "",
zip: "",
country: "Philippines",
full_address: "",
};
}
const PHONE_TYPES = ["mobile", "home", "work", "other"];
const ADDRESS_TYPES = ["home", "work", "billing", "other"];
// ─── Component ────────────────────────────────────────────────────────────────
const EditProfile = () => {
const navigate = useNavigate();
const { profile, profileLoading, updateProfile, getProfile, uploadAvatar, deleteAvatar, avatarLoading } = useProfile();
const [avatarDialogOpen, setAvatarDialogOpen] = useState(false);
// ── Form state ─────────────────────────────────────────────────────────────
const [givenName, setGivenName] = useState("");
const [middleName, setMiddleName] = useState("");
const [lastName, setLastName] = useState("");
const [extensionName, setExtensionName] = useState("");
const [occupation, setOccupation] = useState("");
const [phones, setPhones] = useState([emptyPhone()]);
const [addresses, setAddresses] = useState([emptyAddress()]);
const [avatarPreview, setAvatarPreview] = useState("");
useEffect(() => { getProfile(); }, []); // fetch on mount
useEffect(() => { // seed fields when profile loads
if (!profile) return;
const pi = profile.personal_info ?? {};
setGivenName(pi.name?.given_name ?? "");
setMiddleName(pi.name?.middle_name ?? "");
setLastName(pi.name?.last_name ?? "");
setExtensionName(pi.name?.extension_name ?? "");
setOccupation(pi.occupation ?? "");
setPhones(pi.phone_number?.length ? pi.phone_number : [emptyPhone()]);
setAddresses(pi.addresses?.length ? pi.addresses : [emptyAddress()]);
setAvatarPreview(resolveAssetSrc(pi.avatar) ?? "");
}, [profile]);
// ── Phone helpers ──────────────────────────────────────────────────────────
const updatePhone = (i, field, value) => {
setPhones((prev) => {
const next = [...prev];
next[i] = { ...next[i], [field]: value };
next[i].full_number = `${next[i].country_code}${next[i].number}`;
return next;
});
};
const addPhone = () => setPhones((p) => [...p, emptyPhone()]);
const removePhone = (i) => setPhones((p) => p.filter((_, idx) => idx !== i));
// ── Address helpers ────────────────────────────────────────────────────────
const updateAddress = (i, field, value) => {
setAddresses((prev) => {
const next = [...prev];
next[i] = { ...next[i], [field]: value };
const a = next[i];
next[i].full_address = [a.street, a.city, a.state, a.zip, a.country]
.filter(Boolean)
.join(", ");
return next;
});
};
const addAddress = () => setAddresses((a) => [...a, emptyAddress()]);
const removeAddress = (i) => setAddresses((a) => a.filter((_, idx) => idx !== i));
// ── Submit ─────────────────────────────────────────────────────────────────
const handleSubmit = async () => {
const full_name = [givenName, middleName, lastName, extensionName]
.filter(Boolean)
.join(" ");
const personal_info = {
name: {
given_name: givenName,
middle_name: middleName,
last_name: lastName,
extension_name: extensionName,
full_name,
},
occupation,
phone_number: phones.filter((p) => p.number.trim() !== ""),
addresses: addresses.filter((a) => a.street.trim() !== "" || a.city.trim() !== ""),
};
const result = await updateProfile(personal_info);
if (result?.success) navigate("/profile");
};
const fullName = [givenName, lastName].filter(Boolean).join(" ");
const initials = getInitials(fullName);
return (
<div className="mt-17 bg-muted min-h-screen">
<div className="p-6 lg:container lg:max-w-3xl lg:mx-auto space-y-4">
{/* Header */}
<div className="flex items-center gap-3">
<Button variant="ghost" size="icon" onClick={() => navigate("/profile")}>
<ArrowLeft className="size-4" />
</Button>
<div>
<h1 className="text-base font-semibold">Edit Profile</h1>
<p className="text-xs text-muted-foreground">Update your personal information</p>
</div>
</div>
{/* Avatar */}
<Card>
<CardContent className="py-4 px-6">
<div className="flex items-center gap-4">
<div className="relative">
<Avatar className="h-16 w-16">
<AvatarImage src={avatarPreview} />
<AvatarFallback className="text-base">{initials || "PH"}</AvatarFallback>
</Avatar>
<button
type="button"
className="absolute bottom-0 right-0 h-5 w-5 rounded-full bg-foreground flex items-center justify-center hover:opacity-80 transition-opacity"
onClick={() => setAvatarDialogOpen(true)}
>
<Camera className="h-3 w-3 text-background" />
</button>
</div>
<div>
<p className="text-sm font-medium">{fullName || "—"}</p>
<p className="text-xs text-muted-foreground">{profile?.email ?? ""}</p>
</div>
</div>
</CardContent>
</Card>
{/* Name */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Name</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Given Name</Label>
<Input
value={givenName}
onChange={(e) => setGivenName(e.target.value)}
placeholder="Juan"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Middle Name</Label>
<Input
value={middleName}
onChange={(e) => setMiddleName(e.target.value)}
placeholder="Santos"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Last Name</Label>
<Input
value={lastName}
onChange={(e) => setLastName(e.target.value)}
placeholder="Dela Cruz"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Extension Name</Label>
<Input
value={extensionName}
onChange={(e) => setExtensionName(e.target.value)}
placeholder="Jr., Sr., III"
/>
</div>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Occupation</Label>
<Input
value={occupation}
onChange={(e) => setOccupation(e.target.value)}
placeholder="e.g. Real Estate Agent"
/>
</div>
</CardContent>
</Card>
{/* Phone numbers */}
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-medium">Phone Numbers</CardTitle>
<Button variant="outline" size="sm" onClick={addPhone}>
<Plus className="size-3.5" />
Add
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
{phones.map((phone, i) => (
<div key={i}>
{i > 0 && <Separator className="mb-4" />}
<div className="space-y-3">
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">Phone {i + 1}</p>
{phones.length > 1 && (
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-destructive hover:text-destructive"
onClick={() => removePhone(i)}
>
<Trash2 className="size-3.5" />
</Button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Country Code</Label>
<Input
value={phone.country_code}
onChange={(e) => updatePhone(i, "country_code", e.target.value)}
placeholder="+63"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Number</Label>
<Input
value={phone.number}
onChange={(e) => updatePhone(i, "number", e.target.value)}
placeholder="9XX XXX XXXX"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Type</Label>
<Select
value={phone.phone_type}
onValueChange={(v) => updatePhone(i, "phone_type", v)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{PHONE_TYPES.map((t) => (
<SelectItem key={t} value={t}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
</div>
))}
</CardContent>
</Card>
{/* Addresses */}
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-medium">Addresses</CardTitle>
<Button variant="outline" size="sm" onClick={addAddress}>
<Plus className="size-3.5" />
Add
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
{addresses.map((addr, i) => (
<div key={i}>
{i > 0 && <Separator className="mb-4" />}
<div className="space-y-3">
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">Address {i + 1}</p>
{addresses.length > 1 && (
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-destructive hover:text-destructive"
onClick={() => removeAddress(i)}
>
<Trash2 className="size-3.5" />
</Button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1.5 sm:col-span-2">
<Label className="text-xs">Address Type</Label>
<Select
value={addr.address_type}
onValueChange={(v) => updateAddress(i, "address_type", v)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{ADDRESS_TYPES.map((t) => (
<SelectItem key={t} value={t}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label className="text-xs">Street</Label>
<Input
value={addr.street}
onChange={(e) => updateAddress(i, "street", e.target.value)}
placeholder="123 Rizal Street, Barangay Poblacion"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">City / Municipality</Label>
<Input
value={addr.city}
onChange={(e) => updateAddress(i, "city", e.target.value)}
placeholder="Makati"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">State / Region</Label>
<Input
value={addr.state}
onChange={(e) => updateAddress(i, "state", e.target.value)}
placeholder="Metro Manila"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">ZIP Code</Label>
<Input
value={addr.zip}
onChange={(e) => updateAddress(i, "zip", e.target.value)}
placeholder="1200"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Country</Label>
<Input
value={addr.country}
onChange={(e) => updateAddress(i, "country", e.target.value)}
placeholder="Philippines"
/>
</div>
</div>
</div>
</div>
))}
</CardContent>
</Card>
{/* Actions */}
<div className="flex justify-end gap-2 pb-6">
<Button variant="outline" onClick={() => navigate("/profile")}>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={profileLoading}>
{profileLoading && <Loader2 className="size-4 animate-spin" />}
Save changes
</Button>
</div>
</div>
<AvatarUploadDialog
open={avatarDialogOpen}
onClose={() => setAvatarDialogOpen(false)}
currentAvatarUrl={avatarPreview}
initials={initials || "PH"}
onUpload={uploadAvatar}
onDelete={deleteAvatar}
loading={avatarLoading}
/>
</div>
);
};
export default EditProfile;
@@ -0,0 +1,158 @@
/***********************************************************************************************************************************************************************
* File Name : GroupList.jsx
* Type : Page (Client)
* Description : Lists all task lists assigned to the user's group.
* Flat grid — no status tabs (those live in ViewTaskDetails.jsx
* at the task level instead).
* Route: /group/:groupId
***********************************************************************************************************************************************************************/
import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useGroup } from '@/contexts/ClientGroupContext';
import { useTask } from '@/contexts/ClientTaskContext';
import { PageMeta } from '@/contexts/MetadataContext';
import AppBreadcrumb from '@/components/generic/Breadcrumb/AppBreadcrumb';
import { Skeleton } from '@/components/ui/skeleton';
import {
House, Calendar, ListChecks, LayoutList, ArrowRight,
} from 'lucide-react';
import { formatDate } from '@/utils/table.util';
import { cn } from '@/lib/utils';
// ─── Task-count badge ──────────────────────────────────────────────────────────
const TaskCountBadge = ({ count = 0 }) => (
<span className="inline-flex items-center gap-1 text-xs font-medium bg-muted text-muted-foreground rounded-full px-2.5 py-1">
<ListChecks className="size-3.5" />
{count} task{count !== 1 ? 's' : ''}
</span>
);
// ─── Task list card ─────────────────────────────────────────────────────────────
const TaskListCard = ({ taskList, navigate }) => {
const taskCount = taskList.tasks?.length ?? 0;
// earliest upcoming deadline among this task list's tasks
const nextDeadline = (taskList.tasks ?? [])
.map((t) => t.deadline)
.filter(Boolean)
.sort((a, b) => new Date(a) - new Date(b))[0];
return (
<div
onClick={() => navigate(`view/${taskList.task_list_id}`)}
className={cn(
'border bg-card rounded-lg flex flex-col cursor-pointer transition-colors',
'hover:border-blue-400 dark:hover:border-blue-500',
)}
>
<div className="p-4 flex flex-col gap-2.5 flex-1">
<h1 className="text-base font-medium leading-snug">
{taskList.name}
</h1>
{taskList.description && (
<p className="text-sm text-muted-foreground leading-relaxed line-clamp-2">
{taskList.description}
</p>
)}
<div className="flex items-center gap-1.5 text-xs mt-auto pt-1 [&_svg]:size-3.5">
<Calendar />
{nextDeadline ? `Next due ${formatDate(nextDeadline)}` : 'No due date'}
</div>
</div>
<div className="px-4 py-2.5 border-t flex items-center justify-between">
<TaskCountBadge count={taskCount} />
<ArrowRight className="size-4 text-muted-foreground/60" />
</div>
</div>
);
};
// ─── Skeleton grid ────────────────────────────────────────────────────────────
const GridSkeleton = () => (
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3.5">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="border bg-card rounded-lg overflow-hidden">
<div className="p-4 flex flex-col gap-2.5">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-3.5 w-full" />
<Skeleton className="h-3.5 w-2/3" />
<Skeleton className="h-3.5 w-28 mt-1" />
</div>
<div className="px-4 py-2.5 border-t flex items-center justify-between">
<Skeleton className="h-5 w-16 rounded-full" />
</div>
</div>
))}
</div>
);
// ─── Empty state ──────────────────────────────────────────────────────────────
const EmptyState = () => (
<div className="h-64 flex items-center flex-col justify-center w-full gap-4">
<LayoutList className="size-20 text-muted-foreground/40" />
<h1 className="max-w-lg text-sm text-muted-foreground text-center">
No task lists have been assigned to this group yet.
</h1>
</div>
);
// ─── Main page ────────────────────────────────────────────────────────────────
export default function GroupList() {
const navigate = useNavigate();
const { groupId } = useParams();
const { group, fetchGroup } = useGroup();
const { taskLists, loading, fetchTaskLists } = useTask();
// ── Fetch group info + all task lists (no status filter) ─────────────────
useEffect(() => {
fetchGroup(groupId);
fetchTaskLists(groupId);
}, [groupId]);
const breadcrumbItems = [
{ label: 'Home', icon: <House className="size-4" />, to: '/dashboard' },
{ label: group?.name ?? '…' },
];
return (
<div className="mt-17">
<PageMeta title={group ? `${group.name} - STARR` : undefined} description="View your group's task lists." />
<div className="lg:container lg:mx-auto flex flex-col gap-6 py-6 xs:px-6 lg:px-0">
{/* ── Header ────────────────────────────────────────────────── */}
<header className="flex flex-col gap-4">
<AppBreadcrumb items={breadcrumbItems} />
<div className="space-y-2">
{group
? <h1 className="font-bold text-2xl max-w-xl">{group.name}</h1>
: <Skeleton className="h-7 w-48" />
}
<p className="text-muted-foreground text-sm">
View all task lists assigned to your group.
</p>
</div>
</header>
{/* ── Task list grid ────────────────────────────────────────── */}
{loading ? (
<GridSkeleton />
) : !taskLists.length ? (
<EmptyState />
) : (
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3.5">
{taskLists.map((tl) => (
<TaskListCard
key={tl.task_list_id}
taskList={tl}
navigate={navigate}
/>
))}
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,316 @@
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import {
House, CheckCheck, Check, Hourglass, Clock, Video, ListChecks, ArrowUpRight,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { useCallback, useEffect, useRef, useState } from "react";
import { useLibrary } from "@/contexts/ClientLibraryContext";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { PageMeta } from "@/contexts/MetadataContext";
import LockedContentPanel from "@/modules/client/components/LockedContentPanel";
import LessonBlock from "../components/LessonBlock.jsx";
import MarkCompleteButton from "@/modules/client/components/MarkCompleteButton.jsx";
import api from "@/utils/api.util";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function formatDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) return `${h}hr ${m}min`;
return `${m}min`;
}
// ─── Lesson Details ─────────────────────────────────────────────────────────
const LessonDetails = () => {
const { uuid } = useParams();
const navigate = useNavigate();
const location = useLocation();
// Task context: state-first, endpoint fallback — same pattern as UnitList.jsx.
// If navigated here from a task's requirement card, taskCtx is in location.state;
// if the user opened this lesson directly (e.g. from /lessons), fetch it instead,
// so the "Task mode" banner still shows up when this lesson is a task requirement.
const [taskCtx, setTaskCtx] = useState(null);
useEffect(() => {
const stateCtx = location.state?.taskCtx;
if (stateCtx) { setTaskCtx(stateCtx); return; }
api.get(`/client/courses/lesson/uuid/${uuid}/task-context`)
.then(({ data }) => { if (data?.data?.has_task) setTaskCtx(data.data); })
.catch(() => {}); // non-critical — silently swallow
}, [uuid]); // eslint-disable-line react-hooks/exhaustive-deps
const {
getLesson, lesson, lessonLoading, unitBlocked, unitBlockedInfo, resetLesson,
upsertLessonProgress, upsertWatchProgress, markComplete,
} = useLibrary();
const { tierMap, getTierCategories } = useClientTiers();
const completedSessionRef = useRef(new Set());
const hasCompleted = lesson?.status === "completed";
const unit = lesson?.unit ?? null;
const hasUnit = !!unit?.uuid;
const hasCourse = !!unit?.course;
// duration_seconds is derived from authored lesson content (see duration.util.js) —
// zero means no lesson content has been built yet, so it isn't ready to view.
const contentNotReady = !lesson?.duration_seconds
|| (hasUnit && !unit?.duration_seconds)
|| (hasCourse && !unit.course.duration_seconds);
const blockTypes = new Set((lesson?.blocks ?? []).map((b) => b.type));
const isVideoLesson = blockTypes.has("video") || blockTypes.has("text-video");
// read_all_content (or unconfigured/default) → scroll-to-bottom tracking, below.
// watch_percent / manual_complete → their own dedicated triggers — same dispatch
// pattern as UnitList.jsx / UnitReader.jsx, brought here for standalone lessons.
const lessonCompletionType = lesson?.completion?.type ?? 'read_all_content';
useEffect(() => {
getTierCategories();
getLesson(uuid);
return () => resetLesson();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [uuid]);
// ── Scroll progress (read_all_content) — mirrors UnitList.jsx/UnitReader.jsx's
// scrollY-based indicator, only meaningful for content-only standalone lessons.
const [scrollProgress, setScrollProgress] = useState(0);
useEffect(() => {
setScrollProgress(0);
window.scrollTo(0, 0);
}, [uuid]);
useEffect(() => {
// Content shorter than the viewport (nothing to scroll) used to flag 100%
// on the spot — but right after mount the video/image blocks haven't
// finished loading yet, so that snapshot is often taken against a
// still-collapsed layout and fires a false "completed" before the real
// (taller) content has even rendered. Debounce a settle window and
// re-check before trusting it.
let settleTimer = null;
const evaluate = () => {
const scrollTop = window.scrollY;
const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
if (scrollHeight <= 0) {
if (settleTimer) return;
settleTimer = setTimeout(() => {
settleTimer = null;
const stillShort = document.documentElement.scrollHeight - window.innerHeight <= 0;
if (stillShort) setScrollProgress(100);
}, 1200);
return;
}
if (settleTimer) { clearTimeout(settleTimer); settleTimer = null; }
// Percentage rounding alone can hit 100 a few pixels short of the real
// bottom (e.g. 99.5% rounds up), which was enough to auto-fire
// completion before the reader actually reached the end. Cap the
// ratio-derived value at 90 and only award the true 100 when the
// scroll position has actually reached the bottom.
const atBottom = scrollTop >= scrollHeight - 4;
setScrollProgress(atBottom ? 100 : Math.min(Math.round((scrollTop / scrollHeight) * 100), 90));
};
evaluate(); // seed a measurement — short content may never fire a scroll event
window.addEventListener("scroll", evaluate, { passive: true });
return () => {
window.removeEventListener("scroll", evaluate);
if (settleTimer) clearTimeout(settleTimer);
};
}, [uuid]);
// ── Mark lesson completed when user scrolls to the bottom ─────────────
// Only fires in Task mode — outside of it, this standalone lesson page is a
// passive preview/reader with no automatic progress persistence (matches the
// "Task mode — progress is being tracked automatically" banner's promise: no
// banner, no tracking).
useEffect(() => {
if (!taskCtx?.has_task) return;
if (lessonCompletionType !== 'read_all_content') return;
if (scrollProgress < 100 || !lesson?.uuid) return;
if (completedSessionRef.current.has(lesson.uuid)) return;
if (hasCompleted) return;
completedSessionRef.current.add(lesson.uuid);
upsertLessonProgress(lesson.uuid, 'completed', unit?.uuid ?? null);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scrollProgress]);
// watch_percent / watch_video / listen_audio — safe to always pass through, the
// backend no-ops whichever type (if any) isn't configured on this lesson.
const handleWatchProgress = useCallback((percent, meta) => {
if (!lesson?.uuid) return;
upsertWatchProgress(lesson.uuid, unit?.uuid ?? null, percent, meta);
}, [lesson, unit, upsertWatchProgress]);
// ── manual_complete trigger: learner clicks the Mark Complete button ────
const handleMarkComplete = useCallback(async () => {
if (!lesson?.uuid) return;
await markComplete(lesson.uuid, unit?.uuid ?? null);
}, [lesson, unit, markComplete]);
const items = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: "Lessons", to: `/lessons` },
...(hasCourse ? [{ label: unit.course.title, to: `/course/${unit.course.course_id}` }] : []),
...(hasUnit ? [{ label: unit.title, to: `/units/${unit.uuid}` }] : []),
{ label: lesson?.title ?? "Lesson" },
];
// ── Deep-link to a lesson under a locked unit — inline blocked panel ────
if (unitBlocked) {
return (
<LockedContentPanel
course={unitBlockedInfo?.course}
item={unitBlockedInfo?.item}
tierMap={tierMap}
/>
);
}
if (lessonLoading || !lesson) {
return (
<div className="my-17 p-8 lg:container lg:mx-auto space-y-4">
<Skeleton className="h-4 w-48" />
<Skeleton className="h-10 w-2/3" />
<Skeleton className="h-5 w-full max-w-2xl" />
</div>
);
}
return (
<div className="flex-1 flex flex-col">
<PageMeta title={`${lesson.title} - STARR`} description={lesson.description} />
{/* Scroll progress indicator — Task mode only (matches the "progress is being
tracked automatically" banner's promise), read_all_content lessons only,
fixed edge-to-edge under the navbar, same style as the Course > Unit >
Lesson reader's top bar. */}
{taskCtx?.has_task && !contentNotReady && lessonCompletionType === 'read_all_content' && (
<div
className="fixed left-0 right-0 z-30 h-1.5 bg-border"
style={{ top: "var(--navbar-h)" }}
>
<div
className={`h-full transition-all duration-150 ease-out ${scrollProgress >= 100 ? 'bg-green-500' : 'bg-primary'}`}
style={{ width: `${scrollProgress}%` }}
/>
</div>
)}
<div
className="flex-1 flex flex-col"
style={{ paddingTop: "var(--navbar-h)" }}
>
<div className="flex flex-col gap-6 lg:container lg:max-w-4xl mx-auto xs:px-4 xs:py-8 lg:px-16 lg:py-10">
<AppBreadcrumb items={items} />
{taskCtx?.has_task && (
<div className={`flex items-center gap-2 text-white text-xs font-medium px-4 py-1.5 rounded-md shadow-sm w-fit transition-colors ${
hasCompleted ? 'bg-green-600' : 'bg-blue-600'
}`}>
<ListChecks className="size-3.5 shrink-0" />
<span>
{hasCompleted
? 'Lesson complete — tracking finished'
: 'Task mode — progress is being tracked automatically'
}
</span>
</div>
)}
<div className="flex flex-col gap-3 max-w-2xl">
<h1 className="font-bold xs:text-2xl lg:text-3xl">{lesson.title}</h1>
<p className="text-muted-foreground">{lesson.description ?? ""}</p>
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground [&_svg]:size-4">
{formatDuration(lesson.duration_seconds) && (
<span className="flex items-center gap-1"><Clock /> {formatDuration(lesson.duration_seconds)}</span>
)}
{/* Reading/video type only means anything when there's an actual
task tracking this lesson — outside task mode there's nothing
being "completed", so hide it. The completion-requirement label
itself is dropped entirely — redundant with the lesson's own
working completion mechanism (scroll/watch/mark-complete). */}
{taskCtx?.has_task && (
<>
{formatDuration(lesson.duration_seconds) && <span>·</span>}
<span className="flex items-center gap-1">
<Video /> {isVideoLesson ? "Video lesson" : "Reading lesson"}
</span>
</>
)}
</div>
{hasCompleted && (
<div className="flex items-center gap-1.5 text-sm font-medium text-emerald-600 dark:text-emerald-400 w-fit">
<CheckCheck className="size-4" />
Success — you've completed this lesson.
</div>
)}
</div>
{/* Optional — never forced. Lets a learner who wants the full
multi-lesson navigator (sidebar, quiz, up-next) opt into it,
instead of always being redirected there. */}
{hasUnit && (
<Button
variant="outline"
size="sm"
className="w-fit"
onClick={() => navigate(`/units/${unit.uuid}/read`, { state: { lessonId: lesson.lesson_id } })}
>
Continue in "{unit.title}" <ArrowUpRight className="size-4" />
</Button>
)}
</div>
{lesson.objectives?.length > 0 && (
<div className="bg-background border rounded-lg p-4 flex flex-col gap-3 max-w-2xl">
<span className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">What you'll learn</span>
<ul className="flex flex-col gap-2">
{lesson.objectives.map((obj) => (
<li key={obj.objective_id} className="flex items-start gap-2 text-card-foreground">
<Check className="size-4 text-emerald-500 shrink-0 mt-0.5" />
{obj.text}
</li>
))}
</ul>
</div>
)}
{contentNotReady ? (
<div className="w-fit flex items-center gap-2 rounded-lg border bg-muted px-4 py-2.5 text-sm text-muted-foreground">
<Hourglass className="size-4 shrink-0" />
This lesson is currently being prepared. Please check back later.
</div>
) : (
<div className="w-full">
<LessonBlock
lesson={lesson}
loading={lessonLoading}
showHeader={false}
onWatchProgress={['watch_percent', 'watch_video', 'listen_audio'].includes(lessonCompletionType) ? handleWatchProgress : undefined}
/>
{taskCtx?.has_task && !lessonLoading && lesson && lessonCompletionType === 'manual_complete' && (
<MarkCompleteButton
label={lesson?.completion?.button_label}
completed={hasCompleted}
onMarkComplete={handleMarkComplete}
/>
)}
</div>
)}
</div>
</div>
</div>
);
};
export default LessonDetails;
@@ -0,0 +1,211 @@
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { House, ChevronLeft, ChevronRight, Layers, Search } from "lucide-react";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { Input } from "@/components/ui/input";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { useLibrary } from "@/contexts/ClientLibraryContext";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import LessonUpsellModal from "../components/LessonUpsellModal";
import { LessonCard, LessonCardSkeleton } from "../components/LessonCard";
import { PageMeta } from "@/contexts/MetadataContext";
const ITEMS_PER_PAGE = 10;
// ─── Pagination ───────────────────────────────────────────────────────────────
const Pagination = ({ currentPage, totalPages, totalItems, itemsPerPage, onPageChange }) => {
const start = (currentPage - 1) * itemsPerPage + 1;
const end = Math.min(currentPage * itemsPerPage, totalItems);
const getPages = () => {
const pages = [];
if (totalPages <= 5) {
for (let i = 1; i <= totalPages; i++) pages.push(i);
} else {
pages.push(1);
if (currentPage > 3) pages.push("...");
for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) pages.push(i);
if (currentPage < totalPages - 2) pages.push("...");
pages.push(totalPages);
}
return pages;
};
return (
<div className="flex items-center justify-between w-full pt-4 border-t">
<div className="text-sm text-muted-foreground">
Showing <span className="font-medium text-foreground">{start}–{end}</span> of{" "}
<span className="font-medium text-foreground">{totalItems}</span> lessons
</div>
<div className="flex items-center gap-1">
<Button onClick={() => onPageChange(currentPage - 1)} disabled={currentPage === 1} variant="ghost" size="sm">
<ChevronLeft />
</Button>
{getPages().map((page, i) =>
page === "..." ? (
<span key={`ellipsis-${i}`} className="w-7 h-7 flex items-center justify-center text-xs text-muted-foreground">···</span>
) : (
<Button key={page} size="sm" variant={currentPage === page ? "default" : "outline"} onClick={() => onPageChange(page)}>
{page}
</Button>
)
)}
<Button onClick={() => onPageChange(currentPage + 1)} disabled={currentPage === totalPages} variant="ghost" size="sm">
<ChevronRight />
</Button>
</div>
</div>
);
};
// ─── Main Page ────────────────────────────────────────────────────────────────
const LessonsList = () => {
const navigate = useNavigate();
const { lessons, lessonsLoading, getLessons } = useLibrary();
const { tierMap, getTierCategories } = useClientTiers();
const [currentPage, setCurrentPage] = useState(1);
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
const [lockFilter, setLockFilter] = useState("All");
const [modalOpen, setModalOpen] = useState(false);
const [selectedLesson, setSelectedLesson] = useState(null);
useEffect(() => {
getLessons();
getTierCategories();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const filtered = useMemo(() =>
lessons
.filter((l) => {
const matchSearch = l.title.toLowerCase().includes(search.toLowerCase()) ||
(l.description ?? "").toLowerCase().includes(search.toLowerCase());
const matchLock = lockFilter === "All"
|| (lockFilter === "Unlocked" && !l.is_locked)
|| (lockFilter === "Locked" && l.is_locked);
return matchSearch && matchLock;
})
.sort((a, b) => a.title.localeCompare(b.title)),
[lessons, search, lockFilter]
);
const totalPages = Math.max(1, Math.ceil(filtered.length / ITEMS_PER_PAGE));
const paginated = filtered.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE);
const runSearch = () => { setSearch(searchInput); setCurrentPage(1); };
const handleViewDetails = (lesson) => {
if (lesson.is_locked) {
setSelectedLesson(lesson);
setModalOpen(true);
} else {
navigate(`/lessons/${lesson.uuid}`);
}
};
const items = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: "Lessons" },
];
return (
<div>
<PageMeta title="Lessons - STARR" description="Browse standalone lessons you can start right away." />
<div className="py-24 bg-accent/70 min-h-screen">
<div className="flex flex-col gap-4 justify-between lg:container lg:mx-auto pt-2">
<AppBreadcrumb items={items} />
{/* Search & Filters */}
<div className="fixed top-[67px] left-0 right-0 z-10 bg-card border-b lg:static lg:bg-transparent lg:border-none py-3 xs:px-4 md:px-6 lg:px-0">
<div className="flex items-center xs:flex-col lg:flex-row gap-4">
<div className="flex items-center gap-2 w-full lg:max-w-64">
<Input
placeholder="Search lessons..."
className="w-full bg-card text-sm"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") runSearch(); }}
/>
<Button size="icon" variant="outline" className="shrink-0 bg-card" onClick={runSearch} aria-label="Search">
<Search />
</Button>
</div>
<Select value={lockFilter} onValueChange={(v) => { setLockFilter(v); setCurrentPage(1); }}>
<SelectTrigger className="w-full lg:w-48 bg-card">
<SelectValue placeholder="Access" />
</SelectTrigger>
<SelectContent>
<SelectItem value="All">All Lessons</SelectItem>
<SelectItem value="Unlocked">Unlocked</SelectItem>
<SelectItem value="Locked">Locked</SelectItem>
</SelectContent>
</Select>
<Select value="lessons" onValueChange={(v) => {
if (v === "courses") navigate("/course");
if (v === "units") navigate("/units");
}}>
<SelectTrigger className="w-full lg:w-48 bg-card">
<SelectValue placeholder="Browse" />
</SelectTrigger>
<SelectContent>
<SelectItem value="courses">Courses</SelectItem>
<SelectItem value="units">Units</SelectItem>
<SelectItem value="lessons">Lessons</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Lesson Grid */}
{lessonsLoading ? (
<div className="xs:pt-12 lg:pt-0 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{Array.from({ length: 8 }).map((_, i) => <LessonCardSkeleton key={i} />)}
</div>
) : paginated.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20">
<Layers className="size-40 text-primary" />
<p className="text-md">No lessons found</p>
</div>
) : (
<div className="xs:pt-12 lg:pt-0 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-4 xs:px-4 lg:px-0">
{paginated.map((lesson) => (
<LessonCard
key={lesson.lesson_id}
lesson={lesson}
tierMap={tierMap}
onViewDetails={handleViewDetails}
/>
))}
</div>
)}
{!lessonsLoading && filtered.length > ITEMS_PER_PAGE && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
totalItems={filtered.length}
itemsPerPage={ITEMS_PER_PAGE}
onPageChange={setCurrentPage}
/>
)}
</div>
</div>
<LessonUpsellModal
open={modalOpen}
onOpenChange={setModalOpen}
lesson={selectedLesson}
tierMap={tierMap}
/>
</div>
);
};
export default LessonsList;
@@ -0,0 +1,87 @@
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import * as LucideIcons from "lucide-react";
import { Trophy, BadgeCheck, ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { useProfile } from "@/contexts/ProfileProvider";
import { useDateFormat } from "@/hooks/useDateFormat";
const getFallbackIcon = (type) => type === "badge" ? BadgeCheck : Trophy;
export default function MyAchievements() {
const navigate = useNavigate();
const { achievements, achievementsLoading, getAchievements } = useProfile();
const { fmtDate } = useDateFormat();
useEffect(() => { getAchievements(); }, []);
const sorted = [...achievements].sort(
(a, b) => new Date(b.granted_at) - new Date(a.granted_at)
);
return (
<section className="mt-17 bg-muted min-h-full">
<div className="p-6 lg:container lg:max-w-3xl lg:mx-auto space-y-5">
<div className="flex items-center gap-3">
<Button type="button" variant="ghost" size="icon" onClick={() => navigate("/dashboard")}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-xl font-semibold">Achievements</h1>
<p className="text-sm text-muted-foreground">All your earned milestones and badges.</p>
</div>
</div>
{achievementsLoading ? (
<div className="rounded-xl border bg-card divide-y">
{[...Array(4)].map((_, i) => (
<div key={i} className="flex items-center gap-4 p-4">
<Skeleton className="h-10 w-10 rounded-full shrink-0" />
<div className="space-y-1.5 flex-1">
<Skeleton className="h-3.5 w-36" />
<Skeleton className="h-3 w-52" />
<Skeleton className="h-3 w-24" />
</div>
</div>
))}
</div>
) : sorted.length === 0 ? (
<div className="flex flex-col items-center justify-center py-24 text-center">
<Trophy className="h-10 w-10 text-muted-foreground/40 mb-3" />
<p className="text-sm font-medium">No achievements yet</p>
<p className="text-xs text-muted-foreground">Complete courses and activities to earn achievements.</p>
</div>
) : (
<div className="rounded-xl border bg-card">
{sorted.map((item, i) => {
const Icon = LucideIcons[item.icon] ?? getFallbackIcon(item.type);
return (
<div key={item.achievement_id ?? i}>
<div className="flex items-center gap-4 p-4">
<div className="h-10 w-10 rounded-full bg-secondary flex items-center justify-center shrink-0">
<Icon className="size-5 text-secondary-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold">{item.label}</p>
<p className="text-xs text-muted-foreground mt-0.5">{item.description}</p>
{item.granted_at && (
<p className="text-xs text-muted-foreground/70 mt-1">
{fmtDate(item.granted_at)}
</p>
)}
</div>
</div>
{i < sorted.length - 1 && <Separator />}
</div>
);
})}
</div>
)}
</div>
</section>
);
}
@@ -0,0 +1,171 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Award, Download, LockIcon, ArrowLeft, BadgeCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { useProfile } from "@/contexts/ProfileProvider";
import { useDateFormat } from "@/hooks/useDateFormat";
import api from "@/utils/api.util";
import { toast } from "sonner";
import CourseBadge from "@/modules/admin/components/courses/CourseBadge";
const CertificateCard = ({ courseTitle, issuedAt, courseUuid, badgeColor, badgeImageUrl }) => {
const [downloading, setDownloading] = useState(false);
const { fmtDate } = useDateFormat();
const issuedLabel = issuedAt ? fmtDate(issuedAt) : "—";
const handleDownload = async () => {
setDownloading(true);
try {
const res = await api.get(`/client/certificates/${courseUuid}`, { responseType: "blob" });
const disposition = res.headers["content-disposition"] ?? "";
const match = disposition.match(/filename="([^"]+)"/);
const filename = match ? match[1] : `certificate-${courseUuid}.pdf`;
const url = URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
} catch {
toast("Could not download certificate.");
} finally {
setDownloading(false);
}
};
return (
<div className="rounded-2xl border bg-card p-6 flex flex-col items-center gap-4 shadow-sm">
<CourseBadge
title={courseTitle}
color={badgeColor ?? "purple"}
imageUrl={badgeImageUrl ?? null}
/>
<div className="w-full rounded-lg border px-3 py-2.5">
<p className="text-[10px] uppercase tracking-widest text-muted-foreground font-semibold">Course</p>
<p className="text-sm font-medium mt-1 line-clamp-2">{courseTitle}</p>
</div>
<div className="w-full flex items-end justify-between">
<div>
<p className="text-[10px] uppercase tracking-widest text-muted-foreground font-semibold">Issued</p>
<p className="text-sm font-medium">{issuedLabel}</p>
</div>
<Badge className="bg-green-100 text-green-700 border-green-400 dark:bg-green-900/40 dark:text-green-400 dark:border-green-700 gap-1">
<BadgeCheck className="size-3" /> Verified
</Badge>
</div>
<Button size="sm" variant="outline" className="w-full" onClick={handleDownload} disabled={downloading}>
<Download className="size-3.5" />
{downloading ? "Downloading…" : "Download PDF"}
</Button>
</div>
);
};
export default function MyCertificates() {
const navigate = useNavigate();
const { achievements, achievementsLoading, getAchievements } = useProfile();
// { [courseUuid]: { badge_color, badge_image_url, badge_asset_id } }
const [badgeDataMap, setBadgeDataMap] = useState({});
useEffect(() => { getAchievements(); }, []);
const certAchievements = achievements.filter((a) => a.key.startsWith("course_completed_"));
// Fetch badge data for all certificates once the list is known
useEffect(() => {
if (!certAchievements.length) return;
const STREAM_BASE = `${import.meta.env.VITE_API_URL}/client/media/stream`;
certAchievements.forEach((cert) => {
const uuid = cert.metadata?.courseUuid ?? cert.key.replace("course_completed_", "");
if (!uuid || badgeDataMap[uuid]) return;
api.get(`/client/courses/uuid/${uuid}`)
.then(({ data }) => {
const c = data.data ?? data;
if (!c) return;
if (c.badge_asset_id) {
api.post("/client/media/token", { asset_id: c.badge_asset_id })
.then(({ data: td }) => {
const token = td.data?.token;
setBadgeDataMap((prev) => ({
...prev,
[uuid]: {
badge_color: c.badge_color ?? "purple",
badge_image_url: token ? `${STREAM_BASE}/${token}` : null,
},
}));
})
.catch(() => setBadgeDataMap((prev) => ({
...prev,
[uuid]: { badge_color: c.badge_color ?? "purple", badge_image_url: null },
})));
} else {
setBadgeDataMap((prev) => ({
...prev,
[uuid]: { badge_color: c.badge_color ?? "purple", badge_image_url: c.badge_image_url ?? null },
}));
}
})
.catch(() => {});
});
}, [certAchievements.length]);
return (
<section className="mt-17 bg-muted min-h-full">
<div className="p-6 lg:container lg:max-w-3xl lg:mx-auto space-y-5">
<div className="flex items-center gap-3">
<Button type="button" variant="ghost" size="icon" onClick={() => navigate("/dashboard")}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<div className="flex items-center gap-2">
<h1 className="text-xl font-semibold">My Certificates</h1>
<Badge variant="outline" className="gap-1 text-xs">
<LockIcon className="h-3 w-3" /> Only you
</Badge>
</div>
<p className="text-sm text-muted-foreground">Certificates earned from completed courses.</p>
</div>
</div>
{achievementsLoading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{[...Array(2)].map((_, i) => (
<Skeleton key={i} className="h-80 rounded-2xl" />
))}
</div>
) : certAchievements.length === 0 ? (
<div className="flex flex-col items-center justify-center py-24 text-center">
<Award className="h-10 w-10 text-muted-foreground/40 mb-3" />
<p className="text-sm font-medium">No certificates yet</p>
<p className="text-xs text-muted-foreground">Pass a course assessment to earn your first certificate.</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{certAchievements.map((cert) => {
const uuid = cert.metadata?.courseUuid ?? cert.key.replace("course_completed_", "");
const bData = badgeDataMap[uuid] ?? {};
return (
<CertificateCard
key={cert.achievement_id}
courseTitle={cert.description}
issuedAt={cert.granted_at}
courseUuid={uuid}
badgeColor={bData.badge_color ?? "purple"}
badgeImageUrl={bData.badge_image_url ?? null}
/>
);
})}
</div>
)}
</div>
</section>
);
}
@@ -0,0 +1,206 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowLeft, BookOpen, Layers, FileText, LockIcon, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { useDateFormat } from "@/hooks/useDateFormat";
import api from "@/utils/api.util";
// Polls in the background so items completed elsewhere (another tab, another
// device) show up here without a manual refresh — same convention as
// ClientNotificationContext's badge polling, kept local since only this page
// consumes it.
const POLL_INTERVAL = 30_000;
const EMPTY = { courses: [], units: [], lessons: [] };
const EmptyState = ({ icon: Icon, label }) => (
<div className="flex flex-col items-center justify-center py-20 text-center">
<Icon className="h-10 w-10 text-muted-foreground/40 mb-3" />
<p className="text-sm font-medium">Nothing completed yet</p>
<p className="text-xs text-muted-foreground">{label}</p>
</div>
);
const RowSkeleton = () => (
<div className="flex items-center gap-4 p-4">
<Skeleton className="h-9 w-9 rounded-full shrink-0" />
<div className="space-y-1.5 flex-1">
<Skeleton className="h-3.5 w-48" />
<Skeleton className="h-3 w-32" />
</div>
</div>
);
const CompletedRow = ({ icon: Icon, title, subtitle, completedAt, onClick }) => {
const { fmtDate } = useDateFormat();
return (
<div
className="flex items-center gap-4 p-4 cursor-pointer hover:bg-accent/40 transition-colors"
onClick={onClick}
>
<div className="h-9 w-9 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center shrink-0">
<Icon className="size-4 text-green-700 dark:text-green-400" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{title}</p>
{subtitle && <p className="text-xs text-muted-foreground truncate mt-0.5">{subtitle}</p>}
</div>
<div className="shrink-0 text-right">
<Badge variant="outline" className="gap-1 text-xs">
<CheckCircle2 className="size-3" /> {completedAt ? fmtDate(completedAt) : "—"}
</Badge>
</div>
</div>
);
};
export default function MyCompletedContent() {
const navigate = useNavigate();
const [data, setData] = useState(EMPTY);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
const load = async (silent = false) => {
if (!silent) setLoading(true);
try {
const { data: res } = await api.get("/client/courses/completed");
if (cancelled) return;
setData({
courses: res.data?.courses ?? [],
units: res.data?.units ?? [],
lessons: res.data?.lessons ?? [],
});
} catch {
// silent — keep last known state on a failed poll
} finally {
if (!silent) setLoading(false);
}
};
load();
const interval = setInterval(() => load(true), POLL_INTERVAL);
return () => { cancelled = true; clearInterval(interval); };
}, []);
const total = data.courses.length + data.units.length + data.lessons.length;
return (
<section className="mt-17 bg-muted min-h-full">
<div className="p-6 lg:container lg:max-w-3xl lg:mx-auto space-y-5">
<div className="flex items-center gap-3">
<Button type="button" variant="ghost" size="icon" onClick={() => navigate("/profile")}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<div className="flex items-center gap-2">
<h1 className="text-xl font-semibold">Completed</h1>
<Badge variant="outline" className="gap-1 text-xs">
<LockIcon className="h-3 w-3" /> Only you
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Every lesson, unit, and course you've finished.
</p>
</div>
</div>
<Tabs defaultValue="courses" className="w-full">
<TabsList>
<TabsTrigger value="courses">
Courses {!loading && <Badge variant="secondary" className="ml-1.5">{data.courses.length}</Badge>}
</TabsTrigger>
<TabsTrigger value="units">
Units {!loading && <Badge variant="secondary" className="ml-1.5">{data.units.length}</Badge>}
</TabsTrigger>
<TabsTrigger value="lessons">
Lessons {!loading && <Badge variant="secondary" className="ml-1.5">{data.lessons.length}</Badge>}
</TabsTrigger>
</TabsList>
<TabsContent value="courses">
<div className="rounded-xl border bg-card divide-y">
{loading ? (
[...Array(3)].map((_, i) => <RowSkeleton key={i} />)
) : data.courses.length === 0 ? (
<EmptyState icon={BookOpen} label="Finish a course to see it here." />
) : (
data.courses.map((c, i) => (
<div key={c.course_id}>
<CompletedRow
icon={BookOpen}
title={c.title}
subtitle={c.certificate ? `Certificate ${c.certificate.cert_no}` : null}
completedAt={c.completed_at}
onClick={() => navigate(`/course/${c.course_id}`)}
/>
{i < data.courses.length - 1 && <Separator />}
</div>
))
)}
</div>
</TabsContent>
<TabsContent value="units">
<div className="rounded-xl border bg-card divide-y">
{loading ? (
[...Array(3)].map((_, i) => <RowSkeleton key={i} />)
) : data.units.length === 0 ? (
<EmptyState icon={Layers} label="Finish a unit to see it here." />
) : (
data.units.map((u, i) => (
<div key={u.uuid}>
<CompletedRow
icon={Layers}
title={u.title}
subtitle={u.course ? u.course.title : "Standalone"}
completedAt={u.completed_at}
onClick={() => navigate(`/units/${u.uuid}`)}
/>
{i < data.units.length - 1 && <Separator />}
</div>
))
)}
</div>
</TabsContent>
<TabsContent value="lessons">
<div className="rounded-xl border bg-card divide-y">
{loading ? (
[...Array(3)].map((_, i) => <RowSkeleton key={i} />)
) : data.lessons.length === 0 ? (
<EmptyState icon={FileText} label="Finish a lesson to see it here." />
) : (
data.lessons.map((l, i) => (
<div key={l.uuid}>
<CompletedRow
icon={FileText}
title={l.title}
subtitle={l.course ? l.course.title : "Standalone"}
completedAt={l.completed_at}
onClick={() => navigate(`/lessons/${l.uuid}`)}
/>
{i < data.lessons.length - 1 && <Separator />}
</div>
))
)}
</div>
</TabsContent>
</Tabs>
{!loading && total === 0 && (
<p className="text-center text-xs text-muted-foreground">
Nothing completed yet — your finished lessons, units, and courses will appear here in real time.
</p>
)}
</div>
</section>
);
}
@@ -0,0 +1,283 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowLeft, Bell, LockIcon, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
Pagination, PaginationContent, PaginationItem,
PaginationLink, PaginationPrevious, PaginationNext, PaginationEllipsis,
} from "@/components/ui/pagination";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useClientNotifications } from "@/contexts/ClientNotificationContext";
import { cn } from "@/lib/utils";
import { NotificationIcon, getTypeAccent, timeAgo } from "@/components/generic/notificationDisplay";
import NotificationDetailDialog from "@/components/generic/NotificationDetailDialog";
import { toast } from "sonner";
const PAGE_SIZES = [10, 20, 50];
function ClearAllDialog({ open, onOpenChange, onConfirm, loading }) {
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Clear all notifications</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete all of your notifications. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={loading}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={onConfirm}
disabled={loading}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{loading && <Spinner className="size-4 mr-2" />}
Clear all
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
// Always rendered — even with 0 pages — so the footer stays visible as notifications come in.
function PaginationControls({ page, totalPages, onPage }) {
const pages = [];
for (let i = 1; i <= totalPages; i++) pages.push(i);
const getVisible = () => {
if (totalPages <= 5) return pages;
if (page <= 3) return [1, 2, 3, 4, null, totalPages];
if (page >= totalPages - 2) return [1, null, totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
return [1, null, page - 1, page, page + 1, null, totalPages];
};
return (
<Pagination className="mx-0 w-auto">
<PaginationContent>
<PaginationItem>
<PaginationPrevious
href="#"
onClick={(e) => { e.preventDefault(); if (page > 1) onPage(page - 1); }}
className={page === 1 ? "pointer-events-none opacity-50" : ""}
/>
</PaginationItem>
{getVisible().map((p, i) =>
p === null ? (
<PaginationItem key={`ellipsis-${i}`}>
<PaginationEllipsis />
</PaginationItem>
) : (
<PaginationItem key={p}>
<PaginationLink
href="#"
isActive={p === page}
onClick={(e) => { e.preventDefault(); onPage(p); }}
>
{p}
</PaginationLink>
</PaginationItem>
)
)}
<PaginationItem>
<PaginationNext
href="#"
onClick={(e) => { e.preventDefault(); if (page < totalPages) onPage(page + 1); }}
className={page === totalPages ? "pointer-events-none opacity-50" : ""}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
);
}
export default function Notifications() {
const navigate = useNavigate();
const {
notifications, unseenCount, loading, pagination,
fetchNotifications, markSeen, markAllSeen, clearAll,
} = useClientNotifications();
const [selected, setSelected] = useState(null);
const [clearOpen, setClearOpen] = useState(false);
const [clearing, setClearing] = useState(false);
useEffect(() => { fetchNotifications(1, PAGE_SIZES[0]); }, [fetchNotifications]);
function handleClickNotification(n) {
if (!n.seen) markSeen(n.notification_id);
setSelected(n);
}
function handlePageChange(page) {
fetchNotifications(page, pagination.limit);
}
function handlePageSizeChange(value) {
fetchNotifications(1, Number(value));
}
async function handleClearAll() {
setClearing(true);
const ok = await clearAll();
setClearing(false);
setClearOpen(false);
if (ok) toast("All notifications cleared.");
else toast("Could not clear notifications.");
}
const rangeStart = pagination.total === 0 ? 0 : (pagination.page - 1) * pagination.limit + 1;
const rangeEnd = Math.min(pagination.page * pagination.limit, pagination.total);
return (
<section className="mt-17 bg-muted min-h-full">
<div className="p-6 lg:container lg:max-w-3xl lg:mx-auto space-y-5">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3">
<Button type="button" variant="ghost" size="icon" onClick={() => navigate("/dashboard")}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<div className="flex items-center gap-2">
<h1 className="text-xl font-semibold">Notifications</h1>
<Badge variant="outline" className="gap-1 text-xs">
<LockIcon className="h-3 w-3" /> Only you
</Badge>
</div>
<p className="text-sm text-muted-foreground">
{unseenCount > 0 ? `${unseenCount} unread` : "You're all caught up."}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{unseenCount > 0 && (
<Button variant="outline" size="sm" onClick={markAllSeen}>
Mark all as read
</Button>
)}
{/* <Button
variant="outline"
size="sm"
className="gap-1.5 text-destructive hover:text-destructive"
disabled={notifications.length === 0}
onClick={() => setClearOpen(true)}
>
<Trash2 className="size-3.5" />
Clear all
</Button> */}
</div>
</div>
<div className="rounded-2xl border bg-card overflow-hidden">
{loading && notifications.length === 0 ? (
<div className="p-4 space-y-3">
{[...Array(5)].map((_, i) => (
<Skeleton key={i} className="h-16 rounded-lg" />
))}
</div>
) : notifications.length === 0 ? (
<div className="flex flex-col items-center justify-center py-40 text-center">
<Bell className="h-10 w-10 text-muted-foreground/40 mb-3" />
<p className="text-sm font-medium">No notifications yet</p>
<p className="text-xs text-muted-foreground">You'll see updates about your courses and account here.</p>
</div>
) : (
<ul>
{notifications.map((n, i) => (
<li key={n.notification_id}>
<button
onClick={() => handleClickNotification(n)}
className={cn(
"w-full text-left px-5 py-4 hover:bg-muted/50 transition-colors",
!n.seen && "bg-blue-50 dark:bg-blue-950/20"
)}
>
<div className="flex items-start gap-3">
<div className={cn("mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full", getTypeAccent(n.type))}>
<NotificationIcon type={n.type} className="h-4 w-4" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
{!n.seen && (
<span className="h-2 w-2 shrink-0 rounded-full bg-blue-500" />
)}
<p className="text-sm font-medium truncate">{n.title}</p>
</div>
<p className="text-sm text-muted-foreground mt-0.5 line-clamp-2">{n.message}</p>
<p className="text-[11px] text-muted-foreground mt-1">{timeAgo(n.createdAt)}</p>
</div>
</div>
</button>
{i < notifications.length - 1 && <Separator />}
</li>
))}
</ul>
)}
</div>
{/* Footer stays visible even when the list is empty, so it's ready as notifications come in */}
<div className="flex items-center justify-between gap-3 flex-wrap px-1">
<p className="text-sm text-muted-foreground">
Showing {rangeStart}-{rangeEnd} of {pagination.total}
</p>
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">Rows per page</span>
<Select value={String(pagination.limit)} onValueChange={handlePageSizeChange}>
<SelectTrigger className="h-8 w-[80px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{PAGE_SIZES.map((size) => (
<SelectItem key={size} value={String(size)}>{size}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<PaginationControls
page={pagination.page}
totalPages={pagination.pages}
onPage={handlePageChange}
/>
</div>
</div>
</div>
<NotificationDetailDialog
notification={selected}
onOpenChange={(isOpen) => { if (!isOpen) setSelected(null); }}
/>
<ClearAllDialog
open={clearOpen}
onOpenChange={setClearOpen}
onConfirm={handleClearAll}
loading={clearing}
/>
</section>
);
}
@@ -0,0 +1,514 @@
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
Card, CardContent, CardDescription,
CardFooter, CardHeader, CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import {
BookOpen, Star, Lock, Sparkles,
RotateCcw, Plus, Ban, BadgeCheck,
GraduationCap, Book, Medal,
} from "lucide-react";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { toast } from "sonner";
import api from "@/utils/api.util";
import { PageMeta } from "@/contexts/MetadataContext";
import { useDateFormat } from "@/hooks/useDateFormat";
import { useClientAdvertisements } from "@/contexts/ClientAdvertisementContext";
import { Banner, BannerSkeleton } from "@/components/generic/Blocks/Client/Advertisements/Banner";
import { resolveTierBadge } from "@/utils/tierBadge.util";
import { getBundleContent, overlapsExistingAccess, isPlanCurrent } from "@/utils/planBundle.util";
import { TablePagination } from "@/components/generic/Table/TablePagination";
// ─── Helpers ──────────────────────────────────────────────────────────────────
const REFUND_WINDOW_SECS = 5 * 60;
function formatCountdown(secs) {
const m = Math.floor(secs / 60);
const s = secs % 60;
return `${m}:${String(s).padStart(2, "0")}`;
}
function formatDuration(days, unit) {
if (!days) return null;
const UNIT_TO_DAYS = { minute: 1 / 1440, hour: 1 / 24, day: 1, month: 30, year: 365 };
const multiplier = UNIT_TO_DAYS[unit] ?? 1;
const value = Math.round((days / multiplier) * 1000) / 1000;
const label = unit ?? "day";
return `${value} ${label}${value !== 1 ? "s" : ""}`;
}
// ─── Skeleton ──────────────────────────────────────────────────────────────────
const PlanSkeleton = () => (
<Card className="flex flex-col">
<CardHeader>
<div className="flex items-center justify-between">
<Skeleton className="h-5 w-20" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
<Skeleton className="h-8 w-24 mt-2" />
</CardHeader>
<CardContent className="flex-1 space-y-2">
{Array.from({ length: 3 }).map((_, i) => (
<Skeleton key={i} className="h-4 w-full" />
))}
</CardContent>
<CardFooter>
<Skeleton className="h-9 w-full" />
</CardFooter>
</Card>
);
// ─── Plan Card ────────────────────────────────────────────────────────────────
function ChecklistItem({ item, icon: Icon = Star, onClick }) {
return (
<div
className={`flex items-center gap-2 py-1.5 text-sm ${onClick ? "cursor-pointer hover:underline w-fit" : ""}`}
onClick={onClick}
>
<Icon className="text-blue-500 shrink-0" size={16} />
<span className="line-clamp-1">{item}</span>
</div>
);
}
// Per-bundle-type icon for "Benefits" rows — distinguishes a course
// grant from a unit or lesson grant at a glance instead of a flat checkmark.
const BUNDLE_ITEM_ICONS = { course: GraduationCap, unit: Book, lesson: Medal };
const PlanCard = ({ plan, myTier, tierMap, onSelect, onView, onRefund, refundSecsLeft }) => {
const { fmtCurrency } = useDateFormat();
const [notAvailableOpen, setNotAvailableOpen] = useState(false);
const [previewItem, setPreviewItem] = useState(null);
const { label: tierLabel, cls: badgeCls, panel, gradient } = resolveTierBadge(plan.tier, tierMap);
// Admin-controlled — set from the "Recommended for you" toggle on the
// plan's Edit Plan page, drives the featured frame treatment below.
// Color comes from the plan's own tier category's actual gradient (same
// one used for its badge), not a hardcoded blue or a pale flat tint.
const isRecommended = !!plan.is_recommended;
// "Current" means the user actually purchased THIS exact plan (matched by
// plan_id) and it's still active — NOT just any plan sharing the same tier
// slug. Two different plans can be the same tier (e.g. two Premium
// bundles) and stay independently active (Tier Plans v2).
const isCurrent = isPlanCurrent(plan, myTier);
// Blocked-by-overlap ("already covered") — the plan isn't itself owned,
// but at least one of its bundle items is already granted by something
// else the user holds. Card stays visible but disabled (Scenario 3).
const isBlockedByOverlap = !isCurrent && overlapsExistingAccess(plan, myTier?.my_grants);
const duration = formatDuration(plan.duration_days, plan.duration_unit);
const bundle = getBundleContent(plan);
// Footer button state — always visible when there's an actual action to
// take. A not-yet-owned free plan has nothing to do (it's the default),
// so it's the one case with no button. Base color follows the recommended
// flag (dark = recommended, light = plain), overridden for refund/blocked.
let footerLabel = null;
let footerAction = null;
let footerDisabled = false;
let footerBtnCls = "";
if (isCurrent && refundSecsLeft > 0) {
footerLabel = <><RotateCcw className="size-4" /> Refund ({formatCountdown(refundSecsLeft)})</>;
footerAction = () => onRefund(plan);
footerBtnCls = "bg-red-600 hover:bg-red-700 text-white";
} else if (!plan.is_active) {
footerLabel = <><Ban className="size-4" /> Not Available</>;
footerAction = () => setNotAvailableOpen(true);
footerDisabled = true;
footerBtnCls = "bg-gray-100 text-slate-800 dark:bg-primary dark:text-primary-foreground shadow-none";
} else if (isBlockedByOverlap) {
footerLabel = <><Lock className="size-4" /> Already Included</>;
footerDisabled = true;
footerBtnCls = "bg-gray-100 text-slate-400 shadow-none";
} else if (isCurrent && plan.tier !== "free") {
footerLabel = <><BadgeCheck className="size-4" /> Extend {tierLabel}</>;
footerAction = () => onSelect(plan);
} else if (!isCurrent && plan.tier !== "free") {
footerLabel = <><Sparkles className="size-4" /> Get {tierLabel}</>;
footerAction = () => onSelect(plan);
}
return (
<>
{/* Actual Card */}
<div
className={`flex flex-col h-full rounded-2xl px-2 pb-2 relative ${isRecommended ? `${gradient} border-transparent` : "bg-transparent border border-transparent"
} ${isBlockedByOverlap ? "opacity-60" : ""}`}
>
<div className={`text-center text-sm font-medium my-2 ${isRecommended ? "text-white" : "text-slate-500 invisible"}`}>
Recommended for you
</div>
<div
className={`flex flex-col flex-1 rounded-xl p-6 relative overflow-hidden ${isRecommended ? "bg-card" : "bg-card border border-gray-100 dark:border-blue-900 shadow-sm"
}`}
>
<div className="relative space-y-1.5 max-w-sm">
<h1
className="font-bold text-xl leading-relaxed hover:underline cursor-pointer w-fit"
onClick={() => onView(plan)}
>
{plan.label}
</h1>
<p className="text-sm text-slate-500 leading-relaxed line-clamp-2">
{plan.description || "No information provided"}
</p>
</div>
<div className="relative flex items-center gap-1.5 mt-3 flex-wrap">
{isBlockedByOverlap && (
<Badge variant="secondary" className="gap-1">
<Lock className="size-3" />
Already Included
</Badge>
)}
</div>
<div className="relative flex flex-col items-start gap-4 my-6">
<div className="flex items-end gap-1">
<h1 className="text-5xl font-bold">
{fmtCurrency(plan.price, plan.currency)}
</h1>
{duration && <p className="text-muted-foreground mb-1">/ {duration}</p>}
</div>
<div className="w-full h-px bg-gray-200" />
<div className="flex flex-col gap-1 items-start w-full">
<h1 className="font-medium text-sm text-muted-foreground mb-1">
{bundle ? `Bundle (${bundle.noun}s):` : "Bundle:"}
</h1>
<div className="w-full">
{bundle ? (
bundle.items.map((item) => (
<ChecklistItem
key={item[bundle.idKey]}
item={item.title}
icon={BUNDLE_ITEM_ICONS[bundle.type]}
onClick={() => setPreviewItem(item)}
/>
))
) : !plan.description ? (
<p className="text-sm text-slate-500 py-1.5">
Access to all free course content.
</p>
) : null}
</div>
</div>
</div>
{footerLabel && (
<Button
className={`w-full mt-auto ${footerBtnCls}`}
size="lg"
disabled={footerDisabled}
onClick={footerAction}
>
{footerLabel}
</Button>
)}
</div>
</div>
{/* ── Not Available Dialog ──────────────────────────────────────── */}
<Dialog open={notAvailableOpen} onOpenChange={setNotAvailableOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Unavailable</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground py-1">
The <span className="font-medium text-foreground">{plan.label}</span> plan
is currently not available for purchase. Please check back later.
</p>
<DialogFooter>
<Button variant="outline" onClick={() => setNotAvailableOpen(false)}>
Got it
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* ── Bundle Item Preview ─────────────────────────────────────────── */}
<ResponsiveModal
open={!!previewItem}
onOpenChange={(v) => !v && setPreviewItem(null)}
title={previewItem?.title}
description={`Upgrade your plan to access this ${bundle?.noun?.toLowerCase() ?? "item"}.`}
>
<div className="py-2">
<div className={`p-5 rounded-2xl border ${panel.bg} ${panel.border}`}>
<div className="flex items-center gap-3 mb-3">
<Badge className={badgeCls}>
<Lock className="size-3" /> {tierLabel}
</Badge>
</div>
<ul className="space-y-2 text-sm [&_svg]:size-4 mb-4">
<li className="flex items-center gap-2"><Star className="text-blue-500" /> Access to {tierLabel} content</li>
<li className="flex items-center gap-2"><Star className="text-blue-500" /> Certificates & achievements</li>
</ul>
<p className="text-sm text-muted-foreground">
Upgrade to a <span className="font-medium">{tierLabel}</span> plan to unlock this {bundle?.noun?.toLowerCase() ?? "item"}.
</p>
</div>
</div>
</ResponsiveModal>
</>
);
};
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function PlanList() {
const navigate = useNavigate();
const { plans, plansLoading, myTier, tierLoading, tierMap, getPlans, getMyTier, getTierCategories, resetMyTier } = useClientTiers();
const { fmtDate, fmtCurrency } = useDateFormat();
const { adLists, listLoading: adLoading, getActiveAdvertisementList, handleAdCtaClick } = useClientAdvertisements();
// Plans are fetched all at once — pagination here just slices the
// already-loaded list client-side, it doesn't refetch.
const [plansPage, setPlansPage] = useState(1);
const [plansLimit, setPlansLimit] = useState(10);
const [refundPlan, setRefundPlan] = useState(null); // plan being refunded
const [refundLoading, setRefundLoading] = useState(false);
// Keyed by plan_id, not tier slug — two different plans can share a tier
// (Tier Plans v2) and each has its own independent refund window based on
// its own starts_at.
const [refundSecsLeftByTier, setRefundSecsLeftByTier] = useState({});
const refundTimerRef = useRef(null);
useEffect(() => {
getPlans();
getMyTier();
getTierCategories();
getActiveAdvertisementList("tier_plans.banner");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [getPlans, getMyTier]);
const bannerAds = adLists["tier_plans.banner"] ?? [];
useEffect(() => {
clearInterval(refundTimerRef.current);
const activeTiers = myTier?.active_tiers ?? [];
if (!activeTiers.length) { setRefundSecsLeftByTier({}); return; }
const compute = () => {
const map = {};
for (const t of activeTiers) {
if (!t.starts_at || t.plan_id == null) continue;
const elapsed = Math.floor((Date.now() - new Date(t.starts_at).getTime()) / 1000);
map[t.plan_id] = Math.max(0, REFUND_WINDOW_SECS - elapsed);
}
return map;
};
setRefundSecsLeftByTier(compute());
refundTimerRef.current = setInterval(() => {
setRefundSecsLeftByTier(compute());
}, 1000);
return () => clearInterval(refundTimerRef.current);
}, [myTier?.active_tiers]);
const handleViewPlan = (plan) => navigate(`/subscriptions/view/${plan.plan_id}`);
const handleSelectPlan = (plan) => navigate(`/subscriptions/checkout?plan_id=${plan.plan_id}`);
const handleRefundClick = (plan) => setRefundPlan(plan);
// The plan being refunded may not be the user's "best" tier (myTier), since
// more than one can be active at once — resolve its own record by plan_id
// (not tier slug, since two plans can share a tier) for its own
// expires_at/refund window instead of assuming it matches myTier.
const refundPlanTier = (myTier?.active_tiers ?? []).find((t) => t.plan_id != null && String(t.plan_id) === String(refundPlan?.plan_id)) ?? null;
const refundPlanSecsLeft = refundSecsLeftByTier[refundPlan?.plan_id] ?? 0;
const isOnlyActiveTier = (myTier?.active_tiers ?? []).length <= 1;
const plansTotalPages = Math.max(1, Math.ceil(plans.length / plansLimit));
const pagedPlans = plans.slice((plansPage - 1) * plansLimit, plansPage * plansLimit);
const plansPagination = {
page: plansPage,
limit: plansLimit,
totalPages: plansTotalPages,
totalRecords: plans.length,
hasPrevPage: plansPage > 1,
hasNextPage: plansPage < plansTotalPages,
};
const handlePlansPageSize = (size) => {
setPlansLimit(size);
setPlansPage(1);
};
const handleConfirmRefund = async () => {
setRefundLoading(true);
try {
// plan_id disambiguates which active subscription to refund now that a
// user can hold more than one concurrently.
const { data } = await api.post("/client/tiers/checkout/refund", { plan_id: refundPlan?.plan_id });
toast(data.message ?? "Refund processed. Your access has been revoked.");
setRefundPlan(null);
resetMyTier();
getMyTier();
} catch (err) {
toast(err?.response?.data?.message ?? "Refund failed. Please try again.");
} finally {
setRefundLoading(false);
}
};
return (
<div className="mt-17">
<PageMeta title="Subscriptions - STARR" description="Browse available subscription plans." />
<div className="relative overflow-hidden bg-gradient-to-b from-primary/5 via-background to-background min-h-screen">
<div className="lg:container lg:mx-auto space-y-8 p-6">
<div className="relative xs:pt-2 lg:pt-8 space-y-4">
{/* Advertisement Banner */}
{/* {adLoading["tier_plans.banner"] ? (
<BannerSkeleton />
) : (
<Banner ads={bannerAds} onCtaClick={handleAdCtaClick} />
)} */}
<Banner ads={bannerAds} onCtaClick={handleAdCtaClick} />
{/* Section Header */}
<div className="relative flex flex-col items-center gap-4 mt-6">
<div className="text-center my-8">
<h2 className="text-3xl font-bold">Available Subscriptions</h2>
<p className="text-muted-foreground mt-2">
Choose a subscription that matches your goals.
</p>
</div>
</div>
{/* Plan Cards */}
{plansLoading || tierLoading ? (
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
{Array.from({ length: 3 }).map((_, i) => <PlanSkeleton key={i} />)}
</div>
) : plans.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20">
<BookOpen className="size-10 mb-3" />
<p className="text-sm">No plans available at the moment.</p>
</div>
) : (
<>
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
{pagedPlans.map((plan) => (
<PlanCard
key={plan.plan_id}
plan={plan}
myTier={myTier}
tierMap={tierMap}
onSelect={handleSelectPlan}
onView={handleViewPlan}
onRefund={handleRefundClick}
refundSecsLeft={refundSecsLeftByTier[plan.plan_id] ?? 0}
/>
))}
</div>
<TablePagination
pagination={plansPagination}
onPageChange={setPlansPage}
rowCount={pagedPlans.length}
totalRecords={plans.length}
onPageSizeChange={handlePlansPageSize}
recordLabel="plan"
/>
</>
)}
</div>
</div>
</div>
{/* ── Refund Confirmation Modal ──────────────────────────────────── */}
<ResponsiveModal
open={!!refundPlan}
onOpenChange={(v) => !v && setRefundPlan(null)}
title="Request Refund"
description={`Are you sure you want to refund your ${refundPlan?.label ?? "current"} plan?`}
footer={
<>
<Button
variant="outline"
onClick={() => setRefundPlan(null)}
disabled={refundLoading}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={handleConfirmRefund}
disabled={refundLoading || refundPlanSecsLeft === 0}
>
<RotateCcw className="size-4" />
{refundLoading ? "Processing..." : "Confirm Refund"}
</Button>
</>
}
>
<div className="space-y-4 py-2">
<div className="rounded-xl border bg-muted/60 p-4 space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Plan</span>
<span className="font-medium capitalize">{refundPlan?.tier}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Refund amount</span>
<span className="font-medium">
{refundPlan ? fmtCurrency(refundPlan.price, refundPlan.currency) : "—"}
</span>
</div>
{refundPlanTier?.expires_at && (
<div className="flex justify-between">
<span className="text-muted-foreground">Access until</span>
<span className="font-medium">
{fmtDate(refundPlanTier.expires_at)}
</span>
</div>
)}
<div className="flex justify-between items-center pt-1 border-t">
<span className="text-muted-foreground">Refund window</span>
{refundPlanSecsLeft > 0 ? (
<span className="font-semibold tabular-nums text-destructive">
{formatCountdown(refundPlanSecsLeft)} remaining
</span>
) : (
<span className="font-semibold text-muted-foreground">Expired</span>
)}
</div>
</div>
{refundPlanSecsLeft > 0 ? (
<p className="text-sm text-muted-foreground">
Your refund will be processed through PayPal.{" "}
<span className="font-medium text-foreground">
Access will be revoked immediately
</span>{" "}
{isOnlyActiveTier
? "and your account will be downgraded to Free."
: "Your other active plan(s) will be unaffected."}
</p>
) : (
<p className="text-sm text-destructive">
The 5-minute refund window has expired. Refunds are no longer available for this payment.
</p>
)}
</div>
</ResponsiveModal>
</div>
);
}
@@ -0,0 +1,784 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
Edit, BookOpen, Award, Trophy, Shield, Star, Zap, Target, BadgeCheck, Medal, Flame, LockIcon, Camera, ChevronRight, Download, RefreshCcw
} from "lucide-react";
import * as LucideIcons from "lucide-react";
import { getTierColor } from "@/utils/tierColors";
import AvatarUploadDialog from "@/components/generic/AvatarUploadDialog";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import { useProfile } from "@/contexts/ProfileProvider";
import { useAuth } from "@/contexts/AuthContext";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { useDateFormat } from "@/hooks/useDateFormat";
import api from "@/utils/api.util";
import { toast } from "sonner";
import CourseBadge from "@/modules/admin/components/courses/CourseBadge";
// ─── Tier badge fallbacks (used when no policy is configured in DB) ───────────
const TIER_BADGE_FALLBACKS = {
free: {
src: "/badges/free-access-badge-leaf-flaticon.svg",
label: "Free",
description: "Active member using the Free Plan.",
information: "Free users have access to the platform's core features without a subscription.",
},
premium: {
src: "/badges/premium-badge-sheriff-flaticon.svg",
label: "Premium",
description: "Subscriber with access to premium learning content.",
information: "Premium members can access all premium courses available on the platform.",
},
exclusive: {
src: "/badges/exclusive-award-flaticon.svg",
label: "Exclusive",
description: "Premium member with access to exclusive course content.",
information: "This badge represents a member with access to exclusive courses.",
},
};
const EARLY_ACCESS_FALLBACK = {
src: "/badges/early-access-badge-percent-flaticon.svg",
label: "Early Access",
description: "Registered during the Philproperties beta period.",
information: "Exclusive to members who registered before Dec 31, 2026.",
};
// Renders either a Lucide icon badge or an image badge.
function TierBadgeDisplay({ badge, className }) {
if (badge?.src) return <img src={badge.src} alt={badge.label} className={className} />;
if (badge?.icon) {
const Icon = LucideIcons[badge.icon];
if (!Icon) return null;
const swatch = getTierColor(badge.colorKey ?? "green").swatch;
return <Icon className={className} style={{ color: swatch }} />;
}
return null;
}
function resolveTierBadge(myTier) {
const tier = myTier?.tier ?? "free";
const category = myTier?.plan?.category ?? myTier?.category ?? null;
if (category) {
const hasBadge = category.badgeAsset || category.badge_icon || category.badge_label;
if (hasBadge) {
return {
src: category.badgeAsset?.file_url ?? null,
icon: !category.badgeAsset ? (category.badge_icon ?? null) : null,
colorKey: category.color ?? "green",
label: category.badge_label ?? category.name ?? tier,
description: "",
information: category.description ?? "",
};
}
}
return TIER_BADGE_FALLBACKS[tier] ?? TIER_BADGE_FALLBACKS.free;
}
function resolveEarlyAccessBadge(systemBadges) {
const found = systemBadges?.find((b) => b.key === "early_access");
if (!found) return EARLY_ACCESS_FALLBACK;
return {
src: found.asset?.file_url ?? EARLY_ACCESS_FALLBACK.src,
label: found.label ?? EARLY_ACCESS_FALLBACK.label,
description: found.description ?? EARLY_ACCESS_FALLBACK.description,
information: found.information ?? EARLY_ACCESS_FALLBACK.information,
};
}
// ─── Achievement icon map (by key) ───────────────────────────────────────────
const ACHIEVEMENT_ICONS = {
early_access: Star,
premium_first_time: BadgeCheck,
exclusive_first_time: Medal,
first_course_completed: BookOpen,
courses_completed_5: Flame,
courses_completed_10: Zap,
perfect_quiz_score: Target,
profile_completed: Shield,
first_referral: Award,
};
const getFallbackIcon = (type) => type === "badge" ? BadgeCheck : Trophy;
// ─── Certificate landscape card (profile preview) ────────────────────────────
const LandscapeCertCard = ({ courseTitle, issuedAt, courseUuid, badgeColor, badgeImageUrl }) => {
const [downloading, setDownloading] = useState(false);
const { fmtDate } = useDateFormat();
const issuedLabel = issuedAt ? fmtDate(issuedAt) : "—";
const handleDownload = async () => {
setDownloading(true);
try {
const res = await api.get(`/client/certificates/${courseUuid}`, { responseType: "blob" });
const disposition = res.headers["content-disposition"] ?? "";
const match = disposition.match(/filename="([^"]+)"/);
const filename = match ? match[1] : `certificate-${courseUuid}.pdf`;
const url = URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
} catch {
toast("Could not download certificate.");
} finally {
setDownloading(false);
}
};
return (
<div className="rounded-xl border bg-muted/40 p-3.5 flex items-center gap-3.5">
<CourseBadge mini color={badgeColor ?? "purple"} imageUrl={badgeImageUrl ?? null} />
<div className="flex-1 min-w-0">
<p className="text-[10px] uppercase tracking-widest text-muted-foreground font-semibold">Certificate of Completion</p>
<p className="text-sm font-semibold truncate mt-0.5">{courseTitle}</p>
<div className="flex items-center gap-2 mt-1">
<span className="text-xs text-muted-foreground">Issued {issuedLabel}</span>
<Badge className="gap-1 text-[10px] py-0 bg-green-100 text-green-700 border-green-400 dark:bg-green-900/40 dark:text-green-400 dark:border-green-700">
<BadgeCheck className="size-2.5" /> Verified
</Badge>
</div>
</div>
<Button size="sm" variant="outline" className="shrink-0" onClick={handleDownload} disabled={downloading}>
<Download className="size-3.5" />
{downloading ? "…" : "PDF"}
</Button>
</div>
);
};
// ─── Component ───────────────────────────────────────────────────────────────
const ProfilePage = () => {
const navigate = useNavigate();
const { user } = useAuth();
const { fmtDate } = useDateFormat();
const {
profile, profileLoading, getProfile,
achievements, achievementsLoading, getAchievements,
fullName, avatarUrl, occupation,
uploadAvatar, deleteAvatar, avatarLoading,
} = useProfile();
const [avatarDialogOpen, setAvatarDialogOpen] = useState(false);
const { myTier, tierLoading, getMyTier, systemBadges, getSystemBadges } = useClientTiers();
const [badgeOpen, setBadgeOpen] = useState(false);
const [selectedBadge, setSelectedBadge] = useState(null);
const [badgeSrc, setBadgeSrc] = useState(null);
const [firstCertBadge, setFirstCertBadge] = useState({ color: "purple", imageUrl: null });
useEffect(() => {
const asset = myTier?.plan?.category?.badgeAsset ?? myTier?.category?.badgeAsset
if (!asset) { setBadgeSrc(null); return }
if (asset.storage_provider !== 's3') { setBadgeSrc(asset.file_url ?? null); return }
api.post('/client/media/token', { asset_id: asset.asset_id })
.then(({ data }) => {
const base = (import.meta.env.VITE_API_URL ?? '').replace(/\/$/, '')
setBadgeSrc(`${base}/client/media/stream/${data?.data?.token}`)
})
.catch(() => setBadgeSrc(null))
}, [myTier])
const [inProgressCourses, setInProgressCourses] = useState([]);
const [inProgressCoursesLoading, setInProgressCoursesLoading] = useState(false);
const [pendingModalOpen, setPendingModalOpen] = useState(false);
const [pendingModalCourse, setPendingModalCourse] = useState(null);
const [completedTotal, setCompletedTotal] = useState(0);
const [completedLoading, setCompletedLoading] = useState(false);
useEffect(() => {
getProfile();
getAchievements();
getMyTier();
getSystemBadges();
(async () => {
setInProgressCoursesLoading(true);
try {
const { data } = await api.get("/client/courses/in-progress");
setInProgressCourses(data.data ?? []);
} catch {
// silent — empty state handles it
} finally {
setInProgressCoursesLoading(false);
}
})();
(async () => {
setCompletedLoading(true);
try {
const { data } = await api.get("/client/courses/completed");
const counts = data.data?.counts ?? {};
setCompletedTotal((counts.courses ?? 0) + (counts.units ?? 0) + (counts.lessons ?? 0));
} catch {
// silent — empty state handles it
} finally {
setCompletedLoading(false);
}
})();
}, []);
// ── Derived ────────────────────────────────────────────────────────────────
const tier = myTier?.tier ?? user?.tier ?? "free";
const tierBadge = { ...resolveTierBadge(myTier), ...(badgeSrc ? { src: badgeSrc } : {}) };
const earlyAccessBadge = resolveEarlyAccessBadge(systemBadges);
const displayName = fullName || user?.personal_info?.name?.full_name || user?.email?.split("@")[0] || "—";
const initials = displayName.split(" ").map((w) => w[0]).join("").slice(0, 2).toUpperCase();
const tierRank = { free: 0, premium: 1, exclusive: 2 };
const userRank = tierRank[tier] ?? 0;
const certAchievements = achievements.filter((a) => a.key.startsWith("course_completed_"));
// Fetch badge color/image for the first certificate shown in the profile preview
useEffect(() => {
if (!certAchievements.length) return;
const first = certAchievements[0];
const uuid = first.metadata?.courseUuid ?? first.key.replace("course_completed_", "");
if (!uuid) return;
const STREAM_BASE = `${import.meta.env.VITE_API_URL}/client/media/stream`;
api.get(`/client/courses/uuid/${uuid}`)
.then(({ data }) => {
const c = data.data ?? data;
if (!c) return;
if (c.badge_asset_id) {
api.post("/client/media/token", { asset_id: c.badge_asset_id })
.then(({ data: td }) => {
const token = td.data?.token;
setFirstCertBadge({
color: c.badge_color ?? "purple",
imageUrl: token ? `${STREAM_BASE}/${token}` : null,
});
})
.catch(() => setFirstCertBadge({ color: c.badge_color ?? "purple", imageUrl: null }));
} else {
setFirstCertBadge({ color: c.badge_color ?? "purple", imageUrl: c.badge_image_url ?? null });
}
})
.catch(() => {});
}, [certAchievements.length]);
const hasEarlyAccess = achievements.some((a) => a.key === "early_access");
// Premium badge only shows when currently exclusive (went through premium to get here)
const hasPremiumBadge = achievements.some((a) => a.key === "premium_first_time") && userRank >= 2;
// Exclusive badge only shows when currently exclusive
const hasExclusiveBadge = achievements.some((a) => a.key === "exclusive_first_time") && userRank >= 2;
const badgesReady = !tierLoading && !achievementsLoading;
// Build badge object with earnedAt from achievements for modal
const getBadgeWithDate = (achievementKey, tierKey) => {
const achievement = achievements.find((a) => a.key === achievementKey);
const earnedAt = achievement?.granted_at ? fmtDate(achievement.granted_at) : null;
return { ...TIER_BADGE_FALLBACKS[tierKey], earnedAt };
};
const getEarlyAccessBadge = () => {
const achievement = achievements.find((a) => a.key === "early_access");
const earnedAt = achievement?.granted_at ? fmtDate(achievement.granted_at) : null;
return { ...earlyAccessBadge, earnedAt };
};
const getActiveTierBadgeWithDate = () => {
const achievementKey = tier === "premium"
? "premium_first_time"
: tier === "exclusive"
? "exclusive_first_time"
: null;
return achievementKey ? getBadgeWithDate(achievementKey, tier) : tierBadge;
};
return (
<div className="mt-17 bg-muted min-h-screen">
<div className="p-6 lg:container lg:max-w-5xl lg:mx-auto space-y-4">
{/* ── Header card ──────────────────────────────────────────────────── */}
<Card>
<CardContent className="py-2 px-6">
<div className="flex items-center gap-5">
<div className="relative">
<Avatar className="h-20 w-20">
<AvatarImage src={avatarUrl || ""} />
<AvatarFallback className="text-lg">{initials}</AvatarFallback>
</Avatar>
<button
className="absolute -bottom-1 -right-1 p-1.5 rounded-full bg-primary text-primary-foreground shadow hover:opacity-80 transition-opacity"
onClick={() => setAvatarDialogOpen(true)}
>
<Camera size={11} />
</button>
</div>
<div className="flex-1">
<div className="flex items-center gap-2">
{profileLoading ? (
<Skeleton className="h-4 w-32" />
) : (
<p className="text-base font-medium">{displayName}</p>
)}
{/* ── Badges ─────────────────────────────────────────────── */}
{badgesReady ? (
<div className="flex items-center gap-1.5 select-none">
{/* Early access — always show if earned */}
{hasEarlyAccess && (
<Tooltip>
<TooltipTrigger asChild>
<img
className="size-4.5 cursor-pointer"
src={earlyAccessBadge.src}
alt={earlyAccessBadge.label}
onClick={() => { setSelectedBadge(getEarlyAccessBadge()); setBadgeOpen(true); }}
/>
</TooltipTrigger>
<TooltipContent><p>{earlyAccessBadge.label}</p></TooltipContent>
</Tooltip>
)}
{/* Premium badge — only when currently exclusive */}
{hasPremiumBadge && (
<Tooltip>
<TooltipTrigger asChild>
<img
className="size-4.5 cursor-pointer"
src={TIER_BADGE_FALLBACKS.premium.src}
alt="Premium"
onClick={() => { setSelectedBadge(getBadgeWithDate("premium_first_time", "premium")); setBadgeOpen(true); }}
/>
</TooltipTrigger>
<TooltipContent><p>Premium</p></TooltipContent>
</Tooltip>
)}
{/* Exclusive badge — only when currently exclusive */}
{hasExclusiveBadge && (
<Tooltip>
<TooltipTrigger asChild>
<img
className="size-4.5 cursor-pointer"
src={TIER_BADGE_FALLBACKS.exclusive.src}
alt="Exclusive"
onClick={() => { setSelectedBadge(getBadgeWithDate("exclusive_first_time", "exclusive")); setBadgeOpen(true); }}
/>
</TooltipTrigger>
<TooltipContent><p>Exclusive</p></TooltipContent>
</Tooltip>
)}
{/* Current active tier badge — always shown */}
{/* For free tier, show free badge. For premium/exclusive already shown above via hasPremiumBadge/hasExclusiveBadge */}
{userRank === 0 && (
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-pointer" onClick={() => { setSelectedBadge(tierBadge); setBadgeOpen(true); }}>
<TierBadgeDisplay badge={tierBadge} className="size-4.5" />
</span>
</TooltipTrigger>
<TooltipContent><p>{tierBadge.label}</p></TooltipContent>
</Tooltip>
)}
{/* For premium tier without achievement yet (edge case) */}
{userRank === 1 && !hasPremiumBadge && (
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-pointer" onClick={() => { setSelectedBadge(getActiveTierBadgeWithDate()); setBadgeOpen(true); }}>
<TierBadgeDisplay badge={tierBadge} className="size-4.5" />
</span>
</TooltipTrigger>
<TooltipContent><p>{tierBadge.label}</p></TooltipContent>
</Tooltip>
)}
</div>
) : (
<Skeleton className="h-4.5 w-16 rounded" />
)}
</div>
<p className="text-sm text-muted-foreground mb-2">{user?.email ?? "—"}</p>
<div className="flex items-center gap-2 flex-wrap">
{occupation && <Badge variant="outline">{occupation}</Badge>}
</div>
</div>
<Button variant="outline" size="sm" onClick={() => navigate("/profile/edit")}>
<Edit />
Edit profile
</Button>
</div>
</CardContent>
</Card>
{/* ── Badge modal ───────────────────────────────────────────────────── */}
<ResponsiveModal
open={badgeOpen}
onOpenChange={setBadgeOpen}
title="Badge"
description={selectedBadge?.description}
footer={
<Button variant="outline" onClick={() => setBadgeOpen(false)}>Close</Button>
}
>
<div className="flex flex-col items-center gap-4 py-2">
{(selectedBadge?.src || selectedBadge?.icon) && (
<TierBadgeDisplay badge={selectedBadge} className="size-16" />
)}
<div className="text-center space-y-1">
<p className="text-sm font-medium">{selectedBadge?.label}</p>
{selectedBadge?.earnedAt && (
<p className="text-sm text-muted-foreground">{selectedBadge.earnedAt}</p>
)}
</div>
<Separator className="w-full" />
<p className="text-sm">{selectedBadge?.information}</p>
</div>
</ResponsiveModal>
{/* ── Two columns ──────────────────────────────────────────────────── */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Left column */}
<div className="space-y-4">
{/* Learning progress */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium flex items-center gap-2">
<BookOpen className="size-4" />
Learning progress
<Badge><LockIcon className="size-3" /> Only you</Badge>
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{inProgressCoursesLoading ? (
<div className="space-y-3">
{[...Array(2)].map((_, i) => (
<div key={i} className="space-y-1.5">
<Skeleton className="h-3.5 w-40" />
<Skeleton className="h-1.5 w-full rounded-full" />
</div>
))}
</div>
) : inProgressCourses.length === 0 ? (
<p className="text-sm text-muted-foreground">No courses in progress.</p>
) : (
inProgressCourses.slice(0, 2).map((course, i) => {
const pct = course.lessons_total > 0
? Math.round((course.lessons_completed / course.lessons_total) * 100)
: 0;
const quizPending = course.reading_status === 'completed';
return (
<div key={course.course_id} className="space-y-2">
<div className="flex items-center justify-between mb-1.5">
<p className="text-sm font-medium leading-none truncate flex-1 mr-3">{course.title}</p>
<span className="text-sm text-muted-foreground shrink-0">{pct}%</span>
</div>
<Progress value={pct} className="h-1.5" />
{quizPending ? (
<Badge
className="select-none cursor-pointer"
variant="outline"
onClick={() => { setPendingModalCourse(course); setPendingModalOpen(true); }}
>
<RefreshCcw /> Quiz / Assessment Pending
</Badge>
) : (
<p className="text-xs text-muted-foreground mt-1">
{course.lessons_completed} / {course.lessons_total} lessons
</p>
)}
{i < Math.min(inProgressCourses.length, 2) - 1 && <Separator className="mt-3" />}
</div>
);
})
)}
</CardContent>
</Card>
{/* Quiz / Assessment Pending detail modal */}
<ResponsiveModal
open={pendingModalOpen}
onOpenChange={(v) => { setPendingModalOpen(v); if (!v) setPendingModalCourse(null); }}
title={pendingModalCourse?.title ?? 'Pending Items'}
description="You've finished reading all lessons. Complete the items below to earn your certificate."
hideDrawerClose={false}
footer={
<Button
className="w-full sm:w-auto"
onClick={() => {
setPendingModalOpen(false);
navigate(`/course/${pendingModalCourse?.course_id}/unit`);
}}
>
Go to Course
</Button>
}
>
{pendingModalCourse && (() => {
const { pending_quizzes = [], pending_assessment, assessment_configured = true } = pendingModalCourse;
const hasQuizzes = pending_quizzes.length > 0;
const hasAssessment = !!pending_assessment;
if (!hasQuizzes && !hasAssessment && assessment_configured) {
return (
<p className="text-sm text-muted-foreground py-2">No pending items found.</p>
);
}
return (
<div className="space-y-4 py-1">
{!assessment_configured && (
<p className="text-sm text-muted-foreground">
You've finished all lessons, but this course's final assessment hasn't been set up yet.
Check back once it's available — the course can't be marked complete until then.
</p>
)}
{hasQuizzes && (
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2">Unit Quizzes</p>
<ul className="space-y-2">
{pending_quizzes.map((q) => (
<li key={q.quiz_id} className="flex items-start justify-between rounded-lg border px-3 py-2.5 gap-3">
<div className="min-w-0">
<p className="text-sm font-medium leading-none truncate">{q.title || 'Unit Quiz'}</p>
<p className="text-xs text-muted-foreground mt-0.5">{q.unit_title}</p>
</div>
<div className="shrink-0 text-right space-y-0.5">
<p className="text-xs text-muted-foreground">Pass: {q.passing_score}%</p>
<p className="text-xs text-muted-foreground">
{q.attempt_count === 0 ? 'Not attempted' : `${q.attempt_count} attempt${q.attempt_count === 1 ? '' : 's'}`}
</p>
{q.is_required && (
<span className="inline-block rounded-full bg-amber-100 dark:bg-amber-900/30 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-400">
Required
</span>
)}
</div>
</li>
))}
</ul>
</div>
)}
{hasAssessment && (
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2">Final Assessment</p>
<div className="flex items-start justify-between rounded-lg border px-3 py-2.5 gap-3">
<div className="min-w-0">
<p className="text-sm font-medium leading-none truncate">{pending_assessment.title || 'Course Assessment'}</p>
</div>
<div className="shrink-0 text-right space-y-0.5">
<p className="text-xs text-muted-foreground">Pass: {pending_assessment.passing_score}%</p>
<p className="text-xs text-muted-foreground">
{pending_assessment.attempt_count === 0 ? 'Not attempted' : `${pending_assessment.attempt_count} attempt${pending_assessment.attempt_count === 1 ? '' : 's'}`}
</p>
{pending_assessment.is_required && (
<span className="inline-block rounded-full bg-amber-100 dark:bg-amber-900/30 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-400">
Required
</span>
)}
</div>
</div>
</div>
)}
</div>
);
})()}
</ResponsiveModal>
{/* Account info */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Account info</CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Member since</span>
<span className="font-medium">
{profile?.createdAt ? fmtDate(profile.createdAt) : "—"}
</span>
</div>
<Separator />
<div className="flex justify-between items-center">
<span className="text-muted-foreground">Plan</span>
{tierLoading ? (
<Skeleton className="h-5 w-20" />
) : (
<span className="font-medium capitalize">
{tier}{myTier?.expires_at && ` · until ${fmtDate(myTier.expires_at)}`}
</span>
)}
</div>
</CardContent>
</Card>
</div>
{/* Right column */}
<div className="space-y-4">
{/* Certificates — preview + full list at /certificates */}
<Card>
<CardContent
className="flex items-center justify-between cursor-pointer hover:bg-accent/40 transition-colors rounded-t-lg"
onClick={() => navigate("/certificates")}
>
<div className="flex items-center gap-2">
<Award className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">My Certificates</span>
<Badge><LockIcon className="size-3" /> Only you</Badge>
</div>
<div className="flex items-center gap-2">
{achievementsLoading ? (
<Skeleton className="h-5 w-5 rounded-full" />
) : certAchievements.length > 0 ? (
<Badge variant="secondary" className="text-xs">{certAchievements.length}</Badge>
) : null}
<ChevronRight className="h-4 w-4 text-muted-foreground" />
</div>
</CardContent>
{!achievementsLoading && certAchievements.length > 0 && (
<CardContent className="pt-0">
<LandscapeCertCard
courseTitle={certAchievements[0].description}
issuedAt={certAchievements[0].granted_at}
courseUuid={certAchievements[0].metadata?.courseUuid ?? certAchievements[0].key.replace("course_completed_", "")}
badgeColor={firstCertBadge.color}
badgeImageUrl={firstCertBadge.imageUrl}
/>
</CardContent>
)}
</Card>
{/* Achievements — latest 2, full list at /achievements */}
<Card>
<CardContent
className="flex items-center justify-between cursor-pointer hover:bg-accent/40 transition-colors rounded-t-lg"
onClick={() => navigate("/achievements")}
>
<div className="flex items-center gap-2">
<Trophy className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">Achievements</span>
</div>
<div className="flex items-center gap-2">
{achievementsLoading ? (
<Skeleton className="h-5 w-5 rounded-full" />
) : achievements.length > 0 ? (
<Badge variant="secondary" className="text-xs">{achievements.length}</Badge>
) : null}
<ChevronRight className="h-4 w-4 text-muted-foreground" />
</div>
</CardContent>
<CardContent className="pt-0">
{achievementsLoading ? (
<div className="space-y-3">
{[...Array(2)].map((_, i) => (
<div key={i} className="flex items-center gap-3">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="space-y-1 flex-1">
<Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-48" />
</div>
</div>
))}
</div>
) : achievements.length > 0 ? (() => {
const latest = [...achievements]
.sort((a, b) => new Date(b.granted_at) - new Date(a.granted_at))
.slice(0, 2);
return (
<div className="space-y-3">
{latest.map((item, i) => {
const Icon = ACHIEVEMENT_ICONS[item.key] ?? getFallbackIcon(item.type);
return (
<div key={item.achievement_id ?? i}>
<div className="flex items-center gap-3">
<div className="h-8 w-8 rounded-full bg-secondary flex items-center justify-center shrink-0">
<Icon className="size-4 text-secondary-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium">{item.label}</p>
<p className="text-xs text-muted-foreground">{item.description}</p>
{item.granted_at && (
<p className="text-xs mt-0.5">
{fmtDate(item.granted_at)}
</p>
)}
</div>
</div>
{i < latest.length - 1 && <Separator className="mt-3" />}
</div>
);
})}
</div>
);
})() : (
<div className="flex flex-col items-center justify-center py-8 gap-2 text-center">
<Shield className="h-8 w-8 text-muted-foreground/40" />
<p className="text-sm font-medium text-muted-foreground">Nothing to show yet</p>
<p className="text-xs text-muted-foreground/60">
Complete more courses to unlock achievements.
</p>
</div>
)}
</CardContent>
</Card>
{/* Completed — live count, full list at /completed */}
<Card>
<CardContent
className="flex items-center justify-between cursor-pointer hover:bg-accent/40 transition-colors rounded-lg"
onClick={() => navigate("/completed")}
>
<div className="flex items-center gap-2">
<BookOpen className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">Completed</span>
<Badge><LockIcon className="size-3" /> Only you</Badge>
</div>
<div className="flex items-center gap-2">
{completedLoading ? (
<Skeleton className="h-5 w-5 rounded-full" />
) : completedTotal > 0 ? (
<Badge variant="secondary" className="text-xs">{completedTotal}</Badge>
) : null}
<ChevronRight className="h-4 w-4 text-muted-foreground" />
</div>
</CardContent>
</Card>
</div>
</div>
</div>
<AvatarUploadDialog
open={avatarDialogOpen}
onClose={() => setAvatarDialogOpen(false)}
currentAvatarUrl={avatarUrl ?? ''}
initials={initials}
onUpload={uploadAvatar}
onDelete={deleteAvatar}
loading={avatarLoading}
/>
</div>
);
};
export default ProfilePage;
@@ -0,0 +1,284 @@
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { useParams, useNavigate } from "react-router-dom";
import {
House, Timer, CheckCircle2, Check, CheckCheck, ClipboardList, Hourglass, Sparkles,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { motion } from "framer-motion";
import { useEffect, useState } from "react";
import { useLibrary } from "@/contexts/ClientLibraryContext";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { PageMeta } from "@/contexts/MetadataContext";
import UnitUpsellModal from "@/modules/client/components/UnitUpsellModal";
import { TYPE_DEFS } from "@/modules/admin/components/courses/completionRequirementTypes";
// ─── Helpers ──────────────────────────────────────────────────────────────────
function formatDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) return `${h}hr ${m}min`;
return `${m}min`;
}
// A unit under 5 lessons is assumed still being built out — nudge learners
// that more is coming rather than let it read as a thin/finished unit.
const ESTABLISHED_LESSON_COUNT = 5;
const GrowingUnitNote = () => (
<div className="flex items-center gap-2 rounded-lg border border-dashed bg-muted/40 px-4 py-2.5 text-sm text-muted-foreground w-fit">
<Sparkles className="size-4 shrink-0" />
This unit is constantly improving — more lessons will be added soon.
</div>
);
// ─── Lessons roadmap (single unit — lessons in order + trailing quiz row) ─────
const LessonsRoadmap = ({ unitDetail, currentLessonId, onLessonClick, onContinue, onQuizClick }) => {
const lessons = unitDetail.lessons ?? [];
const quiz = unitDetail.quiz ?? null;
return (
<div className="flex flex-col gap-1 ">
{lessons.map((lesson, index) => {
const completed = lesson.status === "completed";
const isCurrent = lesson.lesson_id === currentLessonId;
return (
<motion.div
key={lesson.lesson_id}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.25, ease: "easeOut" }}
className={cn(
"flex items-center justify-between gap-3 py-3 px-3 rounded-lg cursor-pointer transition-colors",
isCurrent ? "bg-blue-50 dark:bg-blue-950/40" : "hover:bg-muted/60"
)}
onClick={() => onLessonClick(lesson)}
>
<div className="flex items-start gap-3 min-w-0">
<div className={cn(
"w-7 h-7 rounded-full border bg-background flex items-center justify-center text-xs font-medium shrink-0",
completed
? "border-emerald-500 text-emerald-500"
: isCurrent
? "border-blue-500 text-blue-500"
: "border-border text-muted-foreground"
)}>
{completed ? <Check className="size-3.5" /> : index + 1}
</div>
<div className="min-w-0">
<span className={cn(
"block truncate",
completed || isCurrent ? "font-medium text-card-foreground" : "text-muted-foreground"
)}>
{lesson.title}
</span>
<span className="text-sm text-muted-foreground">
{formatDuration(lesson.duration_seconds) ?? "—"}
{completed && " · Completed"}
{isCurrent && !completed && " · In progress"}
</span>
</div>
</div>
{isCurrent && !completed && (
<Button
size="sm"
className="bg-blue-500 shrink-0"
onClick={(e) => { e.stopPropagation(); onContinue(lesson); }}
>
Continue
</Button>
)}
</motion.div>
);
})}
{quiz && (
<div
className="flex items-center justify-between py-3 px-3 mt-1 rounded-lg border border-dashed border-blue-300 dark:border-blue-700 bg-blue-50/60 dark:bg-blue-950/30 hover:bg-blue-100 dark:hover:bg-blue-900/40 transition-colors cursor-pointer"
onClick={() => onQuizClick()}
>
<div className="flex items-center gap-3 select-none min-w-0">
{quiz.has_passed
? <CheckCircle2 className="size-5 text-emerald-500 shrink-0" />
: <ClipboardList className="size-5 text-blue-500 shrink-0" />
}
<span className="font-medium text-blue-700 dark:text-blue-300 truncate">{quiz.title || "Quiz"}</span>
</div>
<Badge className={cn(
"shrink-0 ml-2 text-[10px]",
quiz.has_passed
? "bg-green-100 text-green-700 border border-green-400 dark:bg-green-900/40 dark:text-green-400 dark:border-green-700"
: "bg-blue-100 text-blue-700 border border-blue-300 dark:bg-blue-900/40 dark:text-blue-400 dark:border-blue-700"
)}>
{quiz.has_passed ? "Passed" : "Quiz"}
</Badge>
</div>
)}
</div>
);
};
// ─── Unit Details ───────────────────────────────────────────────────────────
const UnitDetails = () => {
const { uuid } = useParams();
const navigate = useNavigate();
const { getUnitDetail, unitDetail, unitDetailLoading, unitBlocked, unitBlockedInfo, resetUnitDetail } = useLibrary();
const { tierMap, getTierCategories } = useClientTiers();
const [upsellOpen, setUpsellOpen] = useState(false);
// Locked units never get unitDetail (403'd) — fall back to the trimmed
// shell info so the header still renders title/description/duration.
const displayUnit = unitDetail ?? unitBlockedInfo?.item;
const contentNotReady = !displayUnit?.duration_seconds;
useEffect(() => {
getTierCategories();
getUnitDetail(uuid);
return () => resetUnitDetail();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [uuid]);
const items = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: "Units", to: `/units` },
{ label: displayUnit?.title ?? "Unit" },
];
if (unitDetailLoading) {
return (
<div className="my-17 p-8 lg:container lg:mx-auto space-y-4">
<Skeleton className="h-4 w-48" />
<Skeleton className="h-10 w-2/3" />
<Skeleton className="h-5 w-full max-w-2xl" />
</div>
);
}
const lessons = unitDetail?.lessons ?? [];
const completedCount = lessons.filter((l) => l.status === "completed").length;
const currentLesson = lessons.find((l) => l.status !== "completed") ?? null;
const progressPct = lessons.length > 0 ? Math.round((completedCount / lessons.length) * 100) : 0;
// Locked unit's own lessons/quiz — titles/durations only, a preview outline
// that mirrors the unlocked layout but every row opens the upsell modal.
const blockedLessons = unitBlockedInfo?.item?.lessons ?? [];
const blockedQuiz = unitBlockedInfo?.item?.quiz ?? null;
// Units always complete by passing their quiz now (registry.js hard-overrides
// this regardless of what's actually configured) — reflect that here too.
const requirementDef = TYPE_DEFS.pass_quiz;
const RequirementIcon = requirementDef?.icon;
const handleLessonClick = (lesson) => {
navigate(`/lessons/${lesson.uuid}`);
};
const handleContinue = (lesson) => {
navigate(`/units/${uuid}/read`, { state: { lessonId: lesson.lesson_id } });
};
const handleQuizClick = () => {
navigate(`/units/${uuid}/read`, { state: { quizId: true } });
};
return (
<div>
<PageMeta title={displayUnit ? `${displayUnit.title} - STARR` : undefined} description={displayUnit?.description} />
<div className="xs:py-24 xs:px-8 lg:px-0 lg:py-28 flex flex-col gap-6 lg:container lg:mx-auto lg:max-w-2xl">
<AppBreadcrumb items={items} />
<div className="flex flex-col gap-3">
<span className="text-xs font-semibold tracking-wide text-blue-600 dark:text-blue-400 uppercase">Unit</span>
<h1 className="font-bold xs:text-2xl lg:text-4xl">{displayUnit?.title ?? "Unit"}</h1>
<p className="text-muted-foreground lg:text-lg">{displayUnit?.description ?? ""}</p>
</div>
{contentNotReady ? (
<div className="flex items-center gap-2 rounded-lg border bg-muted px-4 py-2.5 text-sm text-muted-foreground w-fit">
<Hourglass className="size-4 shrink-0" />
This unit is currently being prepared. Please check back later.
</div>
) : unitBlocked ? (
<>
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground [&_svg]:size-4">
<span>{blockedLessons.length} {blockedLessons.length === 1 ? "lesson" : "lessons"}</span>
<span>·</span>
<span className="flex items-center gap-1"><Timer /> {formatDuration(displayUnit.duration_seconds) ?? "—"} total</span>
</div>
<div className="flex flex-col gap-3">
<h2 className="font-bold text-xl">Lessons in this unit</h2>
<LessonsRoadmap
unitDetail={{ lessons: blockedLessons, quiz: blockedQuiz }}
currentLessonId={blockedLessons[0]?.lesson_id}
onLessonClick={() => setUpsellOpen(true)}
onContinue={() => setUpsellOpen(true)}
onQuizClick={() => setUpsellOpen(true)}
/>
{blockedLessons.length > 0 && blockedLessons.length < ESTABLISHED_LESSON_COUNT && <GrowingUnitNote />}
</div>
</>
) : (
<>
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground [&_svg]:size-4">
<span>{lessons.length} {lessons.length === 1 ? "lesson" : "lessons"}</span>
<span>·</span>
<span className="flex items-center gap-1"><Timer /> {formatDuration(unitDetail.duration_seconds) ?? "—"} total</span>
<span>·</span>
<span className="text-blue-600 dark:text-blue-400 font-medium">{completedCount} of {lessons.length} complete</span>
{requirementDef && (
<>
<span>·</span>
<span className="flex items-center gap-1">
{RequirementIcon && <RequirementIcon />} {requirementDef.label}
</span>
</>
)}
</div>
<Progress value={progressPct} />
{unitDetail.is_completed && (
<div className="flex items-center gap-1.5 text-sm font-medium text-emerald-600 dark:text-emerald-400 w-fit">
<CheckCheck className="size-4" />
Success — you've completed this unit.
</div>
)}
</div>
<div className="flex flex-col gap-3">
<h2 className="font-bold text-xl">Lessons in this unit</h2>
<LessonsRoadmap
unitDetail={unitDetail}
currentLessonId={currentLesson?.lesson_id}
onLessonClick={handleLessonClick}
onContinue={handleContinue}
onQuizClick={handleQuizClick}
/>
{lessons.length > 0 && lessons.length < ESTABLISHED_LESSON_COUNT && <GrowingUnitNote />}
</div>
</>
)}
</div>
<UnitUpsellModal
open={upsellOpen}
onOpenChange={setUpsellOpen}
unit={unitBlockedInfo?.item ? {
title: unitBlockedInfo.item.title,
subscription: unitBlockedInfo.item.subscription,
courses: unitBlockedInfo.course ? [unitBlockedInfo.course] : [],
} : null}
tierMap={tierMap}
/>
</div>
);
};
export default UnitDetails;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,661 @@
import { useState, useCallback, useEffect, useRef } from "react";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { useParams, useNavigate, useLocation, useBlocker } from "react-router-dom";
import { House, TableOfContents, ArrowRight, ClipboardList, Lock, CheckCircle2, CheckCheck, Circle, Zap, ChevronsLeft, ChevronsRight, Hourglass, ListChecks, HelpCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import ResponsiveModal from "@/components/generic/ResponsiveModal";
import LessonBlock from "../components/LessonBlock.jsx";
import QuizBlock from "../components/blocks/QuizBlock.jsx";
import MarkCompleteButton from "../components/MarkCompleteButton.jsx";
import { useLibrary } from "@/contexts/ClientLibraryContext";
import { PageMeta } from "@/contexts/MetadataContext";
import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "sonner";
import api from "@/utils/api.util";
import { TYPE_DEFS } from "@/modules/admin/components/courses/completionRequirementTypes";
// ─── Sidebar (single unit — flat lessons + quiz, no unit-accordion nesting) ──
const SidebarContent = ({
lessons, quiz, selectedLessonId, selectedQuizId,
onLessonClick, onQuizClick, loading,
}) => (
<ScrollArea className="h-full p-3 md:p-4">
<p className="text-xs font-semibold uppercase tracking-widest text-muted-foreground mb-2 px-2">
Unit Content
</p>
{loading ? (
<div className="space-y-2 px-2 pt-1">
{Array.from({ length: 4 }).map((_, i) => (
<Skeleton key={i} className="h-8 w-full rounded-md" />
))}
</div>
) : (
<ul className="space-y-0.5">
{lessons.map((lesson) => (
<li
key={lesson.lesson_id}
onClick={() => onLessonClick(lesson)}
className={`flex items-center gap-2 pl-3 pr-3 py-1.5 text-sm rounded-md hover:bg-muted-foreground/10 hover:text-foreground cursor-pointer transition-colors ${selectedLessonId === lesson.lesson_id
? "bg-muted-foreground/10 text-foreground font-medium"
: "text-muted-foreground"
}`}
>
{lesson.status === "completed"
? <CheckCircle2 className="size-3.5 text-emerald-500 shrink-0" />
: <Circle className="size-3.5 text-muted-foreground/30 shrink-0" />
}
<span className="truncate lg:w-44">{lesson.title}</span>
</li>
))}
{quiz && (
<li
onClick={onQuizClick}
className={`flex items-center gap-2 pl-3 pr-3 py-1.5 text-sm rounded-md cursor-pointer transition-colors ${selectedQuizId
? "bg-muted-foreground/10 text-foreground font-medium"
: quiz.has_passed
? "text-emerald-600 dark:text-emerald-400 hover:bg-muted-foreground/10"
: "text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground"
}`}
>
{quiz.has_passed
? <CheckCircle2 className="size-3.5 text-emerald-500 shrink-0" />
: <ClipboardList className="size-3.5 shrink-0" />
}
{quiz.title || "Quiz"}
</li>
)}
</ul>
)}
<ScrollBar orientation="vertical" />
</ScrollArea>
);
// ─── UnitReader ─────────────────────────────────────────────────────────────
const UnitReader = () => {
const { uuid } = useParams();
const navigate = useNavigate();
const location = useLocation();
const {
unitDetail, unitDetailLoading, unitBlocked, getUnitDetail, resetUnitDetail,
lesson, lessonLoading, getLesson, resetLesson,
quiz, quizLoading, getUnitQuiz, resetQuiz, submitUnitQuiz, saveUnitQuizDraft,
upsertLessonProgress, upsertWatchProgress, markComplete,
} = useLibrary();
// Tracks which lessons have been marked completed this session to avoid duplicate calls
const completedSessionRef = useRef(new Set());
// ── Task context: state-first, endpoint fallback — same pattern as UnitList.jsx.
// If navigated here from a task's requirement card, taskCtx is in location.state;
// if the user opened this unit directly (e.g. from /units), fetch it instead, so
// the "Task mode" banner still shows up when this unit is a task requirement.
const [taskCtx, setTaskCtx] = useState(null);
useEffect(() => {
const stateCtx = location.state?.taskCtx;
if (stateCtx) { setTaskCtx(stateCtx); return; }
api.get(`/client/courses/unit/uuid/${uuid}/task-context`)
.then(({ data }) => { if (data?.data?.has_task) setTaskCtx(data.data); })
.catch(() => {}); // non-critical — silently swallow
}, [uuid]); // eslint-disable-line react-hooks/exhaustive-deps
// ── Local UI state ──────────────────────────────────────────────────────
const [selectedLessonId, setSelectedLessonId] = useState(null);
const [selectedQuizId, setSelectedQuizId] = useState(null);
const [sidebarOpen, setSidebarOpen] = useState(false);
const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(true);
const [helpOpen, setHelpOpen] = useState(false);
// ── Session guard — block navigation while a quiz is in progress ─────────
const quizActiveRef = useRef(false);
const [quizSessionActive, setQuizSessionActive] = useState(false);
const [pendingNav, setPendingNav] = useState(null);
const setQuizActive = useCallback((active) => {
quizActiveRef.current = active;
setQuizSessionActive(active);
}, []);
const blocker = useBlocker(
({ currentLocation, nextLocation }) =>
quizSessionActive && currentLocation.pathname !== nextLocation.pathname
);
useEffect(() => {
if (blocker.state !== "blocked") return;
setPendingNav(() => () => blocker.proceed());
}, [blocker.state]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!quizSessionActive) return;
const handler = (e) => { e.preventDefault(); e.returnValue = ''; };
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [quizSessionActive]);
// ── Flatten content: lessons + optional quiz ──────────────────────────
const lessons = unitDetail?.lessons ?? [];
const allContent = [
...lessons.map((l) => ({ type: "lesson", lesson: l })),
...(unitDetail?.quiz ? [{ type: "quiz", quiz: unitDetail.quiz }] : []),
];
// ── Scroll progress ────────────────────────────────────────────────────
const [scrollProgress, setScrollProgress] = useState(0);
useEffect(() => {
setScrollProgress(0);
window.scrollTo(0, 0);
}, [selectedLessonId, selectedQuizId]);
useEffect(() => {
// Content shorter than the viewport (nothing to scroll) used to flag 100%
// on the spot — but right after switching lessons the video/image blocks
// haven't finished loading yet, so that snapshot is often taken against a
// still-collapsed layout and fires a false "completed" before the real
// (taller) content has even rendered. Debounce a settle window and
// re-check before trusting it.
let settleTimer = null;
const evaluate = () => {
const scrollTop = window.scrollY;
const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
if (scrollHeight <= 0) {
if (settleTimer) return;
settleTimer = setTimeout(() => {
settleTimer = null;
const stillShort = document.documentElement.scrollHeight - window.innerHeight <= 0;
if (stillShort) setScrollProgress(100);
}, 1200);
return;
}
if (settleTimer) { clearTimeout(settleTimer); settleTimer = null; }
// Percentage rounding alone can hit 100 a few pixels short of the real
// bottom (e.g. 99.5% rounds up), which was enough to auto-fire
// completion before the reader actually reached the end — while a "How
// to complete" explainer sits right there telling the learner it isn't
// done yet. Cap the ratio-derived value at 90 and only award the true
// 100 when the scroll position has actually reached the bottom.
const atBottom = scrollTop >= scrollHeight - 4;
setScrollProgress(atBottom ? 100 : Math.min(Math.round((scrollTop / scrollHeight) * 100), 90));
};
evaluate(); // seed a measurement — short content may never fire a scroll event
window.addEventListener("scroll", evaluate, { passive: true });
return () => {
window.removeEventListener("scroll", evaluate);
if (settleTimer) clearTimeout(settleTimer);
};
}, [selectedLessonId, selectedQuizId]);
// ── Lesson completion-trigger dispatch (mirrors UnitList.jsx) ──────────
// read_all_content (or unconfigured/default) → scroll-to-bottom, below.
// watch_percent / manual_complete → their own dedicated triggers — the scroll
// trigger must NOT also fire completion for those, so it's gated here.
const lessonCompletionType = lesson?.completion?.type ?? 'read_all_content';
// ── "How to complete" help text — explains this lesson's and this unit's
// configured completion requirement (or the default implicit rule).
// Units always complete by passing their quiz now (registry.js hard-overrides
// this regardless of what's actually configured) — reflect that here too.
const unitCompletionType = 'pass_quiz';
const lessonRequirementText = TYPE_DEFS[lessonCompletionType]?.describe('lesson');
const unitRequirementText = TYPE_DEFS[unitCompletionType]?.describe('unit');
// ── Mark lesson completed when user scrolls to the bottom ─────────────
useEffect(() => {
if (lessonCompletionType !== 'read_all_content') return;
if (scrollProgress < 100 || !selectedLessonId || !lesson?.uuid) return;
if (completedSessionRef.current.has(selectedLessonId)) return;
const stub = lessons.find((l) => l.lesson_id === selectedLessonId);
if (stub?.status === 'completed') return;
completedSessionRef.current.add(selectedLessonId);
// Trust the server's evaluated unit status, not a local "all fetched
// lessons read" re-derivation — that drifted from the real completion
// requirement (e.g. a unit needing its quiz passed too) and fired a
// premature "Unit complete!" toast. Same fix already applied to
// upsertLessonProgress's own unitDetail update; UnitList.jsx's
// handleMarkComplete already uses this authoritative pattern.
upsertLessonProgress(lesson.uuid, 'completed', uuid).then((result) => {
if (result?.unit?.status === 'completed') {
toast.success('Unit complete!', { duration: 4000 });
}
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scrollProgress]);
// ── Fetch unit + reset on unmount ──────────────────────────────────────
useEffect(() => {
getUnitDetail(uuid);
return () => {
resetUnitDetail();
resetLesson();
resetQuiz();
completedSessionRef.current.clear();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [uuid]);
// ── Auto-load lesson once unit data is available ───────────────────────
useEffect(() => {
if (!unitDetail || selectedLessonId || selectedQuizId) return;
const { lessonId, quizId } = location.state ?? {};
if (quizId && unitDetail.quiz) {
setSelectedQuizId(unitDetail.quiz.quiz_id);
getUnitQuiz(uuid);
return;
}
if (lessonId) {
const target = lessons.find((l) => l.lesson_id === lessonId);
if (target) {
setSelectedLessonId(target.lesson_id);
getLesson(target.uuid);
return;
}
}
const firstIncomplete = lessons.find((l) => l.status !== 'completed') ?? lessons[0];
if (firstIncomplete) {
setSelectedLessonId(firstIncomplete.lesson_id);
getLesson(firstIncomplete.uuid);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [unitDetail]);
// ── Breadcrumbs ─────────────────────────────────────────────────────────
const currentLessonStub = lessons.find((l) => l.lesson_id === selectedLessonId) ?? null;
const pageTitle = (() => {
if (!unitDetail) return undefined;
if (selectedQuizId) return `${unitDetail.title} – Quiz - STARR`;
const lessonTitle = lesson?.title ?? currentLessonStub?.title;
if (selectedLessonId && lessonTitle) return `${lessonTitle} - STARR`;
return `${unitDetail.title} - STARR`;
})();
const breadcrumbItemsFull = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: "Units", to: `/units` },
{ label: unitDetail?.title ?? "Unit", to: `/units/${uuid}` },
{ label: selectedQuizId ? "Quiz" : (currentLessonStub?.title ?? "Select a lesson") },
];
const breadcrumbItemsMobile = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: selectedQuizId ? "Quiz" : (currentLessonStub?.title ?? unitDetail?.title ?? "Unit") },
];
// ── Session guard helpers ──────────────────────────────────────────────
const handleConfirmNav = useCallback(() => {
const fn = pendingNav;
setPendingNav(null);
quizActiveRef.current = false;
setQuizSessionActive(false);
if (blocker.state === "blocked") blocker.proceed();
else fn?.();
}, [pendingNav, blocker]);
const handleCancelNav = useCallback(() => {
setPendingNav(null);
if (blocker.state === "blocked") blocker.reset();
}, [blocker]);
// ── Lesson click ───────────────────────────────────────────────────────
const handleLessonClick = useCallback(async (lessonStub) => {
if (lessonStub.lesson_id === selectedLessonId) { setSidebarOpen(false); return; }
const doNav = async () => {
setSelectedLessonId(lessonStub.lesson_id);
setSelectedQuizId(null);
resetQuiz();
setSidebarOpen(false);
await getLesson(lessonStub.uuid);
};
if (quizActiveRef.current) { setPendingNav(() => doNav); return; }
await doNav();
}, [selectedLessonId, getLesson, resetQuiz]);
// ── Quiz click ─────────────────────────────────────────────────────────
const handleQuizClick = useCallback(async () => {
if (selectedQuizId) { setSidebarOpen(false); return; }
const doNav = async () => {
setSelectedQuizId(unitDetail.quiz.quiz_id);
setSelectedLessonId(null);
resetLesson();
setSidebarOpen(false);
await getUnitQuiz(uuid);
};
if (quizActiveRef.current) { setPendingNav(() => doNav); return; }
await doNav();
}, [selectedQuizId, uuid, getUnitQuiz, resetLesson, unitDetail]);
const handleQuizDraft = useCallback((answers) => {
saveUnitQuizDraft(uuid, selectedQuizId, answers);
}, [uuid, selectedQuizId, saveUnitQuizDraft]);
// watch_percent / watch_video / listen_audio — safe to always pass through, the
// backend no-ops whichever type (if any) isn't configured on this lesson.
const handleWatchProgress = useCallback((percent, meta) => {
if (!lesson?.uuid) return;
upsertWatchProgress(lesson.uuid, uuid, percent, meta);
}, [lesson, uuid, upsertWatchProgress]);
// ── manual_complete trigger: learner clicks the Mark Complete button ────
const handleMarkComplete = useCallback(async () => {
if (!lesson?.uuid) return;
await markComplete(lesson.uuid, uuid);
}, [lesson, uuid, markComplete]);
// ── Next content item ──────────────────────────────────────────────────
const getNextContent = useCallback(() => {
const idx = allContent.findIndex((item) =>
(item.type === "lesson" && item.lesson.lesson_id === selectedLessonId) ||
(item.type === "quiz" && selectedQuizId)
);
return idx !== -1 && idx < allContent.length - 1 ? allContent[idx + 1] : null;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedLessonId, selectedQuizId, allContent]);
const nextContent = getNextContent();
const nextLabel = nextContent
? nextContent.type === "lesson" ? nextContent.lesson.title : (nextContent.quiz.title || "Quiz")
: null;
const showSidebarContent = desktopSidebarOpen && !quizSessionActive;
const handleNextContentClick = () => {
if (!nextContent) return;
if (nextContent.type === "lesson") handleLessonClick(nextContent.lesson);
else handleQuizClick();
};
// ── Access blocked (403 from getUnitDetail) ──────────────────────────────
if (unitBlocked) {
return (
<div className="flex flex-col items-center gap-6 py-32 text-center px-4">
<div className="h-16 w-16 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
<Lock className="size-7 text-amber-500" />
</div>
<div className="space-y-2 max-w-sm">
<h2 className="text-xl font-semibold">Premium / Exclusive Content</h2>
<p className="text-sm text-muted-foreground leading-relaxed">
To access this unit, subscribe to one of our available tier plans.
</p>
</div>
<Button onClick={() => navigate('/subscriptions')} className="gap-1.5">
<Zap className="size-4" /> View Available Plans
</Button>
</div>
);
}
// ── Content not ready ──────────────────────────────────────────────────
if (!unitDetailLoading && unitDetail && !unitDetail.duration_seconds) {
return (
<div className="flex flex-col items-center gap-6 py-32 text-center px-4">
<div className="h-16 w-16 rounded-full bg-muted flex items-center justify-center">
<Hourglass className="size-7 text-muted-foreground" />
</div>
<div className="space-y-2 max-w-sm">
<h2 className="text-xl font-semibold">Unit Not Yet Available</h2>
<p className="text-sm text-muted-foreground leading-relaxed">
This unit is currently being prepared. Please check back later.
</p>
</div>
<Button variant="outline" onClick={() => navigate(`/units/${uuid}`)} className="gap-1.5">
Back to Unit Details
</Button>
</div>
);
}
return (
<>
<PageMeta title={pageTitle} />
{/* ── Session-guard dialog ── */}
<ResponsiveModal
open={!!pendingNav || blocker.state === "blocked"}
onOpenChange={(open) => !open && handleCancelNav()}
title="Leave Quiz?"
description=""
footer={
<>
<Button variant="outline" onClick={handleCancelNav}>Stay</Button>
<Button variant="destructive" onClick={handleConfirmNav}>Leave Anyway</Button>
</>
}
>
<div className="space-y-3 text-sm text-muted-foreground">
<p>
You have an ongoing <strong className="text-foreground">quiz</strong> session in progress.
Leaving now will not submit your answers — your session will remain open.
</p>
</div>
</ResponsiveModal>
{/* ── "How to complete" help dialog ── */}
<ResponsiveModal
open={helpOpen}
onOpenChange={setHelpOpen}
title="How to complete this content"
description=""
footer={<Button onClick={() => setHelpOpen(false)}>Got it</Button>}
>
<div className="space-y-3 text-sm">
<div className="flex items-start gap-3 rounded-lg border p-3">
{(() => {
const Icon = TYPE_DEFS[lessonCompletionType]?.icon;
return Icon ? <Icon className="size-4 mt-0.5 text-muted-foreground shrink-0" /> : null;
})()}
<div>
<p className="font-medium">This lesson</p>
<p className="text-muted-foreground">{lessonRequirementText}</p>
</div>
</div>
<div className="flex items-start gap-3 rounded-lg border p-3">
{(() => {
const Icon = TYPE_DEFS[unitCompletionType]?.icon;
return Icon ? <Icon className="size-4 mt-0.5 text-muted-foreground shrink-0" /> : null;
})()}
<div>
<p className="font-medium">This unit</p>
<p className="text-muted-foreground">{unitRequirementText}</p>
{unitDetail?.quiz && unitCompletionType !== 'pass_quiz' && (
<p className="text-muted-foreground mt-1">
This unit also has a quiz — passing it is tracked separately from the unit's completion status.
</p>
)}
</div>
</div>
</div>
</ResponsiveModal>
{/* ── Up next floating button ── */}
{scrollProgress >= 100 && nextContent && !selectedQuizId && (
<div className="fixed bottom-6 right-6 z-20 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div
onClick={handleNextContentClick}
className="flex items-center gap-3 bg-card border rounded-xl dark:hover:border-blue-500 dark:hover:shadow-blue-500 px-4 py-3 shadow-xl hover:bg-muted transition-colors text-sm font-medium cursor-pointer select-none"
>
<div className="flex flex-col items-start">
<span className="text-sm text-muted-foreground font-normal">Up next</span>
{nextContent.type === "lesson" ? nextContent.lesson.title : (nextContent.quiz.title || "Quiz")}
</div>
<ArrowRight className="size-4 text-muted-foreground" />
</div>
</div>
)}
{selectedQuizId && quiz?.has_passed && !quizSessionActive && nextContent && (
<div className="fixed bottom-6 right-6 z-20 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div
onClick={handleNextContentClick}
className="flex items-center gap-3 bg-card border rounded-xl dark:hover:border-blue-500 dark:hover:shadow-blue-500 px-4 py-3 shadow-xl hover:bg-muted transition-colors text-sm font-medium cursor-pointer select-none"
>
<div className="flex flex-col items-start">
<span className="text-sm text-muted-foreground font-normal">Up next</span>
{nextContent.type === "lesson" ? nextContent.lesson.title : (nextContent.quiz.title || "Quiz")}
</div>
<ArrowRight className="size-4 text-muted-foreground" />
</div>
</div>
)}
{/* ── Top sticky bar ── */}
<div className="fixed top-[67px] left-0 right-0 z-40 bg-card border-b py-3 px-4 md:px-6">
<div className="w-full flex items-center justify-between gap-2">
<div className="flex items-center gap-2 justify-between w-full">
<div className="hidden sm:block min-w-0">
<AppBreadcrumb items={breadcrumbItemsFull} />
</div>
<div className="sm:hidden min-w-0 truncate">
<AppBreadcrumb items={breadcrumbItemsMobile} />
</div>
{!selectedQuizId && lesson && (
lesson.status === 'completed' ? (
<div className="hidden lg:flex items-center gap-1.5 text-sm font-medium text-emerald-600 dark:text-emerald-400 shrink-0">
<CheckCheck className="size-4" />
Done
</div>
) : (
<Button
variant="outline"
size="sm"
className="hidden lg:flex items-center gap-1.5 text-muted-foreground shrink-0"
onClick={() => setHelpOpen(true)}
>
<HelpCircle className="size-4" />
How to complete
</Button>
)
)}
<Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
<SheetTrigger asChild>
<Button variant="outline" size="icon" className="lg:hidden flex-shrink-0" aria-label="Open unit content">
<TableOfContents className="size-4" />
</Button>
</SheetTrigger>
<SheetContent side="left" className="p-0 w-80">
<SidebarContent
lessons={lessons}
quiz={unitDetail?.quiz}
selectedLessonId={selectedLessonId}
selectedQuizId={selectedQuizId}
onLessonClick={handleLessonClick}
onQuizClick={handleQuizClick}
loading={unitDetailLoading}
/>
</SheetContent>
</Sheet>
</div>
</div>
{lesson && (
<div className="absolute bottom-0 left-0 right-0 h-1 bg-border">
<div
className="h-full bg-primary transition-all duration-150 ease-out"
style={{ width: `${scrollProgress}%` }}
/>
</div>
)}
</div>
{/* ── Task-mode banner ─────────────────────────────────────────── */}
{taskCtx?.has_task && (
<div className={`fixed xs:top-[124px] lg:top-[116px] left-0 right-0 z-30 flex items-center gap-2 text-white text-xs font-medium px-4 py-1.5 shadow-sm transition-colors ${
unitDetail?.is_completed ? 'bg-green-600' : 'bg-blue-600'
}`}>
<ListChecks className="size-3.5 shrink-0" />
<span>
{unitDetail?.is_completed
? 'Unit complete — tracking finished'
: 'Task mode — progress is being tracked automatically'
}
</span>
</div>
)}
{/* ── Desktop sidebar ── */}
<div className={`hidden lg:flex flex-row fixed ${taskCtx?.has_task ? "top-[145px]" : "top-[112px]"} bottom-0 left-0 z-30 bg-muted border-r`}>
<div className="w-14 shrink-0 flex flex-col items-center pt-3">
<Button
variant="ghost"
size="icon"
className="size-8"
onClick={() => setDesktopSidebarOpen((prev) => !prev)}
disabled={quizSessionActive}
title={showSidebarContent ? "Collapse sidebar" : "Expand sidebar"}
>
{showSidebarContent ? <ChevronsLeft className="size-4" /> : <ChevronsRight className="size-4" />}
</Button>
</div>
{showSidebarContent && (
<div className="w-[266px] border-l overflow-hidden">
<SidebarContent
lessons={lessons}
quiz={unitDetail?.quiz}
selectedLessonId={selectedLessonId}
selectedQuizId={selectedQuizId}
onLessonClick={handleLessonClick}
onQuizClick={handleQuizClick}
loading={unitDetailLoading}
/>
</div>
)}
</div>
{/* ── Main content ── */}
<div className={`${taskCtx?.has_task ? "xs:mt-42 lg:mt-36" : "mt-32"} ${showSidebarContent ? "lg:ml-80" : "lg:ml-14"} p-4 md:p-6 min-h-screen`}>
<div className="relative w-full h-full mx-auto max-w-2xl">
{selectedQuizId ? (
<QuizBlock
quiz={quiz}
loading={quizLoading}
onDraft={handleQuizDraft}
onSubmit={async (answers) => {
const result = await submitUnitQuiz(uuid, selectedQuizId, answers);
await getUnitDetail(uuid);
return result;
}}
onRetake={() => getUnitQuiz(uuid)}
onActiveChange={setQuizActive}
onNextContent={nextContent ? handleNextContentClick : undefined}
nextLabel={nextLabel}
/>
) : (
<>
<LessonBlock
lesson={lesson}
loading={lessonLoading}
onWatchProgress={['watch_percent', 'watch_video', 'listen_audio'].includes(lessonCompletionType) ? handleWatchProgress : undefined}
/>
{!lessonLoading && lesson && lessonCompletionType === 'manual_complete' && (
<MarkCompleteButton
label={lesson?.completion?.button_label}
completed={lesson?.status === 'completed'}
onMarkComplete={handleMarkComplete}
/>
)}
</>
)}
</div>
</div>
</>
);
};
export default UnitReader;
@@ -0,0 +1,194 @@
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { House, ChevronLeft, ChevronRight, Layers, Search } from "lucide-react";
import AppBreadcrumb from "@/components/generic/Breadcrumb/AppBreadcrumb";
import { Input } from "@/components/ui/input";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { useLibrary } from "@/contexts/ClientLibraryContext";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { UnitCard, UnitCardSkeleton } from "../components/UnitCard";
import { PageMeta } from "@/contexts/MetadataContext";
const ITEMS_PER_PAGE = 10;
// ─── Pagination ───────────────────────────────────────────────────────────────
const Pagination = ({ currentPage, totalPages, totalItems, itemsPerPage, onPageChange }) => {
const start = (currentPage - 1) * itemsPerPage + 1;
const end = Math.min(currentPage * itemsPerPage, totalItems);
const getPages = () => {
const pages = [];
if (totalPages <= 5) {
for (let i = 1; i <= totalPages; i++) pages.push(i);
} else {
pages.push(1);
if (currentPage > 3) pages.push("...");
for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) pages.push(i);
if (currentPage < totalPages - 2) pages.push("...");
pages.push(totalPages);
}
return pages;
};
return (
<div className="flex items-center justify-between w-full pt-4 border-t">
<div className="text-sm text-muted-foreground">
Showing <span className="font-medium text-foreground">{start}–{end}</span> of{" "}
<span className="font-medium text-foreground">{totalItems}</span> units
</div>
<div className="flex items-center gap-1">
<Button onClick={() => onPageChange(currentPage - 1)} disabled={currentPage === 1} variant="ghost" size="sm">
<ChevronLeft />
</Button>
{getPages().map((page, i) =>
page === "..." ? (
<span key={`ellipsis-${i}`} className="w-7 h-7 flex items-center justify-center text-xs text-muted-foreground">···</span>
) : (
<Button key={page} size="sm" variant={currentPage === page ? "default" : "outline"} onClick={() => onPageChange(page)}>
{page}
</Button>
)
)}
<Button onClick={() => onPageChange(currentPage + 1)} disabled={currentPage === totalPages} variant="ghost" size="sm">
<ChevronRight />
</Button>
</div>
</div>
);
};
// ─── Main Page ────────────────────────────────────────────────────────────────
const UnitsList = () => {
const navigate = useNavigate();
const { units, unitsLoading, getUnits } = useLibrary();
const { tierMap, getTierCategories } = useClientTiers();
const [currentPage, setCurrentPage] = useState(1);
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
const [lockFilter, setLockFilter] = useState("All");
useEffect(() => {
getUnits();
getTierCategories();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const filtered = useMemo(() =>
units
.filter((u) => {
const matchSearch = u.title.toLowerCase().includes(search.toLowerCase()) ||
(u.description ?? "").toLowerCase().includes(search.toLowerCase());
const matchLock = lockFilter === "All"
|| (lockFilter === "Unlocked" && !u.is_locked)
|| (lockFilter === "Locked" && u.is_locked);
return matchSearch && matchLock;
})
.sort((a, b) => a.title.localeCompare(b.title)),
[units, search, lockFilter]
);
const totalPages = Math.max(1, Math.ceil(filtered.length / ITEMS_PER_PAGE));
const paginated = filtered.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE);
const runSearch = () => { setSearch(searchInput); setCurrentPage(1); };
const handleViewDetails = (unit) => navigate(`/units/${unit.uuid}`);
const items = [
{ label: "Home", icon: <House className="size-4" />, to: `/dashboard` },
{ label: "Units" },
];
return (
<div>
<PageMeta title="Units - STARR" description="Browse standalone units you can start right away." />
<div className="py-24 bg-accent/70 min-h-screen">
<div className="flex flex-col gap-4 justify-between lg:container lg:mx-auto pt-2">
<AppBreadcrumb items={items} />
{/* Search & Filters */}
<div className="fixed top-[67px] left-0 right-0 z-10 bg-card border-b lg:static lg:bg-transparent lg:border-none py-3 xs:px-4 md:px-6 lg:px-0">
<div className="flex items-center xs:flex-col lg:flex-row gap-4">
<div className="flex items-center gap-2 w-full lg:max-w-64">
<Input
placeholder="Search units..."
className="w-full bg-card text-sm"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") runSearch(); }}
/>
<Button size="icon" variant="outline" className="shrink-0 bg-card" onClick={runSearch} aria-label="Search">
<Search />
</Button>
</div>
<Select value={lockFilter} onValueChange={(v) => { setLockFilter(v); setCurrentPage(1); }}>
<SelectTrigger className="w-full lg:w-48 bg-card">
<SelectValue placeholder="Access" />
</SelectTrigger>
<SelectContent>
<SelectItem value="All">All Units</SelectItem>
<SelectItem value="Unlocked">Unlocked</SelectItem>
<SelectItem value="Locked">Locked</SelectItem>
</SelectContent>
</Select>
<Select value="units" onValueChange={(v) => {
if (v === "courses") navigate("/course");
if (v === "lessons") navigate("/lessons");
}}>
<SelectTrigger className="w-full lg:w-48 bg-card">
<SelectValue placeholder="Browse" />
</SelectTrigger>
<SelectContent>
<SelectItem value="courses">Courses</SelectItem>
<SelectItem value="units">Units</SelectItem>
<SelectItem value="lessons">Lessons</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Unit Grid */}
{unitsLoading ? (
<div className="xs:pt-12 lg:pt-0 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{Array.from({ length: 8 }).map((_, i) => <UnitCardSkeleton key={i} />)}
</div>
) : paginated.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20">
<Layers className="size-40 text-primary" />
<p className="text-md">No units found</p>
</div>
) : (
<div className="xs:pt-12 lg:pt-0 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-4 xs:px-4 lg:px-0">
{paginated.map((unit) => (
<UnitCard
key={unit.unit_id}
unit={unit}
tierMap={tierMap}
onViewDetails={handleViewDetails}
/>
))}
</div>
)}
{!unitsLoading && filtered.length > ITEMS_PER_PAGE && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
totalItems={filtered.length}
itemsPerPage={ITEMS_PER_PAGE}
onPageChange={setCurrentPage}
/>
)}
</div>
</div>
</div>
);
};
export default UnitsList;
@@ -0,0 +1,287 @@
import { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import * as LucideIcons from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
ArrowLeft, BookOpen, Clock, Check, Lock,
Tag, CalendarDays,
} from "lucide-react";
import { useClientTiers } from "@/contexts/ClientTiersProvider";
import { useProfile } from "@/contexts/ProfileProvider";
import { PageMeta } from "@/contexts/MetadataContext";
import { useDateFormat } from "@/hooks/useDateFormat";
import { resolveTierBadge } from "@/utils/tierBadge.util";
import { getTierColor } from "@/utils/tierColors";
import { getBundleContent, overlapsExistingAccess, isPlanCurrent } from "@/utils/planBundle.util";
// ─── Helpers ──────────────────────────────────────────────────────────────────
const UNIT_TO_DAYS = { minute: 1 / 1440, hour: 1 / 24, day: 1, month: 30, year: 365 };
function formatDuration(days, unit) {
if (!days) return null;
const multiplier = UNIT_TO_DAYS[unit] ?? 1;
const value = Math.round((days / multiplier) * 1000) / 1000;
const label = unit ?? "day";
return `${value} ${label}${value !== 1 ? "s" : ""}`;
}
function formatCourseDuration(seconds = 0) {
if (!seconds) return null;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h && m) return `${h}h ${m}m`;
if (h) return `${h}h`;
return `${m}m`;
}
// ─── Skeleton ─────────────────────────────────────────────────────────────────
const ViewPlanSkeleton = () => (
<div className="mt-17 bg-muted min-h-screen">
<Skeleton className="h-72 w-full" />
<div className="p-6 lg:container lg:max-w-3xl lg:mx-auto space-y-4 mt-4">
<Skeleton className="h-28 w-full rounded-2xl" />
<Skeleton className="h-64 w-full rounded-2xl" />
</div>
</div>
);
// ─── Component ────────────────────────────────────────────────────────────────
const ViewPlan = () => {
const { id } = useParams();
const navigate = useNavigate();
const { myTier, getMyTier, plans, plansLoading, getPlans, tierMap, getTierCategories } = useClientTiers();
const { getProfile } = useProfile();
const { fmtCurrency } = useDateFormat();
useEffect(() => {
getProfile();
getMyTier();
getTierCategories();
if (!plans.length) getPlans();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
const plan = plans.find((p) => String(p.plan_id) === String(id)) ?? null;
const loading = plansLoading;
if (loading) return <ViewPlanSkeleton />;
if (!plan) return null;
const { label: tierLabel, cls: badgeCls } = resolveTierBadge(plan.tier, tierMap);
const Icon = LucideIcons[tierMap[plan.tier]?.badge_icon] ?? Tag;
const colors = getTierColor(tierMap[plan.tier]?.color ?? "purple");
const accentSwatch = colors.swatch;
const accentStyle = { color: accentSwatch };
const accentBg = colors.panel.bg;
const accentBorder = colors.panel.border;
const features = plan.features ?? [];
const duration = formatDuration(plan.duration_days, plan.duration_unit);
// "Current" means the user actually purchased THIS exact plan (matched by
// plan_id), not just any plan sharing the same tier slug — two different
// plans can share a tier and stay independently active (Tier Plans v2).
const isCurrent = isPlanCurrent(plan, myTier);
// Blocked-by-overlap ("already covered") — plan isn't owned, but at least
// one of its bundle items is already granted by something else the user
// holds (Scenario 3): shown, not hidden, but purchase is disabled.
const isBlockedByOverlap = !isCurrent && overlapsExistingAccess(plan, myTier?.my_grants);
const bundle = getBundleContent(plan);
const bundleCount = bundle?.items?.length ?? 0;
const BundleIcon = bundle?.icon ?? BookOpen;
const totalSeconds = (bundle?.items ?? []).reduce((sum, c) => sum + (c.duration_seconds ?? 0), 0);
const totalDuration = formatCourseDuration(totalSeconds);
return (
<div className="mt-17 bg-muted min-h-screen">
<PageMeta title={plan ? `${plan.label} - STARR` : undefined} />
{/* ── Hero Banner ───────────────────────────────────────────── */}
<div className={`relative ${badgeCls} overflow-hidden`}>
{/* Decorative blobs */}
<div className="absolute inset-0 pointer-events-none overflow-hidden">
<div className="absolute -top-24 -right-24 w-96 h-96 rounded-full bg-white/5" />
<div className="absolute -bottom-16 -left-16 w-72 h-72 rounded-full bg-white/5" />
<div className="absolute top-1/2 left-1/3 w-48 h-48 rounded-full bg-white/5" />
</div>
<div className="relative px-6 pt-8 pb-10 lg:container lg:max-w-3xl lg:mx-auto">
<button
onClick={() => navigate("/subscriptions")}
className="flex items-center gap-1.5 text-white/70 hover:text-white text-sm mb-8 transition-colors"
>
<ArrowLeft className="size-4" /> Back to Subscriptions
</button>
<Badge className="bg-white/20 border border-white/30 text-white mb-4 text-sm px-3 py-1">
<Icon className="size-3.5 mr-1" /> {tierLabel}
</Badge>
<h1 className="text-3xl sm:text-4xl font-extrabold text-white mb-2 leading-tight tracking-tight">
{plan.label}
</h1>
<p className="text-white/70 text-sm mb-8 max-w-md leading-relaxed">
{plan.description || `Everything you need with the ${tierLabel} plan.`}
</p>
<div className="flex flex-wrap items-end gap-4">
<div>
<span className="text-5xl font-black text-white leading-none">
{fmtCurrency(plan.price, plan.currency)}
</span>
{duration && (
<span className="text-white/60 text-sm ml-2">/ {duration}</span>
)}
</div>
{isCurrent ? (
<Badge className="bg-white/20 border border-white/30 text-white px-4 py-2 text-sm font-medium">
<Check className="size-3.5 mr-1" /> Your Current Plan
</Badge>
) : !plan.is_active ? (
<Badge className="bg-white/20 border border-white/30 text-white px-4 py-2 text-sm font-medium">
Not Available at the Moment
</Badge>
) : isBlockedByOverlap ? (
<Badge className="bg-white/20 border border-white/30 text-white px-4 py-2 text-sm font-medium">
<Lock className="size-3.5 mr-1" /> Already Included in Your Plan
</Badge>
) : null}
</div>
</div>
</div>
<div className="px-6 lg:container lg:max-w-3xl lg:mx-auto space-y-5 py-6">
{/* ── Benefits ───────────────────────────────────── */}
{features.length > 0 && (
<div className={`rounded-2xl border ${accentBorder} ${accentBg} p-5`}>
<p className="text-xs font-bold uppercase tracking-widest mb-4" style={accentStyle}>
Benefits
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{features.map(({ text }, i) => (
<div key={i} className="flex items-center gap-3">
<div className={`h-8 w-8 rounded-lg ${accentBg} border ${accentBorder} flex items-center justify-center shrink-0`}>
<Check className="size-4" style={accentStyle} />
</div>
<span className="text-sm font-medium">{text}</span>
</div>
))}
</div>
</div>
)}
{/* ── Stats row ─────────────────────────────────────────── */}
<div className="grid grid-cols-3 gap-3">
{[
{ label: bundle ? `${bundle.noun}s` : "Courses", value: bundleCount, icon: BundleIcon },
{ label: "Content", value: totalDuration ?? "—", icon: Clock },
{ label: "Access", value: duration ?? "Lifetime", icon: CalendarDays },
].map(({ label, value, icon: StatIcon }) => (
<div key={label} className="rounded-xl bg-card border p-4 flex flex-col items-center gap-1 text-center">
<StatIcon className="size-4" style={accentStyle} />
<p className="text-2xl font-bold leading-none mt-1">{value}</p>
<p className="text-xs text-muted-foreground">{label}</p>
</div>
))}
</div>
{/* ── Included Items ─────────────────────────────────────── */}
<div className="rounded-2xl bg-card border overflow-hidden">
<div className="px-5 py-4 border-b flex items-center justify-between">
<div className="flex items-center gap-2">
<BundleIcon className="size-4" style={accentStyle} />
<span className="text-sm font-semibold">Bundle</span>
</div>
<Badge variant="secondary">{bundleCount}</Badge>
</div>
<div className="divide-y">
{bundle ? (
bundle.items.map((item) => (
<div key={item[bundle.idKey]} className="flex items-start gap-4 px-5 py-4">
<div className={`h-10 w-10 rounded-xl ${accentBg} border ${accentBorder} flex items-center justify-center shrink-0`}>
<bundle.icon className="size-5" style={accentStyle} />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold line-clamp-1">{item.title}</p>
<div className="flex items-center gap-2 mt-1 flex-wrap">
{item.level && (
<Badge variant="outline" className="text-xs capitalize h-5">
{item.level}
</Badge>
)}
{formatCourseDuration(item.duration_seconds) && (
<span className="text-xs text-muted-foreground flex items-center gap-1">
<Clock className="size-3" />
{formatCourseDuration(item.duration_seconds)}
</span>
)}
{item.course_code && (
<span className="text-xs text-muted-foreground">{item.course_code}</span>
)}
</div>
</div>
<div className="h-6 w-6 rounded-full bg-green-100 dark:bg-green-950 flex items-center justify-center shrink-0">
<Check className="size-3.5 text-green-600 dark:text-green-400" />
</div>
</div>
))
) : (
<div className="flex flex-col items-center justify-center py-10 text-center px-6">
<div className={`h-14 w-14 rounded-2xl ${accentBg} border ${accentBorder} flex items-center justify-center mb-3`}>
<BookOpen className="size-7" style={accentStyle} />
</div>
<p className="font-semibold text-sm">Content coming soon</p>
<p className="text-xs text-muted-foreground mt-1 max-w-xs">
We're curating the best content for this plan. Subscribe now and get instant access the moment they go live.
</p>
</div>
)}
</div>
</div>
{/* ── Bottom CTA ────────────────────────────────────────── */}
{!isCurrent && (
<div className={`rounded-2xl ${badgeCls} p-6 text-center relative overflow-hidden`}>
<div className="absolute inset-0 pointer-events-none overflow-hidden">
<div className="absolute -top-10 -right-10 w-40 h-40 rounded-full bg-white/5" />
<div className="absolute -bottom-8 -left-8 w-32 h-32 rounded-full bg-white/5" />
</div>
<div className="relative">
<p className="text-white font-bold text-lg mb-1">
{isBlockedByOverlap ? "Already Included" : plan.is_active ? "Ready to get started?" : "Coming Soon"}
</p>
<p className="text-white/70 text-sm mb-5 max-w-xs mx-auto">
{isBlockedByOverlap
? "Your existing access already covers item(s) in this bundle, so it can't be purchased separately."
: plan.is_active
? (plan.description || `Everything you need with the ${tierLabel} plan.`)
: "This plan is not available for purchase at the moment. Check back later."}
</p>
<div className="flex flex-col sm:flex-row gap-3 justify-center">
{plan.is_active && !isBlockedByOverlap && (
<Button
size="lg"
className="bg-white text-gray-900 hover:bg-white/90 font-bold shadow-lg"
onClick={() => navigate(`/subscriptions/checkout?plan_id=${plan.plan_id}`)}
>
Get {tierLabel} Plan — {fmtCurrency(plan.price, plan.currency)}
</Button>
)}
</div>
</div>
</div>
)}
</div>
</div>
);
};
export default ViewPlan;
@@ -0,0 +1,778 @@
/*
* ViewRequirement.jsx
* Route: /group/:groupId/view/:taskListId/task/:taskId/requirement
*
* Sidebar: sectioned flat list — one plain heading per requirement type,
* each requirement is a clickable button. When selected, its lesson
* sub-tree renders inline below the item (no accordion, no scoping).
*
* read_course → CourseUnitLessonView (on-demand lesson fetch)
* read_unit → LessonBlock (lessons from unitLessonsMap)
* read_lesson → LessonView (standalone fetch by uuid)
*/
import { useState, useCallback, useEffect, useRef, useMemo } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import AppBreadcrumb from '@/components/generic/Breadcrumb/AppBreadcrumb';
import {
House, TableOfContents, CheckCheck, Circle,
Layers, ArrowLeft, Lock, Zap, RefreshCw, Tag,
ClipboardList, GraduationCap, CheckCircle2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { Skeleton } from '@/components/ui/skeleton';
import { useTask } from '@/contexts/ClientTaskContext';
import { PageMeta } from '@/contexts/MetadataContext';
import { useTaskProgress } from '@/contexts/ClientTaskProgressContext';
import LessonBlock from '@/modules/client/components/LessonBlock';
import api from '@/utils/api.util';
import { useClientTiers } from '@/contexts/ClientTiersProvider';
import { resolveTierBadge } from '@/utils/tierBadge.util';
// ─── Constants ────────────────────────────────────────────────────────────────
const TYPE_LABEL = {
read_course: 'Read a Course',
read_unit: 'Read a Unit',
read_lesson: 'Read a Lesson',
};
// ─── Compact tier badge ───────────────────────────────────────────────────────
const TierBadge = ({ tier }) => {
const { tierMap } = useClientTiers();
if (!tier) return null;
const { label, cls } = resolveTierBadge(tier, tierMap);
return (
<Badge className={`${cls} text-[10px] px-1.5 py-0 h-[18px] leading-none shrink-0`}>
{label}
</Badge>
);
};
// ─── Sidebar ──────────────────────────────────────────────────────────────────
const SidebarContent = ({
requirements,
selection,
onSelectReq,
onSelectLesson,
isCompleted,
unitLessonsMap,
unitLoadingMap,
courseUnitsMap,
courseLoadingMap,
referenceMetaMap,
onNavigateToCourse,
}) => {
const groups = ['read_course', 'read_unit', 'read_lesson']
.map((type) => ({ type, items: requirements.filter((r) => r.type === type) }))
.filter((g) => g.items.length > 0);
return (
<ScrollArea className="h-full">
<div className="p-4 space-y-6">
<div className="flex items-center justify-between gap-2 pr-10 lg:pr-0">
<p className="text-xs font-semibold uppercase tracking-widest text-muted-foreground shrink-0">
Requirements
</p>
{groups.length === 1 && (
<span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/60 bg-muted px-2 py-0.5 rounded-full shrink-0">
{TYPE_LABEL[groups[0].type]}
</span>
)}
</div>
{groups.map(({ type, items }) => (
<div key={type} className="space-y-1">
{/* Section heading — hidden when only one type is visible (entry-scoped) */}
{groups.length > 1 && (
<p className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground px-1 mb-2">
{TYPE_LABEL[type]}
</p>
)}
{items.map((req) => {
const isSelected = selection?.reqId === req.requirement_id;
const done = isCompleted(req.requirement_id, req.reference_id);
const meta = referenceMetaMap[req.requirement_id];
return (
<div key={req.requirement_id}>
{/* Requirement button */}
<button
onClick={() => onSelectReq(req)}
className={`w-full flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors text-left ${
isSelected
? 'bg-muted text-foreground'
: 'text-muted-foreground hover:bg-muted/60 hover:text-foreground'
}`}
>
{done
? <CheckCheck className="size-3.5 text-green-500 shrink-0" />
: <Circle className="size-3.5 shrink-0 opacity-40" />
}
<span className="truncate flex-1 font-medium min-w-0">
{req.reference_label ?? req.type}
</span>
<TierBadge tier={meta?.subscription} />
</button>
{/* Breadcrumb — always visible below the button */}
{type === 'read_unit' && meta?.courseTitle && (
<p className="pl-9 text-[11px] text-muted-foreground truncate -mt-0.5 mb-1">
from <span className="font-medium">{meta.courseTitle}</span>
</p>
)}
{type === 'read_lesson' && (meta?.unitTitle || meta?.courseTitle) && (
<p className="pl-9 text-[11px] text-muted-foreground truncate -mt-0.5 mb-1">
{[meta.unitTitle, meta.courseTitle].filter(Boolean).join(' › ')}
</p>
)}
{/* Sub-tree — only for the selected item */}
{isSelected && type === 'read_unit' && (() => {
const lessons = unitLessonsMap[req.requirement_id]?.lessons ?? [];
const loading = unitLoadingMap[req.requirement_id];
return (
<div className="pl-5 mt-1 space-y-0.5 border-l ml-4 mb-2">
{loading && (
<div className="py-1 space-y-1.5">
<Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-24" />
</div>
)}
{lessons.map((lesson, i) => {
const active = selection?.lessonUuid === lesson.uuid;
return (
<button
key={lesson.uuid}
onClick={() => onSelectLesson(req, lesson)}
className={`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-left transition-colors ${
active
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:bg-muted hover:text-foreground'
}`}
>
<span className="text-xs tabular-nums w-4 shrink-0 opacity-40">{i + 1}</span>
<span className="truncate">{lesson.title}</span>
</button>
);
})}
</div>
);
})()}
{isSelected && type === 'read_course' && (() => {
const courseData = courseUnitsMap[req.requirement_id] ?? {};
const units = courseData.units ?? [];
const assessment = courseData.assessment ?? null;
const courseId = courseData.course_id;
const loading = courseLoadingMap[req.requirement_id];
return (
<div className="pl-5 mt-1 space-y-3 border-l ml-4 mb-2">
{loading && (
<div className="py-1 space-y-1.5">
<Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-24" />
</div>
)}
{units.map((unit) => (
<div key={unit.unit_id} className="space-y-0.5">
<p className="flex items-center gap-1.5 px-2 py-0.5 text-[11px] font-semibold text-muted-foreground uppercase tracking-wide truncate">
<Layers className="size-3 shrink-0 opacity-50" />
{unit.title}
</p>
{(unit.lessons ?? []).map((lesson, lIdx) => {
const active = selection?.lessonUuid === lesson.uuid;
return (
<button
key={lesson.uuid}
onClick={() => onSelectLesson(req, lesson)}
className={`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-left transition-colors ${
active
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:bg-muted hover:text-foreground'
}`}
>
<span className="text-xs tabular-nums w-4 shrink-0 opacity-40">{lIdx + 1}</span>
<span className="truncate">{lesson.title}</span>
</button>
);
})}
{unit.quiz && (
<button
onClick={() => onNavigateToCourse(courseId, { quizUnitId: String(unit.unit_id) })}
className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-left transition-colors text-muted-foreground hover:bg-muted hover:text-foreground"
>
<ClipboardList className="size-3.5 shrink-0 opacity-50" />
<span className="truncate flex-1">{unit.quiz.title || 'Quiz'}</span>
{unit.quiz.has_passed
? <CheckCircle2 className="size-3 text-green-500 shrink-0" />
: <Circle className="size-3 shrink-0 opacity-30" />
}
</button>
)}
</div>
))}
{assessment && (
<button
onClick={() => onNavigateToCourse(courseId, { seekAssessment: true })}
className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-left transition-colors text-muted-foreground hover:bg-muted hover:text-foreground border-t pt-2 mt-1"
>
<GraduationCap className="size-3.5 shrink-0 opacity-50" />
<span className="truncate flex-1">{assessment.title || 'Final Assessment'}</span>
{assessment.has_passed
? <CheckCircle2 className="size-3 text-green-500 shrink-0" />
: <Circle className="size-3 shrink-0 opacity-30" />
}
</button>
)}
</div>
);
})()}
</div>
);
})}
</div>
))}
</div>
</ScrollArea>
);
};
// ─── Course overview (before first lesson selected) ───────────────────────────
const CourseOverview = ({ meta }) => {
const { tierMap } = useClientTiers();
return (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2 flex-wrap">
{meta?.subscription && (() => {
const { rank, label, cls } = resolveTierBadge(meta.subscription, tierMap);
return (
<Badge className={`${cls} capitalize`}>
{rank > 0 ? <Lock className="size-3 mr-1" /> : <Tag className="size-3 mr-1" />}
{label}
</Badge>
);
})()}
{meta?.level && <Badge variant="outline" className="text-xs capitalize">{meta.level}</Badge>}
</div>
<h1 className="text-2xl font-bold">{meta?.title ?? 'Course'}</h1>
{meta?.description && <p className="text-sm text-muted-foreground leading-relaxed">{meta.description}</p>}
<p className="text-sm text-blue-500 dark:text-blue-400 mt-2">Select a lesson from the sidebar to begin reading.</p>
</div>
);
};
// ─── On-demand lesson fetch for read_course ───────────────────────────────────
const CourseUnitLessonView = ({ lessonUuid }) => {
const [lesson, setLesson] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!lessonUuid) return;
setLoading(true);
setLesson(null);
api.get(`/client/courses/lesson/uuid/${lessonUuid}`)
.then((r) => {
const d = r.data?.data;
if (d) setLesson({ ...d, blocks: d.blocks ?? [] });
})
.catch(() => {})
.finally(() => setLoading(false));
}, [lessonUuid]);
if (loading) return <ContentSkeleton />;
return <LessonBlock lesson={lesson} loading={false} />;
};
// ─── Standalone lesson view (read_lesson) ─────────────────────────────────────
const LessonView = ({ req, onMeta }) => {
const [lesson, setLesson] = useState(null);
const [loading, setLoading] = useState(true);
const [locked, setLocked] = useState(false);
useEffect(() => {
if (!req.reference_id) { setLoading(false); return; }
api.get(`/client/courses/lesson/uuid/${req.reference_id}`)
.then((r) => {
const d = r.data?.data;
if (d) {
setLesson({ ...d, blocks: d.blocks ?? [] });
onMeta?.(req.requirement_id, {
subscription: d.unit?.course?.subscription,
courseTitle: d.unit?.course?.title,
unitTitle: d.unit?.title,
});
}
})
.catch((err) => { if (err?.response?.status === 403) setLocked(true); })
.finally(() => setLoading(false));
}, [req.reference_id]);
if (loading) return <ContentSkeleton />;
if (locked) return <LockedContent />;
return <LessonBlock lesson={lesson} loading={false} />;
};
// ─── Skeletons / locked ───────────────────────────────────────────────────────
const ContentSkeleton = () => (
<div className="flex flex-col gap-3">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-7 w-64" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
</div>
);
const LockedContent = () => {
const navigate = useNavigate();
return (
<div className="flex flex-col items-center gap-6 py-20 text-center">
<div className="h-16 w-16 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
<Lock className="size-7 text-amber-500" />
</div>
<div className="space-y-2 max-w-sm">
<h2 className="text-lg font-semibold">Premium / Exclusive Content</h2>
<p className="text-sm text-muted-foreground leading-relaxed">
Subscribe to one of our available tier plans to unlock access to this content.
</p>
</div>
<div className="flex flex-col items-center gap-2">
<Button onClick={() => navigate('/subscriptions')} className="gap-1.5">
<Zap className="size-4" /> View Available Plans
</Button>
<p className="text-xs text-muted-foreground">Already subscribed? Your plan may not cover this subscription.</p>
</div>
</div>
);
};
// ─── Main page ────────────────────────────────────────────────────────────────
const ViewRequirement = () => {
const { groupId, taskListId, taskId } = useParams();
const navigate = useNavigate();
const location = useLocation();
const { task, taskList, loading, fetchTask, fetchTaskList } = useTask();
const { fetchProgress, isCompleted, updateLessonProgress, loading: progressLoading } = useTaskProgress();
const [selection, setSelection] = useState(null);
const [unitLessonsMap, setUnitLessonsMap] = useState({});
const [unitLoadingMap, setUnitLoadingMap] = useState({});
const [courseUnitsMap, setCourseUnitsMap] = useState({});
const [courseLoadingMap, setCourseLoadingMap] = useState({});
const [referenceMetaMap, setReferenceMetaMap] = useState({});
const [lockedReqs, setLockedReqs] = useState(new Set());
const [sidebarOpen, setSidebarOpen] = useState(false);
const [desktopOpen, setDesktopOpen] = useState(true);
const [scrollPct, setScrollPct] = useState(0);
const initialised = useRef(false);
const lastAutoMarkRef = useRef(null);
// ── Fetch task + progress ─────────────────────────────────────────────────
useEffect(() => {
fetchTaskList(groupId, taskListId);
fetchTask(groupId, taskListId, taskId);
fetchProgress(groupId, taskListId, taskId);
}, [groupId, taskListId, taskId]);
// ── read_* requirements only ─────────────────────────────────────────────
const requirements = (task?.requirements ?? []).filter((r) =>
['read_course', 'read_unit', 'read_lesson'].includes(r.type)
);
// ── Scope sidebar to the type that was clicked in ViewTaskDetails ─────────
const entryType = useMemo(() => {
const s = location.state ?? {};
if (s.course) return 'read_course';
if (s.unit) return 'read_unit';
if (s.lesson) return 'read_lesson';
return null;
}, [location.state]);
const sidebarRequirements = entryType
? requirements.filter((r) => r.type === entryType)
: requirements;
// ── Fetch lessons for read_unit requirements ──────────────────────────────
useEffect(() => {
requirements.forEach((req) => {
if (req.type !== 'read_unit') return;
if (unitLessonsMap[req.requirement_id] || unitLoadingMap[req.requirement_id]) return;
setUnitLoadingMap((p) => ({ ...p, [req.requirement_id]: true }));
api.get(`/client/courses/unit/uuid/${req.reference_id}/lessons`)
.then((r) => {
const data = r.data?.data ?? null;
setUnitLessonsMap((p) => ({ ...p, [req.requirement_id]: { meta: data, lessons: data?.lessons ?? [] } }));
})
.catch((err) => {
if (err?.response?.status === 403)
setLockedReqs((p) => new Set(p).add(req.requirement_id));
})
.finally(() => setUnitLoadingMap((p) => ({ ...p, [req.requirement_id]: false })));
});
}, [requirements.length]);
// ── Fetch unit + lesson tree for read_course requirements ─────────────────
useEffect(() => {
requirements.forEach(async (req) => {
if (req.type !== 'read_course') return;
if (courseUnitsMap[req.requirement_id] || courseLoadingMap[req.requirement_id]) return;
setCourseLoadingMap((p) => ({ ...p, [req.requirement_id]: true }));
try {
const uuidRes = await api.get(`/client/courses/uuid/${req.reference_id}`);
const meta = uuidRes.data?.data;
if (!meta?.course_id) return;
const fullRes = await api.get(`/client/courses/${meta.course_id}`);
const full = fullRes.data?.data;
setCourseUnitsMap((p) => ({
...p,
[req.requirement_id]: {
meta: { ...meta, description: full?.description ?? meta.description },
units: full?.units ?? [],
assessment: full?.assessment ?? null,
course_id: meta.course_id,
},
}));
setReferenceMetaMap((p) => ({ ...p, [req.requirement_id]: { subscription: meta.subscription } }));
} catch (err) {
if (err?.response?.status === 403)
setLockedReqs((p) => new Set(p).add(req.requirement_id));
} finally {
setCourseLoadingMap((p) => ({ ...p, [req.requirement_id]: false }));
}
});
}, [requirements.length]);
// ── Tier meta for read_unit from unitLessonsMap ───────────────────────────
useEffect(() => {
requirements.forEach((req) => {
if (req.type !== 'read_unit') return;
const data = unitLessonsMap[req.requirement_id];
if (!data?.meta?.course || referenceMetaMap[req.requirement_id]) return;
setReferenceMetaMap((p) => ({
...p,
[req.requirement_id]: {
subscription: data.meta.course.subscription,
courseTitle: data.meta.course.title,
},
}));
});
}, [unitLessonsMap]);
// ── Tier meta for read_lesson (separate fetch) ────────────────────────────
useEffect(() => {
requirements.forEach(async (req) => {
if (req.type !== 'read_lesson' || referenceMetaMap[req.requirement_id]) return;
try {
const res = await api.get(`/client/courses/lesson/uuid/${req.reference_id}`);
const d = res.data?.data;
if (d) setReferenceMetaMap((p) => ({
...p,
[req.requirement_id]: {
subscription: d.unit?.course?.subscription,
courseTitle: d.unit?.course?.title,
unitTitle: d.unit?.title,
},
}));
} catch { /* silently fail */ }
});
}, [requirements.length]);
// ── Auto-select from router state or first item ───────────────────────────
useEffect(() => {
if (initialised.current || !requirements.length) return;
const state = location.state ?? {};
const trySelect = (key, type) => {
if (!state[key]?.id) return false;
const req = requirements.find((r) => r.requirement_id === state[key].id);
if (!req) return false;
const needsLesson = type === 'read_unit' || type === 'read_course';
setSelection({ reqId: req.requirement_id, ...(needsLesson ? { lessonUuid: null } : {}) });
return true;
};
if (!trySelect('course', 'read_course') && !trySelect('unit', 'read_unit') && !trySelect('lesson', 'read_lesson')) {
const first = requirements[0];
const needsLesson = first.type === 'read_unit' || first.type === 'read_course';
setSelection({ reqId: first.requirement_id, ...(needsLesson ? { lessonUuid: null } : {}) });
}
initialised.current = true;
}, [requirements, location.state]);
// ── Auto-pick first lesson once unit/course lessons load ─────────────────
useEffect(() => {
if (!selection || selection.lessonUuid !== null) return;
const req = requirements.find((r) => r.requirement_id === selection.reqId);
if (req?.type === 'read_unit') {
const lessons = unitLessonsMap[req.requirement_id]?.lessons ?? [];
if (lessons.length) setSelection((p) => ({ ...p, lessonUuid: lessons[0].uuid }));
}
if (req?.type === 'read_course') {
const units = courseUnitsMap[req.requirement_id]?.units ?? [];
const first = units.flatMap((u) => u.lessons ?? [])[0];
if (first) setSelection((p) => ({ ...p, lessonUuid: first.uuid }));
}
}, [unitLessonsMap, courseUnitsMap, selection?.reqId]);
// ── Derived objects ───────────────────────────────────────────────────────
const selectedReq = requirements.find((r) => r.requirement_id === selection?.reqId) ?? null;
const selectedLesson = (() => {
if (!selectedReq || !selection?.lessonUuid) return null;
if (selectedReq.type === 'read_unit') {
return (unitLessonsMap[selectedReq.requirement_id]?.lessons ?? [])
.find((l) => l.uuid === selection.lessonUuid) ?? null;
}
if (selectedReq.type === 'read_course') {
const units = courseUnitsMap[selectedReq.requirement_id]?.units ?? [];
return units.flatMap((u) => u.lessons ?? []).find((l) => l.uuid === selection.lessonUuid) ?? null;
}
return null;
})();
// ── Next lesson (cross-unit for read_course) ──────────────────────────────
const nextLesson = (() => {
if (!selectedReq) return null;
if (selectedReq.type === 'read_unit') {
const lessons = unitLessonsMap[selectedReq.requirement_id]?.lessons ?? [];
const idx = lessons.findIndex((l) => l.uuid === selection?.lessonUuid);
return idx !== -1 && idx < lessons.length - 1 ? lessons[idx + 1] : null;
}
if (selectedReq.type === 'read_course') {
const flat = (courseUnitsMap[selectedReq.requirement_id]?.units ?? []).flatMap((u) => u.lessons ?? []);
const idx = flat.findIndex((l) => l.uuid === selection?.lessonUuid);
return idx !== -1 && idx < flat.length - 1 ? flat[idx + 1] : null;
}
return null;
})();
// ── Scroll tracking ───────────────────────────────────────────────────────
useEffect(() => {
window.scrollTo(0, 0);
const h = document.documentElement.scrollHeight - window.innerHeight;
setScrollPct(h <= 40 ? 100 : 0);
}, [selection]);
useEffect(() => {
const onScroll = () => {
const h = document.documentElement.scrollHeight - window.innerHeight;
const y = window.scrollY;
if (h <= 0 || h - y <= 40) { setScrollPct(100); return; }
setScrollPct(Math.min(99, Math.round((y / h) * 100)));
};
window.addEventListener('scroll', onScroll, { passive: true });
return () => window.removeEventListener('scroll', onScroll);
}, []);
// ── Breadcrumbs ───────────────────────────────────────────────────────────
const crumbsFull = [
{ label: 'Home', icon: <House className="size-4" />, to: '/dashboard' },
{ label: taskList?.name ?? '…', to: `/group/${groupId}/view/${taskListId}` },
{ label: task?.name ?? '…', to: `/group/${groupId}/view/${taskListId}/task/${taskId}` },
{ label: 'Requirements' },
];
const crumbsMobile = [
{ label: 'Home', icon: <House className="size-4" />, to: '/dashboard' },
{ label: 'Requirements' },
];
// ── Handlers ─────────────────────────────────────────────────────────────
const handleSelectReq = useCallback((req) => {
const needsLesson = req.type === 'read_unit' || req.type === 'read_course';
setSelection({ reqId: req.requirement_id, ...(needsLesson ? { lessonUuid: null } : {}) });
setSidebarOpen(false);
}, []);
const handleSelectLesson = useCallback((req, lesson) => {
setSelection({ reqId: req.requirement_id, lessonUuid: lesson.uuid });
setSidebarOpen(false);
}, []);
const handleMarkDone = useCallback(async () => {
if (!selectedReq) return;
const completed = !isCompleted(selectedReq.requirement_id, selectedReq.reference_id);
await updateLessonProgress(groupId, taskListId, taskId, selectedReq.requirement_id, {
reference_id: selectedReq.reference_id,
completed,
siblingLessons: [],
});
}, [selectedReq, groupId, taskListId, taskId, isCompleted, updateLessonProgress]);
const selectedDone = selectedReq ? isCompleted(selectedReq.requirement_id, selectedReq.reference_id) : false;
const isLastContent = !nextLesson;
const canMarkDone = scrollPct >= 100 && isLastContent;
// ── Auto turn-in ──────────────────────────────────────────────────────────
useEffect(() => {
if (!canMarkDone || selectedDone || progressLoading || !selectedReq) return;
if (lockedReqs.has(selectedReq.requirement_id)) return;
const key = selectedReq.requirement_id + (selection?.lessonUuid ?? '');
if (lastAutoMarkRef.current === key) return;
lastAutoMarkRef.current = key;
handleMarkDone();
}, [canMarkDone, selectedDone]); // eslint-disable-line react-hooks/exhaustive-deps
const handleNavigateToCourse = useCallback((courseId, opts) => {
navigate(`/course/${courseId}/unit`, { state: opts });
}, [navigate]);
const sidebarProps = {
requirements: sidebarRequirements,
selection,
onSelectReq: handleSelectReq,
onSelectLesson: handleSelectLesson,
isCompleted,
unitLessonsMap,
unitLoadingMap,
courseUnitsMap,
courseLoadingMap,
referenceMetaMap,
onNavigateToCourse: handleNavigateToCourse,
};
return (
<>
<PageMeta title={task ? `${task.name} – Requirements - STARR` : undefined} />
{/* ── Floating "up next" ────────────────────────────────────────── */}
{scrollPct >= 100 && nextLesson && (
<div className="fixed bottom-6 right-6 z-20 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div
onClick={() => handleSelectLesson(selectedReq, nextLesson)}
className="flex items-center gap-3 bg-card border rounded-xl dark:hover:border-blue-500 px-4 py-3 shadow-xl hover:bg-muted transition-colors text-sm font-medium cursor-pointer select-none"
>
<div className="flex flex-col items-start">
<span className="text-xs text-muted-foreground font-normal">Up next</span>
{nextLesson.title}
</div>
</div>
</div>
)}
{/* ── Top sticky bar ────────────────────────────────────────────── */}
<div className="fixed top-[67px] left-0 right-0 z-40 bg-card border-b py-3 px-4 md:px-6">
<div className="w-full flex items-center justify-between gap-2">
<Button
variant="ghost"
size="icon"
className="sm:hidden shrink-0"
onClick={() => navigate(`/group/${groupId}/view/${taskListId}/task/${taskId}`)}
>
<ArrowLeft className="size-4" />
</Button>
<div className="hidden sm:block min-w-0 flex-1">
<AppBreadcrumb items={crumbsFull} />
</div>
<div className="sm:hidden min-w-0 flex-1 truncate">
<AppBreadcrumb items={crumbsMobile} />
</div>
<div className="flex items-center gap-2">
{selectedDone && (
<span className="hidden sm:flex items-center gap-1.5 text-sm text-green-600 dark:text-green-400">
<CheckCheck className="size-4" /> Done
</span>
)}
<Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
<SheetTrigger asChild>
<Button variant="outline" size="icon" className="lg:hidden flex-shrink-0">
<TableOfContents className="size-4" />
</Button>
</SheetTrigger>
<SheetContent side="left" className="p-0 w-80">
<SidebarContent {...sidebarProps} />
</SheetContent>
</Sheet>
<Button
variant="outline"
className="hidden lg:flex"
onClick={() => setDesktopOpen((p) => !p)}
>
<TableOfContents />
</Button>
</div>
</div>
{selectedReq && (
<div className="absolute bottom-0 left-0 right-0 h-1.5 bg-border">
<div
className={`h-full transition-all duration-150 ease-out ${
scrollPct >= 100 ? 'bg-green-500' : 'bg-primary'
}`}
style={{ width: `${scrollPct}%` }}
/>
</div>
)}
</div>
{/* ── Desktop sidebar ───────────────────────────────────────────── */}
{desktopOpen && (
<div className="hidden lg:block fixed top-[124px] bottom-0 left-0 w-96 bg-muted/60 border-r">
<SidebarContent {...sidebarProps} />
</div>
)}
{/* ── Main content ──────────────────────────────────────────────── */}
<div className={`mt-32 ${desktopOpen ? 'lg:ml-96' : 'lg:ml-0'} p-4 md:p-6 min-h-screen`}>
<div className="relative w-full h-full max-w-3xl mx-auto">
{loading ? (
<ContentSkeleton />
) : !requirements.length ? (
<p className="text-muted-foreground text-sm">This task has no read requirements.</p>
) : !selectedReq ? (
<p className="text-muted-foreground text-sm">Select a requirement to view.</p>
) : (
<div className="flex flex-col gap-6">
{selectedReq.type === 'read_course' && (
lockedReqs.has(selectedReq.requirement_id) ? <LockedContent /> :
selection?.lessonUuid ? <CourseUnitLessonView lessonUuid={selection.lessonUuid} /> :
courseLoadingMap[selectedReq.requirement_id] ? <ContentSkeleton /> :
<CourseOverview meta={courseUnitsMap[selectedReq.requirement_id]?.meta} />
)}
{selectedReq.type === 'read_unit' && (
lockedReqs.has(selectedReq.requirement_id) ? <LockedContent /> :
selectedLesson ? <LessonBlock lesson={selectedLesson} loading={false} /> :
<ContentSkeleton />
)}
{selectedReq.type === 'read_lesson' && (
<LessonView
req={selectedReq}
onMeta={(reqId, meta) =>
setReferenceMetaMap((p) => ({ ...p, [reqId]: meta }))
}
/>
)}
{/* Turn-in footer — only shown while not yet completed */}
{!lockedReqs.has(selectedReq.requirement_id) && !selectedDone && (
<div className="flex items-center pt-4 border-t">
{nextLesson ? (
<p className="text-sm text-muted-foreground">Continue reading all lessons to complete this requirement.</p>
) : !canMarkDone ? (
<p className="text-sm text-muted-foreground">Scroll to the end to complete this requirement.</p>
) : (
<span className="flex items-center gap-1.5 text-sm text-muted-foreground">
<RefreshCw className="size-3.5 animate-spin" /> Turning in…
</span>
)}
</div>
)}
</div>
)}
</div>
</div>
</>
);
};
export default ViewRequirement;
@@ -0,0 +1,654 @@
/***********************************************************************************************************************************************************************
* File Name : ViewTask.jsx
* Type : Page (Client)
* Description : Displays a single task within a task list, with all its
* requirements and the user's completion status.
* Wired to TaskContext + TaskProgressContext.
* Route: /group/:groupId/view/:taskListId/task/:taskId (index)
***********************************************************************************************************************************************************************/
import { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
Trophy, Clock, Paperclip, Plus,
Link, BookOpen, LayoutList, FileText, House,
Image, Video, Music, PenLine, Hourglass, XCircle,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Skeleton } from '@/components/ui/skeleton';
import AppBreadcrumb from '@/components/generic/Breadcrumb/AppBreadcrumb';
import ResponsiveModal from '@/components/generic/ResponsiveModal';
import { toast } from 'sonner';
import FileUpload from '../components/blocks/FileUpload';
import FilePreview from '../components/FilePreview';
import VisitLink from '../components/blocks/VisitLink';
import ReadCourse from '../components/blocks/ReadCourse';
import ReadUnit from '../components/blocks/ReadUnit';
import ReadLesson from '../components/blocks/ReadLesson';
import { useTask } from '@/contexts/ClientTaskContext';
import { PageMeta } from '@/contexts/MetadataContext';
import { useTaskProgress } from '@/contexts/ClientTaskProgressContext';
import { useGroup } from '@/contexts/ClientGroupContext';
import { formatDate, formatDateTime } from '@/utils/table.util';
import api from '@/utils/api.util';
// ─── Status badge ─────────────────────────────────────────────────────────────
const StatusBadge = ({ latestCompletion, requiresReview }) => {
if (!latestCompletion) return <Badge variant="outline">Assigned</Badge>;
if (requiresReview) {
if (latestCompletion.status === 'approved') {
return <Badge className="bg-green-100 text-green-700 border-green-400 dark:bg-green-900/40 dark:text-green-400 dark:border-green-700">Approved</Badge>;
}
if (latestCompletion.status === 'rejected') {
return <Badge variant="destructive" className="gap-1"><XCircle className="size-3" /> Rejected — resubmit</Badge>;
}
return <Badge className="bg-amber-100 text-amber-700 border-amber-400 dark:bg-amber-900/40 dark:text-amber-400 dark:border-amber-700 gap-1"><Hourglass className="size-3" /> Pending Review</Badge>;
}
return <Badge variant="outline">Turned in</Badge>;
};
// ─── Requirements status panel ────────────────────────────────────────────────
const RequirementsStatusPanel = ({ requirements = [], latestCompletion, isVisited, isCompleted }) => {
const reqTypes = requirements.map((r) => r.type);
// upload_file and submit_text share one TaskCompletion — "done" also needs
// status === 'approved' when either requirement opted into requires_review.
const submissionDone = (type) => {
const reqs = requirements.filter((r) => r.type === type);
if (!reqs.length || !latestCompletion) return false;
const needsReview = reqs.some((r) => r.requires_review);
return needsReview ? latestCompletion.status === 'approved' : true;
};
const items = [
{
key: 'upload_file',
label: 'File upload',
icon: <Paperclip className="size-4 shrink-0 text-muted-foreground" />,
getValue: () => {
const done = submissionDone('upload_file');
return { done: done ? 1 : 0, total: 1, binary: true };
},
},
{
key: 'submit_text',
label: 'Written response',
icon: <PenLine className="size-4 shrink-0 text-muted-foreground" />,
getValue: () => {
const done = submissionDone('submit_text');
return { done: done ? 1 : 0, total: 1, binary: true };
},
},
{
key: 'visit_link',
label: 'Visit links',
icon: <Link className="size-4 shrink-0 text-muted-foreground" />,
getValue: () => {
const reqs = requirements.filter((r) => r.type === 'visit_link');
const done = reqs.filter((r) => isVisited(r.requirement_id)).length;
return { done, total: reqs.length, binary: false };
},
},
{
key: 'read_course',
label: 'Read courses',
icon: <BookOpen className="size-4 shrink-0 text-muted-foreground" />,
getValue: () => {
const reqs = requirements.filter((r) => r.type === 'read_course');
const done = reqs.filter((r) => isCompleted(r.requirement_id, r.reference_id)).length;
return { done, total: reqs.length, binary: false };
},
},
{
key: 'read_unit',
label: 'Read units',
icon: <LayoutList className="size-4 shrink-0 text-muted-foreground" />,
getValue: () => {
const reqs = requirements.filter((r) => r.type === 'read_unit');
const done = reqs.filter((r) => isCompleted(r.requirement_id, r.reference_id)).length;
return { done, total: reqs.length, binary: false };
},
},
{
key: 'read_lesson',
label: 'Read lessons',
icon: <FileText className="size-4 shrink-0 text-muted-foreground" />,
getValue: () => {
const reqs = requirements.filter((r) => r.type === 'read_lesson');
const done = reqs.filter((r) => isCompleted(r.requirement_id, r.reference_id)).length;
return { done, total: reqs.length, binary: false };
},
},
];
const provided = items.filter(({ key }) => reqTypes.includes(key));
const completedCount = provided.filter(({ getValue }) => {
const { done, total } = getValue();
return total > 0 && done >= total;
}).length;
const overallPercent = provided.length > 0
? Math.round((completedCount / provided.length) * 100)
: 0;
return (
<div className="border shadow-lg bg-card rounded-lg p-5 flex flex-col gap-4">
<h2 className="font-semibold text-base">Requirements</h2>
<div className="flex flex-col gap-3">
{provided.map(({ key, label, icon, getValue }) => {
const { done, total, binary } = getValue();
const complete = total > 0 && done >= total;
return (
<div key={key} className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
{icon}
<span className="text-sm">{label}</span>
</div>
{binary ? (
<Badge variant="secondary" className="text-xs">
{complete ? 'Done' : 'Missing'}
</Badge>
) : (
<Badge variant="secondary" className="text-xs">
{done} / {total}
</Badge>
)}
</div>
);
})}
</div>
<div className="flex flex-col gap-2 pt-2 border-t">
<div className="flex items-center justify-between">
<span className="text-sm">Overall progress</span>
{provided.length > 0 && completedCount >= provided.length && (
<span className="text-sm">Completed</span>
)}
</div>
<Progress
value={overallPercent}
className={`h-1.5 ${provided.length > 0 && completedCount >= provided.length ? "[&>div]:bg-green-500" : ""}`}
/>
</div>
</div>
);
};
// ─── File row — clickable, opens FilePreview ─────────────────────────────────
const FileRow = ({ file, onClick }) => {
const Icon = (() => {
const mime = file.mime_type ?? '';
if (mime.startsWith('image/')) return Image;
if (mime.startsWith('video/')) return Video;
if (mime.startsWith('audio/')) return Music;
if (mime === 'application/pdf') return FileText;
return Paperclip;
})();
return (
<button
type="button"
onClick={onClick}
className="flex items-center gap-2 border rounded-md px-3 py-2 text-sm bg-muted hover:bg-muted/70 transition-colors text-left w-full"
>
<Icon className="size-4 shrink-0 text-muted-foreground" />
<span className="truncate flex-1">{file.file_name}</span>
</button>
);
};
// ─── Submission panel (Your Work) — upload_file and/or submit_text ────────────
const SubmissionPanel = ({ latestCompletion, onAddAttachment, submitting, onFileClick, requiresReview, hasTextRequirement, acceptsSubmissions }) => {
const files = latestCompletion?.files ?? [];
return (
<div className="border shadow-lg bg-card rounded-lg p-5 flex flex-col gap-4 xs:order-1 lg:order-0">
<div className="flex items-center justify-between">
<h2 className="font-semibold text-base">Your work</h2>
<div className="flex items-center gap-2">
<StatusBadge latestCompletion={latestCompletion} requiresReview={requiresReview} />
{files.length >= 2 && (
<Badge>
<Paperclip className="size-3 mr-1" />
+{files.length} Attachments
</Badge>
)}
</div>
</div>
{latestCompletion?.status === 'rejected' && latestCompletion?.review_note && (
<p className="text-sm text-destructive bg-destructive/5 border border-destructive/30 rounded-md p-3">
{latestCompletion.review_note}
</p>
)}
{hasTextRequirement && latestCompletion?.response_text && (
<p className="text-sm border rounded-md p-3 whitespace-pre-wrap bg-muted/40">{latestCompletion.response_text}</p>
)}
{files.length > 0 ? (
files.length >= 2 ? (
<ScrollArea className="max-h-[210px]">
<div className="flex flex-col gap-2">
{files.map((f) => (
<FileRow key={f.file_id} file={f} onClick={() => onFileClick(f)} />
))}
</div>
</ScrollArea>
) : (
<div className="flex flex-col gap-2">
{files.map((f) => (
<FileRow key={f.file_id} file={f} onClick={() => onFileClick(f)} />
))}
</div>
)
) : !(hasTextRequirement && latestCompletion?.response_text) ? (
<p className="text-sm text-center py-6 text-muted-foreground">No work attached</p>
) : null}
<div className="flex flex-col gap-3">
{acceptsSubmissions ? (
<Button className="w-full" onClick={onAddAttachment} disabled={submitting}>
<Plus /> {latestCompletion ? 'Resubmit' : 'Turn In'}
</Button>
) : (
<p className="text-sm text-center text-muted-foreground py-2">
This task no longer accepts submissions
</p>
)}
</div>
</div>
);
};
// ─── Main page ────────────────────────────────────────────────────────────────
const ViewTask = () => {
const { groupId, taskListId, taskId } = useParams();
const navigate = useNavigate();
const {
task, taskList, loading,
fetchTask, fetchTaskList,
latestCompletion,
completeTask, completionLoading,
} = useTask();
const {
fetchProgress,
isVisited, isCompleted,
visitLink,
unvisitLink,
resetProgress,
} = useTaskProgress();
const { group, fetchGroup } = useGroup();
const [taskModal, setTaskModal] = useState(false);
const [uploadState, setUploadState] = useState({ files: [], isUploading: false });
const [note, setNote] = useState('');
const [responseText, setResponseText] = useState('');
const [submitting, setSubmitting] = useState(false);
const [previewFile, setPreviewFile] = useState(null);
// ── Fetch task list (for breadcrumb), task, and progress ──────────────────
useEffect(() => {
fetchTaskList(groupId, taskListId);
fetchTask(groupId, taskListId, taskId);
fetchProgress(groupId, taskListId, taskId);
fetchGroup(groupId);
return () => resetProgress();
}, [groupId, taskListId, taskId]);
// ── Loading state ──────────────────────────────────────────────────────────
const isResolving = loading || !task;
// ── Requirements from task ────────────────────────────────────────────────
const requirements = task?.requirements ?? [];
const reqTypes = requirements.map((r) => r.type);
const hasFileUpload = reqTypes.includes('upload_file');
const hasTextReq = reqTypes.includes('submit_text');
const hasSubmission = hasFileUpload || hasTextReq;
const requiresReview = requirements.some((r) => ['upload_file', 'submit_text'].includes(r.type) && r.requires_review);
// ── Upload file requirement config (allowed types, max count) ─────────────
const uploadFileReq = requirements.find((r) => r.type === 'upload_file');
const allowedFileTypes = uploadFileReq?.allowed_file_types ?? [];
const maxFileCount = uploadFileReq?.max_file_count ?? null;
const textReq = requirements.find((r) => r.type === 'submit_text');
// ── Visit link handler (passed to VisitLink block) ────────────────────────
const handleVisitLink = useCallback(async (requirementId) => {
await visitLink(groupId, taskListId, taskId, requirementId);
}, [groupId, taskListId, taskId, visitLink]);
const handleUnvisitLink = useCallback(async (requirementId) => {
await unvisitLink(groupId, taskListId, taskId, requirementId);
}, [groupId, taskListId, taskId, unvisitLink]);
// ── Submit handler ────────────────────────────────────────────────────────
const handleSubmit = async () => {
if (uploadState.isUploading) return;
if (hasFileUpload && !uploadState.files.length) return;
if (!hasFileUpload && hasTextReq && !responseText.trim()) return;
setSubmitting(true);
try {
// 1. Upload each file to the task-scoped upload endpoint first
const uploadedFiles = [];
for (const f of uploadState.files) {
if (f.status !== 'done' || !f.rawFile) continue;
const formData = new FormData();
formData.append('file', f.rawFile); // ← rawFile exposed by FileUpload onChange
const res = await api.post(
`/client/groups/${groupId}/task-lists/${taskListId}/tasks/${taskId}/upload`,
formData,
{ headers: { 'Content-Type': 'multipart/form-data' } }
);
const data = res.data?.data;
uploadedFiles.push({
file_url: data.file_url,
file_name: data.file_name,
file_size: data.file_size,
mime_type: data.mime_type,
storage_key: data.storage_key,
});
}
if (hasFileUpload && !uploadedFiles.length) {
toast('No files were uploaded successfully.');
return;
}
// 2. Submit completion with uploaded file references + response text
await completeTask(groupId, taskListId, taskId, {
note: note.trim() || null,
files: uploadedFiles,
response_text: hasTextReq ? (responseText.trim() || null) : undefined,
});
setTaskModal(false);
setNote('');
setResponseText('');
setUploadState({ files: [], isUploading: false });
} catch (err) {
toast('Failed to submit. Please try again.');
} finally {
setSubmitting(false);
}
};
// ── Derived data ──────────────────────────────────────────────────────────
const visitLinkReqs = requirements.filter((r) => r.type === 'visit_link');
const readCourseReqs = requirements.filter((r) => r.type === 'read_course');
const readUnitReqs = requirements.filter((r) => r.type === 'read_unit');
const readLessonReqs = requirements.filter((r) => r.type === 'read_lesson');
const breadcrumbItems = [
{ label: 'Home', icon: <House className="size-4" />, to: '/dashboard' },
{ label: group?.name ?? '…', to: `/group/${groupId}` },
{ label: taskList?.name ?? '…', to: `/group/${groupId}/view/${taskListId}` },
{ label: task?.name ?? '…' },
];
return (
<div className="mt-17">
<PageMeta title={task ? `${task.name} - STARR` : undefined} />
{/* ── Submission modal (files and/or text response) ────────────────── */}
{hasSubmission && (
<ResponsiveModal
open={taskModal}
onOpenChange={setTaskModal}
title={hasFileUpload ? 'Add Attachment' : 'Submit Response'}
description={task?.name ?? ''}
footer={
<>
<Button variant="outline" onClick={() => setTaskModal(false)}>
Cancel
</Button>
<Button
onClick={handleSubmit}
disabled={
submitting ||
uploadState.isUploading ||
(hasFileUpload && uploadState.files.length === 0) ||
(!hasFileUpload && hasTextReq && !responseText.trim())
}
>
{submitting ? 'Submitting…' : uploadState.isUploading ? 'Uploading…' : 'Turn in'}
</Button>
</>
}
>
{hasTextReq && (
<div className="flex flex-col gap-1.5 mb-3">
<label className="text-sm font-medium">
{textReq?.prompt || 'Your response'}
</label>
<textarea
className="w-full rounded-md border bg-muted/50 px-3 py-2 text-sm resize-none focus:outline-none focus:ring-1 focus:ring-ring"
rows={5}
placeholder="Write your response…"
value={responseText}
onChange={(e) => setResponseText(e.target.value)}
/>
</div>
)}
{/* Optional note */}
<div className="flex flex-col gap-1.5 mb-3">
<label className="text-sm font-medium">Note (optional)</label>
<textarea
className="w-full rounded-md border bg-muted/50 px-3 py-2 text-sm resize-none focus:outline-none focus:ring-1 focus:ring-ring"
rows={2}
placeholder="Add a note for your submission…"
value={note}
onChange={(e) => setNote(e.target.value)}
/>
</div>
{hasFileUpload && (
<FileUpload
allowedFileTypes={allowedFileTypes}
maxFileCount={maxFileCount}
onChange={(state) => setUploadState(state)}
/>
)}
</ResponsiveModal>
)}
<div className="lg:container lg:mx-auto flex flex-col gap-6 py-6 xs:px-6 lg:px-0">
<AppBreadcrumb items={breadcrumbItems} />
<div className="grid lg:grid-cols-[1fr_350px] gap-6 items-start">
{/* ── Left ──────────────────────────────────────────────── */}
<div className="flex flex-col gap-6 min-w-0 w-full max-w-full">
{/* Task header card */}
<div className="border rounded-lg bg-card overflow-hidden">
<div className="p-6 border-b flex flex-col gap-2">
{isResolving ? (
<>
<Skeleton className="h-4 w-32" />
<Skeleton className="h-7 w-64 mt-1" />
<Skeleton className="h-4 w-48 mt-1" />
</>
) : (
<>
<p className="text-sm text-muted-foreground">
{taskList?.name} &nbsp;·&nbsp; {task?.createdAt ? formatDate(task.createdAt) : ''}
</p>
<h1 className="text-2xl font-bold">{task?.name}</h1>
<div className="flex items-center gap-4 text-sm [&_svg]:size-4">
{task?.deadline && (
<span className="flex items-center gap-1.5">
<Clock /> Due {formatDateTime(task.deadline)}
</span>
)}
</div>
</>
)}
</div>
<div className="p-6">
{isResolving
? <Skeleton className="h-4 w-full" />
: <p className="text-md leading-relaxed">{task?.description ?? '—'}</p>
}
</div>
</div>
{/* Requirements status panel — mobile only, right after the header */}
{!isResolving && requirements.length > 0 && (
<div className="lg:hidden">
<RequirementsStatusPanel
requirements={requirements}
latestCompletion={latestCompletion}
isVisited={isVisited}
isCompleted={isCompleted}
/>
</div>
)}
{/* Requirements section */}
{!isResolving && requirements.length > 0 && (
<>
{/* visit_link */}
{visitLinkReqs.length > 0 && (
<VisitLink
links={visitLinkReqs.map((r) => ({
id: r.requirement_id,
requirement_id: r.requirement_id,
label: r.link_label ?? r.reference_label ?? 'Link',
url: r.link_url,
}))}
visitedMap={
Object.fromEntries(
visitLinkReqs.map((r) => [r.requirement_id, isVisited(r.requirement_id)])
)
}
onVisit={handleVisitLink}
onUnvisit={handleUnvisitLink}
/>
)}
{/* read_course */}
{readCourseReqs.length > 0 && (
<ReadCourse
courses={readCourseReqs.map((r) => ({
id: r.requirement_id,
reference_id: r.reference_id,
title: r.reference_label ?? 'Course',
description: r.description ?? '',
completed: isCompleted(r.requirement_id, r.reference_id),
}))}
groupId={groupId}
taskListId={taskListId}
taskId={taskId}
/>
)}
{/* read_unit */}
{readUnitReqs.length > 0 && (
<ReadUnit
units={readUnitReqs.map((r) => ({
id: r.requirement_id,
reference_id: r.reference_id,
title: r.reference_label ?? 'Unit',
description: r.description ?? '',
completed: isCompleted(r.requirement_id, r.reference_id),
}))}
groupId={groupId}
taskListId={taskListId}
taskId={taskId}
/>
)}
{/* read_lesson */}
{readLessonReqs.length > 0 && (
<ReadLesson
lessons={readLessonReqs.map((r) => ({
id: r.requirement_id,
reference_id: r.reference_id,
title: r.reference_label ?? 'Lesson',
description: r.description ?? '',
completed: isCompleted(r.requirement_id, r.reference_id),
}))}
groupId={groupId}
taskListId={taskListId}
taskId={taskId}
/>
)}
</>
)}
{/* Your work — mobile only, at the very end */}
{hasSubmission && (
<div className="lg:hidden">
<SubmissionPanel
latestCompletion={latestCompletion}
onAddAttachment={() => setTaskModal(true)}
submitting={submitting}
onFileClick={(file) => setPreviewFile(file)}
requiresReview={requiresReview}
hasTextRequirement={hasTextReq}
acceptsSubmissions={task?.accepts_submissions !== false}
/>
</div>
)}
</div>
{/* ── Right (desktop sidebar only) ───────────────────────── */}
<div className="hidden lg:flex lg:flex-col gap-4 lg:sticky lg:top-24 lg:self-start select-none">
{hasSubmission && (
<SubmissionPanel
latestCompletion={latestCompletion}
onAddAttachment={() => setTaskModal(true)}
submitting={submitting}
onFileClick={(file) => setPreviewFile(file)}
requiresReview={requiresReview}
hasTextRequirement={hasTextReq}
acceptsSubmissions={task?.accepts_submissions !== false}
/>
)}
<RequirementsStatusPanel
requirements={requirements}
latestCompletion={latestCompletion}
isVisited={isVisited}
isCompleted={isCompleted}
/>
</div>
</div>
</div>
{/* ── File preview dialog ──────────────────────────────────────── */}
<FilePreview
file={previewFile}
open={!!previewFile}
onOpenChange={(v) => !v && setPreviewFile(null)}
streamUrl={
previewFile && latestCompletion?.completion_id
? `${import.meta.env.VITE_API_URL ?? ''}/client/groups/${groupId}/task-lists/${taskListId}/tasks/${taskId}/completions/${latestCompletion.completion_id}/files/${previewFile.file_id}/stream`
: undefined
}
downloadUrl={
previewFile && latestCompletion?.completion_id
? `${import.meta.env.VITE_API_URL ?? ''}/client/groups/${groupId}/task-lists/${taskListId}/tasks/${taskId}/completions/${latestCompletion.completion_id}/files/${previewFile.file_id}/download`
: undefined
}
/>
</div>
);
};
export default ViewTask;
@@ -0,0 +1,392 @@
/***********************************************************************************************************************************************************************
* File Name : ViewTaskDetails.jsx
* Type : Page (Client)
* Description : Lists tasks within a task list, grouped by status tabs:
* Ongoing | Completed | Overdue. Supports grid and list views.
* Server-side filtered via fetchTaskList(groupId, taskListId, { status }).
* Route: /group/:groupId/view/:taskListId (index)
***********************************************************************************************************************************************************************/
import { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTask } from '@/contexts/ClientTaskContext';
import { useGroup } from '@/contexts/ClientGroupContext';
import { PageMeta } from '@/contexts/MetadataContext';
import api from '@/utils/api.util';
import AppBreadcrumb from '@/components/generic/Breadcrumb/AppBreadcrumb';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Progress } from '@/components/ui/progress';
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription,
} from '@/components/ui/dialog';
import {
House, Calendar, AlertTriangle, Check, ArrowRight, ListChecks, LayoutList,
LaptopMinimal, Table, Lock,
} from 'lucide-react';
import { Tabs, TabsList, TabsPanel, TabsTab } from '@/components/coss/tabs';
import { formatDateTime } from '@/utils/table.util';
import { cn } from '@/lib/utils';
import ClientTaskListTable from '../components/TaskListTable';
// ─── Status tab map ───────────────────────────────────────────────────────────
const TABS = [
{ value: 'tab-ongoing', label: 'Ongoing', status: 'ongoing' },
{ value: 'tab-completed', label: 'Completed', status: 'completed' },
{ value: 'tab-overdue', label: 'Overdue', status: 'overdue' },
];
const DAY_MS = 24 * 60 * 60 * 1000;
// ─── Status pill per task ─────────────────────────────────────────────────────
const TaskStatusBadge = ({ task }) => {
const now = Date.now();
const deadline = task.deadline ? new Date(task.deadline).getTime() : null;
const overdue = !task.has_completed && deadline && deadline < now;
const dueSoon = !task.has_completed && deadline && (deadline - now) > 0 && (deadline - now) <= DAY_MS;
if (task.has_completed) {
return (
<span className="inline-flex items-center gap-1 text-xs font-medium bg-green-500/10 text-green-700 dark:text-green-400 rounded-full px-2.5 py-1">
<Check className="size-3.5" />
Completed
</span>
);
}
if (overdue) {
return (
<Badge variant="destructive" className="text-xs gap-1">
<AlertTriangle className="size-3.5" />
Overdue
</Badge>
);
}
if (dueSoon) {
return (
<span className="inline-flex items-center gap-1 text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400 rounded-full px-2.5 py-1">
<AlertTriangle className="size-3" />
Due soon
</span>
);
}
return (
<span className="inline-flex items-center gap-1 text-xs font-medium bg-muted text-muted-foreground rounded-full px-2.5 py-1">
Ongoing
</span>
);
};
// ─── Task card ────────────────────────────────────────────────────────────────
const TaskCard = ({ task, onClick, locked, lockedBy, onLockedClick }) => {
const reqCount = task.requirements?.length ?? 0;
return (
<div
onClick={() => (locked ? onLockedClick(lockedBy) : onClick())}
className={cn(
'border bg-card rounded-lg flex flex-col transition-colors cursor-pointer',
locked
? 'opacity-60 hover:border-muted-foreground/30'
: 'hover:border-blue-400 dark:hover:border-blue-500',
task.has_completed && 'opacity-90',
)}
>
<div className="p-4 flex flex-col gap-2.5 flex-1">
<div className="flex items-start justify-between gap-2">
<h1 className="text-base font-medium leading-snug line-clamp-2 min-w-0 flex-1">{task.name}</h1>
{locked
? (
<span className="inline-flex items-center gap-1 text-xs font-medium bg-muted text-muted-foreground rounded-full px-2.5 py-1">
<Lock className="size-3" /> Locked
</span>
)
: <TaskStatusBadge task={task} />
}
</div>
<p className="text-sm text-muted-foreground leading-relaxed line-clamp-2">
{task.description || 'No information details provided'}
</p>
<div className="flex items-center gap-1.5 text-xs text-muted-foreground mt-auto pt-1 [&_svg]:size-3.5">
<Calendar />
{task.deadline ? `Due ${formatDateTime(task.deadline)}` : 'No due date'}
</div>
{locked && (
<p className="text-xs text-muted-foreground">Tap to see what's required to unlock this task.</p>
)}
</div>
<div className="px-4 py-2.5 border-t flex items-center justify-between">
<span className="inline-flex items-center gap-1 text-xs font-medium bg-muted text-muted-foreground rounded-full px-2.5 py-1">
<ListChecks className="size-3.5" />
{reqCount} requirement{reqCount !== 1 ? 's' : ''}
</span>
<ArrowRight className="size-4 text-muted-foreground/60" />
</div>
</div>
);
};
// ─── Skeleton ─────────────────────────────────────────────────────────────────
const TaskCardSkeleton = () => (
<div className="border bg-card rounded-lg overflow-hidden">
<div className="p-4 flex flex-col gap-2.5">
<div className="flex items-start justify-between gap-2">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-5 w-16 rounded-full" />
</div>
<Skeleton className="h-3.5 w-full" />
<Skeleton className="h-3.5 w-2/3" />
<Skeleton className="h-3.5 w-28 mt-1" />
</div>
<div className="px-4 py-2.5 border-t flex items-center justify-between">
<Skeleton className="h-5 w-24 rounded-full" />
</div>
</div>
);
const GridSkeleton = () => (
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3.5">
{Array.from({ length: 3 }).map((_, i) => <TaskCardSkeleton key={i} />)}
</div>
);
// ─── Empty state ──────────────────────────────────────────────────────────────
const EmptyState = ({ label }) => (
<div className="h-64 flex items-center flex-col justify-center w-full gap-4">
<LayoutList className="size-20 text-muted-foreground/40" />
<h1 className="max-w-lg text-sm text-muted-foreground text-center">
{label}
</h1>
</div>
);
// ─── Main page ────────────────────────────────────────────────────────────────
const ViewTaskDetails = () => {
const { groupId, taskListId } = useParams();
const navigate = useNavigate();
const { taskList, loading, fetchTaskList } = useTask();
const { group, fetchGroup } = useGroup();
const [view, setView] = useState('grid');
const [activeTab, setActiveTab] = useState('tab-ongoing');
const [allTasks, setAllTasks] = useState([]);
const [lockedInfo, setLockedInfo] = useState(null); // task names blocking the last-clicked locked card
// ── Fetch group info once ─────────────────────────────────────────────────
useEffect(() => {
fetchGroup(groupId);
}, [groupId]);
// ── Fetch task list (with server-side status filter on tasks) ────────────
useEffect(() => {
const tab = TABS.find((t) => t.value === activeTab);
if (tab) fetchTaskList(groupId, taskListId, { status: tab.status });
}, [groupId, taskListId, activeTab]);
// ── Fetch the FULL, unfiltered, order_index-sorted task array separately —
// the tab fetch above is server-side status-filtered, so it alone can't
// tell us whether an earlier task (possibly in a different tab) is done.
// Kept in local state rather than context so it never clobbers the
// tab-driven fetch's `taskList.tasks`.
useEffect(() => {
api.get(`/client/groups/${groupId}/task-lists/${taskListId}`)
.then(({ data }) => setAllTasks(data?.data?.tasks ?? []))
.catch(() => {});
}, [groupId, taskListId]);
// ── Sequencing/prerequisite lock — computed server-side (task.locked,
// task.lockedBy), since an explicit prerequisite graph can't be expressed
// as a one-line client-side scan the way the old order_index-only rule could.
const lockedTaskIds = new Set(
allTasks.filter((t) => t.locked).map((t) => t.task_id)
);
const lockedByById = new Map(allTasks.map((t) => [t.task_id, t.lockedBy ?? []]));
const completedCount = allTasks.filter((t) => t.has_completed).length;
const handleTabChange = useCallback((val) => {
setActiveTab(val);
}, []);
const handleRefresh = useCallback(() => {
const tab = TABS.find((t) => t.value === activeTab);
if (tab) fetchTaskList(groupId, taskListId, { status: tab.status });
}, [groupId, taskListId, activeTab]);
const tasks = taskList?.tasks ?? [];
const breadcrumbItems = [
{ label: 'Home', icon: <House className="size-4" />, to: '/dashboard' },
{ label: group?.name ?? '…', to: `/group/${groupId}` },
{ label: taskList?.name ?? '…' },
];
// ── Renderer per tab — grid or table depending on view ────────────────────
const renderTab = (emptyLabel, statusLabel) => {
if (view === 'list') {
// ClientTaskListTable expects TaskList-shaped rows (task_list_id, name,
// description, tasks[]). Wrap each Task as its own "row" using its
// own task_id as the row key, single-element tasks[] for deadline lookup.
const rows = tasks.map((t) => ({
task_list_id: t.task_id,
name: t.name,
description: t.description,
tasks: [t],
}));
return (
<ClientTaskListTable
taskLists={rows}
loading={loading}
onRefresh={handleRefresh}
onRowClick={(row) => navigate(`task/${row.task_list_id}`)}
statusLabel={statusLabel}
/>
);
}
if (loading) return <GridSkeleton />;
if (!tasks.length) return <EmptyState label={emptyLabel} />;
return (
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3.5">
{tasks.map((task) => (
<TaskCard
key={task.task_id}
task={task}
locked={lockedTaskIds.has(task.task_id)}
lockedBy={lockedByById.get(task.task_id) ?? []}
onLockedClick={setLockedInfo}
onClick={() => navigate(`task/${task.task_id}`)}
/>
))}
</div>
);
};
return (
<div className="mt-17">
<PageMeta title={taskList ? `${taskList.name} - STARR` : undefined} />
<div className="lg:container lg:mx-auto flex flex-col gap-6 py-6 xs:px-6 lg:px-0">
{/* ── Header ────────────────────────────────────────────────── */}
<div className="flex flex-col gap-4">
<AppBreadcrumb items={breadcrumbItems} />
<div className="space-y-2">
{loading && !taskList ? (
<>
<Skeleton className="h-7 w-48" />
<Skeleton className="h-4 w-72" />
</>
) : (
<>
<h1 className="font-bold text-2xl max-w-xl">{taskList?.name}</h1>
{taskList?.description && (
<p className="max-w-2xl text-base xs:text-sm">{taskList.description}</p>
)}
</>
)}
</div>
{/* ── List-level progress rollup ── */}
{allTasks.length > 0 && (
<div className="max-w-md flex flex-col gap-1.5">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
{completedCount} of {allTasks.length} task{allTasks.length !== 1 ? 's' : ''} complete
</span>
{completedCount >= allTasks.length && (
<span className="flex items-center gap-1 text-green-600 dark:text-green-400 font-medium">
<Check className="size-3.5" /> All done
</span>
)}
</div>
<Progress
value={(completedCount / allTasks.length) * 100}
className={cn('h-1.5', completedCount >= allTasks.length && '[&>div]:bg-green-500')}
/>
</div>
)}
</div>
{/* ── Tabs + view toggle ────────────────────────────────────── */}
<div className="relative">
<Tabs defaultValue="tab-ongoing" onValueChange={handleTabChange}>
<div className="flex items-center justify-between flex-wrap gap-2">
<TabsList>
{TABS.map((t) => (
<TabsTab key={t.value} value={t.value}>
{t.label}
</TabsTab>
))}
</TabsList>
{/* ── View toggle ── */}
<div className="flex items-center gap-2">
<Button
size="sm"
variant={view === 'grid' ? 'default' : 'outline'}
onClick={() => setView('grid')}
>
<LaptopMinimal /> Grid
</Button>
<Button
size="sm"
variant={view === 'list' ? 'default' : 'outline'}
onClick={() => setView('list')}
>
<Table /> List
</Button>
</div>
</div>
{/* ── Ongoing ── */}
<TabsPanel value="tab-ongoing" className="pt-4">
{renderTab('No ongoing tasks right now.', 'ongoing')}
</TabsPanel>
{/* ── Completed ── */}
<TabsPanel value="tab-completed" className="pt-4">
{renderTab('No completed tasks yet.', 'completed')}
</TabsPanel>
{/* ── Overdue ── */}
<TabsPanel value="tab-overdue" className="pt-4">
{renderTab('No overdue tasks.', 'overdue')}
</TabsPanel>
</Tabs>
</div>
</div>
{/* ── Locked task requirement dialog ── */}
<Dialog open={!!lockedInfo} onOpenChange={(open) => !open && setLockedInfo(null)}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Lock className="size-4" /> Task locked
</DialogTitle>
<DialogDescription>
{lockedInfo?.length
? `Complete the following task${lockedInfo.length !== 1 ? 's' : ''} first to unlock this one:`
: 'Complete the earlier required tasks first to unlock this one.'}
</DialogDescription>
</DialogHeader>
{!!lockedInfo?.length && (
<ul className="flex flex-col gap-2">
{lockedInfo.map((t) => (
<li
key={t.task_id}
className="flex items-center gap-2 text-sm bg-muted rounded-md px-3 py-2"
>
<ListChecks className="size-3.5 text-muted-foreground shrink-0" />
{t.name}
</li>
))}
</ul>
)}
</DialogContent>
</Dialog>
</div>
);
};
export default ViewTaskDetails;
@@ -0,0 +1,156 @@
import ProtectedRoute from '../../../routes/ProtectedRoute'
import Client from '../pages/Dashboard'
import ClientLayout from '../layout/ClientLayout'
import CoursesList from '../pages/CourseList'
import { Navigate, Outlet } from "react-router-dom"
import ScrollToTop from '@/components/generic/ScrollToTop'
import CourseDetails from '../pages/CourseDetails'
import UnitList from '../pages/UnitList'
import UnitsList from '../pages/UnitsList'
import UnitDetails from '../pages/UnitDetails'
import LessonDetails from '../pages/LessonDetails'
import LessonsList from '../pages/LessonsList'
import UnitReader from '../pages/UnitReader'
import { Fragment } from 'react'
import GroupList from '../pages/GroupList'
import ViewTaskDetails from '../pages/ViewTaskDetails'
import ProfilePage from '../pages/Profile'
import Checkout from '../pages/Checkout'
import EditProfile from '../pages/EditProfile'
import PlanList from '../pages/PlanList'
import ViewPlan from '../pages/ViewPlan'
import ViewTask from '../pages/ViewTask'
import CourseCheckout from '../pages/CourseCheckout'
import MyCertificates from '../pages/MyCertificates'
import MyAchievements from '../pages/MyAchievements'
import MyCompletedContent from '../pages/MyCompletedContent'
import AccountSettings from '../pages/AccountSettings'
import Notifications from '../pages/Notifications'
import AdvertisementLandingPage from '../pages/AdvertisementLandingPage'
import IntroPage from '@/modules/auth/pages/Intro'
import { useAuth } from '@/contexts/AuthContext'
const ClientWrapper = () => {
const { user } = useAuth()
// New users must complete the intro before accessing any client page
if (user?.needs_intro) return <Navigate to="/intro" replace />
return (
<Fragment>
{/* Wrapper components belong here. */}
<ScrollToTop />
<ClientLayout />
</Fragment>
)
}
export const ClientRoutes = {
element: <ProtectedRoute allowedRoles={['user']} />,
children: [
// Intro — full-screen, outside ClientLayout, no nav
{ path: 'intro', element: <IntroPage /> },
{
element: <ClientWrapper />,
children: [
{
path: 'dashboard', element: <Outlet />,
children: [
{ index: true, element: <Client /> },
],
},
{
path: 'profile', element: <Outlet />,
children: [
{ index: true, element: <ProfilePage /> },
{ path: 'edit', element: <EditProfile /> },
],
},
{ path: 'certificates', element: <MyCertificates /> },
{ path: 'achievements', element: <MyAchievements /> },
{ path: 'completed', element: <MyCompletedContent /> },
{ path: 'settings', element: <AccountSettings /> },
{ path: 'notifications', element: <Notifications /> },
{ path: 'ads/:uuid', element: <AdvertisementLandingPage /> },
{
path: 'subscriptions', element: <Outlet />,
children: [
// { index: true, element: <Checkout /> },
{ index: true, element: <PlanList /> },
{ path: 'view/:id', element: <ViewPlan /> },
{ path: 'checkout', element: <Checkout /> },
],
},
{
path: 'course',
element: <Outlet />,
children: [
{ index: true, element: <CoursesList /> },
{
path: ':id', element: <Outlet />,
children: [
{ index: true, element: <CourseDetails /> },
{ path: 'unit', element: <UnitList />, handle: { showFooter: false } },
{ path: 'checkout', element: <CourseCheckout /> },
],
},
],
},
{
path: 'units',
element: <Outlet />,
children: [
{ index: true, element: <UnitsList /> },
{
path: ':uuid', element: <Outlet />,
children: [
{ index: true, element: <UnitDetails /> },
{ path: 'read', element: <UnitReader />, handle: { showFooter: false } },
],
},
],
},
{
path: 'lessons',
element: <Outlet />,
children: [
{ index: true, element: <LessonsList /> },
{
path: ':uuid', element: <Outlet />,
children: [
{ index: true, element: <LessonDetails /> },
],
},
],
},
{
path: 'group', element: <Outlet />,
children: [
{
path: ':groupId', element: <Outlet />,
children: [
{ index: true, element: <GroupList /> },
{
path: 'view/:taskListId', element: <Outlet />,
children: [
{ index: true, element: <ViewTaskDetails /> },
{
path: 'task/:taskId', element: <Outlet />,
children: [
{ index: true, element: <ViewTask /> },
]
},
]
},
],
},
]
},
],
},
],
}