Spaces:
Sleeping
Sleeping
File size: 29,774 Bytes
5463318 38ee1b6 5463318 38ee1b6 5463318 38ee1b6 5463318 38ee1b6 5463318 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 | import React, { useState, useEffect, useRef } from "react";
import { Outlet, NavLink, useNavigate, Link } from "react-router-dom";
import { useTheme } from "../../context/ThemeContext";
import { cn } from "../../utils/cn";
import { motion, AnimatePresence } from "framer-motion";
import { supabase } from "../../utils/supabaseClient";
import { API_BASE_URL } from "../../utils/api";
import {
LayoutDashboard,
UploadCloud,
BrainCircuit,
History as HistoryIcon,
Settings,
LogOut,
ChevronLeft,
ChevronRight,
Sun,
Moon,
Bell,
Search,
Menu,
X,
KeyRound,
AlertCircle
} from "lucide-react";
export default function DashboardLayout() {
const [isSidebarOpen, setSidebarOpen] = useState(true);
const [isMobileOpen, setMobileOpen] = useState(false);
const [isProfileOpen, setProfileOpen] = useState(false);
const [isNotificationsOpen, setNotificationsOpen] = useState(false);
const [userProfile, setUserProfile] = useState(null);
const [notifications, setNotifications] = useState([]);
// Exam Password States
const [showPasswordPopup, setShowPasswordPopup] = useState(false);
const [examPassword, setExamPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [passwordError, setPasswordError] = useState("");
const [isSavingPassword, setIsSavingPassword] = useState(false);
const profileRef = useRef(null);
const notificationsRef = useRef(null);
const { theme, toggleTheme } = useTheme();
const navigate = useNavigate();
useEffect(() => {
const fetchUser = async () => {
const { data: { session } } = await supabase.auth.getSession();
if (session?.user) {
try {
const response = await fetch(`${API_BASE_URL}/api/profile`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session.access_token}`
}
});
if (response.ok) {
const data = await response.json();
if (data && data.full_name) {
setUserProfile(data);
// Detect if exam_password is not set
if (data.has_exam_password === false) {
setNotifications([{
id: 'exam_password_setup',
title: 'Set Exam Password',
message: 'A 6-digit exam password is required to secure your papers.',
isUnread: true
}]);
// Prevent sending emails repeatedly per session
if (!sessionStorage.getItem('passwordReminderSent')) {
sessionStorage.setItem('passwordReminderSent', 'true');
fetch(`${API_BASE_URL}/api/send-password-reminder`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${session.access_token}` }
}).catch(err => console.error("Email API Err:", err));
}
}
} else {
setUserProfile(session.user.user_metadata);
}
} else {
setUserProfile(session.user.user_metadata);
}
} catch (error) {
console.error("Failed to fetch profile via API", error);
setUserProfile(session.user.user_metadata);
}
}
};
fetchUser();
}, []);
// Close profile and notification dropdowns when clicking outside
useEffect(() => {
const handleClickOutside = (event) => {
if (profileRef.current && !profileRef.current.contains(event.target)) {
setProfileOpen(false);
}
if (notificationsRef.current && !notificationsRef.current.contains(event.target)) {
setNotificationsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const handleSavePassword = async (e) => {
e.preventDefault();
setPasswordError("");
if (!/^\d{6}$/.test(examPassword)) {
setPasswordError("Password must be exactly 6 digits.");
return;
}
if (examPassword !== confirmPassword) {
setPasswordError("Passwords do not match.");
return;
}
setIsSavingPassword(true);
try {
const { data: { session } } = await supabase.auth.getSession();
const response = await fetch(`${API_BASE_URL}/api/profile`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session.access_token}`
},
body: JSON.stringify({ exam_password: examPassword })
});
if (!response.ok) throw new Error("Failed to save password");
setUserProfile(prev => ({ ...prev, has_exam_password: true }));
setNotifications(prev => prev.filter(n => n.id !== 'exam_password_setup'));
setShowPasswordPopup(false);
setExamPassword("");
setConfirmPassword("");
} catch (error) {
setPasswordError(error.message);
} finally {
setIsSavingPassword(false);
}
};
const navItems = [
{ name: "Dashboard", path: "/app", icon: LayoutDashboard },
{ name: "Upload", path: "/app/upload", icon: UploadCloud },
{ name: "Generate", path: "/app/generate", icon: BrainCircuit },
{ name: "History", path: "/app/history", icon: HistoryIcon },
{ name: "Settings", path: "/app/settings", icon: Settings },
];
return (
<div className="flex h-screen w-full bg-background overflow-hidden selection:bg-primary/30">
{/* Sidebar Desktop */}
<motion.aside
initial={{ width: 260 }}
animate={{ width: isSidebarOpen ? 260 : 80 }}
transition={{ duration: 0.3, ease: "easeInOut" }}
className={cn(
"hidden md:flex flex-col border-r border-border bg-card shadow-sm z-20 relative",
"glass dark:bg-card/80 transition-colors"
)}
>
<div className="flex items-center h-16 px-4 shrink-0 overflow-hidden border-b border-border/50">
<BrainCircuit className="h-8 w-8 text-primary shrink-0" />
<AnimatePresence>
{isSidebarOpen && (
<motion.span
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -10 }}
className="ml-3 font-bold text-xl tracking-tight text-foreground whitespace-nowrap"
>
ExamCraft.<span className="text-primary">AI</span>
</motion.span>
)}
</AnimatePresence>
</div>
<button
onClick={() => setSidebarOpen(!isSidebarOpen)}
className="absolute -right-4 top-5 bg-card border border-border rounded-full p-1.5 shadow-md text-muted-foreground hover:text-foreground hover:bg-accent/10 transition-colors"
>
{isSidebarOpen ? <ChevronLeft size={16} /> : <ChevronRight size={16} />}
</button>
<nav className="flex-1 overflow-y-auto w-full px-3 py-6 space-y-2">
{navItems.map((item) => (
<NavLink
key={item.name}
to={item.path}
end={item.path === "/app"}
className={({ isActive }) =>
cn(
"flex items-center space-x-3 px-3 py-3 rounded-lg transition-all duration-200 group relative",
isActive
? "bg-primary text-primary-foreground shadow-[0_0_15px_rgba(var(--primary),0.3)]"
: "text-muted-foreground hover:bg-primary/10 hover:text-foreground"
)
}
>
{({ isActive }) => (
<>
<item.icon className={cn("h-5 w-5 shrink-0 transition-transform", isActive ? "scale-110" : "group-hover:scale-110")} />
<AnimatePresence>
{isSidebarOpen && (
<motion.span
initial={{ opacity: 0, width: 0 }}
animate={{ opacity: 1, width: "auto" }}
exit={{ opacity: 0, width: 0 }}
className="font-medium whitespace-nowrap overflow-hidden"
>
{item.name}
</motion.span>
)}
</AnimatePresence>
</>
)}
</NavLink>
))}
</nav>
<div className="p-4 border-t border-border/50 shrink-0">
<button
onClick={() => navigate('/login')}
className={cn(
"flex w-full items-center justify-center space-x-3 px-3 py-3 rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors group",
!isSidebarOpen && "px-0"
)}>
<LogOut className="h-5 w-5 shrink-0 transition-transform group-hover:-translate-x-1" />
{isSidebarOpen && <span className="font-medium">Logout</span>}
</button>
</div>
</motion.aside>
{/* Main Content Area */}
<main className="flex-1 flex flex-col min-w-0">
{/* Top Navbar */}
<header className="h-16 px-4 flex items-center justify-between border-b border-border/50 bg-background/80 backdrop-blur-md z-10 sticky top-0">
<div className="flex items-center gap-4">
<button className="md:hidden p-2 text-muted-foreground" onClick={() => setMobileOpen(true)}>
<Menu size={24} />
</button>
<div className="relative hidden sm:block">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<input
type="text"
placeholder="Search exams, topics..."
className="h-10 w-64 rounded-full border border-border bg-input/20 pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
/>
</div>
</div>
<div className="flex items-center gap-4">
<button onClick={toggleTheme} className="p-2 rounded-full hover:bg-accent/10 transition-colors text-muted-foreground hover:text-foreground">
{theme === "dark" ? <Sun size={20} className="text-accent" /> : <Moon size={20} />}
</button>
<div className="relative" ref={notificationsRef}>
<button onClick={() => setNotificationsOpen(!isNotificationsOpen)} className="p-2 rounded-full hover:bg-accent/10 transition-colors text-muted-foreground hover:text-foreground relative">
<Bell size={20} />
{notifications.length > 0 && notifications.some(n => n.isUnread) && (
<span className="absolute top-1.5 right-2 h-2.5 w-2.5 bg-destructive rounded-full border-2 border-background animate-pulse"></span>
)}
</button>
<AnimatePresence>
{isNotificationsOpen && (
<motion.div
initial={{ opacity: 0, y: 10, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 10, scale: 0.95 }}
transition={{ duration: 0.15 }}
className="absolute right-0 mt-3 w-80 rounded-xl border border-border bg-card shadow-lg flex flex-col overflow-hidden z-50 py-1"
>
<div className="px-4 py-3 border-b border-border/50 flex justify-between items-center">
<h3 className="font-semibold text-foreground">Notifications</h3>
<span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded-full font-medium">{notifications.length} New</span>
</div>
<div className="max-h-80 overflow-y-auto w-full p-2 space-y-1">
{notifications.length === 0 ? (
<div className="py-6 text-center text-muted-foreground text-sm">
No new notifications
</div>
) : (
notifications.map(notif => (
<div key={notif.id}
onClick={() => {
setNotificationsOpen(false);
if(notif.id === 'exam_password_setup') setShowPasswordPopup(true);
}}
className="flex items-start gap-3 p-3 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors relative"
>
{notif.isUnread && <span className="absolute top-4 left-2 w-2 h-2 rounded-full bg-primary shrink-0" />}
<div className="bg-primary/10 p-2 rounded-full shrink-0 ml-2">
<Bell size={16} className="text-primary" />
</div>
<div className="flex-1 min-w-0">
<h4 className="text-sm font-semibold text-foreground">{notif.title}</h4>
<p className="text-xs text-muted-foreground mt-0.5 leading-snug">{notif.message}</p>
</div>
</div>
))
)}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
<div className="relative" ref={profileRef}>
<button
onClick={() => setProfileOpen(!isProfileOpen)}
className="h-9 w-9 rounded-full bg-gradient-to-tr from-primary flex items-center justify-center font-bold text-white to-accent shadow-md cursor-pointer ring-2 ring-primary/20 transition-all hover:ring-primary/50 overflow-hidden"
>
{userProfile?.avatar_url ? (
<img src={userProfile.avatar_url} alt="Profile" className="h-full w-full object-cover" />
) : (
userProfile?.full_name ? userProfile.full_name.charAt(0).toUpperCase() : "U"
)}
</button>
<AnimatePresence>
{isProfileOpen && (
<motion.div
initial={{ opacity: 0, y: 10, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 10, scale: 0.95 }}
transition={{ duration: 0.15 }}
className="absolute right-0 mt-3 w-56 rounded-xl border border-border bg-card shadow-lg flex flex-col overflow-hidden z-50 py-1"
>
<div className="px-4 py-3 border-b border-border/50">
<p className="text-sm font-semibold text-foreground truncate">{userProfile?.full_name || "User"}</p>
<p className="text-xs text-muted-foreground truncate leading-tight mt-0.5">{userProfile?.work_email || "user@examcraft.ai"}</p>
</div>
<div className="p-1">
<Link
to="/app/settings"
onClick={() => setProfileOpen(false)}
className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground rounded-md hover:bg-accent/10 hover:text-foreground transition-colors w-full text-left"
>
<Settings size={16} /> Profile Settings
</Link>
<button
onClick={async () => {
await supabase.auth.signOut();
navigate('/login');
}}
className="flex items-center gap-2 px-3 py-2 text-sm text-destructive rounded-md hover:bg-destructive/10 transition-colors w-full text-left mt-1"
>
<LogOut size={16} /> Logout
</button>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
</header>
{/* Dynamic Page Content */}
<div className="flex-1 overflow-auto p-4 md:p-8 bg-background relative selection:bg-primary/30">
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.3 }}
className="h-full w-full max-w-7xl mx-auto"
>
<Outlet />
</motion.div>
</div>
</main>
{/* Mobile Bottom Navigation (Visible on mobile) */}
<nav className="md:hidden fixed bottom-0 left-0 right-0 border-t border-border bg-card/95 backdrop-blur z-50 flex justify-around p-2 pb-safe">
{navItems.slice(0, 4).map((item) => (
<NavLink
key={item.name}
to={item.path}
end={item.path === "/app"}
className={({ isActive }) => cn(
"flex flex-col items-center p-2 rounded-lg text-xs font-medium space-y-1 transition-colors",
isActive ? "text-primary" : "text-muted-foreground"
)}
>
<item.icon className="h-5 w-5" />
<span>{item.name}</span>
</NavLink>
))}
</nav>
{/* Exam Password Creation Popup */}
<AnimatePresence>
{showPasswordPopup && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] bg-background/80 backdrop-blur-sm flex items-center justify-center p-4"
>
<motion.div
initial={{ scale: 0.95, opacity: 0, y: 20 }}
animate={{ scale: 1, opacity: 1, y: 0 }}
exit={{ scale: 0.95, opacity: 0, y: 20 }}
className="bg-card w-full max-w-md rounded-2xl border border-border shadow-[0_0_40px_rgba(0,0,0,0.1)] relative overflow-hidden"
>
{/* Decorative Top Gradient */}
<div className="absolute top-0 left-0 right-0 h-1.5 bg-gradient-to-r from-primary via-accent to-primary"></div>
<button
onClick={() => setShowPasswordPopup(false)}
className="absolute top-5 right-5 p-2 text-muted-foreground hover:bg-muted rounded-full transition-colors z-10"
>
<X size={18} />
</button>
<div className="px-6 pt-10 pb-6 border-b border-border/40 flex flex-col items-center text-center relative">
<div className="absolute -top-10 -right-10 w-24 h-24 bg-primary/10 rounded-full blur-2xl"></div>
<div className="absolute -bottom-10 -left-10 w-24 h-24 bg-accent/10 rounded-full blur-2xl"></div>
<div className="h-16 w-16 rounded-2xl bg-gradient-to-tr from-primary/20 to-accent/20 flex flex-col items-center justify-center mb-5 text-primary shadow-inner border border-primary/10 relative">
<KeyRound size={32} />
<div className="absolute -bottom-1 -right-1 w-4 h-4 rounded-full bg-emerald-500 border-2 border-card flex items-center justify-center animate-pulse">
</div>
</div>
<h2 className="text-2xl font-bold text-foreground">Set Exam PIN</h2>
<p className="text-sm text-muted-foreground mt-2 max-w-[90%]">
Create a secure <span className="text-foreground font-semibold">6-digit PIN</span> to protect your generated resources and control exam sessions.
</p>
</div>
<form onSubmit={handleSavePassword} className="p-6 space-y-5 bg-muted/10">
{passwordError && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
className="p-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-start gap-2 shadow-sm"
>
<AlertCircle size={16} className="shrink-0 mt-0.5" />
<span>{passwordError}</span>
</motion.div>
)}
<div className="space-y-4">
<div className="group">
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 group-focus-within:text-primary transition-colors">6-Digit PIN</label>
<input
type="password"
required
maxLength={6}
value={examPassword}
onChange={(e) => setExamPassword(e.target.value.replace(/\D/g, ''))}
className="w-full h-12 rounded-xl border border-input bg-background/50 backdrop-blur-sm px-4 text-center text-2xl font-mono tracking-[0.5em] placeholder:tracking-normal placeholder:text-sm placeholder:text-center shadow-sm focus:bg-background focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all disabled:opacity-50"
placeholder="••••••"
/>
</div>
<div className="group">
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 group-focus-within:text-primary transition-colors">Confirm PIN</label>
<input
type="password"
required
maxLength={6}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value.replace(/\D/g, ''))}
className="w-full h-12 rounded-xl border border-input bg-background/50 backdrop-blur-sm px-4 text-center text-2xl font-mono tracking-[0.5em] placeholder:tracking-normal placeholder:text-sm placeholder:text-center shadow-sm focus:bg-background focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all disabled:opacity-50"
placeholder="••••••"
/>
</div>
</div>
<div className="pt-4">
<button
type="submit"
disabled={isSavingPassword || examPassword.length !== 6 || confirmPassword.length !== 6}
className="w-full bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 text-primary-foreground shadow-md h-12 rounded-xl flex items-center justify-center text-sm font-bold transition-all disabled:opacity-50 disabled:pointer-events-none hover:shadow-lg hover:-translate-y-0.5"
>
{isSavingPassword ? (
<div className="flex items-center gap-2">
<div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
<span>Saving Securely...</span>
</div>
) : "Save Exam PIN"}
</button>
</div>
</form>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
|