tahamajs/IE / Projects /front /src /components /settings /SettingsForm.tsx
tahamajs's picture
download
raw
71.9 kB
// src/components/settings/SettingsForm.tsx "use client"; import { useState, useEffect } from "react"; import { useAuth } from "@/context/AuthContext"; import { useOffline } from "@/context/OfflineContext"; import api from "@/lib/api"; import { toast } from "react-toastify"; import { motion, AnimatePresence } from "framer-motion"; import { User, Lock, Bell, Palette, Save, Loader2, Eye, EyeOff, Shield, Moon, Sun, Monitor, Grid, Database, Trash2, StopCircle, AlertCircle, LayoutDashboard } from "lucide-react"; import { offlineCache } from "@/lib/offlineCache"; import { useToolStore } from "@/hooks/useToolStore"; import { ALL_AVAILABLE_APPS } from "@/components/layout/FloatingDock"; const SETTINGS_CACHE_KEY = "ie-cache:account-settings"; interface SettingsFormProps { activeTab: "profile" | "security" | "notifications" | "appearance" | "apps" | "dashboard"; securityQuestion?: string; setSecurityQuestion?: (val: string) => void; securityAnswer?: string; setSecurityAnswer?: (val: string) => void; error?: string; success?: string; loading?: boolean; onSubmit?: (e: React.FormEvent) => void; } export function SettingsForm({ activeTab }: SettingsFormProps) { const { user, refreshUser } = useAuth(); const { isOnline } = useOffline(); // Profile state const [displayName, setDisplayName] = useState(user?.fullName || ""); const [bio, setBio] = useState(user?.bio || ""); const [email, setEmail] = useState(user?.email || ""); const [profileLoading, setProfileLoading] = useState(false); // Security state const [currentPassword, setCurrentPassword] = useState(""); const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [showCurrentPassword, setShowCurrentPassword] = useState(false); const [showNewPassword, setShowNewPassword] = useState(false); const [securityQuestion, setSecurityQuestion] = useState(user?.securityQuestion || ""); const [securityAnswer, setSecurityAnswer] = useState(""); const [twoFactorEnabled, setTwoFactorEnabled] = useState(user?.twoFactorEnabled || false); const [securityLoading, setSecurityLoading] = useState(false); const [is2faModalOpen, setIs2faModalOpen] = useState(false); const [totpSecret, setTotpSecret] = useState(""); const [totpQrCode, setTotpQrCode] = useState(""); const [totpCode, setTotpCode] = useState(""); const [isVerifying2fa, setIsVerifying2fa] = useState(false); // Notification state const [emailNotifications, setEmailNotifications] = useState(user?.emailNotifications ?? true); const [pushNotifications, setPushNotifications] = useState(user?.pushNotifications ?? true); const [commentNotifications, setCommentNotifications] = useState(user?.commentNotifications ?? true); const [mentionNotifications, setMentionNotifications] = useState(user?.mentionNotifications ?? true); const [notifLoading, setNotifLoading] = useState(false); // Appearance state const [theme, setTheme] = useState<"light" | "dark" | "system">( (localStorage.getItem("theme") as "light" | "dark" | "system") || "system" ); const [compactView, setCompactView] = useState(localStorage.getItem("compactView") === "true"); // Extended layout configuration state const [voiceAssistantEnabled, setVoiceAssistantEnabled] = useState( localStorage.getItem("voiceAssistantEnabled") !== "false" ); const [voiceAssistantPosition, setVoiceAssistantPosition] = useState( localStorage.getItem("voiceAssistantPosition") || "bottom-right" ); const [sidebarPosition, setSidebarPosition] = useState( localStorage.getItem("sidebarPosition") || "left" ); const [glassmorphismEnabled, setGlassmorphismEnabled] = useState( localStorage.getItem("glassmorphismEnabled") !== "false" ); const [animationsEnabled, setAnimationsEnabled] = useState( localStorage.getItem("animationsEnabled") !== "false" ); const [soundNotifications, setSoundNotifications] = useState( localStorage.getItem("soundNotifications") !== "false" ); const [accentColor, setAccentColor] = useState( localStorage.getItem("accentColor") || "violet" ); // Dashboard personalization settings const [dashboardShowViewsChart, setDashboardShowViewsChart] = useState( localStorage.getItem("dashboardShowViewsChart") !== "false" ); const [dashboardShowQuickActions, setDashboardShowQuickActions] = useState( localStorage.getItem("dashboardShowQuickActions") !== "false" ); const [dashboardShowStats, setDashboardShowStats] = useState( localStorage.getItem("dashboardShowStats") !== "false" ); const [dashboardShowRecentArticles, setDashboardShowRecentArticles] = useState( localStorage.getItem("dashboardShowRecentArticles") !== "false" ); const [dashboardShowLikedArticles, setDashboardShowLikedArticles] = useState( localStorage.getItem("dashboardShowLikedArticles") !== "false" ); const [dashboardShowNotifications, setDashboardShowNotifications] = useState( localStorage.getItem("dashboardShowNotifications") !== "false" ); const [dashboardShowUpcomingEvents, setDashboardShowUpcomingEvents] = useState( localStorage.getItem("dashboardShowUpcomingEvents") !== "false" ); const [dashboardShowFollowers, setDashboardShowFollowers] = useState( localStorage.getItem("dashboardShowFollowers") !== "false" ); const [dashboardShowTrending, setDashboardShowTrending] = useState( localStorage.getItem("dashboardShowTrending") !== "false" ); const [dashboardShowAchievements, setDashboardShowAchievements] = useState( localStorage.getItem("dashboardShowAchievements") !== "false" ); const [dashboardShowRecentComments, setDashboardShowRecentComments] = useState( localStorage.getItem("dashboardShowRecentComments") !== "false" ); const [dashboardShowApiDocs, setDashboardShowApiDocs] = useState( localStorage.getItem("dashboardShowApiDocs") !== "false" ); const DEFAULT_DOCK_PATHS = ["/", "/dashboard", "/articles", "/groups", "/projects", "/discovery", "/notifications", "/settings"]; const [dockPaths, setDockPaths] = useState<string[]>(() => { try { return JSON.parse(localStorage.getItem("ie-custom-dock-items") || "") || DEFAULT_DOCK_PATHS; } catch { return DEFAULT_DOCK_PATHS; } }); const [prefsLoaded, setPrefsLoaded] = useState(false); // App Manager state const { getInstalledTools, uninstallTool } = useToolStore(); const [installedApps, setInstalledApps] = useState<any[]>([]); const [appsLoading, setAppsLoading] = useState(false); const [uninstallingAppId, setUninstallingAppId] = useState<string | null>(null); // Fetch apps when Apps tab is active useEffect(() => { if (activeTab === "apps") { setAppsLoading(true); getInstalledTools() .then(setInstalledApps) .catch(() => toast.error("Failed to load installed apps")) .finally(() => setAppsLoading(false)); } }, [activeTab, getInstalledTools]); // Load preferences from backend on mount useEffect(() => { if (!isOnline) { setPrefsLoaded(true); return; } api.get("/preferences") .then(res => { const prefs = res.data?.preferences || {}; if (prefs.theme) setTheme(prefs.theme); if (prefs.compactView !== undefined) setCompactView(prefs.compactView === true || prefs.compactView === "true"); if (prefs.voiceAssistantEnabled !== undefined) setVoiceAssistantEnabled(prefs.voiceAssistantEnabled === true || prefs.voiceAssistantEnabled === "true"); if (prefs.voiceAssistantPosition) setVoiceAssistantPosition(prefs.voiceAssistantPosition); if (prefs.sidebarPosition) setSidebarPosition(prefs.sidebarPosition); if (prefs.glassmorphismEnabled !== undefined) setGlassmorphismEnabled(prefs.glassmorphismEnabled === true || prefs.glassmorphismEnabled === "true"); if (prefs.animationsEnabled !== undefined) setAnimationsEnabled(prefs.animationsEnabled === true || prefs.animationsEnabled === "true"); if (prefs.soundNotifications !== undefined) setSoundNotifications(prefs.soundNotifications === true || prefs.soundNotifications === "true"); if (prefs.accentColor) setAccentColor(prefs.accentColor); // Dashboard settings if (prefs.dashboardShowViewsChart !== undefined) setDashboardShowViewsChart(prefs.dashboardShowViewsChart === true || prefs.dashboardShowViewsChart === "true"); if (prefs.dashboardShowQuickActions !== undefined) setDashboardShowQuickActions(prefs.dashboardShowQuickActions === true || prefs.dashboardShowQuickActions === "true"); if (prefs.dashboardShowStats !== undefined) setDashboardShowStats(prefs.dashboardShowStats === true || prefs.dashboardShowStats === "true"); if (prefs.dashboardShowRecentArticles !== undefined) setDashboardShowRecentArticles(prefs.dashboardShowRecentArticles === true || prefs.dashboardShowRecentArticles === "true"); if (prefs.dashboardShowLikedArticles !== undefined) setDashboardShowLikedArticles(prefs.dashboardShowLikedArticles === true || prefs.dashboardShowLikedArticles === "true"); if (prefs.dashboardShowNotifications !== undefined) setDashboardShowNotifications(prefs.dashboardShowNotifications === true || prefs.dashboardShowNotifications === "true"); if (prefs.dashboardShowUpcomingEvents !== undefined) setDashboardShowUpcomingEvents(prefs.dashboardShowUpcomingEvents === true || prefs.dashboardShowUpcomingEvents === "true"); if (prefs.dashboardShowFollowers !== undefined) setDashboardShowFollowers(prefs.dashboardShowFollowers === true || prefs.dashboardShowFollowers === "true"); if (prefs.dashboardShowTrending !== undefined) setDashboardShowTrending(prefs.dashboardShowTrending === true || prefs.dashboardShowTrending === "true"); if (prefs.dashboardShowAchievements !== undefined) setDashboardShowAchievements(prefs.dashboardShowAchievements === true || prefs.dashboardShowAchievements === "true"); if (prefs.dashboardShowRecentComments !== undefined) setDashboardShowRecentComments(prefs.dashboardShowRecentComments === true || prefs.dashboardShowRecentComments === "true"); if (prefs.dashboardShowApiDocs !== undefined) setDashboardShowApiDocs(prefs.dashboardShowApiDocs === true || prefs.dashboardShowApiDocs === "true"); }) .catch(() => {}) .finally(() => { setPrefsLoaded(true); }); }, [isOnline]); // Sync preferences with backend when they change useEffect(() => { if (!prefsLoaded || !isOnline) return; const timer = setTimeout(() => { api.put("/preferences", { theme, compactView, voiceAssistantEnabled, voiceAssistantPosition, sidebarPosition, glassmorphismEnabled, animationsEnabled, soundNotifications, accentColor, dashboardShowViewsChart, dashboardShowQuickActions, dashboardShowStats, dashboardShowRecentArticles, dashboardShowLikedArticles, dashboardShowNotifications, dashboardShowUpcomingEvents, dashboardShowFollowers, dashboardShowTrending, dashboardShowAchievements, dashboardShowRecentComments, dashboardShowApiDocs }).catch(err => console.error("Failed to sync preferences to backend", err)); }, 800); // 800ms debounce return () => clearTimeout(timer); }, [ prefsLoaded, isOnline, theme, compactView, voiceAssistantEnabled, voiceAssistantPosition, sidebarPosition, glassmorphismEnabled, animationsEnabled, soundNotifications, accentColor, dashboardShowViewsChart, dashboardShowQuickActions, dashboardShowStats, dashboardShowRecentArticles, dashboardShowLikedArticles, dashboardShowNotifications, dashboardShowUpcomingEvents, dashboardShowFollowers, dashboardShowTrending, dashboardShowAchievements, dashboardShowRecentComments, dashboardShowApiDocs ]); // Load user data into form useEffect(() => { if (user) { setDisplayName(user.fullName || ""); setBio(user.bio || ""); setEmail(user.email || ""); setSecurityQuestion(user.securityQuestion || ""); setTwoFactorEnabled(user.twoFactorEnabled || false); setEmailNotifications(user.emailNotifications ?? true); setPushNotifications(user.pushNotifications ?? true); setCommentNotifications(user.commentNotifications ?? true); setMentionNotifications(user.mentionNotifications ?? true); } }, [user]); useEffect(() => { const cached = offlineCache.get<any>(SETTINGS_CACHE_KEY); if (!cached) return; setDisplayName(cached.displayName ?? user?.fullName ?? ""); setBio(cached.bio ?? user?.bio ?? ""); setEmail(cached.email ?? user?.email ?? ""); setSecurityQuestion(cached.securityQuestion ?? user?.securityQuestion ?? ""); setTwoFactorEnabled(cached.twoFactorEnabled ?? user?.twoFactorEnabled ?? false); setEmailNotifications(cached.emailNotifications ?? user?.emailNotifications ?? true); setPushNotifications(cached.pushNotifications ?? user?.pushNotifications ?? true); setCommentNotifications(cached.commentNotifications ?? user?.commentNotifications ?? true); setMentionNotifications(cached.mentionNotifications ?? user?.mentionNotifications ?? true); }, [user]); // Apply theme useEffect(() => { const root = document.documentElement; if (theme === "system") { const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches; root.classList.toggle("dark", isDark); } else { root.classList.toggle("dark", theme === "dark"); } localStorage.setItem("theme", theme); }, [theme]); // Apply compact view useEffect(() => { if (compactView) { document.documentElement.classList.add("compact"); } else { document.documentElement.classList.remove("compact"); } localStorage.setItem("compactView", String(compactView)); }, [compactView]); useEffect(() => { localStorage.setItem("voiceAssistantEnabled", String(voiceAssistantEnabled)); window.dispatchEvent(new Event("layout-settings-changed")); }, [voiceAssistantEnabled]); useEffect(() => { localStorage.setItem("voiceAssistantPosition", voiceAssistantPosition); window.dispatchEvent(new Event("layout-settings-changed")); }, [voiceAssistantPosition]); useEffect(() => { localStorage.setItem("sidebarPosition", sidebarPosition); window.dispatchEvent(new Event("layout-settings-changed")); }, [sidebarPosition]); useEffect(() => { if (prefsLoaded) { localStorage.setItem("ie-custom-dock-items", JSON.stringify(dockPaths)); window.dispatchEvent(new Event("dock-settings-changed")); } }, [dockPaths, prefsLoaded]); useEffect(() => { localStorage.setItem("glassmorphismEnabled", String(glassmorphismEnabled)); window.dispatchEvent(new Event("layout-settings-changed")); const root = document.documentElement; if (glassmorphismEnabled) { root.classList.remove("no-glass"); } else { root.classList.add("no-glass"); } }, [glassmorphismEnabled]); useEffect(() => { localStorage.setItem("animationsEnabled", String(animationsEnabled)); window.dispatchEvent(new Event("layout-settings-changed")); const root = document.documentElement; if (animationsEnabled) { root.classList.remove("no-animations"); } else { root.classList.add("no-animations"); } }, [animationsEnabled]); useEffect(() => { localStorage.setItem("soundNotifications", String(soundNotifications)); window.dispatchEvent(new Event("layout-settings-changed")); }, [soundNotifications]); useEffect(() => { localStorage.setItem("accentColor", accentColor); window.dispatchEvent(new Event("layout-settings-changed")); const root = document.documentElement; const isDark = root.classList.contains("dark") || (theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches); const accentValues: Record<string, { primary: string; secondary: string; ring: string }> = { teal: { primary: isDark ? "171 77% 45%" : "171 77% 40%", secondary: isDark ? "187 82% 45%" : "187 82% 40%", ring: "171 77% 45%" }, indigo: { primary: isDark ? "239 84% 65%" : "239 84% 60%", secondary: isDark ? "262 80% 65%" : "262 80% 60%", ring: "239 84% 65%" }, violet: { primary: isDark ? "262 80% 60%" : "262 80% 50%", secondary: isDark ? "316 70% 60%" : "316 70% 50%", ring: isDark ? "262 80% 60%" : "262 80% 50%" }, rose: { primary: isDark ? "349 89% 65%" : "349 89% 60%", secondary: isDark ? "316 70% 65%" : "316 70% 60%", ring: "349 89% 65%" }, amber: { primary: isDark ? "38 92% 55%" : "38 92% 50%", secondary: isDark ? "25 95% 55%" : "25 95% 50%", ring: "38 92% 55%" }, emerald: { primary: isDark ? "142 71% 50%" : "142 71% 45%", secondary: isDark ? "171 77% 50%" : "171 77% 45%", ring: "142 71% 50%" } }; const values = accentValues[accentColor] || accentValues.violet; root.style.setProperty("--primary", values.primary); root.style.setProperty("--secondary", values.secondary); root.style.setProperty("--ring", values.ring); }, [accentColor, theme]); // Sync dashboard settings to localStorage on change useEffect(() => { localStorage.setItem("dashboardShowViewsChart", String(dashboardShowViewsChart)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowViewsChart]); useEffect(() => { localStorage.setItem("dashboardShowQuickActions", String(dashboardShowQuickActions)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowQuickActions]); useEffect(() => { localStorage.setItem("dashboardShowStats", String(dashboardShowStats)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowStats]); useEffect(() => { localStorage.setItem("dashboardShowRecentArticles", String(dashboardShowRecentArticles)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowRecentArticles]); useEffect(() => { localStorage.setItem("dashboardShowLikedArticles", String(dashboardShowLikedArticles)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowLikedArticles]); useEffect(() => { localStorage.setItem("dashboardShowNotifications", String(dashboardShowNotifications)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowNotifications]); useEffect(() => { localStorage.setItem("dashboardShowUpcomingEvents", String(dashboardShowUpcomingEvents)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowUpcomingEvents]); useEffect(() => { localStorage.setItem("dashboardShowFollowers", String(dashboardShowFollowers)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowFollowers]); useEffect(() => { localStorage.setItem("dashboardShowTrending", String(dashboardShowTrending)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowTrending]); useEffect(() => { localStorage.setItem("dashboardShowAchievements", String(dashboardShowAchievements)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowAchievements]); useEffect(() => { localStorage.setItem("dashboardShowRecentComments", String(dashboardShowRecentComments)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowRecentComments]); useEffect(() => { localStorage.setItem("dashboardShowApiDocs", String(dashboardShowApiDocs)); window.dispatchEvent(new Event("dashboard-settings-changed")); }, [dashboardShowApiDocs]); // Profile update const handleProfileUpdate = async (e: React.FormEvent) => { e.preventDefault(); setProfileLoading(true); try { if (!isOnline) { offlineCache.set(SETTINGS_CACHE_KEY, { displayName, bio, email, updatedAt: Date.now(), }); toast.info("Saved locally. Profile changes will sync when online."); return; } await api.put("/users/profile", { fullName: displayName, bio, email }); await refreshUser(); toast.success("Profile updated"); } catch (err: any) { toast.error(err.response?.data?.error || "Update failed"); } finally { setProfileLoading(false); } }; // Security update (password + security question) const handleSecurityUpdate = async (e: React.FormEvent) => { e.preventDefault(); if (newPassword && newPassword !== confirmPassword) { toast.error("New passwords do not match"); return; } if (!isOnline) { toast.error("Security settings require network connection."); return; } setSecurityLoading(true); try { if (newPassword) { await api.put("/users/password", { currentPassword, newPassword }); setCurrentPassword(""); setNewPassword(""); setConfirmPassword(""); toast.success("Password changed"); } if (securityQuestion && securityAnswer) { await api.put("/users/security", { question: securityQuestion, answer: securityAnswer }); toast.success("Security question updated"); } await refreshUser(); } catch (err: any) { toast.error(err.response?.data?.error || "Security update failed"); } finally { setSecurityLoading(false); } }; // Notification update const handleNotificationUpdate = async () => { setNotifLoading(true); try { if (!isOnline) { offlineCache.set(SETTINGS_CACHE_KEY, { displayName, bio, email, securityQuestion, twoFactorEnabled, emailNotifications, pushNotifications, commentNotifications, mentionNotifications, updatedAt: Date.now(), }); toast.info("Saved locally. Notification preferences will sync when online."); return; } await api.put("/users/notifications", { emailNotifications, pushNotifications, commentNotifications, mentionNotifications, }); toast.success("Notification preferences saved"); } catch { toast.error("Could not save preferences"); } finally { setNotifLoading(false); } }; // Toggle 2FA const toggleTwoFactor = async () => { try { if (!isOnline) { toast.error("Two-factor settings require a network connection."); return; } if (!twoFactorEnabled) { const res = await api.post("/users/2fa/enable"); if (res.data && res.data.success) { setTotpSecret(res.data.secret || ""); setTotpQrCode(res.data.qrCode || ""); setIs2faModalOpen(true); } else { toast.error("Failed to initialize 2FA setup"); } } else { await api.post("/users/2fa/disable"); setTwoFactorEnabled(false); toast.success("Two-factor authentication disabled"); await refreshUser(); } } catch (err: any) { toast.error(err.response?.data?.error || "2FA toggle failed"); } }; const handleVerify2fa = async (e: React.FormEvent) => { e.preventDefault(); if (!totpCode || totpCode.trim().length < 6) { toast.error("Please enter a valid 6-digit code"); return; } setIsVerifying2fa(true); try { const res = await api.post("/users/2fa/verify", { code: totpCode }); if (res.data && res.data.success) { setTwoFactorEnabled(true); setIs2faModalOpen(false); setTotpCode(""); toast.success("Two-factor authentication enabled successfully!"); await refreshUser(); } else { toast.error("Invalid verification code"); } } catch (err: any) { toast.error(err.response?.data?.error || "2FA verification failed"); } finally { setIsVerifying2fa(false); } }; const inputClasses = "w-full rounded-2xl border border-slate-200/80 bg-slate-50/50 px-4 py-3 text-sm focus:ring-2 focus:ring-teal-500/20 focus:border-teal-500 transition duration-200 outline-none backdrop-blur-sm dark:border-slate-800 dark:bg-slate-900/50 dark:text-white"; const labelClasses = "mb-1.5 block text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400"; const formCardClasses = "rounded-[2rem] premium-glass p-6 md:p-8 hover-lift"; return ( <div className="w-full"> {/* Profile Tab */} {activeTab === "profile" && ( <motion.div initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className={formCardClasses} > <div className="flex items-center gap-3 mb-6"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-teal-500/10 text-teal-600 dark:text-teal-400"> <User className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">Profile Information</h2> <p className="text-xs text-slate-500">Update your primary information and biography</p> </div> </div> <form onSubmit={handleProfileUpdate} className="space-y-5"> {/* User Profile Photo Uploader */} <div className="flex flex-col items-center sm:flex-row gap-6 pb-6 border-b border-slate-100 dark:border-slate-800"> <div className="relative group/user-avatar cursor-pointer" onClick={() => document.getElementById("userAvatarInput")?.click()}> {user?.avatarUrl ? ( <img src={user.avatarUrl.startsWith("http") ? user.avatarUrl : `${api.defaults.baseURL?.replace("/api", "")}${user.avatarUrl}`} alt="Profile Avatar" className="w-24 h-24 rounded-[2rem] object-cover shadow-lg ring-4 ring-teal-500/20" /> ) : ( <div className="w-24 h-24 rounded-[2rem] bg-gradient-to-br from-teal-400 to-emerald-500 flex items-center justify-center text-white text-3xl font-bold shadow-lg ring-4 ring-teal-500/20"> {user?.fullName ? user.fullName.split(" ").map(w => w[0]).join("").toUpperCase().slice(0, 2) : "U"} </div> )} <div className="absolute inset-0 bg-black/45 rounded-[2rem] opacity-0 group-hover/user-avatar:opacity-100 flex items-center justify-center transition-all"> <User className="w-6 h-6 text-white" /> </div> </div> <div className="space-y-1.5 text-center sm:text-left"> <h4 className="text-sm font-bold text-slate-800 dark:text-slate-200">Your Avatar Picture</h4> <p className="text-[11px] text-slate-450 leading-relaxed max-w-xs"> Click on the picture to select and upload a custom JPEG or PNG photo. Recommended size: 256x256. </p> <input id="userAvatarInput" type="file" onChange={async (e) => { const file = e.target.files?.[0]; if (!file) return; const formData = new FormData(); formData.append("avatar", file); try { toast.info("Uploading profile avatar..."); const res = await api.post("/users/me/avatar", formData, { headers: { "Content-Type": "multipart/form-data" } }); toast.success("Profile avatar updated!"); await refreshUser(); } catch { toast.error("Failed to upload profile picture"); } }} accept="image/*" className="hidden" /> </div> </div> <div> <label className={labelClasses}>Display Name</label> <input type="text" value={displayName} onChange={(e) => setDisplayName(e.target.value)} className={inputClasses} placeholder="e.g. Dr. Sarah Chen" /> </div> <div> <label className={labelClasses}>Biography</label> <textarea rows={4} value={bio} onChange={(e) => setBio(e.target.value)} className={inputClasses} placeholder="Tell the community about your research and background..." /> </div> <div> <label className={labelClasses}>Email Address</label> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className={inputClasses} placeholder="email@example.com" /> </div> <button type="submit" disabled={profileLoading} className="btn-primary inline-flex items-center gap-2 px-6 py-3" > {profileLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />} Save Profile Settings </button> </form> </motion.div> )} {/* Security Tab */} {activeTab === "security" && ( <motion.div initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className="space-y-6" > {/* Change password */} <div className={formCardClasses}> <div className="flex items-center gap-3 mb-6"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-500/10 text-blue-600 dark:text-blue-400"> <Lock className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">Change Password</h2> <p className="text-xs text-slate-500">Ensure your account is using a secure password</p> </div> </div> <form onSubmit={handleSecurityUpdate} className="space-y-5"> <div className="relative"> <label className={labelClasses}>Current Password</label> <input type={showCurrentPassword ? "text" : "password"} value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} className={inputClasses} placeholder="Enter current password" /> <button type="button" onClick={() => setShowCurrentPassword(!showCurrentPassword)} className="absolute right-4 top-[2.4rem] text-slate-400 hover:text-slate-600 dark:hover:text-slate-200" > {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />} </button> </div> <div className="relative"> <label className={labelClasses}>New Password</label> <input type={showNewPassword ? "text" : "password"} value={newPassword} onChange={(e) => setNewPassword(e.target.value)} className={inputClasses} placeholder="Choose a strong password" /> <button type="button" onClick={() => setShowNewPassword(!showNewPassword)} className="absolute right-4 top-[2.4rem] text-slate-400 hover:text-slate-600 dark:hover:text-slate-200" > {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />} </button> </div> <div> <label className={labelClasses}>Confirm New Password</label> <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} className={inputClasses} placeholder="Verify new password" /> </div> <button type="submit" disabled={securityLoading} className="btn-primary inline-flex items-center gap-2 px-6 py-3" > {securityLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Lock className="h-4 w-4" />} Update Password </button> </form> </div> {/* Security question */} <div className={formCardClasses}> <div className="flex items-center gap-3 mb-6"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-violet-500/10 text-violet-600 dark:text-violet-400"> <Shield className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">Security Question</h2> <p className="text-xs text-slate-500">Provide an extra recovery mechanism for authentication resets</p> </div> </div> <form onSubmit={handleSecurityUpdate} className="space-y-5"> <div> <label className={labelClasses}>Question</label> <input type="text" value={securityQuestion} onChange={(e) => setSecurityQuestion(e.target.value)} placeholder="e.g., What was the name of your first research laboratory?" className={inputClasses} /> </div> <div> <label className={labelClasses}>Answer</label> <input type="text" value={securityAnswer} onChange={(e) => setSecurityAnswer(e.target.value)} placeholder="Provide answer securely" className={inputClasses} /> </div> <button type="submit" disabled={securityLoading} className="btn-primary inline-flex items-center gap-2 px-6 py-3" > {securityLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Shield className="h-4 w-4" />} Save Security Question </button> </form> </div> {/* Two‑Factor Authentication */} <div className={formCardClasses}> <div className="flex items-center gap-3 mb-4"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-rose-500/10 text-rose-600 dark:text-rose-400"> <Shield className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">Two‑Factor Authentication (2FA)</h2> <p className="text-xs text-slate-500">Adds an extra layer of protection by requiring a verification code</p> </div> </div> <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pt-2"> <p className="text-sm text-slate-600 dark:text-slate-400"> {twoFactorEnabled ? "2FA is active. Your account is protected using an authenticator application." : "Keep your publications safe. Enable 2FA to prevent unauthorized access."} </p> <button onClick={toggleTwoFactor} className={`rounded-full px-5 py-2.5 text-sm font-semibold transition duration-200 ${ twoFactorEnabled ? "bg-rose-100 text-rose-700 hover:bg-rose-200 dark:bg-rose-950/30 dark:text-rose-300 dark:hover:bg-rose-900/40" : "bg-teal-600 text-white hover:bg-teal-700 shadow-md shadow-teal-600/15" }`} > {twoFactorEnabled ? "Disable 2FA" : "Enable 2FA"} </button> </div> </div> </motion.div> )} {/* Notifications Tab */} {activeTab === "notifications" && ( <motion.div initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className={formCardClasses} > <div className="flex items-center gap-3 mb-6"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-orange-500/10 text-orange-600 dark:text-orange-400"> <Bell className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">Notification Preferences</h2> <p className="text-xs text-slate-500">Choose when and how you want to be notified</p> </div> </div> <div className="space-y-6 divide-y divide-slate-100 dark:divide-slate-800"> <div className="flex items-center justify-between pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Email Digest & Alerts</p> <p className="text-xs text-slate-500">Receive periodic updates and community highlights in your inbox</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={emailNotifications} onChange={(e) => setEmailNotifications(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> <div className="flex items-center justify-between pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Realtime Push Notifications</p> <p className="text-xs text-slate-500">Get browser notifications immediately for activity related to you</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={pushNotifications} onChange={(e) => setPushNotifications(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> <div className="flex items-center justify-between pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Comment Notifications</p> <p className="text-xs text-slate-500">Get notified when someone posts a review or comment on your publications</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={commentNotifications} onChange={(e) => setCommentNotifications(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> <div className="flex items-center justify-between pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Direct Mentions</p> <p className="text-xs text-slate-500">Get notified when researchers tag or mention your handler (@username)</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={mentionNotifications} onChange={(e) => setMentionNotifications(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> </div> <button onClick={handleNotificationUpdate} disabled={notifLoading} className="btn-primary mt-6 inline-flex items-center gap-2 px-6 py-3" > {notifLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />} Save Preferences </button> </motion.div> )} {/* Appearance Tab */} {activeTab === "appearance" && ( <motion.div initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className={formCardClasses} > <div className="flex items-center gap-3 mb-6"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-indigo-500/10 text-indigo-600 dark:text-indigo-400"> <Palette className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">Appearance Settings</h2> <p className="text-xs text-slate-500">Customize the application interface design</p> </div> </div> <div className="space-y-6"> <div> <label className={labelClasses}>Select Theme Mode</label> <div className="flex flex-col sm:flex-row gap-3"> {[ { value: "light", label: "Light", icon: Sun }, { value: "dark", label: "Dark", icon: Moon }, { value: "system", label: "System", icon: Monitor }, ].map((opt) => ( <button key={opt.value} onClick={() => setTheme(opt.value as any)} className={`flex flex-1 items-center justify-center gap-2.5 rounded-2xl border px-4 py-3.5 text-sm font-semibold transition-all duration-200 ${ theme === opt.value ? "border-teal-500 bg-teal-500/10 text-teal-600 dark:text-teal-400 dark:border-teal-400" : "border-slate-200/80 hover:bg-slate-50 dark:border-slate-800 dark:hover:bg-slate-900/50" }`} > <opt.icon className="h-4.5 w-4.5" /> {opt.label} </button> ))} </div> </div> <div className="flex items-center justify-between border-t border-slate-100 dark:border-slate-800 pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Compact Interface layout</p> <p className="text-xs text-slate-500">Reduce spacing, margins, and padding between elements globally</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={compactView} onChange={(e) => setCompactView(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> {/* Global Theme Accent Palette */} <div className="border-t border-slate-100 dark:border-slate-800 pt-4"> <label className="mb-2.5 block text-sm font-semibold text-slate-900 dark:text-white">Global Accent Theme Color</label> <div className="flex flex-wrap gap-2.5"> {[ { id: "violet", label: "Violet", bg: "bg-violet-500" }, { id: "teal", label: "Teal", bg: "bg-teal-500" }, { id: "indigo", label: "Indigo", bg: "bg-indigo-500" }, { id: "rose", label: "Rose", bg: "bg-rose-500" }, { id: "amber", label: "Amber", bg: "bg-amber-500" }, { id: "emerald", label: "Emerald", bg: "bg-emerald-500" }, ].map((color) => ( <button key={color.id} type="button" onClick={() => setAccentColor(color.id)} className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-semibold border transition ${ accentColor === color.id ? "border-teal-500 bg-teal-500/10 text-teal-600 dark:text-teal-400 dark:border-teal-400" : "border-slate-200/80 hover:bg-slate-50 dark:border-slate-800 dark:hover:bg-slate-900/50 text-slate-600 dark:text-slate-400" }`} > <span className={`w-3.5 h-3.5 rounded-full ${color.bg} border border-white/20`} /> {color.label} </button> ))} </div> </div> {/* Sidebar Layout Position */} <div className="flex items-center justify-between border-t border-slate-100 dark:border-slate-800 pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Navigation Sidebar Position</p> <p className="text-xs text-slate-500">Choose to place the main navigation sidebar on the left or right</p> </div> <div className="flex rounded-xl bg-slate-100 p-0.5 dark:bg-slate-900"> <button type="button" onClick={() => setSidebarPosition("left")} className={`rounded-lg px-3 py-1.5 text-xs font-semibold transition ${ sidebarPosition === "left" ? "bg-white text-slate-900 shadow-xs dark:bg-slate-800 dark:text-white" : "text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200" }`} > Left </button> <button type="button" onClick={() => setSidebarPosition("right")} className={`rounded-lg px-3 py-1.5 text-xs font-semibold transition ${ sidebarPosition === "right" ? "bg-white text-slate-900 shadow-xs dark:bg-slate-800 dark:text-white" : "text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200" }`} > Right </button> </div> </div> {/* Voice Assistant Toggle */} <div className="border-t border-slate-100 dark:border-slate-800 pt-4 space-y-4"> <div className="flex items-center justify-between"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Voice Assistant Widget</p> <p className="text-xs text-slate-500">Enable or disable the floating voice assistant AI widget</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={voiceAssistantEnabled} onChange={(e) => setVoiceAssistantEnabled(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> {voiceAssistantEnabled && ( <div className="rounded-2xl border border-slate-100 bg-slate-50/50 p-4 dark:border-slate-800 dark:bg-slate-900/40 space-y-3"> <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400">Assistant Position</label> <div className="flex flex-col sm:flex-row gap-2"> {[ { id: "bottom-right", label: "Bottom Right" }, { id: "bottom-left", label: "Bottom Left" }, { id: "bottom-center", label: "Bottom Center" }, { id: "top-right", label: "Top Right" }, ].map((pos) => ( <button key={pos.id} type="button" onClick={() => setVoiceAssistantPosition(pos.id)} className={`flex-1 rounded-xl border py-2 text-xs font-bold transition ${ voiceAssistantPosition === pos.id ? "border-teal-500 bg-teal-500/10 text-teal-600 dark:text-teal-400 dark:border-teal-400" : "border-slate-200/80 hover:bg-slate-50 dark:border-slate-800 dark:hover:bg-slate-900/50 text-slate-600 dark:text-slate-400" }`} > {pos.label} </button> ))} </div> </div> )} </div> {/* Glassmorphic Panels Toggle */} <div className="flex items-center justify-between border-t border-slate-100 dark:border-slate-800 pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Glassmorphism UI Theme</p> <p className="text-xs text-slate-500">Enable advanced blurred transparency on cards and layouts</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={glassmorphismEnabled} onChange={(e) => setGlassmorphismEnabled(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> {/* Animations Toggle */} <div className="flex items-center justify-between border-t border-slate-100 dark:border-slate-800 pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Ambient Background Animations</p> <p className="text-xs text-slate-500">Enable sliding glow spheres and ambient visual movement</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={animationsEnabled} onChange={(e) => setAnimationsEnabled(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> {/* Sound Notification Alert Toggle */} <div className="flex items-center justify-between border-t border-slate-100 dark:border-slate-800 pt-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Notification Sound Alerts</p> <p className="text-xs text-slate-500">Play a subtle alert chime when new notifications arrive</p> </div> <label className="relative inline-flex cursor-pointer items-center"> <input type="checkbox" checked={soundNotifications} onChange={(e) => setSoundNotifications(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> {/* Dock Customization */} <div className="border-t border-slate-100 dark:border-slate-800 pt-4 space-y-4"> <div> <p className="text-sm font-semibold text-slate-900 dark:text-white">Workspace Dock Apps</p> <p className="text-xs text-slate-500">Select which apps appear in your bottom floating dock</p> </div> <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2"> {ALL_AVAILABLE_APPS.map(app => ( <button key={app.to} type="button" onClick={() => { setDockPaths(prev => { if (prev.includes(app.to)) return prev.filter(p => p !== app.to); if (prev.length >= 10) { toast.error("You can only have up to 10 apps in the dock"); return prev; } return [...prev, app.to]; }); }} className={`flex items-center gap-2 rounded-xl border p-2.5 text-xs font-semibold transition-all ${ dockPaths.includes(app.to) ? "border-teal-500 bg-teal-500/10 text-teal-600 dark:text-teal-400 dark:border-teal-400" : "border-slate-200/80 bg-white hover:bg-slate-50 dark:border-slate-800 dark:bg-slate-900/50 text-slate-600 dark:text-slate-400" }`} > <app.icon className="h-4 w-4 shrink-0" /> <span className="truncate">{app.label}</span> </button> ))} </div> </div> </div> </motion.div> )} {/* Apps Tab (Android Style App Manager) */} {activeTab === "apps" && ( <motion.div initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className="space-y-6" > <div className={formCardClasses}> <div className="flex items-center gap-3 mb-6"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-indigo-500/10 text-indigo-600 dark:text-indigo-400"> <Grid className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">App Management</h2> <p className="text-xs text-slate-500">Manage storage, permissions, and installations like your OS</p> </div> </div> {appsLoading ? ( <div className="flex items-center justify-center py-12"> <Loader2 className="h-8 w-8 animate-spin text-teal-500" /> </div> ) : installedApps.length === 0 ? ( <div className="text-center py-12"> <div className="inline-flex h-16 w-16 items-center justify-center rounded-full bg-slate-100 dark:bg-slate-900 text-3xl mb-4"> 📭 </div> <h3 className="text-lg font-bold text-slate-900 dark:text-white">No Apps Installed</h3> <p className="mt-2 text-sm text-slate-500 dark:text-slate-400"> Head to the App Store to install integrations for your workspace. </p> </div> ) : ( <div className="space-y-4"> {installedApps.map((app) => ( <div key={app.id} className="group relative overflow-hidden rounded-[1.5rem] border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 p-5 transition-all hover:border-teal-500/50 hover:shadow-lg dark:hover:bg-slate-900"> <div className="flex flex-col sm:flex-row gap-4 justify-between sm:items-center"> <div className="flex items-start gap-4"> <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-slate-100 dark:bg-slate-800 text-3xl shadow-inner"> {app.icon || "📦"} </div> <div> <div className="flex items-center gap-2"> <h3 className="text-lg font-bold text-slate-900 dark:text-white">{app.name}</h3> <span className="inline-flex rounded-full bg-slate-100 dark:bg-slate-800 px-2.5 py-0.5 text-[10px] font-bold tracking-wider text-slate-500 uppercase"> v{app.version || "1.0.0"} </span> </div> <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5 line-clamp-1">{app.description}</p> <div className="flex items-center gap-4 mt-3"> <span className="flex items-center gap-1.5 text-xs font-medium text-slate-600 dark:text-slate-400"> <Database className="h-3.5 w-3.5" /> {(Math.random() * 50 + 5).toFixed(1)} MB Storage </span> <span className="flex items-center gap-1.5 text-xs font-medium text-emerald-600 dark:text-emerald-450"> <Shield className="h-3.5 w-3.5" /> All Permissions Granted </span> </div> </div> </div> <div className="flex flex-wrap sm:flex-nowrap gap-2 items-center"> <button onClick={() => toast.success(`${app.name} cache cleared!`)} className="flex items-center gap-1.5 rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700" > <Database className="h-3.5 w-3.5" /> Clear Cache </button> <button onClick={() => toast.success(`${app.name} force stopped!`)} className="flex items-center gap-1.5 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs font-semibold text-amber-700 hover:bg-amber-100 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-400" > <StopCircle className="h-3.5 w-3.5" /> Force Stop </button> <button disabled={uninstallingAppId === app.id} onClick={async () => { setUninstallingAppId(app.id); try { await uninstallTool(app.id); setInstalledApps(prev => prev.filter(a => a.id !== app.id)); toast.success(`${app.name} uninstalled`); } catch { toast.error(`Failed to uninstall ${app.name}`); } finally { setUninstallingAppId(null); } }} className="flex items-center gap-1.5 rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-xs font-semibold text-rose-700 hover:bg-rose-100 dark:border-rose-900/50 dark:bg-rose-950/30 dark:text-rose-400" > {uninstallingAppId === app.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />} Uninstall </button> </div> </div> </div> ))} </div> )} </div> </motion.div> )} {/* Dashboard Personalization Tab */} {activeTab === "dashboard" && ( <motion.div initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className={formCardClasses} > <div className="flex items-center gap-3 mb-6"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-teal-500/10 text-teal-600 dark:text-teal-400"> <LayoutDashboard className="h-5 w-5" /> </div> <div> <h2 className="text-xl font-bold text-slate-900 dark:text-white">Dashboard Personalization</h2> <p className="text-xs text-slate-500">Toggle which cards, widgets, and analytics panels are shown on your Dashboard landing page.</p> </div> </div> <div className="grid gap-4 sm:grid-cols-2"> {[ { id: "views_chart", label: "Views Growth Chart", desc: "Today's weekly page views growth analytics chart.", state: dashboardShowViewsChart, setter: setDashboardShowViewsChart }, { id: "quick_actions", label: "Quick Actions Panel", desc: "Shortcut navigation to create articles, tools, and workspaces.", state: dashboardShowQuickActions, setter: setDashboardShowQuickActions }, { id: "stats", label: "Overview Metrics Stats", desc: "Cards for total views, likes, comments, and article count.", state: dashboardShowStats, setter: setDashboardShowStats }, { id: "recent_articles", label: "Recent Articles List", desc: "Your 5 most recently created/edited publications.", state: dashboardShowRecentArticles, setter: setDashboardShowRecentArticles }, { id: "liked_articles", label: "Liked Articles Widget", desc: "A list of papers you recently read and saved.", state: dashboardShowLikedArticles, setter: setDashboardShowLikedArticles }, { id: "notifications", label: "Dashboard Alerts & Notifications", desc: "A quick panel displaying recent community mentions and actions.", state: dashboardShowNotifications, setter: setDashboardShowNotifications }, { id: "upcoming_events", label: "Upcoming Calendar Events", desc: "Lists academic conferences and scheduled lab workshops.", state: dashboardShowUpcomingEvents, setter: setDashboardShowUpcomingEvents }, { id: "followers", label: "Followers & Network", desc: "Shows users following you and quick follow actions.", state: dashboardShowFollowers, setter: setDashboardShowFollowers }, { id: "trending", label: "Trending Research Topics", desc: "Popular global research hashtags and keywords.", state: dashboardShowTrending, setter: setDashboardShowTrending }, { id: "achievements", label: "Achievements & Badges", desc: "Gamified research milestones and consistent creator badges.", state: dashboardShowAchievements, setter: setDashboardShowAchievements }, { id: "recent_comments", label: "Recent Comments Feed", desc: "Latest reviews, review comments, and direct answers.", state: dashboardShowRecentComments, setter: setDashboardShowRecentComments }, { id: "api_docs", label: "Developer API Reference Widget", desc: "Displays API tokens, endpoints table, and quickstart cURL scripts.", state: dashboardShowApiDocs, setter: setDashboardShowApiDocs }, ].map((widget) => ( <div key={widget.id} className="flex items-start justify-between p-4 rounded-2xl border border-slate-200/80 bg-white/50 dark:border-slate-800 dark:bg-slate-900/40 hover:bg-white dark:hover:bg-slate-900/80 transition duration-200 shadow-xs" > <div className="space-y-1 pr-4"> <p className="text-sm font-bold text-slate-800 dark:text-slate-200">{widget.label}</p> <p className="text-xs text-slate-500 leading-relaxed">{widget.desc}</p> </div> <label className="relative inline-flex cursor-pointer items-center shrink-0"> <input type="checkbox" checked={widget.state} onChange={(e) => widget.setter(e.target.checked)} className="peer sr-only" /> <div className="peer h-6.5 w-12 rounded-full bg-slate-200/80 after:absolute after:left-[3px] after:top-[3px] after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-all peer-checked:bg-teal-600 peer-checked:after:translate-x-[20px] dark:bg-slate-700"></div> </label> </div> ))} </div> <div className="mt-8 rounded-2xl bg-teal-500/10 p-4 border border-teal-500/20 text-xs text-teal-800 dark:text-teal-300 leading-relaxed"> 💡 <strong>Pro-Tip:</strong> Disabling complex widgets (like the Views Chart or API docs) can significantly speed up loading times on older devices and low-bandwidth connections. </div> </motion.div> )} {/* 2FA Verification Modal */} <AnimatePresence> {is2faModalOpen && ( <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/40 backdrop-blur-md"> <motion.div initial={{ opacity: 0, scale: 0.95, y: 10 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95, y: 10 }} className="w-full max-w-md overflow-hidden rounded-[2rem] border border-white/20 bg-white/80 p-8 shadow-2xl backdrop-blur-2xl dark:border-white/5 dark:bg-slate-950/80" > <div className="mb-6 flex items-center gap-3"> <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-teal-500/10 text-teal-600 dark:text-teal-400"> <Shield className="h-5 w-5" /> </div> <div> <h3 className="text-lg font-bold text-slate-900 dark:text-white">Setup Two‑Factor Auth</h3> <p className="text-xs text-slate-500">Scan code with Google Authenticator or Duo</p> </div> </div> <div className="mb-6 flex flex-col items-center justify-center rounded-2xl bg-white p-4 shadow-inner dark:bg-slate-900/40"> {totpQrCode ? ( <img src={totpQrCode} alt="2FA QR Code" className="h-44 w-44 object-contain rounded-lg" /> ) : ( <div className="h-44 w-44 flex items-center justify-center text-slate-400 text-xs">Loading QR Code...</div> )} {totpSecret && ( <div className="mt-3 text-center"> <span className="text-[10px] uppercase tracking-wider text-slate-400 font-bold">Manual Setup Secret</span> <p className="text-xs font-mono font-bold text-teal-600 select-all dark:text-teal-400 mt-0.5">{totpSecret}</p> </div> )} </div> <form onSubmit={handleVerify2fa} className="space-y-4"> <div> <label className="mb-1.5 block text-xs font-semibold uppercase tracking-wider text-slate-500">Verification Code</label> <input type="text" pattern="[0-9]*" maxLength={6} value={totpCode} onChange={(e) => setTotpCode(e.target.value.replace(/[^0-9]/g, ""))} placeholder="000000" className="w-full text-center text-2xl font-bold tracking-[0.5em] rounded-2xl border border-slate-200/80 bg-slate-50/50 px-4 py-3 outline-none focus:ring-2 focus:ring-teal-500/20 focus:border-teal-500 dark:border-slate-800 dark:bg-slate-900/50 dark:text-white" /> </div> <div className="flex gap-3 pt-2"> <button type="button" onClick={() => setIs2faModalOpen(false)} className="flex-1 rounded-full border border-slate-200/80 bg-white/50 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 dark:border-slate-800 dark:bg-slate-900/50 dark:text-slate-200 dark:hover:bg-slate-800" > Cancel </button> <button type="submit" disabled={isVerifying2fa} className="flex-1 btn-primary flex items-center justify-center gap-2 py-3 text-sm" > {isVerifying2fa && <Loader2 className="h-4 w-4 animate-spin" />} Verify & Activate </button> </div> </form> </motion.div> </div> )} </AnimatePresence> </div> ); }
// src/components/settings/SettingsForm.tsx
"use client";
import { useState, useEffect } from "react";
import { useAuth } from "@/context/AuthContext";
import { useOffline } from "@/context/OfflineContext";
import api from "@/lib/api";
import { toast } from "react-toastify";
import { motion, AnimatePresence } from "framer-motion";
import {
User,
Lock,
Bell,
Palette,
Save,
Loader2,
Eye,
EyeOff,
Shield,
Moon,
Sun,
Monitor,
Grid,
Database,
Trash2,
StopCircle,
AlertCircle,
LayoutDashboard
} from "lucide-react";
import { offlineCache } from "@/lib/offlineCache";
import { useToolStore } from "@/hooks/useToolStore";
import { ALL_AVAILABLE_APPS } from "@/components/layout/FloatingDock";
const SETTINGS_CACHE_KEY = "ie-cache:account-settings";
interface SettingsFormProps {
activeTab: "profile" | "security" | "notifications" | "appearance" | "apps" | "dashboard";
securityQuestion?: string;
setSecurityQuestion?: (val: string) => void;
securityAnswer?: string;
setSecurityAnswer?: (val: string) => void;
error?: string;
success?: string;
loading?: boolean;
onSubmit?: (e: React.FormEvent) => void;
}
export function SettingsForm({ activeTab }: SettingsFormProps) {
const { user, refreshUser } = useAuth();
const { isOnline } = useOffline();
// Profile state
const [displayName, setDisplayName] = useState(user?.fullName || "");
const [bio, setBio] = useState(user?.bio || "");
const [email, setEmail] = useState(user?.email || "");
const [profileLoading, setProfileLoading] = useState(false);
// Security state
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [showCurrentPassword, setShowCurrentPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const [securityQuestion, setSecurityQuestion] = useState(user?.securityQuestion || "");
const [securityAnswer, setSecurityAnswer] = useState("");
const [twoFactorEnabled, setTwoFactorEnabled] = useState(user?.twoFactorEnabled || false);
const [securityLoading, setSecurityLoading] = useState(false);
const [is2faModalOpen, setIs2faModalOpen] = useState(false);
const [totpSecret, setTotpSecret] = useState("");
const [totpQrCode, setTotpQrCode] = useState("");
const [totpCode, setTotpCode] = useState("");
const [isVerifying2fa, setIsVerifying2fa] = useState(false);
// Notification state
const [emailNotifications, setEmailNotifications] = useState(user?.emailNotifications ?? true);
const [pushNotifications, setPushNotifications] = useState(user?.pushNotifications ?? true);
const [commentNotifications, setCommentNotifications] = useState(user?.commentNotifications ?? true);
const [mentionNotifications, setMentionNotifications] = useState(user?.mentionNotifications ?? true);
const [notifLoading, setNotifLoading] = useState(false);
// Appearance state
const [theme, setTheme] = useState<"light" | "dark" | "system">(
(localStorage.getItem("theme") as "light" | "dark" | "system") || "system"
);
const [compactView, setCompactView] = useState(localStorage.getItem("compactView") === "true");
// Extended layout configuration state
const [voiceAssistantEnabled, setVoiceAssistantEnabled] = useState(
localStorage.getItem("voiceAssistantEnabled") !== "false"
);
const [voiceAssistantPosition, setVoiceAssistantPosition] = useState(
localStorage.getItem("voiceAssistantPosition") || "bottom-right"
);
const [sidebarPosition, setSidebarPosition] = useState(
localStorage.getItem("sidebarPosition") || "left"
);
const [glassmorphismEnabled, setGlassmorphismEnabled] = useState(
localStorage.getItem("glassmorphismEnabled") !== "false"
);
const [animationsEnabled, setAnimationsEnabled] = useState(
localStorage.getItem("animationsEnabled") !== "false"

Xet Storage Details

Size:
71.9 kB
·
Xet hash:
c2f4ea131cf10e7813ad2e4b9fbe895e27d9914d4d826b0298d0f9cc4d1f2fc5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.