Files
pragativeer-v2/src/app/dashboard/dpp/page.tsx

339 lines
18 KiB
TypeScript

"use client"
import { fetchWithAuth } from "@/lib/apiClient";
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { BrainCircuit, Play, CheckCircle2, Download, Filter, Lock, FileText, Eye, ShieldAlert, X, Sparkles, Share2, Maximize2, Minimize2 } from "lucide-react"
import { useEffect, useState } from "react"
import Link from "next/link"
import { useActiveUser } from "@/hooks/useActiveUser"
export default function DPPPage() {
const { user, userId } = useActiveUser()
const [dpps, setDpps] = useState<any[]>([])
const [attempts, setAttempts] = useState<any[]>([])
const [loading, setLoading] = useState(true)
const [dateFilter, setDateFilter] = useState("")
const [selectedPdfDpp, setSelectedPdfDpp] = useState<any | null>(null)
const [isFullScreen, setIsFullScreen] = useState(false)
const [copiedShare, setCopiedShare] = useState(false)
useEffect(() => {
async function fetchDpps() {
if (!user) return; // Wait for user to be available
try {
const pattern = user.target_exam || "JEE_Main";
// Also fetch from the correct Next.js proxied route instead of localhost:8000
const res = await fetchWithAuth(`/api/tests?type=DPS&exam_pattern=${pattern}`);
if (res.ok) {
const data = await res.json()
setDpps(data)
}
if (userId) {
const attemptsRes = await fetchWithAuth(`/api/users/${userId}/attempts`);
if (attemptsRes.ok) {
const attemptsData = await attemptsRes.json();
setAttempts(attemptsData);
}
}
} catch (err) {
console.error("Failed to fetch DPPs", err)
} finally {
setLoading(false)
}
}
fetchDpps()
}, [user])
const getDifficultyColor = (diff: string) => {
switch(diff) {
case 'Easy': return 'text-emerald-500 bg-emerald-500/10 border-emerald-500/20';
case 'Medium': return 'text-amber-500 bg-amber-500/10 border-amber-500/20';
case 'Hard': return 'text-destructive bg-destructive/10 border-destructive/20';
default: return 'text-primary bg-primary/10 border-primary/20';
}
}
const attemptsByTest = attempts.reduce((acc, curr) => {
// Isolate analytics to first attempt only - ignore retakes
if (curr.is_retake) return acc;
if (!acc[curr.source_id] || acc[curr.source_id].score < curr.score) {
acc[curr.source_id] = curr;
}
return acc;
}, {} as Record<string, any>);
const filteredDpps = dpps.filter(dpp => {
if (dateFilter) {
if (!dpp.scheduled_date) return false;
const scheduledDate = new Date(dpp.scheduled_date).toISOString().split('T')[0];
if (scheduledDate !== dateFilter) return false;
}
const isNeet = user?.target_exam === "NEET";
const title = dpp.title.toLowerCase();
if (isNeet && (title.includes("math") || title.includes("mth"))) return false;
if (!isNeet && title.includes("bio")) return false;
return true;
});
const formatDate = (dateStr: string) => {
return new Date(dateStr).toLocaleDateString("en-US", { year: 'numeric', month: 'short', day: 'numeric' });
}
const getPdfUrl = (title: string) => {
const t = title.toLowerCase();
if (t.includes('phys')) return '/dpps/dps-phy-ch4-20260707.pdf#toolbar=0&navpanes=0&scrollbar=0';
if (t.includes('chem')) return '/dpps/dps-che-ch4-20260707.pdf#toolbar=0&navpanes=0&scrollbar=0';
if (t.includes('math')) return '/dpps/dps-mth-ch4-20260707.pdf#toolbar=0&navpanes=0&scrollbar=0';
if (t.includes('bio')) return '/dpps/dps-bio-ch4-20260707.pdf#toolbar=0&navpanes=0&scrollbar=0';
return '/dpps/dps-phy-ch4-20260707.pdf#toolbar=0&navpanes=0&scrollbar=0';
};
// Strip ugly ExamEnum. prefix from seeded test titles
const cleanTitle = (title: string) => title.replace(/\s*\(ExamEnum\.[^)]+\)/, '');
return (
<div className="p-8 space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500 max-w-7xl mx-auto">
<div className="flex flex-col md:flex-row md:items-center justify-between p-8 bg-gradient-to-r from-secondary/50 to-background border border-border rounded-2xl shadow-sm gap-6">
<div>
<h1 className="text-3xl font-bold tracking-tight mb-2">Daily Practice Problems (DPP)</h1>
<p className="text-muted-foreground font-medium max-w-xl">
Hyper-personalized problem sets generated daily by our AI Evaluator to target your specific weak areas based on past exam performance.
</p>
</div>
</div>
<div className="flex flex-col sm:flex-row justify-between items-center gap-4 border-b border-border pb-6">
<div className="flex items-center gap-2">
<input
type="date"
value={dateFilter}
onChange={(e) => setDateFilter(e.target.value)}
className="px-3 py-1.5 bg-background border border-border rounded-lg text-xs font-bold focus:ring-2 focus:ring-[var(--cyan-ai)] outline-none text-muted-foreground mr-2"
/>
<span className="text-sm font-bold text-muted-foreground mr-2"><Filter size={16} className="inline mr-1"/> Difficulty:</span>
{['Mixed', 'Easy', 'Medium', 'Hard'].map((diff) => (
<button key={diff} className={`px-3 py-1.5 rounded-lg text-xs font-bold border transition-colors ${diff === 'Mixed' ? 'bg-primary text-primary-foreground border-primary' : 'bg-background text-muted-foreground border-border hover:border-primary/50'}`}>
{diff}
</button>
))}
<div className="flex items-center gap-1 ml-2 text-xs text-muted-foreground bg-secondary/50 px-2 py-1 rounded-md">
<Lock size={12}/> Pro
</div>
</div>
<Button
variant="outline"
onClick={() => {
navigator.clipboard.writeText(window.location.origin + '/dashboard/dpp');
setCopiedShare(true);
setTimeout(() => setCopiedShare(false), 2000);
}}
className="gap-2 rounded-xl text-sm font-bold border-primary/30 hover:bg-primary/10 text-primary transition-all shadow-sm"
>
{copiedShare ? <CheckCircle2 size={16} className="text-green-500" /> : <Share2 size={16} />}
{copiedShare ? "Share Link Copied!" : "Share DPPs Link"}
</Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{loading ? (
<div className="col-span-2 text-center py-12 text-muted-foreground">Loading AI-generated DPPs...</div>
) : filteredDpps.length === 0 ? (
<div className="col-span-2 text-center py-12 text-muted-foreground border border-dashed rounded-xl">No DPPs available for the selected criteria.</div>
) : filteredDpps.map((dpp, i) => {
// Calculate total questions dynamically from sections
let count = 0;
if (dpp.sections) {
Object.values(dpp.sections).forEach((s: any) => { count += (s.questions?.length || 0) });
}
const attempt = attemptsByTest[dpp.id];
const isAttempted = !!attempt;
// Date logic
const now = new Date();
const scheduledTime = dpp.scheduled_date ? new Date(dpp.scheduled_date) : now;
const endTime = dpp.end_date ? new Date(dpp.end_date) : null;
const isUpcoming = scheduledTime > now;
const isExpired = endTime ? now > endTime : false;
return (
<Card key={dpp.id} className={`group cursor-pointer transition-all hover:shadow-md ${isAttempted ? 'opacity-70 hover:opacity-100 bg-secondary/10 border-primary/20' : isExpired ? 'opacity-80' : 'hover:border-[var(--cyan-ai-10)] bg-background'}`}>
<CardContent className="p-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex gap-4 items-start w-full">
<div className={`mt-1 flex-shrink-0 ${isAttempted ? 'text-green-500' : 'text-foreground'}`}>
{isAttempted ? <CheckCircle2 size={24} /> : <div className="size-6 rounded-full border-2 border-muted-foreground group-hover:border-[var(--cyan-ai)] transition-colors flex items-center justify-center"></div>}
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<span className="text-xs font-bold uppercase tracking-wider text-[var(--cyan-ai)]">
{user?.target_exam?.replace("_", " ") || "JEE/NEET"}
</span>
<span className="text-muted-foreground text-xs font-bold">•</span>
<span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">{dpp.difficulty} Level</span>
{isUpcoming ? (
<>
<span className="text-muted-foreground text-xs font-bold">•</span>
<span className="text-[10px] font-bold uppercase text-yellow-500 bg-yellow-500/10 px-1.5 py-0.5 rounded">Upcoming</span>
</>
) : isExpired ? (
<>
<span className="text-muted-foreground text-xs font-bold">•</span>
<span className="text-[10px] font-bold uppercase text-muted-foreground bg-secondary px-1.5 py-0.5 rounded">Expired</span>
</>
) : null}
</div>
<h3 className="font-bold text-lg leading-tight group-hover:text-[var(--cyan-ai)] transition-colors">
{cleanTitle(dpp.title)}
<span className={`ml-2 text-[10px] uppercase px-2 py-0.5 rounded-md border font-bold tracking-wider ${getDifficultyColor(dpp.difficulty)}`}>
{dpp.difficulty}
</span>
</h3>
<div className="text-sm text-muted-foreground mt-2 font-medium">
{count} Questions • {dpp.total_time} mins
{dpp.scheduled_date && (
<span className="ml-2 border-l border-border pl-2">
{isUpcoming ? `Available on ${formatDate(dpp.scheduled_date)}` : isExpired ? `Expired on ${formatDate(dpp.end_date!)}` : 'Available Now'}
</span>
)}
</div>
</div>
</div>
<div className="flex flex-col sm:flex-row gap-2 shrink-0 md:self-center">
{isUpcoming ? (
<Button disabled variant="outline" size="sm" className="font-bold">Starts Soon</Button>
) : isExpired && !isAttempted ? (
<Button disabled variant="outline" size="sm" className="font-bold bg-secondary/50">Expired</Button>
) : isAttempted ? (
<>
<Link href={`/cbt/${dpp.id}/result`}>
<Button variant="outline" size="sm" className="font-bold border-border">Result</Button>
</Link>
{!isExpired && (
<Button onClick={() => setSelectedPdfDpp(dpp)} variant="secondary" size="sm" className="font-bold bg-[var(--cyan-ai-10)] text-[var(--cyan-ai)] hover:bg-[var(--cyan-ai-20)] gap-2">
<Eye size={14} /> Read PDF
</Button>
)}
</>
) : (
<Button onClick={() => setSelectedPdfDpp(dpp)} variant="secondary" className="rounded-xl bg-primary/10 text-primary hover:bg-primary/20 font-bold gap-2 text-xs">
<Eye size={14} /> Open PDF
</Button>
)}
</div>
</CardContent>
</Card>
)})}
</div>
{/* ── PROTECTED PDF READER MODAL (FREE TIER) ── */}
{selectedPdfDpp && (
<div className={`fixed inset-0 z-50 bg-black/90 backdrop-blur-md flex items-center justify-center ${isFullScreen ? 'p-0' : 'p-4'} animate-in fade-in duration-300`}>
<div className={`bg-background border border-border ${isFullScreen ? 'w-screen h-screen max-w-none max-h-none rounded-none border-0' : 'rounded-3xl w-full max-w-7xl max-h-[95vh]'} flex flex-col overflow-hidden shadow-2xl transition-all duration-300`}>
{/* Modal Header */}
<div className="p-4 md:p-5 border-b border-border bg-secondary/30 flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="p-2.5 bg-primary/10 rounded-xl border border-primary/20 text-primary hidden sm:flex">
<FileText size={22} />
</div>
<div>
<h3 className="font-black text-base sm:text-lg flex items-center gap-2">
{cleanTitle(selectedPdfDpp.title)}
<span className="text-[10px] bg-yellow-500/10 text-yellow-500 border border-yellow-500/20 px-2 py-0.5 rounded-full uppercase tracking-wider font-extrabold hidden md:inline-block">
Protected In-App PDF View
</span>
</h3>
<p className="text-xs text-muted-foreground font-medium">
{selectedPdfDpp.difficulty} Level • {user?.target_exam?.replace("_", " ") || "JEE/NEET"} Practice Sheet
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Button
size="sm"
variant="outline"
onClick={() => {
navigator.clipboard.writeText(window.location.origin + '/dashboard/dpp');
setCopiedShare(true);
setTimeout(() => setCopiedShare(false), 2000);
}}
className="rounded-xl font-bold text-xs gap-1.5 h-9 px-3"
>
{copiedShare ? <CheckCircle2 size={14} className="text-green-500" /> : <Share2 size={14} />}
<span>{copiedShare ? "Copied" : "Share PDF"}</span>
</Button>
<Button
size="sm"
variant="outline"
onClick={() => setIsFullScreen(!isFullScreen)}
className="rounded-xl font-bold text-xs gap-1.5 h-9 px-3 bg-primary/10 text-primary border-primary/20 hover:bg-primary/20"
>
{isFullScreen ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
<span>{isFullScreen ? "Exit Fullscreen" : "Fullscreen"}</span>
</Button>
<button
onClick={() => { setSelectedPdfDpp(null); setIsFullScreen(false); }}
className="ml-1 flex-shrink-0 w-9 h-9 rounded-full border border-border bg-secondary flex items-center justify-center text-foreground hover:bg-destructive hover:border-destructive hover:text-white transition-all"
>
<X size={18} />
</button>
</div>
</div>
{/* Security Notice Banner */}
<div className="bg-amber-500/10 border-b border-amber-500/20 px-4 sm:px-6 py-2 flex items-center justify-between text-xs text-amber-400 font-bold">
<span className="flex items-center gap-2 truncate">
<ShieldAlert size={16} className="shrink-0" /> Read-Only Mode (Free Tier) — Downloads & direct copying are restricted.
</span>
<Link href="/upgrade" className="hidden sm:block shrink-0 ml-2">
<Button size="sm" className="bg-amber-500 text-black hover:bg-amber-400 font-extrabold h-7 text-[11px] rounded-lg">
Upgrade for Interactive CBT Mode →
</Button>
</Link>
</div>
{/* Protected PDF Document Sheet Content (select-none) */}
<div
onContextMenu={(e) => e.preventDefault()}
className="flex-1 w-full select-none bg-[#525659] overflow-hidden"
style={{minHeight: isFullScreen ? 'calc(100vh - 120px)' : '75vh'}}
>
<embed
src={getPdfUrl(selectedPdfDpp.title)}
type="application/pdf"
className="w-full h-full"
style={{height: isFullScreen ? 'calc(100vh - 120px)' : '75vh'}}
/>
</div>
{/* Modal Footer */}
<div className="p-3.5 sm:p-4 border-t border-border bg-secondary/30 flex items-center justify-between flex-wrap gap-2">
<span className="text-xs text-muted-foreground font-medium flex items-center gap-2">
📄 PragatiVeer Protected PDF Reader v2.0
</span>
<div className="flex gap-2 items-center">
<Button onClick={() => setIsFullScreen(!isFullScreen)} variant="secondary" className="rounded-xl font-bold text-xs h-9 bg-primary/10 text-primary hover:bg-primary/20 flex items-center gap-1.5">
{isFullScreen ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
<span>{isFullScreen ? "Exit Fullscreen" : "Fullscreen"}</span>
</Button>
<Button onClick={() => { setSelectedPdfDpp(null); setIsFullScreen(false); }} variant="outline" className="rounded-xl font-bold text-xs h-9">
Close Reader
</Button>
<Link href="/upgrade">
<Button className="bg-[var(--cyan-ai)] text-black hover:bg-[var(--cyan-ai-80)] font-extrabold rounded-xl shadow-[0_0_15px_rgba(12,96,96,0.2)] text-xs h-9">
<Sparkles size={14} className="mr-1.5" /> Upgrade to AI Coach for CBT
</Button>
</Link>
</div>
</div>
</div>
</div>
)}
</div>
)
}