"use client"; import { useState, useEffect, useCallback } from "react"; import { motion } from "framer-motion"; import { Settings, User, Target, Castle, Check, AlertCircle, Loader2, Download, Database, Sparkles, Plug } from "lucide-react"; import { apiClient, ApiClientError, HF_TOKEN_STORAGE_KEY, HF_MODEL_STORAGE_KEY, } from "@/lib/api-client"; const ACCENT = "var(--primary)"; const DAILY_GOAL_OPTIONS = [ { value: 50, label: "50 XP", description: "Light — ~1 quick exercise" }, { value: 100, label: "100 XP", description: "Standard — ~2–3 exercises" }, { value: 150, label: "150 XP", description: "Focused — ~4 exercises" }, { value: 200, label: "200 XP", description: "Dedicated — ~5–6 exercises" }, { value: 300, label: "300 XP", description: "Hardcore — full session" }, ]; interface SettingsData { name: string; dailyGoalXp: number; lichessUsername: string; chesscomUsername: string; } type SaveState = "idle" | "saving" | "saved" | "error"; function SectionCard({ icon, title, children, }: { icon: React.ReactNode; title: string; children: React.ReactNode; }) { return (
{icon}

{title}

{children}
); } function FieldLabel({ htmlFor, children }: { htmlFor: string; children: React.ReactNode }) { return ( ); } function TextInput({ id, value, onChange, placeholder, maxLength, type = "text", }: { id: string; value: string; onChange: (v: string) => void; placeholder?: string; maxLength?: number; type?: "text" | "password"; }) { return ( onChange(e.target.value)} placeholder={placeholder} maxLength={maxLength} className="w-full px-4 py-2.5 rounded-xl text-sm outline-none transition-all" style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.1)", color: "var(--text-primary)", }} onFocus={(e) => { e.target.style.borderColor = ACCENT; }} onBlur={(e) => { e.target.style.borderColor = "rgba(255,255,255,0.1)"; }} /> ); } export default function SettingsPage() { const [settings, setSettings] = useState({ name: "", dailyGoalXp: 100, lichessUsername: "", chesscomUsername: "", }); const [loading, setLoading] = useState(true); const [saveState, setSaveState] = useState("idle"); const [errorMsg, setErrorMsg] = useState(null); const [exportState, setExportState] = useState<"idle" | "exporting" | "done" | "error">("idle"); // Hugging Face per-user credentials (browser-only — never server-persisted) const [hfToken, setHfToken] = useState(""); const [hfModel, setHfModel] = useState(""); const [hfSaveState, setHfSaveState] = useState("idle"); const [hfTestState, setHfTestState] = useState<"idle" | "testing" | "ok" | "error">("idle"); const [hfTestMsg, setHfTestMsg] = useState(null); // Load current settings useEffect(() => { apiClient.getSettings() .then((data) => { setSettings({ name: data.name ?? "", dailyGoalXp: data.dailyGoalXp ?? 100, lichessUsername: data.lichessUsername ?? "", chesscomUsername: data.chesscomUsername ?? "", }); }) .catch(() => setErrorMsg("Failed to load settings")) .finally(() => setLoading(false)); }, []); // Load Hugging Face credentials from localStorage (client-only) useEffect(() => { try { setHfToken(window.localStorage.getItem(HF_TOKEN_STORAGE_KEY) ?? ""); // eslint-disable-line react-hooks/set-state-in-effect setHfModel(window.localStorage.getItem(HF_MODEL_STORAGE_KEY) ?? ""); } catch { /* localStorage unavailable — ignore */ } }, []); // Persist HF credentials to localStorage so the API client attaches them // as x-hf-token / x-hf-model headers on every request. const persistHf = useCallback(() => { try { if (hfToken.trim()) window.localStorage.setItem(HF_TOKEN_STORAGE_KEY, hfToken.trim()); else window.localStorage.removeItem(HF_TOKEN_STORAGE_KEY); if (hfModel.trim()) window.localStorage.setItem(HF_MODEL_STORAGE_KEY, hfModel.trim()); else window.localStorage.removeItem(HF_MODEL_STORAGE_KEY); } catch { /* ignore */ } }, [hfToken, hfModel]); const handleSaveHf = useCallback(() => { persistHf(); setHfSaveState("saved"); setTimeout(() => setHfSaveState("idle"), 2500); }, [persistHf]); const handleTestHf = useCallback(async () => { persistHf(); // test what the user just typed setHfTestState("testing"); setHfTestMsg(null); try { const res = await apiClient.getLlmHealth(); if (res.ok) { setHfTestState("ok"); setHfTestMsg(`Connected via ${res.provider}${res.model ? ` (${res.model})` : ""}.`); } else { setHfTestState("error"); setHfTestMsg(res.error ?? "Connection failed."); } } catch (err) { setHfTestState("error"); setHfTestMsg(err instanceof Error ? err.message : "Connection failed."); } }, [persistHf]); const handleExport = useCallback(async () => { setExportState("exporting"); try { const data = await apiClient.exportData(); const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; const dateStr = new Date().toISOString().slice(0, 10); a.download = `rotnot-export-${dateStr}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); setExportState("done"); setTimeout(() => setExportState("idle"), 3000); } catch { setExportState("error"); setTimeout(() => setExportState("idle"), 3000); } }, []); const handleSave = useCallback(async () => { setSaveState("saving"); setErrorMsg(null); try { const updated = await apiClient.updateSettings(settings); setSettings({ name: updated.name ?? "", dailyGoalXp: updated.dailyGoalXp ?? 100, lichessUsername: updated.lichessUsername ?? "", chesscomUsername: updated.chesscomUsername ?? "", }); setSaveState("saved"); setTimeout(() => setSaveState("idle"), 2500); } catch (err) { setErrorMsg( err instanceof ApiClientError ? ((err.body as { error?: string })?.error ?? "Save failed") : err instanceof Error ? err.message : "Unknown error", ); setSaveState("error"); setTimeout(() => setSaveState("idle"), 3000); } }, [settings]); if (loading) { return (
); } return (
{/* Header */}

Settings

Customize your RotNot experience

{/* Profile */} } title="Profile"> Display Name setSettings((s) => ({ ...s, name: v }))} placeholder="Your name" maxLength={50} />

