import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; import { useTranslation } from "react-i18next"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Bell, Check, Monitor, RotateCcw, Save, Trash2, User, UserPlus, X } from "lucide-react"; import { SCHEMES, type Scheme, type ThemePrefs } from "../lib/theme"; import { api, type Invite, type Me } from "../lib/api"; import Avatar from "./Avatar"; import { notify, type NotifSettings } from "../lib/notifications"; import Tooltip from "./Tooltip"; import { useConfirm } from "./ConfirmProvider"; // The Settings page edits server-persisted preferences as a draft: changes apply locally // for instant preview but reach the server only on an explicit Save (or revert on Discard). // App owns the draft + baseline (so the leave-the-page guard can see it); this controller is // how the panel reads/writes it. See App.tsx. export type PrefsSaveState = "idle" | "saving" | "saved" | "error"; export interface PrefsController { theme: ThemePrefs; setTheme: (t: ThemePrefs) => void; view: "grid" | "list"; setView: (v: "grid" | "list") => void; perf: boolean; setPerf: (v: boolean) => void; hints: boolean; setHints: (v: boolean) => void; notif: NotifSettings; setNotif: (n: NotifSettings) => void; dirty: boolean; save: () => void; discard: () => void; saveState: PrefsSaveState; } type TabId = "appearance" | "notifications" | "account"; const TABS: { id: TabId; icon: typeof Monitor }[] = [ { id: "appearance", icon: Monitor }, { id: "notifications", icon: Bell }, { id: "account", icon: User }, ]; // Persist the active tab so a reload (F5) keeps the user where they were instead of // snapping back to "appearance". const SETTINGS_TAB_KEY = "siftlode.settingsTab"; function loadSettingsTab(): TabId { const v = localStorage.getItem(SETTINGS_TAB_KEY); return TABS.some((tabItem) => tabItem.id === v) ? (v as TabId) : "appearance"; } // Settings as a page (Design B): rendered in the main content area, not an overlay. It keeps // the frosted `.glass` surface so it still refracts the ambient backdrop. The page title is // shown by the Header; the tab rail stays as in-page sub-navigation. export default function SettingsPanel({ me, prefs, onOpenWizard, }: { me: Me; prefs: PrefsController; onOpenWizard: () => void; }) { const { t } = useTranslation(); const [tab, setTabState] = useState(loadSettingsTab); const setTab = (id: TabId) => { setTabState(id); localStorage.setItem(SETTINGS_TAB_KEY, id); }; return (
{/* Vertical tab rail — never wraps; active is a clear accent pill. */} {/* Render only the active tab so the panel sizes to its actual content. (Stacking every tab in one grid cell made the whole panel as tall as the tallest tab — Account — leaving the short tabs with dead space and a needless scrollbar.) */}
{tab === "appearance" && } {tab === "notifications" && } {tab === "account" && }
{/* Save/Discard bar — spans the whole card (a change can come from any tab). Only the Appearance/Notifications prefs are drafted; the Sync/Account tabs act immediately. */}
); } function PrefsSaveBar({ prefs }: { prefs: PrefsController }) { const { t } = useTranslation(); // Stay mounted while a transient "saved"/"error" message is fading, even after dirty clears. if (!prefs.dirty && prefs.saveState === "idle") return null; const saving = prefs.saveState === "saving"; return (
{prefs.saveState === "saved" ? {t("settings.save.saved")} : prefs.saveState === "error" ? {t("settings.save.failed")} : t("settings.save.unsaved")}
); } function Section({ title, children }: { title: string; children: React.ReactNode }) { return (
{title}
{children}
); } function Row({ label, hint, children, }: { label: string; hint?: string; children: React.ReactNode; }) { return (
{label} {children}
); } function Switch({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) { return ( ); } function Appearance({ prefs }: { prefs: PrefsController }) { const { t } = useTranslation(); // Controlled by App's prefs draft: each change applies locally for preview but is only // persisted on an explicit Save (handled by the panel's Save/Discard bar). const { theme, setTheme, view, setView, perf, setPerf, hints, setHints } = prefs; return ( <>
{SCHEMES.map((s) => (
setTheme({ ...theme, mode: v ? "dark" : "light" })} /> setView(v ? "list" : "grid")} />
setTheme({ ...theme, fontScale: Number(e.target.value) })} className="w-full accent-accent" />
{Math.round(theme.fontScale * 100)}%
); } function Notifications({ prefs }: { prefs: PrefsController }) { const { t } = useTranslation(); // Controlled by App's prefs draft (live preview via configureNotifications there); the // panel's Save bar persists it. The "send test" button below still fires immediately. const { notif: cfg, setNotif } = prefs; const update = (p: Partial) => setNotif({ ...cfg, ...p }); const autoOn = cfg.durationMs > 0; return (
update({ sound: v })} /> update({ durationMs: v ? 6000 : 0 })} /> {autoOn && (
{t("settings.notifications.dismissAfter")} {(cfg.durationMs / 1000).toFixed(0)}s
update({ durationMs: Number(e.target.value) })} className="w-full accent-accent mt-1" />
)}
); } function AccessRow({ title, granted, grantedHint, enableHint, onEnable, }: { title: string; granted: boolean; grantedHint: string; enableHint: string; onEnable: () => void; }) { const { t } = useTranslation(); return (
{title}

{granted ? grantedHint : enableHint}

{granted ? ( {t("settings.account.granted")} ) : ( )}
); } function Account({ me, onOpenWizard }: { me: Me; onOpenWizard: () => void }) { const { t } = useTranslation(); return ( <>
{me.display_name ?? me.email.split("@")[0]}
{me.email}
{me.role}
{me.is_demo ? (

{t("settings.account.demoNotice")}

) : (

{t("settings.account.youtubeAccessIntro")}

{ window.location.href = "/auth/upgrade?access=read"; }} /> { window.location.href = "/auth/upgrade?access=write"; }} />
)} {me.role === "admin" && } {me.role === "admin" && } ); } function AdminInvites() { const { t } = useTranslation(); const qc = useQueryClient(); const invites = useQuery({ queryKey: ["admin-invites"], queryFn: () => api.adminInvites() }); const [newEmail, setNewEmail] = useState(""); const refresh = () => { qc.invalidateQueries({ queryKey: ["admin-invites"] }); qc.invalidateQueries({ queryKey: ["me"] }); // updates the pending badge }; const approve = useMutation({ mutationFn: (id: number) => api.approveInvite(id), onSuccess: () => { refresh(); notify({ level: "success", message: t("settings.invites.approved") }); }, onError: () => notify({ level: "error", message: t("settings.invites.approveFailed") }), }); const deny = useMutation({ mutationFn: (id: number) => api.denyInvite(id), onSuccess: refresh, onError: () => notify({ level: "error", message: t("settings.invites.denyFailed") }), }); const add = useMutation({ mutationFn: (email: string) => api.addInvite(email), onSuccess: () => { setNewEmail(""); refresh(); notify({ level: "success", message: t("settings.invites.addedToWhitelist") }); }, onError: () => notify({ level: "error", message: t("settings.invites.addFailed") }), }); const list = invites.data ?? []; const pending = list.filter((i) => i.status === "pending"); const decided = list.filter((i) => i.status !== "pending"); return (
{pending.length === 0 ? (

{t("settings.invites.noPending")}

) : (
{pending.map((i) => ( approve.mutate(i.id)} onDeny={() => deny.mutate(i.id)} busy={approve.isPending || deny.isPending} /> ))}
)}
{ e.preventDefault(); if (newEmail.trim()) add.mutate(newEmail.trim()); }} className="flex items-center gap-2 mt-3" > setNewEmail(e.target.value)} placeholder={t("settings.invites.addPlaceholder")} className="flex-1 min-w-0 bg-card border border-border rounded-xl px-3 py-2 text-sm outline-none focus:border-accent" />
{decided.length > 0 && (
{t("settings.invites.decided", { count: decided.length })}
{decided.map((i) => (
{i.email} {i.status}
))}
)}
); } function AdminDemo() { const { t } = useTranslation(); const qc = useQueryClient(); const confirm = useConfirm(); const list = useQuery({ queryKey: ["demo-whitelist"], queryFn: () => api.adminDemoWhitelist() }); const [newEmail, setNewEmail] = useState(""); const add = useMutation({ mutationFn: (email: string) => api.addDemoWhitelist(email), onSuccess: () => { setNewEmail(""); qc.invalidateQueries({ queryKey: ["demo-whitelist"] }); notify({ level: "success", message: t("settings.demo.added") }); }, onError: () => notify({ level: "error", message: t("settings.demo.addFailed") }), }); const remove = useMutation({ mutationFn: (id: number) => api.removeDemoWhitelist(id), onSuccess: () => qc.invalidateQueries({ queryKey: ["demo-whitelist"] }), onError: () => notify({ level: "error", message: t("settings.demo.removeFailed") }), }); const reset = useMutation({ mutationFn: () => api.resetDemo(), onSuccess: (r: { playlists_seeded: number }) => notify({ level: "success", message: t("settings.demo.resetDone", { count: r.playlists_seeded }), }), onError: () => notify({ level: "error", message: t("settings.demo.resetFailed") }), }); const rows = list.data ?? []; return (

{t("settings.demo.intro")}

{rows.length > 0 && (
{rows.map((r) => (
{r.email}
{r.added_by && (
{t("settings.demo.addedBy", { who: r.added_by })}
)}
))}
)}
{ e.preventDefault(); if (newEmail.trim()) add.mutate(newEmail.trim()); }} className="flex items-center gap-2" > setNewEmail(e.target.value)} placeholder={t("settings.demo.addPlaceholder")} className="flex-1 min-w-0 bg-card border border-border rounded-xl px-3 py-2 text-sm outline-none focus:border-accent" />
); } function InviteRow({ inv, onApprove, onDeny, busy, }: { inv: Invite; onApprove: () => void; onDeny: () => void; busy: boolean; }) { const { t } = useTranslation(); return (
{inv.email}
{inv.requested_at && (
{t("settings.invites.requested", { time: new Date(inv.requested_at).toLocaleString(), })}
)}
); }