Shown on your profile and leaderboard

{/* Daily Goal */} } title="Daily XP Goal">
{DAILY_GOAL_OPTIONS.map((opt) => { const active = settings.dailyGoalXp === opt.value; return ( ); })}
{/* Connected Accounts */} } title="Connected Accounts">
Lichess Username setSettings((s) => ({ ...s, lichessUsername: v }))} placeholder="e.g. DrNykterstein" maxLength={30} />

Used to fetch Lichess puzzles with your auth token

Chess.com Username setSettings((s) => ({ ...s, chesscomUsername: v }))} placeholder="e.g. MagnusCarlsen" maxLength={30} />

Used to display your Chess.com ratings on the profile

{/* Hugging Face (AI provider) */} } title="Hugging Face (AI)">

Power the AI features (Feynman, Debate, Critical Thinking, coding written grading, …) with your own free Hugging Face token. Create a read token at{" "} huggingface.co/settings/tokens .

Access Token
Model (optional)

Defaults to DeepSeek-V4-Flash. Enter any Hugging Face model id to override (e.g. deepseek-ai/DeepSeek-V4-Flash,{" "} meta-llama/Llama-3.3-70B-Instruct).

{hfSaveState === "saved" ? : null} {hfSaveState === "saved" ? "Saved!" : "Save Token"} {hfTestState === "testing" && } {hfTestState === "ok" && } {hfTestState === "error" && } {hfTestState === "idle" && } {hfTestState === "testing" ? "Testing…" : "Test connection"}
{hfTestMsg && ( {hfTestMsg} )}

🔒 Your token stays in this browser (localStorage) and is sent only with your own requests over HTTPS. It is never logged or stored on the server.

{/* Data & Privacy */} } title="Data & Privacy">

Download a complete JSON export of all your RotNot data — XP history, activities, skill trees, spaced repetition queue, and daily logs.

{exportState === "exporting" && } {exportState === "done" && } {exportState === "error" && } {exportState === "idle" && } {exportState === "exporting" ? "Exporting…" : exportState === "done" ? "Downloaded!" : exportState === "error" ? "Export failed" : "Download your data"}
{/* Save button + feedback */}
{saveState === "saving" && } {saveState === "saved" && } {saveState === "error" && } {saveState === "saving" ? "Saving…" : saveState === "saved" ? "Saved!" : saveState === "error" ? "Error" : "Save Settings"} {errorMsg && ( {errorMsg} )}
); }