refactor: convert to bun workspaces monorepo

- Move web app into apps/web/
- Create packages/shared/ with shared types
- Create plugins/decky-vault/ scaffold
- Root package.json manages workspaces only
This commit is contained in:
2026-06-28 05:20:28 +08:00
parent c4bede20d4
commit cd72b7a948
345 changed files with 488 additions and 126 deletions
+47
View File
@@ -0,0 +1,47 @@
import { ManageSidebar } from "@/components/manage/manage-sidebar"
import { auth } from "@/lib/auth"
import type { Metadata } from "next"
import { headers } from "next/headers"
import { redirect } from "next/navigation"
export const metadata: Metadata = {
title: {
template: "%s | Manage — DeckyVault",
default: "Manage — DeckyVault",
},
robots: { index: false, follow: false },
}
export default async function ManageLayout({
children,
}: {
children: React.ReactNode
}) {
const session = await auth.api.getSession({
headers: await headers(),
})
const role = session?.user?.role ?? "user"
if (role !== "moderator" && role !== "admin") {
redirect("/")
}
return (
<section className='w-full flex flex-col gap-8 py-16'>
<div className='px-4 md:px-8 lg:px-12'>
<div className='mx-auto'>
<h1 className='text-2xl sm:text-3xl font-bold'>Manage</h1>
<p className='text-sm text-text/60 mt-1'>
Manage your platform
</p>
</div>
</div>
<div className='px-4 md:px-8 lg:px-12'>
<div className='mx-auto flex flex-col md:flex-row gap-6'>
<ManageSidebar />
<div className='flex-1 min-w-0'>{children}</div>
</div>
</div>
</section>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { AnalyticsClient } from "@/components/manage/analytics-client"
export const metadata: Metadata = {
title: "Analytics",
}
export default function AnalyticsPage() {
return <AnalyticsClient />
}
@@ -0,0 +1,581 @@
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import {
Loader2,
SearchIcon,
ShieldCheckIcon,
TrashIcon,
RefreshCwIcon,
ExternalLinkIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import { ConfirmDialog } from "@/components/ui/modal"
interface PerformanceEntry {
id: string
versionId: string
hardwareSlug: string
userId: string
fpsAvg: number | null
fpsLow: number | null
fpsHigh: number | null
protonVersion: string | null
osVersion: string | null
upscalerType: string | null
upscalerVersion: string | null
frameGenMethod: string | null
loadTimeSsd: number | null
loadTimeSd: number | null
launchOptions: string | null
settingsJson: string | null
userNotes: string | null
customSystem: string | null
isRemoved: boolean
removedReason: string | null
upvotes: number
downvotes: number
verifiedAt: string | null
verifiedBy: string | null
createdAt: string
updatedAt: string
gameId: string
gameTitle: string
versionString: string
hardwareName: string
authorName: string | null
authorImage: string | null
}
interface PerformanceApiResponse {
data: PerformanceEntry[]
total: number
limit: number
offset: number
}
type StatusFilter = "all" | "active" | "removed" | "unverified"
const LIMIT = 20
function formatDate(value: string | Date | null | undefined) {
if (!value) return "—"
const d = typeof value === "string" ? new Date(value) : value
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
})
}
function getInitial(name: string | null | undefined) {
return name?.charAt(0)?.toUpperCase() || "?"
}
function statusBadgeClasses(entry: PerformanceEntry) {
if (entry.verifiedAt) return "bg-green-500/10 text-green-400"
if (entry.isRemoved) return "bg-red-500/10 text-red-400"
return "bg-text/5 text-text/50"
}
function statusLabel(entry: PerformanceEntry) {
if (entry.verifiedAt) return "Verified"
if (entry.isRemoved) return "Removed"
return "Active"
}
function statusDotClass(entry: PerformanceEntry) {
if (entry.verifiedAt) return "bg-green-400"
if (entry.isRemoved) return "bg-red-400"
return "bg-text/40"
}
function formatFps(entry: PerformanceEntry) {
if (entry.fpsAvg == null) return "—"
if (entry.fpsLow != null && entry.fpsHigh != null) {
return `${entry.fpsAvg} (${entry.fpsLow}${entry.fpsHigh})`
}
return `${entry.fpsAvg}`
}
export function BenchmarksClient() {
const [entries, setEntries] = useState<PerformanceEntry[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all")
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({})
const [confirmAction, setConfirmAction] = useState<
| { type: "verify" | "remove" | "restore" | "hardDelete"; entry: PerformanceEntry }
| null
>(null)
const [removeReason, setRemoveReason] = useState("")
const isSearchChangeRef = useRef(false)
const handleSearchChange = (value: string) => {
setSearch(value)
setOffset(0)
isSearchChangeRef.current = true
}
const handleStatusChange = (value: StatusFilter) => {
setStatusFilter(value)
setOffset(0)
isSearchChangeRef.current = true
}
const handlePrev = () => {
setOffset((prev) => Math.max(0, prev - LIMIT))
isSearchChangeRef.current = false
}
const handleNext = () => {
setOffset((prev) => prev + LIMIT)
isSearchChangeRef.current = false
}
const loadData = useCallback(async () => {
setLoading(true)
try {
const params = new URLSearchParams({
limit: String(LIMIT),
offset: String(offset),
})
if (statusFilter === "active") {
params.set("removed", "false")
} else if (statusFilter === "removed") {
params.set("removed", "true")
} else if (statusFilter === "unverified") {
params.set("verified", "false")
}
if (search.trim()) {
params.set("search", search.trim())
}
const res = await fetch(`/api/admin/performance?${params.toString()}`)
if (res.ok) {
const json = (await res.json()) as PerformanceApiResponse
setEntries(json.data)
setTotal(json.total)
}
} catch {
// ignore
} finally {
setLoading(false)
}
}, [search, offset, statusFilter])
useEffect(() => {
const delay = isSearchChangeRef.current ? 300 : 0
isSearchChangeRef.current = false
let cancelled = false
const timer = setTimeout(async () => {
if (!cancelled) {
await loadData()
}
}, delay)
return () => {
cancelled = true
clearTimeout(timer)
}
}, [loadData])
const handleVerify = async (entry: PerformanceEntry) => {
setActionLoading((prev) => ({ ...prev, [entry.id]: true }))
try {
const res = await fetch(`/api/admin/performance/${entry.id}/verify`, {
method: "PATCH",
})
if (res.ok) {
await loadData()
setConfirmAction(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [entry.id]: false }))
}
}
const handleRemove = async (entry: PerformanceEntry) => {
setActionLoading((prev) => ({ ...prev, [entry.id]: true }))
try {
const body: { reason?: string } = {}
if (removeReason.trim()) {
body.reason = removeReason.trim()
}
const res = await fetch(`/api/admin/performance/${entry.id}/remove`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
if (res.ok) {
setRemoveReason("")
await loadData()
setConfirmAction(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [entry.id]: false }))
}
}
const handleHardDelete = async (entry: PerformanceEntry) => {
setActionLoading((prev) => ({ ...prev, [entry.id]: true }))
try {
const res = await fetch(`/api/admin/performance/${entry.id}/hard-delete`, {
method: "DELETE",
})
if (res.ok) {
setEntries((prev) => prev.filter((e) => e.id !== entry.id))
setTotal((prev) => Math.max(0, prev - 1))
setConfirmAction(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [entry.id]: false }))
}
}
const handleRestore = async (entry: PerformanceEntry) => {
setActionLoading((prev) => ({ ...prev, [entry.id]: true }))
try {
const res = await fetch(`/api/admin/performance/${entry.id}/restore`, {
method: "PATCH",
})
if (res.ok) {
await loadData()
setConfirmAction(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [entry.id]: false }))
}
}
const hasMore = offset + entries.length < total
const tabs: { label: string; value: StatusFilter }[] = [
{ label: "All", value: "all" },
{ label: "Active", value: "active" },
{ label: "Removed", value: "removed" },
{ label: "Unverified", value: "unverified" },
]
return (
<div className="space-y-4">
{/* Search */}
<div className="relative">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text/40" />
<input
type="text"
value={search}
onChange={(e) => handleSearchChange(e.target.value)}
placeholder="Search benchmarks..."
className="w-full pl-9 pr-4 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
{/* Filter tabs */}
<div className="flex items-center gap-1">
{tabs.map((tab) => (
<button
key={tab.value}
onClick={() => handleStatusChange(tab.value)}
className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors cursor-pointer ${
statusFilter === tab.value
? "bg-primary/10 text-primary"
: "bg-text/5 text-text/70 hover:bg-text/10"
}`}
>
{tab.label}
</button>
))}
</div>
{/* Table */}
<div className="rounded-xl border border-border overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm min-w-[800px]">
<thead className="bg-text/[0.03]">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Game
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Author
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Hardware
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
FPS
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Upscaler
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Status
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Votes
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Date
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Actions
</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={9} className="px-4 py-8 text-center text-text/50">
<Loader2 className="h-5 w-5 animate-spin mx-auto" />
</td>
</tr>
) : entries.length === 0 ? (
<tr>
<td colSpan={9} className="px-4 py-8 text-center text-text/50">
No benchmarks found.
</td>
</tr>
) : (
entries.map((entry) => (
<tr
key={entry.id}
className="border-t border-border hover:bg-text/[0.02] transition-colors"
>
<td className="px-4 py-3">
<p className="font-medium text-text truncate max-w-[180px]">
{entry.gameTitle}
</p>
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-3">
{entry.authorImage ? (
<Image
src={entry.authorImage}
alt={entry.authorName || "User"}
width={32}
height={32}
className="h-8 w-8 rounded-full object-cover"
unoptimized
/>
) : (
<div className="h-8 w-8 rounded-full bg-text/10 flex items-center justify-center text-xs font-medium text-text/70">
{getInitial(entry.authorName)}
</div>
)}
<div className="min-w-0">
<p className="font-medium text-text truncate">
{entry.authorName || "Unknown"}
</p>
</div>
</div>
</td>
<td className="px-4 py-3">
<p className="text-text/70 truncate max-w-[120px]">
{entry.hardwareName}
</p>
</td>
<td className="px-4 py-3">
<span className="text-text/70">{formatFps(entry)}</span>
</td>
<td className="px-4 py-3">
<span className="text-text/50">
{entry.upscalerType || "—"}
</span>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${statusBadgeClasses(entry)}`}
>
{entry.verifiedAt ? (
<ShieldCheckIcon className="h-3 w-3" />
) : (
<span
className={`h-1.5 w-1.5 rounded-full ${statusDotClass(entry)}`}
/>
)}
{statusLabel(entry)}
</span>
</td>
<td className="px-4 py-3">
<span className="inline-flex items-center gap-2 text-xs text-text/70">
<span> {entry.upvotes}</span>
<span> {entry.downvotes}</span>
</span>
</td>
<td className="px-4 py-3 text-xs text-text/50">
{formatDate(entry.createdAt)}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2 flex-wrap">
<Link
href={`/game/${entry.gameId}`}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors"
>
<ExternalLinkIcon className="h-3.5 w-3.5" />
View
</Link>
{!entry.verifiedAt && (
<button
onClick={() =>
setConfirmAction({ type: "verify", entry })
}
disabled={actionLoading[entry.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-green-500/10 text-green-400 hover:bg-green-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[entry.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<ShieldCheckIcon className="h-3.5 w-3.5" />
)}
Verify
</button>
)}
{!entry.isRemoved ? (
<button
onClick={() =>
setConfirmAction({ type: "remove", entry })
}
disabled={actionLoading[entry.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[entry.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<TrashIcon className="h-3.5 w-3.5" />
)}
Remove
</button>
) : (
<button
onClick={() =>
setConfirmAction({ type: "restore", entry })
}
disabled={actionLoading[entry.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[entry.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCwIcon className="h-3.5 w-3.5" />
)}
Restore
</button>
)}
<button
onClick={() => setConfirmAction({ type: "hardDelete", entry })}
disabled={actionLoading[entry.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-red-600/10 text-red-500 hover:bg-red-600/20 transition-colors cursor-pointer disabled:opacity-50"
title="Permanently delete"
>
<TrashIcon className="h-3.5 w-3.5" />
Purge
</button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{/* Pagination */}
{entries.length > 0 && (
<div className="flex items-center justify-between">
<p className="text-xs text-text/50">
Showing {offset + 1}{Math.min(offset + entries.length, total)} of{" "}
{total}
</p>
<div className="flex items-center gap-2">
<button
onClick={handlePrev}
disabled={offset === 0 || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
<ChevronLeftIcon className="h-3.5 w-3.5" />
Previous
</button>
<button
onClick={handleNext}
disabled={!hasMore || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
Next
<ChevronRightIcon className="h-3.5 w-3.5" />
</button>
</div>
</div>
)}
{/* Confirmation Dialogs */}
{confirmAction?.type === "verify" && (
<ConfirmDialog
open={!!confirmAction}
onClose={() => setConfirmAction(null)}
onConfirm={() => handleVerify(confirmAction.entry)}
title="Confirm Verify"
message="Are you sure you want to verify this benchmark? It will be marked as verified."
confirmLabel="Verify"
variant="default"
loading={actionLoading[confirmAction.entry.id]}
/>
)}
{confirmAction?.type === "remove" && (
<ConfirmDialog
open={!!confirmAction}
onClose={() => setConfirmAction(null)}
onConfirm={() => handleRemove(confirmAction.entry)}
title="Confirm Remove"
message="Are you sure you want to remove this benchmark?"
confirmLabel="Remove"
variant="destructive"
loading={actionLoading[confirmAction.entry.id]}
>
<textarea
rows={3}
value={removeReason}
onChange={(e) => setRemoveReason(e.target.value)}
placeholder="Optional reason..."
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors resize-none"
/>
</ConfirmDialog>
)}
{confirmAction?.type === "restore" && (
<ConfirmDialog
open={!!confirmAction}
onClose={() => setConfirmAction(null)}
onConfirm={() => handleRestore(confirmAction.entry)}
title="Confirm Restore"
message="Are you sure you want to restore this benchmark?"
confirmLabel="Restore"
variant="default"
loading={actionLoading[confirmAction.entry.id]}
/>
)}
{confirmAction?.type === "hardDelete" && (
<ConfirmDialog
open={!!confirmAction}
onClose={() => setConfirmAction(null)}
onConfirm={() => handleHardDelete(confirmAction.entry)}
title="⚠️ Permanent Delete"
message="This will permanently delete this benchmark entry. This action cannot be undone."
confirmLabel="Delete Forever"
variant="destructive"
loading={actionLoading[confirmAction.entry.id]}
/>
)}
</div>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { BenchmarksClient } from "./benchmarks-client"
export const metadata: Metadata = {
title: "Benchmarks",
}
export default function BenchmarksPage() {
return <BenchmarksClient />
}
@@ -0,0 +1,450 @@
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import {
Loader2,
SearchIcon,
TrashIcon,
RotateCcwIcon,
ExternalLinkIcon,
ChevronLeftIcon,
ChevronRightIcon,
MessageSquareIcon,
} from "lucide-react"
import { ConfirmDialog } from "@/components/ui/modal"
interface Comment {
id: string
gameId: string
content: Record<string, unknown>
upvotes: number
isRemoved: boolean
createdAt: string
updatedAt: string
userId: string
userName: string | null
userImage: string | null
gameTitle: string
parentId: string | null
}
interface CommentsApiResponse {
data: Comment[]
total: number
limit: number
offset: number
}
type StatusFilter = "all" | "active" | "removed"
const LIMIT = 20
function formatDate(value: string | Date | null | undefined) {
if (!value) return "—"
const d = typeof value === "string" ? new Date(value) : value
return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
}
function getInitial(name: string | null | undefined) {
return name?.charAt(0)?.toUpperCase() || "?"
}
function extractPlainText(content: Record<string, unknown>, maxLength = 80): string {
let result = ""
function walk(node: unknown) {
if (typeof node !== "object" || node === null) return
if (Array.isArray(node)) {
for (const item of node) {
walk(item)
if (result.length >= maxLength) return
}
return
}
const obj = node as Record<string, unknown>
if (typeof obj.text === "string") {
result += obj.text
if (result.length >= maxLength) return
}
if (Array.isArray(obj.content)) {
for (const item of obj.content) {
walk(item)
if (result.length >= maxLength) return
}
}
}
walk(content)
return result.length > maxLength ? result.slice(0, maxLength) + "…" : result
}
function statusBadgeClasses(isRemoved: boolean) {
return isRemoved
? "bg-red-500/10 text-red-400"
: "bg-green-500/10 text-green-400"
}
function statusDotClass(isRemoved: boolean) {
return isRemoved ? "bg-red-400" : "bg-green-400"
}
export function CommentsClient() {
const [comments, setComments] = useState<Comment[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all")
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({})
const [confirmAction, setConfirmAction] = useState<
| { type: "remove" | "restore"; comment: Comment }
| null
>(null)
const isSearchChangeRef = useRef(false)
const handleSearchChange = (value: string) => {
setSearch(value)
setOffset(0)
isSearchChangeRef.current = true
}
const handleStatusChange = (value: StatusFilter) => {
setStatusFilter(value)
setOffset(0)
isSearchChangeRef.current = true
}
const handlePrev = () => {
setOffset((prev) => Math.max(0, prev - LIMIT))
isSearchChangeRef.current = false
}
const handleNext = () => {
setOffset((prev) => prev + LIMIT)
isSearchChangeRef.current = false
}
const loadData = useCallback(async () => {
setLoading(true)
try {
const params = new URLSearchParams({
limit: String(LIMIT),
offset: String(offset),
})
if (statusFilter === "active") {
params.set("removed", "false")
} else if (statusFilter === "removed") {
params.set("removed", "true")
}
if (search.trim()) {
params.set("search", search.trim())
}
const res = await fetch(`/api/admin/comments?${params.toString()}`)
if (res.ok) {
const json = (await res.json()) as CommentsApiResponse
setComments(json.data)
setTotal(json.total)
}
} catch {
// ignore
} finally {
setLoading(false)
}
}, [search, offset, statusFilter])
useEffect(() => {
const delay = isSearchChangeRef.current ? 300 : 0
isSearchChangeRef.current = false
let cancelled = false
const timer = setTimeout(async () => {
if (!cancelled) {
await loadData()
}
}, delay)
return () => {
cancelled = true
clearTimeout(timer)
}
}, [loadData])
const handleRemove = async (comment: Comment) => {
setActionLoading((prev) => ({ ...prev, [comment.id]: true }))
try {
const res = await fetch(`/api/admin/comments/${comment.id}/remove`, {
method: "PATCH",
})
if (res.ok) {
await loadData()
setConfirmAction(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [comment.id]: false }))
}
}
const handleRestore = async (comment: Comment) => {
setActionLoading((prev) => ({ ...prev, [comment.id]: true }))
try {
const res = await fetch(`/api/admin/comments/${comment.id}/restore`, {
method: "PATCH",
})
if (res.ok) {
await loadData()
setConfirmAction(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [comment.id]: false }))
}
}
const hasMore = offset + comments.length < total
const tabs: { label: string; value: StatusFilter }[] = [
{ label: "All", value: "all" },
{ label: "Active", value: "active" },
{ label: "Removed", value: "removed" },
]
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center gap-3">
<MessageSquareIcon className="h-5 w-5 text-text/70" />
<h1 className="text-lg font-semibold text-text">Comments</h1>
</div>
{/* Search */}
<div className="relative">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text/40" />
<input
type="text"
value={search}
onChange={(e) => handleSearchChange(e.target.value)}
placeholder="Search comments..."
className="w-full pl-9 pr-4 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
{/* Filter tabs */}
<div className="flex items-center gap-1">
{tabs.map((tab) => (
<button
key={tab.value}
onClick={() => handleStatusChange(tab.value)}
className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors cursor-pointer ${
statusFilter === tab.value
? "bg-primary/10 text-primary"
: "bg-text/5 text-text/70 hover:bg-text/10"
}`}
>
{tab.label}
</button>
))}
</div>
{/* Table */}
<div className="rounded-xl border border-border overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-text/[0.03]">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Author
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Content
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Game
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Upvotes
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Status
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Date
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Actions
</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={7} className="px-4 py-8 text-center text-text/50">
<Loader2 className="h-5 w-5 animate-spin mx-auto" />
</td>
</tr>
) : comments.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-8 text-center text-text/50">
No comments found.
</td>
</tr>
) : (
comments.map((comment) => (
<tr
key={comment.id}
className="border-t border-border hover:bg-text/[0.02] transition-colors"
>
<td className="px-4 py-3">
<div className="flex items-center gap-3">
{comment.userImage ? (
<Image
src={comment.userImage}
alt={comment.userName || "User"}
width={32}
height={32}
className="h-8 w-8 rounded-full object-cover"
unoptimized
/>
) : (
<div className="h-8 w-8 rounded-full bg-text/10 flex items-center justify-center text-xs font-medium text-text/70">
{getInitial(comment.userName)}
</div>
)}
<div className="min-w-0">
<p className="font-medium text-text truncate">
{comment.userName || "Unknown"}
</p>
</div>
</div>
</td>
<td className="px-4 py-3">
<p className="text-text/70 truncate max-w-[240px]">
{extractPlainText(comment.content, 80)}
</p>
</td>
<td className="px-4 py-3">
<p className="font-medium text-text truncate max-w-[150px]">
{comment.gameTitle}
</p>
</td>
<td className="px-4 py-3">
<span className="text-text/70">{comment.upvotes}</span>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${statusBadgeClasses(comment.isRemoved)}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${statusDotClass(comment.isRemoved)}`}
/>
{comment.isRemoved ? "Removed" : "Active"}
</span>
</td>
<td className="px-4 py-3 text-xs text-text/50">
{formatDate(comment.createdAt)}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2 flex-wrap">
<Link
href={`/game/${comment.gameId}`}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors"
>
<ExternalLinkIcon className="h-3.5 w-3.5" />
View
</Link>
{!comment.isRemoved ? (
<button
onClick={() =>
setConfirmAction({ type: "remove", comment })
}
disabled={actionLoading[comment.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[comment.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<TrashIcon className="h-3.5 w-3.5" />
)}
Remove
</button>
) : (
<button
onClick={() =>
setConfirmAction({ type: "restore", comment })
}
disabled={actionLoading[comment.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[comment.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RotateCcwIcon className="h-3.5 w-3.5" />
)}
Restore
</button>
)}
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
{comments.length > 0 && (
<div className="flex items-center justify-between">
<p className="text-xs text-text/50">
Showing {offset + 1}{Math.min(offset + comments.length, total)} of{" "}
{total}
</p>
<div className="flex items-center gap-2">
<button
onClick={handlePrev}
disabled={offset === 0 || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
<ChevronLeftIcon className="h-3.5 w-3.5" />
Previous
</button>
<button
onClick={handleNext}
disabled={!hasMore || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
Next
<ChevronRightIcon className="h-3.5 w-3.5" />
</button>
</div>
</div>
)}
{/* Confirmation Dialogs */}
{confirmAction?.type === "remove" && (
<ConfirmDialog
open={!!confirmAction}
onClose={() => setConfirmAction(null)}
onConfirm={() => handleRemove(confirmAction.comment)}
title="Confirm Remove"
message="Are you sure you want to remove this comment?"
confirmLabel="Remove"
variant="destructive"
loading={actionLoading[confirmAction.comment.id]}
/>
)}
{confirmAction?.type === "restore" && (
<ConfirmDialog
open={!!confirmAction}
onClose={() => setConfirmAction(null)}
onConfirm={() => handleRestore(confirmAction.comment)}
title="Confirm Restore"
message="Are you sure you want to restore this comment?"
confirmLabel="Restore"
variant="default"
loading={actionLoading[confirmAction.comment.id]}
/>
)}
</div>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { CommentsClient } from "./comments-client"
export const metadata: Metadata = {
title: "Comments",
}
export default function CommentsPage() {
return <CommentsClient />
}
@@ -0,0 +1,776 @@
"use client"
import { useEffect, useRef, useState } from "react"
import { createPortal } from "react-dom"
import Image from "next/image"
import Link from "next/link"
import {
Loader2,
SearchIcon,
ExternalLinkIcon,
TrashIcon,
Gamepad2Icon,
RefreshCwIcon,
CheckCircle2Icon,
XCircleIcon,
} from "lucide-react"
interface SyncProgress {
isRunning: boolean
current: number
total: number
currentGame: string | null
synced: number
failed: number
results: Map<string, { success: boolean; error?: string }>
}
interface Game {
id: string
steamAppId: number | null
title: string
description: string | null
developer: string | null
publisher: string | null
genres: string[] | null
headerImage: string | null
capsuleImage: string | null
storeUrl: string | null
source: "steam" | "manual" | "gog" | "epic"
lastSync: string | null
syncStatus: string | null
syncError: string | null
createdAt: string
updatedAt: string
}
interface GamesApiResponse {
data: Game[]
total: number
limit: number
offset: number
}
const LIMIT = 50
export function GamesClient() {
const [games, setGames] = useState<Game[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [deletingIds, setDeletingIds] = useState<Set<string>>(new Set())
const [resyncingIds, setResyncingIds] = useState<Set<string>>(new Set())
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [syncing, setSyncing] = useState(false)
const [syncProgress, setSyncProgress] = useState<SyncProgress>({
isRunning: false,
current: 0,
total: 0,
currentGame: null,
synced: 0,
failed: 0,
results: new Map(),
})
const [syncCompleted, setSyncCompleted] = useState(false)
const handleSelectAll = (checked: boolean) => {
if (checked) {
setSelectedIds(new Set(games.map((g) => g.id)))
} else {
setSelectedIds(new Set())
}
}
const handleSelectOne = (id: string, checked: boolean) => {
setSelectedIds((prev) => {
const next = new Set(prev)
if (checked) next.add(id)
else next.delete(id)
return next
})
}
const handleSyncSelected = async () => {
const ids = Array.from(selectedIds)
if (ids.length === 0) return
const gamesToSync = games.filter((g) => ids.includes(g.id) && g.steamAppId)
if (gamesToSync.length === 0) {
alert("No Steam games selected to sync")
return
}
setSyncing(true)
setSyncCompleted(false)
setSyncProgress({
isRunning: true,
current: 0,
total: gamesToSync.length,
currentGame: "Preparing sync...",
synced: 0,
failed: 0,
results: new Map(),
})
try {
// Use the bulk sync endpoint with streaming progress
const res = await fetch("/api/games/sync/bulk", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
mode: "selected",
gameIds: gamesToSync.map((g) => g.id),
}),
})
if (!res.ok) {
const errorData = await res.json().catch(() => null)
throw new Error(errorData?.error || `Sync failed: HTTP ${res.status}`)
}
// Read streaming response
const reader = res.body?.getReader()
const decoder = new TextDecoder()
let buffer = ""
if (reader) {
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split("\n")
buffer = lines.pop() || ""
for (const line of lines) {
if (!line.trim()) continue
try {
const data = JSON.parse(line)
if (data.type === "progress") {
setSyncProgress((prev) => ({
...prev,
current: data.current,
total: data.total,
synced: data.synced,
failed: data.failed,
currentGame: data.currentGame,
}))
} else if (data.type === "complete") {
setSyncProgress((prev) => ({
...prev,
isRunning: false,
total: data.total,
synced: data.synced,
failed: data.failed,
currentGame: null,
}))
setSyncCompleted(true)
setSelectedIds(new Set())
}
} catch {
// Ignore parse errors
}
}
}
}
} catch (error) {
console.error("Sync selected failed:", error)
alert(`Sync failed: ${error instanceof Error ? error.message : String(error)}`)
setSyncProgress((prev) => ({
...prev,
isRunning: false,
currentGame: null,
}))
} finally {
setSyncing(false)
}
}
const handleSyncAll = async () => {
if (!confirm("This will sync all Steam games. Continue?")) return
setSyncing(true)
setSyncCompleted(false)
setSyncProgress({
isRunning: true,
current: 0,
total: 0,
currentGame: "Preparing sync...",
synced: 0,
failed: 0,
results: new Map(),
})
try {
// Use the bulk sync endpoint with streaming progress
const res = await fetch("/api/games/sync/bulk", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mode: "all" }),
})
if (!res.ok) {
const errorData = await res.json().catch(() => null)
throw new Error(errorData?.error || `Sync failed: HTTP ${res.status}`)
}
// Read streaming response
const reader = res.body?.getReader()
const decoder = new TextDecoder()
let buffer = ""
if (reader) {
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split("\n")
buffer = lines.pop() || ""
for (const line of lines) {
if (!line.trim()) continue
try {
const data = JSON.parse(line)
if (data.type === "progress") {
setSyncProgress((prev) => ({
...prev,
current: data.current,
total: data.total,
synced: data.synced,
failed: data.failed,
currentGame: data.currentGame,
}))
} else if (data.type === "complete") {
setSyncProgress((prev) => ({
...prev,
isRunning: false,
total: data.total,
synced: data.synced,
failed: data.failed,
currentGame: null,
}))
setSyncCompleted(true)
}
} catch {
// Ignore parse errors
}
}
}
}
} catch (error) {
console.error("Sync all failed:", error)
alert(`Sync failed: ${error instanceof Error ? error.message : String(error)}`)
setSyncProgress((prev) => ({
...prev,
isRunning: false,
currentGame: null,
}))
} finally {
setSyncing(false)
}
}
const closeSyncOverlay = () => {
setSyncCompleted(false)
setSyncProgress({
isRunning: false,
current: 0,
total: 0,
currentGame: null,
synced: 0,
failed: 0,
results: new Map(),
})
}
// Close sync overlay on Escape key
useEffect(() => {
if (!syncCompleted) return
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") closeSyncOverlay()
}
document.addEventListener("keydown", handleKeyDown)
return () => document.removeEventListener("keydown", handleKeyDown)
}, [syncCompleted])
const isSearchChangeRef = useRef(false)
const handleSearchChange = (value: string) => {
setSearch(value)
setOffset(0)
isSearchChangeRef.current = true
setSelectedIds(new Set()) // Clear selection on search change
}
const handlePrev = () => {
setOffset((prev) => Math.max(0, prev - LIMIT))
isSearchChangeRef.current = false
setSelectedIds(new Set()) // Clear selection on page change
}
const handleNext = () => {
setOffset((prev) => prev + LIMIT)
isSearchChangeRef.current = false
}
useEffect(() => {
const delay = isSearchChangeRef.current ? 300 : 0
isSearchChangeRef.current = false
let cancelled = false
const timer = setTimeout(async () => {
setLoading(true)
try {
const res = await fetch(
`/api/games?limit=${LIMIT}&offset=${offset}&search=${encodeURIComponent(search)}&sort=createdAt&order=desc`
)
if (res.ok && !cancelled) {
const json = (await res.json()) as GamesApiResponse
setGames(json.data)
setTotal(json.total)
}
} catch {
// ignore
} finally {
if (!cancelled) setLoading(false)
}
}, delay)
return () => {
cancelled = true
clearTimeout(timer)
}
}, [search, offset])
const handleResync = async (game: Game) => {
setResyncingIds((prev) => new Set(prev).add(game.id))
try {
const res = await fetch(`/api/games/${game.id}/sync`, {
method: "POST",
})
if (res.ok) {
setGames((prev) =>
prev.map((g) =>
g.id === game.id
? { ...g, syncStatus: "synced", lastSync: new Date().toISOString() }
: g
)
)
}
} catch (error) {
console.error("Resync failed:", error)
} finally {
setResyncingIds((prev) => {
const next = new Set(prev)
next.delete(game.id)
return next
})
}
}
const handleDelete = async (game: Game) => {
if (!confirm(`Are you sure you want to delete "${game.title}"?`)) return
setDeletingIds((prev) => new Set(prev).add(game.id))
try {
const res = await fetch(`/api/games/${game.id}`, { method: "DELETE" })
if (res.ok) {
setGames((prev) => prev.filter((g) => g.id !== game.id))
setTotal((prev) => Math.max(0, prev - 1))
}
} finally {
setDeletingIds((prev) => {
const next = new Set(prev)
next.delete(game.id)
return next
})
}
}
const hasMore = offset + games.length < total
return (
<div className="space-y-4">
{/* Search */}
<div className="flex items-center gap-2">
<div className="relative flex-1">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text/40" />
<input
type="text"
value={search}
onChange={(e) => handleSearchChange(e.target.value)}
placeholder="Search games..."
className="w-full pl-9 pr-4 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleSyncAll}
disabled={syncing}
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors cursor-pointer disabled:opacity-50"
>
{syncing ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<RefreshCwIcon className="h-4 w-4" />
)}
Sync All
</button>
</div>
</div>
{/* Table */}
<div className="rounded-xl border border-border overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-text/[0.03]">
<tr>
<th className="text-left px-4 py-3 w-10">
<input
type="checkbox"
checked={selectedIds.size === games.length && games.length > 0}
onChange={(e) => handleSelectAll(e.target.checked)}
className="rounded border-border"
/>
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50 w-14">
Cover
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Title
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Developer
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Source
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Sync
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Actions
</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={7} className="px-4 py-8 text-center text-text/50">
<Loader2 className="h-5 w-5 animate-spin mx-auto" />
</td>
</tr>
) : games.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-8 text-center text-text/50">
No games found.
</td>
</tr>
) : (
games.map((game) => (
<tr
key={game.id}
className="border-t border-border hover:bg-text/[0.02] transition-colors"
>
<td className="px-4 py-3">
<input
type="checkbox"
checked={selectedIds.has(game.id)}
onChange={(e) => handleSelectOne(game.id, e.target.checked)}
className="rounded border-border"
/>
</td>
<td className="px-4 py-3">
<div className="h-10 w-10 rounded overflow-hidden bg-text/5 flex items-center justify-center">
{game.capsuleImage || game.headerImage ? (
<Image
src={game.capsuleImage || game.headerImage || ""}
alt={game.title}
width={40}
height={40}
className="h-10 w-10 object-cover"
unoptimized
/>
) : (
<Gamepad2Icon className="h-4 w-4 text-text/40" />
)}
</div>
</td>
<td className="px-4 py-3">
<p className="font-medium text-text truncate max-w-[200px]">
{game.title}
</p>
</td>
<td className="px-4 py-3">
<p className="text-text/50 truncate max-w-[150px]">
{game.developer || "—"}
</p>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${
game.source === "steam"
? "bg-blue-500/10 text-blue-400"
: game.source === "manual"
? "bg-text/5 text-text/50"
: "bg-text/5 text-text/50"
}`}
>
{game.source}
</span>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${
game.syncStatus === "synced"
? "bg-green-500/10 text-green-400"
: game.syncStatus === "failed"
? "bg-red-500/10 text-red-400"
: "bg-yellow-500/10 text-yellow-400"
}`}
title={game.syncStatus === "failed" ? game.syncError || undefined : undefined}
>
<span
className={`h-1.5 w-1.5 rounded-full ${
game.syncStatus === "synced"
? "bg-green-400"
: game.syncStatus === "failed"
? "bg-red-400"
: "bg-yellow-400"
}`}
/>
{game.syncStatus === "synced" ? "Synced" : game.syncStatus === "failed" ? "Failed" : "Stale"}
</span>
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
<Link
href={`/game/${game.id}`}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors"
>
<ExternalLinkIcon className="h-3.5 w-3.5" />
View
</Link>
<button
onClick={() => handleResync(game)}
disabled={resyncingIds.has(game.id)}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{resyncingIds.has(game.id) ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCwIcon className="h-3.5 w-3.5" />
)}
Resync
</button>
<button
onClick={() => handleDelete(game)}
disabled={deletingIds.has(game.id)}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{deletingIds.has(game.id) ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<TrashIcon className="h-3.5 w-3.5" />
)}
Delete
</button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Sync Progress Overlay — portaled to body for guaranteed viewport coverage */}
{(syncProgress.isRunning || syncCompleted) &&
createPortal(
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center">
<div
role="dialog"
aria-modal="true"
aria-labelledby="sync-overlay-title"
className="w-full max-w-md mx-4 p-6 bg-background border border-border rounded-2xl shadow-2xl max-h-[90vh] overflow-y-auto"
>
{syncProgress.isRunning ? (
<>
<div className="flex items-center gap-3 mb-4">
<div className="relative">
<Loader2 className="h-8 w-8 text-primary animate-spin" />
<div className="absolute inset-0 flex items-center justify-center">
<RefreshCwIcon className="h-4 w-4 text-primary" />
</div>
</div>
<div>
<h3 id="sync-overlay-title" className="font-semibold text-text">Syncing Games</h3>
<p className="text-sm text-text/50">
{syncProgress.total > 0
? `${syncProgress.current} of ${syncProgress.total} games`
: "Preparing to sync..."
}
</p>
</div>
</div>
{/* Progress bar */}
<div className="mb-4">
<div className="flex justify-between text-xs text-text/50 mb-1">
<span>Progress</span>
<span>{syncProgress.total > 0 ? Math.round((syncProgress.current / syncProgress.total) * 100) : 0}%</span>
</div>
<div className="h-2 bg-text/10 rounded-full overflow-hidden">
<div
className="h-full bg-primary transition-all duration-300 ease-out"
style={{ width: `${(syncProgress.current / syncProgress.total) * 100}%` }}
/>
</div>
</div>
{/* Current game */}
{syncProgress.currentGame && (
<div className="mb-4 p-3 bg-text/5 rounded-lg">
<p className="text-xs text-text/50 mb-1">Currently syncing:</p>
<p className="text-sm font-medium text-text truncate">{syncProgress.currentGame}</p>
</div>
)}
</>
) : (
<>
{/* Completed state header */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-3">
<CheckCircle2Icon className="h-8 w-8 text-green-400" />
<div>
<h3 id="sync-overlay-title" className="font-semibold text-text">Sync Complete</h3>
<p className="text-sm text-text/50">
{syncProgress.synced} synced, {syncProgress.failed} failed
</p>
</div>
</div>
<button
onClick={closeSyncOverlay}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors cursor-pointer"
>
Close
</button>
</div>
</>
)}
{/* Stats — shown in both running and completed states */}
<div className="flex gap-4 mb-4">
<div className="flex-1 p-3 bg-green-500/10 rounded-lg">
<div className="flex items-center gap-2">
<CheckCircle2Icon className="h-4 w-4 text-green-400" />
<span className="text-sm font-medium text-green-400">{syncProgress.synced}</span>
</div>
<p className="text-xs text-text/50 mt-1">Synced</p>
</div>
<div className="flex-1 p-3 bg-red-500/10 rounded-lg">
<div className="flex items-center gap-2">
<XCircleIcon className="h-4 w-4 text-red-400" />
<span className="text-sm font-medium text-red-400">{syncProgress.failed}</span>
</div>
<p className="text-xs text-text/50 mt-1">Failed</p>
</div>
</div>
{/* Results list — scrollable */}
{syncProgress.results.size > 0 && (
<div className="max-h-48 overflow-y-auto space-y-1">
<p className="text-xs text-text/50 mb-2">
{syncCompleted ? "All results:" : "Recent results:"}
</p>
{(syncCompleted
? Array.from(syncProgress.results.entries())
: Array.from(syncProgress.results.entries()).slice(-5).reverse()
).map(([gameId, result]) => {
const game = games.find((g) => g.id === gameId)
return (
<div key={gameId} className="flex items-center gap-2 py-1">
{result.success ? (
<CheckCircle2Icon className="h-3 w-3 text-green-400 shrink-0" />
) : (
<XCircleIcon className="h-3 w-3 text-red-400 shrink-0" />
)}
<span className="text-xs text-text/70 truncate">
{game?.title || gameId}
</span>
{!result.success && result.error && (
<span className="text-xs text-red-400/70 ml-auto shrink-0 truncate max-w-[150px]" title={result.error}>
{result.error}
</span>
)}
</div>
)
})}
</div>
)}
</div>
</div>,
document.body
)}
{/* Floating action bar */}
{selectedIds.size > 0 && !syncProgress.isRunning && (
<div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 px-4 py-3 bg-background border border-border rounded-xl shadow-lg">
<span className="text-sm text-text/70">
{selectedIds.size} game{selectedIds.size !== 1 ? "s" : ""} selected
</span>
<button
onClick={handleSyncSelected}
disabled={syncing}
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 transition-colors text-sm font-medium cursor-pointer disabled:opacity-50"
>
<RefreshCwIcon className="h-4 w-4" />
Resync Selected
</button>
<button
onClick={handleSyncAll}
disabled={syncing}
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-text/5 text-text hover:bg-text/10 transition-colors text-sm font-medium cursor-pointer disabled:opacity-50"
>
<RefreshCwIcon className="h-4 w-4" />
Resync All
</button>
<button
onClick={() => setSelectedIds(new Set())}
className="px-3 py-2 rounded-lg text-sm text-text/50 hover:text-text/70 transition-colors cursor-pointer"
>
Clear
</button>
</div>
)}
{/* Pagination */}
{games.length > 0 && (
<div className="flex items-center justify-between">
<p className="text-xs text-text/50">
Showing {offset + 1}{Math.min(offset + games.length, total)} of{" "}
{total}
</p>
<div className="flex items-center gap-2">
<button
onClick={handlePrev}
disabled={offset === 0 || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
Previous
</button>
<button
onClick={handleNext}
disabled={!hasMore || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
Next
</button>
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { GamesClient } from "./games-client"
export const metadata: Metadata = {
title: "Games",
}
export default function GamesPage() {
return <GamesClient />
}
@@ -0,0 +1,411 @@
"use client"
import { useEffect, useState, FormEvent } from "react"
import {
Gamepad2Icon,
PlusIcon,
PencilIcon,
TrashIcon,
Loader2,
XIcon,
} from "lucide-react"
import { getDeviceColor } from "@/components/charts/EChartWrapper"
interface DeviceItem {
slug: string
name: string
deviceType: string
image: string | null
sortOrder: number
totalBenchmarks?: number
avgFps?: number | null
gameCount?: number
wattHours?: number | null
tdpMax?: number | null
}
interface DeviceFormData {
slug: string
name: string
deviceType: "handheld" | "console"
image: string
sortOrder: number
wattHours: string
tdpMax: string
}
export function HardwareClient() {
const [devices, setDevices] = useState<DeviceItem[]>([])
const [loading, setLoading] = useState(true)
const [showModal, setShowModal] = useState(false)
const [editingDevice, setEditingDevice] = useState<DeviceItem | null>(null)
const [form, setForm] = useState<DeviceFormData>({
slug: "",
name: "",
deviceType: "handheld",
image: "",
sortOrder: 0,
wattHours: "",
tdpMax: "",
})
const [saving, setSaving] = useState(false)
const [deleting, setDeleting] = useState(false)
const fetchDevices = async () => {
setLoading(true)
try {
const res = await fetch("/api/hardware/stats")
if (res.ok) {
const data = await res.json()
setDevices(
(data as DeviceItem[]).map((item) => ({
...item,
image: item.image ?? null,
}))
)
}
} catch {
// ignore
} finally {
setLoading(false)
}
}
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
fetchDevices()
}, [])
const openCreate = () => {
setEditingDevice(null)
setForm({
slug: "",
name: "",
deviceType: "handheld",
image: "",
sortOrder: 0,
wattHours: "",
tdpMax: "",
})
setShowModal(true)
}
const openEdit = (device: DeviceItem) => {
setEditingDevice(device)
setForm({
slug: device.slug,
name: device.name,
deviceType: device.deviceType as "handheld" | "console",
image: device.image ?? "",
sortOrder: device.sortOrder,
wattHours: device.wattHours != null ? String(device.wattHours) : "",
tdpMax: device.tdpMax != null ? String(device.tdpMax) : "",
})
setShowModal(true)
}
const closeModal = () => {
setShowModal(false)
setEditingDevice(null)
}
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
setSaving(true)
try {
const body = editingDevice
? {
name: form.name,
deviceType: form.deviceType,
image: form.image || null,
sortOrder: form.sortOrder,
wattHours: form.wattHours ? parseFloat(form.wattHours) : null,
tdpMax: form.tdpMax ? parseFloat(form.tdpMax) : null,
}
: {
slug: form.slug,
name: form.name,
deviceType: form.deviceType,
image: form.image || null,
sortOrder: form.sortOrder,
wattHours: form.wattHours ? parseFloat(form.wattHours) : null,
tdpMax: form.tdpMax ? parseFloat(form.tdpMax) : null,
}
const url = editingDevice
? `/api/hardware/${editingDevice.slug}`
: "/api/hardware"
const method = editingDevice ? "PATCH" : "POST"
const res = await fetch(url, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
if (res.ok) {
closeModal()
await fetchDevices()
}
} finally {
setSaving(false)
}
}
const handleDelete = async (slug: string) => {
if (!confirm("Are you sure you want to delete this device?")) return
setDeleting(true)
try {
const res = await fetch(`/api/hardware/${slug}`, { method: "DELETE" })
if (res.ok) {
await fetchDevices()
}
} finally {
setDeleting(false)
}
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-text">Hardware</h1>
<button
onClick={openCreate}
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium bg-primary/10 text-primary hover:bg-primary/20 transition-colors cursor-pointer"
>
<PlusIcon className="h-4 w-4" />
Add Device
</button>
</div>
{loading ? (
<div className="flex items-center justify-center py-16 text-text/50">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : devices.length === 0 ? (
<div className="text-center py-16 text-text/40">
<Gamepad2Icon className="h-10 w-10 mx-auto mb-2" />
<p>No devices found</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{devices.map((device, index) => {
const color = getDeviceColor(index)
return (
<div
key={device.slug}
className="rounded-xl border border-border bg-text/[0.02] p-4 flex flex-col gap-3 hover:bg-text/[0.04] transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div
className="h-10 w-10 rounded-lg flex items-center justify-center"
style={{ backgroundColor: `${color}20`, color }}
>
<Gamepad2Icon className="h-5 w-5" />
</div>
<div>
<h3 className="font-medium text-text text-sm">
{device.name}
</h3>
<p className="text-xs text-text/50">/{device.slug}</p>
</div>
</div>
<span
className={`text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full border ${
device.deviceType === "handheld"
? "text-primary bg-primary/10 border-primary/20"
: "text-secondary bg-secondary/10 border-secondary/20"
}`}
>
{device.deviceType}
</span>
</div>
<div className="text-xs text-text/60">
{device.totalBenchmarks ?? 0} benchmarks
</div>
{(device.wattHours != null || device.tdpMax != null) && (
<div className="text-xs text-text/60 flex gap-2">
{device.wattHours != null && <span>{device.wattHours} Wh</span>}
{device.tdpMax != null && <span>{device.tdpMax}W TDP</span>}
</div>
)}
<div className="flex items-center gap-2 mt-auto">
<button
onClick={() => openEdit(device)}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors cursor-pointer"
>
<PencilIcon className="h-3.5 w-3.5" />
Edit
</button>
<button
onClick={() => handleDelete(device.slug)}
disabled={deleting}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
<TrashIcon className="h-3.5 w-3.5" />
Delete
</button>
</div>
</div>
)
})}
</div>
)}
{showModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center">
<div
className="absolute inset-0 bg-black/50"
onClick={closeModal}
/>
<div className="relative bg-background border border-border rounded-xl p-6 max-w-md w-full mx-4">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-medium text-text">
{editingDevice ? "Edit Device" : "Add Device"}
</h2>
<button
onClick={closeModal}
className="p-1 rounded-md hover:bg-text/5 text-text/60 hover:text-text transition-colors cursor-pointer"
>
<XIcon className="h-4 w-4" />
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs font-medium text-text/70 mb-1">
Slug
</label>
<input
type="text"
value={form.slug}
onChange={(e) =>
setForm((f) => ({ ...f, slug: e.target.value }))
}
disabled={!!editingDevice}
required
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
/>
</div>
<div>
<label className="block text-xs font-medium text-text/70 mb-1">
Name
</label>
<input
type="text"
value={form.name}
onChange={(e) =>
setForm((f) => ({ ...f, name: e.target.value }))
}
required
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
<div>
<label className="block text-xs font-medium text-text/70 mb-1">
Device Type
</label>
<select
value={form.deviceType}
onChange={(e) =>
setForm((f) => ({
...f,
deviceType: e.target.value as "handheld" | "console",
}))
}
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text focus:outline-none focus:border-primary/60 transition-colors"
>
<option value="handheld">Handheld</option>
<option value="console">Console</option>
</select>
</div>
<div>
<label className="block text-xs font-medium text-text/70 mb-1">
Sort Order
</label>
<input
type="number"
value={form.sortOrder}
onChange={(e) =>
setForm((f) => ({
...f,
sortOrder: Number(e.target.value),
}))
}
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
<div>
<label className="block text-xs font-medium text-text/70 mb-1">
Image URL
</label>
<input
type="text"
value={form.image}
onChange={(e) =>
setForm((f) => ({ ...f, image: e.target.value }))
}
placeholder="https://..."
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
<div>
<label className="block text-xs font-medium text-text/70 mb-1">
Battery Capacity (Wh)
</label>
<input
type="number"
value={form.wattHours}
onChange={(e) => setForm((f) => ({ ...f, wattHours: e.target.value }))}
placeholder="e.g. 50.0"
min="0"
max="200"
step="0.1"
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
<p className="text-[10px] text-text/40 mt-1">
Watt-hours (used for battery life estimation)
</p>
</div>
<div>
<label className="block text-xs font-medium text-text/70 mb-1">
Max TDP (W)
</label>
<input
type="number"
value={form.tdpMax}
onChange={(e) => setForm((f) => ({ ...f, tdpMax: e.target.value }))}
placeholder="e.g. 15"
min="0"
max="100"
step="0.1"
className="w-full px-3 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
<p className="text-[10px] text-text/40 mt-1">
Maximum TDP in watts (used for battery life estimation)
</p>
</div>
<div className="flex items-center justify-end gap-2 pt-2">
<button
type="button"
onClick={closeModal}
className="px-3 py-2 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors cursor-pointer"
>
Cancel
</button>
<button
type="submit"
disabled={saving}
className="flex items-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium bg-primary text-white hover:bg-primary/90 transition-colors cursor-pointer disabled:opacity-50"
>
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
{editingDevice ? "Save Changes" : "Create Device"}
</button>
</div>
</form>
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { HardwareClient } from "./hardware-client"
export const metadata: Metadata = {
title: "Hardware",
}
export default function HardwarePage() {
return <HardwareClient />
}
+15
View File
@@ -0,0 +1,15 @@
import { DashboardOverview } from "@/components/manage/dashboard-overview";
export default function ManagePage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Dashboard</h1>
<p className="text-sm text-zinc-400">
Overview of DeckyVault statistics and moderation queue
</p>
</div>
<DashboardOverview />
</div>
);
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { ReportsClient } from "./reports-client"
export const metadata: Metadata = {
title: "Reports",
}
export default function ReportsPage() {
return <ReportsClient />
}
@@ -0,0 +1,460 @@
"use client"
import { useEffect, useMemo, useRef, useState } from "react"
import Image from "next/image"
import {
Loader2,
SearchIcon,
ShieldCheckIcon,
XIcon,
ChevronLeftIcon,
ChevronRightIcon,
FlagIcon,
} from "lucide-react"
import { ConfirmDialog } from "@/components/ui/modal"
interface Report {
id: string
entryId: string
reporterId: string
reporterName: string | null
reason: "inaccurate" | "spam" | "inappropriate" | "other"
details: string | null
status: "open" | "reviewed" | "dismissed"
createdAt: string
entry: {
id: string
userId: string
fpsAvg: number | null
fpsLow: number | null
fpsHigh: number | null
upscalerType: string | null
userNotes: string | null
isRemoved: boolean
authorName: string | null
}
gameVersion: {
id: string
versionString: string
}
game: {
id: string
title: string
headerImage: string | null
}
}
interface ReportsApiResponse {
data: Report[]
total: number
limit: number
offset: number
}
type StatusFilter = "all" | "open" | "reviewed" | "dismissed"
const LIMIT = 20
function formatDate(value: string | Date | null | undefined) {
if (!value) return "—"
const d = typeof value === "string" ? new Date(value) : value
return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
}
function getInitial(name: string | null | undefined) {
return name?.charAt(0)?.toUpperCase() || "?"
}
function truncate(str: string | null | undefined, maxLen = 60) {
if (!str) return "—"
return str.length > maxLen ? str.slice(0, maxLen) + "…" : str
}
function statusBadgeClasses(status: Report["status"]) {
switch (status) {
case "open":
return "bg-yellow-500/10 text-yellow-400"
case "reviewed":
return "bg-green-500/10 text-green-400"
case "dismissed":
return "bg-text/5 text-text/50"
}
}
function reasonBadgeClasses(reason: Report["reason"]) {
switch (reason) {
case "inaccurate":
return "bg-blue-500/10 text-blue-400"
case "spam":
return "bg-red-500/10 text-red-400"
case "inappropriate":
return "bg-orange-500/10 text-orange-400"
case "other":
return "bg-text/5 text-text/50"
}
}
export function ReportsClient() {
const [reports, setReports] = useState<Report[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all")
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({})
const [confirmReport, setConfirmReport] = useState<Report | null>(null)
const isSearchChangeRef = useRef(false)
const handleSearchChange = (value: string) => {
setSearch(value)
setOffset(0)
isSearchChangeRef.current = true
}
const handleStatusChange = (value: StatusFilter) => {
setStatusFilter(value)
setOffset(0)
isSearchChangeRef.current = true
}
const handlePrev = () => {
setOffset((prev) => Math.max(0, prev - LIMIT))
isSearchChangeRef.current = false
}
const handleNext = () => {
setOffset((prev) => prev + LIMIT)
isSearchChangeRef.current = false
}
useEffect(() => {
const delay = isSearchChangeRef.current ? 300 : 0
isSearchChangeRef.current = false
let cancelled = false
const timer = setTimeout(async () => {
setLoading(true)
try {
const params = new URLSearchParams({
limit: String(LIMIT),
offset: String(offset),
})
if (statusFilter !== "all") {
params.set("status", statusFilter)
}
const res = await fetch(`/api/admin/reports?${params.toString()}`)
if (res.ok && !cancelled) {
const json = (await res.json()) as ReportsApiResponse
setReports(json.data)
setTotal(json.total)
}
} catch {
// ignore
} finally {
if (!cancelled) setLoading(false)
}
}, delay)
return () => {
cancelled = true
clearTimeout(timer)
}
}, [search, offset, statusFilter])
const handleUpdateStatus = async (report: Report, status: "reviewed" | "dismissed") => {
setActionLoading((prev) => ({ ...prev, [report.id]: true }))
try {
const res = await fetch(`/api/admin/reports/${report.id}/status`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status }),
})
if (res.ok) {
// Refresh list after action
const params = new URLSearchParams({
limit: String(LIMIT),
offset: String(offset),
})
if (statusFilter !== "all") {
params.set("status", statusFilter)
}
const listRes = await fetch(`/api/admin/reports?${params.toString()}`)
if (listRes.ok) {
const json = (await listRes.json()) as ReportsApiResponse
setReports(json.data)
setTotal(json.total)
}
setConfirmReport(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [report.id]: false }))
}
}
const filteredReports = useMemo(() => {
const term = search.trim().toLowerCase()
if (!term) return reports
return reports.filter(
(r) =>
r.reporterName?.toLowerCase().includes(term) ||
r.game.title.toLowerCase().includes(term) ||
r.reason.toLowerCase().includes(term) ||
r.details?.toLowerCase().includes(term) ||
r.status.toLowerCase().includes(term)
)
}, [reports, search])
const hasMore = offset + filteredReports.length < total
const tabs: { label: string; value: StatusFilter }[] = [
{ label: "All", value: "all" },
{ label: "Open", value: "open" },
{ label: "Reviewed", value: "reviewed" },
{ label: "Dismissed", value: "dismissed" },
]
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center gap-3">
<FlagIcon className="h-5 w-5 text-text/70" />
<h1 className="text-lg font-semibold text-text">Reports</h1>
</div>
{/* Search */}
<div className="relative">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text/40" />
<input
type="text"
value={search}
onChange={(e) => handleSearchChange(e.target.value)}
placeholder="Search reports..."
className="w-full pl-9 pr-4 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
{/* Filter tabs */}
<div className="flex items-center gap-1">
{tabs.map((tab) => (
<button
key={tab.value}
onClick={() => handleStatusChange(tab.value)}
className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors cursor-pointer ${
statusFilter === tab.value
? "bg-primary/10 text-primary"
: "bg-text/5 text-text/70 hover:bg-text/10"
}`}
>
{tab.label}
</button>
))}
</div>
{/* Table */}
<div className="rounded-xl border border-border overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-text/[0.03]">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Reporter
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Game
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
FPS
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Reason
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Details
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Status
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Date
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Actions
</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={8} className="px-4 py-8 text-center text-text/50">
<Loader2 className="h-5 w-5 animate-spin mx-auto" />
</td>
</tr>
) : filteredReports.length === 0 ? (
<tr>
<td colSpan={8} className="px-4 py-8 text-center text-text/50">
No reports found.
</td>
</tr>
) : (
filteredReports.map((report) => (
<tr
key={report.id}
className="border-t border-border hover:bg-text/[0.02] transition-colors"
>
<td className="px-4 py-3">
<div className="flex items-center gap-3">
<div className="h-8 w-8 rounded-full bg-text/10 flex items-center justify-center text-xs font-medium text-text/70">
{getInitial(report.reporterName)}
</div>
<div className="min-w-0">
<p className="font-medium text-text truncate">
{report.reporterName || "Unknown"}
</p>
</div>
</div>
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
{report.game.headerImage ? (
<Image
src={report.game.headerImage}
alt={report.game.title}
width={40}
height={20}
className="h-5 w-10 object-cover rounded"
unoptimized
/>
) : null}
<p className="font-medium text-text truncate max-w-[150px]">
{report.game.title}
</p>
</div>
</td>
<td className="px-4 py-3">
<span className="text-text/70">
{report.entry.fpsAvg ?? "—"}
</span>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${reasonBadgeClasses(report.reason)}`}
>
{report.reason}
</span>
</td>
<td className="px-4 py-3">
<p className="text-text/50 truncate max-w-[200px]">
{truncate(report.details, 80)}
</p>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${statusBadgeClasses(report.status)}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${
report.status === "open"
? "bg-yellow-400"
: report.status === "reviewed"
? "bg-green-400"
: "bg-text/40"
}`}
/>
{report.status}
</span>
</td>
<td className="px-4 py-3 text-xs text-text/50">
{formatDate(report.createdAt)}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
{report.status === "open" ? (
<>
<button
onClick={() => setConfirmReport(report)}
disabled={actionLoading[report.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-green-500/10 text-green-400 hover:bg-green-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[report.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<ShieldCheckIcon className="h-3.5 w-3.5" />
)}
Review
</button>
<button
onClick={() => handleUpdateStatus(report, "dismissed")}
disabled={actionLoading[report.id]}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text/70 hover:bg-text/10 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[report.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<XIcon className="h-3.5 w-3.5" />
)}
Dismiss
</button>
</>
) : (
<span
className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${statusBadgeClasses(report.status)}`}
>
{report.status}
</span>
)}
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
{filteredReports.length > 0 && (
<div className="flex items-center justify-between">
<p className="text-xs text-text/50">
Showing {offset + 1}{Math.min(offset + filteredReports.length, total)} of{" "}
{total}
</p>
<div className="flex items-center gap-2">
<button
onClick={handlePrev}
disabled={offset === 0 || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
<ChevronLeftIcon className="h-3.5 w-3.5" />
Previous
</button>
<button
onClick={handleNext}
disabled={!hasMore || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
Next
<ChevronRightIcon className="h-3.5 w-3.5" />
</button>
</div>
</div>
)}
{/* Confirmation Dialog */}
{confirmReport && (
<ConfirmDialog
open={!!confirmReport}
onClose={() => setConfirmReport(null)}
onConfirm={() => handleUpdateStatus(confirmReport, "reviewed")}
title="Confirm Review"
message="This will also remove the reported benchmark. Are you sure?"
confirmLabel="Review"
variant="default"
loading={actionLoading[confirmReport.id]}
/>
)}
</div>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { StorageClient } from "./storage-client"
export const metadata: Metadata = {
title: "Storage",
}
export default function StoragePage() {
return <StorageClient />
}
@@ -0,0 +1,447 @@
"use client"
import { useEffect, useRef, useState } from "react"
import {
Loader2,
HardDriveIcon,
TrashIcon,
SearchIcon,
RefreshCwIcon,
AlertTriangleIcon,
ChevronLeftIcon,
ChevronRightIcon,
FileIcon,
CheckCircle2Icon,
} from "lucide-react"
import { ConfirmDialog } from "@/components/ui/modal"
type EntityType = "all" | "avatar" | "entry_screenshot" | "game_cover" | "hardware_image" | "orphaned"
interface StorageStats {
configured: boolean
bucketName: string
totalObjects: number
totalSizeBytes: number
orphanedCount: number
orphanedSizeBytes: number
byEntityType: Record<string, { count: number; totalSizeBytes: number }>
}
interface StorageObject {
id: string
key: string
bucket: string
size: number
mimeType: string
entityType: string
entityId: string | null
uploadedBy: string
uploaderName: string | null
createdAt: string
lastAccessedAt: string | null
isOrphaned: boolean
}
interface ObjectsResponse {
data: StorageObject[]
total: number
limit: number
offset: number
}
const LIMIT = 50
function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B"
const k = 1024
const sizes = ["B", "KB", "MB", "GB", "TB"]
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`
}
function formatDate(value: string | null | undefined) {
if (!value) return "—"
return new Date(value).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
}
function entityTypeLabel(type: string) {
const labels: Record<string, string> = {
avatar: "Avatar",
entry_screenshot: "Screenshot",
game_cover: "Game Cover",
hardware_image: "Hardware Img",
}
return labels[type] ?? type
}
function entityTypeBadgeClass(type: string) {
const classes: Record<string, string> = {
avatar: "bg-purple-500/10 text-purple-400",
entry_screenshot: "bg-blue-500/10 text-blue-400",
game_cover: "bg-green-500/10 text-green-400",
hardware_image: "bg-amber-500/10 text-amber-400",
}
return classes[type] ?? "bg-text/5 text-text/50"
}
export function StorageClient() {
const [stats, setStats] = useState<StorageStats | null>(null)
const [objects, setObjects] = useState<StorageObject[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [statsLoading, setStatsLoading] = useState(true)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [entityFilter, setEntityFilter] = useState<EntityType>("all")
const [deleting, setDeleting] = useState<string | null>(null)
const [confirmDelete, setConfirmDelete] = useState<StorageObject | null>(null)
const [cleanupLoading, setCleanupLoading] = useState(false)
const [cleanupResult, setCleanupResult] = useState<{ deleted: number; errors: number } | null>(null)
const isSearchChangeRef = useRef(false)
useEffect(() => {
fetch("/api/admin/storage/stats")
.then((res) => res.json())
.then((data) => {
setStats(data)
setStatsLoading(false)
})
.catch(() => setStatsLoading(false))
}, [])
useEffect(() => {
const delay = isSearchChangeRef.current ? 300 : 0
isSearchChangeRef.current = false
let cancelled = false
const timer = setTimeout(async () => {
setLoading(true)
try {
const params = new URLSearchParams({
limit: String(LIMIT),
offset: String(offset),
})
if (entityFilter === "orphaned") {
params.set("orphaned", "true")
} else if (entityFilter !== "all") {
params.set("entityType", entityFilter)
}
if (search.trim()) {
params.set("search", search.trim())
}
const res = await fetch(`/api/admin/storage/objects?${params.toString()}`)
if (res.ok && !cancelled) {
const json = (await res.json()) as ObjectsResponse
setObjects(json.data)
setTotal(json.total)
}
} catch {
// ignore
} finally {
if (!cancelled) setLoading(false)
}
}, delay)
return () => {
cancelled = true
clearTimeout(timer)
}
}, [search, offset, entityFilter])
const handleSearchChange = (value: string) => {
setSearch(value)
setOffset(0)
isSearchChangeRef.current = true
}
const handleDelete = async (obj: StorageObject) => {
setDeleting(obj.id)
try {
const res = await fetch(`/api/admin/storage/objects/${obj.id}`, {
method: "DELETE",
})
if (res.ok) {
setObjects((prev) => prev.filter((o) => o.id !== obj.id))
setTotal((prev) => Math.max(0, prev - 1))
setConfirmDelete(null)
const statsRes = await fetch("/api/admin/storage/stats")
if (statsRes.ok) {
setStats(await statsRes.json())
}
}
} finally {
setDeleting(null)
}
}
const handleCleanup = async () => {
setCleanupLoading(true)
setCleanupResult(null)
try {
const res = await fetch("/api/admin/storage/cleanup", { method: "POST" })
if (res.ok) {
const data = await res.json()
setCleanupResult({ deleted: data.deleted, errors: data.errors })
const statsRes = await fetch("/api/admin/storage/stats")
if (statsRes.ok) setStats(await statsRes.json())
setOffset(0)
}
} finally {
setCleanupLoading(false)
}
}
const hasMore = offset + objects.length < total
const filterTabs: { label: string; value: EntityType }[] = [
{ label: "All", value: "all" },
{ label: "Avatars", value: "avatar" },
{ label: "Screenshots", value: "entry_screenshot" },
{ label: "Covers", value: "game_cover" },
{ label: "Hardware", value: "hardware_image" },
{ label: "Orphaned", value: "orphaned" },
]
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<HardDriveIcon className="h-5 w-5 text-text/70" />
<h1 className="text-lg font-semibold text-text">Storage</h1>
</div>
{stats && !stats.configured && (
<div className="rounded-lg border border-amber-500/30 bg-amber-500/10 p-4 flex items-start gap-3">
<AlertTriangleIcon className="h-5 w-5 text-amber-400 shrink-0 mt-0.5" />
<div>
<p className="text-sm font-medium text-amber-400">R2 Not Configured</p>
<p className="text-xs text-text/60 mt-1">
Set the R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, and R2_PUBLIC_URL environment variables to enable storage management.
</p>
</div>
</div>
)}
{statsLoading ? (
<div className="animate-pulse h-20 rounded-lg bg-zinc-800" />
) : stats && stats.configured ? (
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="rounded-lg border border-zinc-800 bg-zinc-900 p-4">
<div className="flex items-center gap-2 mb-2">
<FileIcon className="h-4 w-4 text-blue-400" />
<span className="text-xs text-zinc-500">Total Objects</span>
</div>
<p className="text-2xl font-bold">{stats.totalObjects.toLocaleString()}</p>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-900 p-4">
<div className="flex items-center gap-2 mb-2">
<HardDriveIcon className="h-4 w-4 text-green-400" />
<span className="text-xs text-zinc-500">Total Size</span>
</div>
<p className="text-2xl font-bold">{formatBytes(stats.totalSizeBytes)}</p>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-900 p-4">
<div className="flex items-center gap-2 mb-2">
<AlertTriangleIcon className="h-4 w-4 text-amber-400" />
<span className="text-xs text-zinc-500">Orphaned</span>
</div>
<p className="text-2xl font-bold">{stats.orphanedCount.toLocaleString()}</p>
{stats.orphanedSizeBytes > 0 && (
<p className="text-xs text-zinc-500">{formatBytes(stats.orphanedSizeBytes)}</p>
)}
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-900 p-4">
<div className="flex items-center gap-2 mb-2">
<HardDriveIcon className="h-4 w-4 text-purple-400" />
<span className="text-xs text-zinc-500">Bucket</span>
</div>
<p className="text-sm font-mono text-text truncate">{stats.bucketName}</p>
</div>
</div>
) : null}
{stats?.byEntityType && Object.keys(stats.byEntityType).length > 0 && (
<div className="rounded-lg border border-zinc-800 bg-zinc-900 p-4">
<h3 className="mb-3 font-semibold text-sm">Storage by Type</h3>
<div className="flex gap-4 flex-wrap">
{Object.entries(stats.byEntityType).map(([type, data]) => (
<div key={type} className="flex items-center gap-2">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${entityTypeBadgeClass(type)}`}>
{entityTypeLabel(type)}
</span>
<span className="text-xs text-text/70">{data.count} · {formatBytes(data.totalSizeBytes)}</span>
</div>
))}
</div>
</div>
)}
{stats?.configured && (
<div className="flex items-center gap-3">
<button
onClick={handleCleanup}
disabled={cleanupLoading || !stats?.configured}
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-amber-500/10 text-amber-400 text-sm font-medium hover:bg-amber-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{cleanupLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<RefreshCwIcon className="h-4 w-4" />
)}
Run Orphan Cleanup
</button>
{cleanupResult && (
<div className="flex items-center gap-2 text-sm">
<CheckCircle2Icon className="h-4 w-4 text-green-400" />
<span className="text-text/70">
Deleted {cleanupResult.deleted} objects
{cleanupResult.errors > 0 && `, ${cleanupResult.errors} errors`}
</span>
</div>
)}
</div>
)}
<div className="relative">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text/40" />
<input
type="text"
value={search}
onChange={(e) => handleSearchChange(e.target.value)}
placeholder="Search by key..."
className="w-full pl-9 pr-4 py-2 rounded-md bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
<div className="flex items-center gap-1 flex-wrap">
{filterTabs.map((tab) => (
<button
key={tab.value}
onClick={() => {
setEntityFilter(tab.value)
setOffset(0)
}}
className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors cursor-pointer ${
entityFilter === tab.value
? "bg-primary/10 text-primary"
: "bg-text/5 text-text/70 hover:bg-text/10"
}`}
>
{tab.label}
</button>
))}
</div>
<div className="rounded-xl border border-border overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-text/[0.03]">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">Key</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">Type</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">Size</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">Uploaded By</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">Date</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">Status</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">Actions</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={7} className="px-4 py-8 text-center text-text/50">
<Loader2 className="h-5 w-5 animate-spin mx-auto" />
</td>
</tr>
) : objects.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-8 text-center text-text/50">No objects found.</td>
</tr>
) : (
objects.map((obj) => (
<tr
key={obj.id}
className="border-t border-border hover:bg-text/[0.02] transition-colors"
>
<td className="px-4 py-3">
<p className="font-mono text-xs text-text/70 truncate max-w-[300px]" title={obj.key}>{obj.key}</p>
</td>
<td className="px-4 py-3">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${entityTypeBadgeClass(obj.entityType)}`}>
{entityTypeLabel(obj.entityType)}
</span>
</td>
<td className="px-4 py-3 text-xs text-text/70">{formatBytes(obj.size)}</td>
<td className="px-4 py-3 text-xs text-text/70">{obj.uploaderName || "System"}</td>
<td className="px-4 py-3 text-xs text-text/50">{formatDate(obj.createdAt)}</td>
<td className="px-4 py-3">
{obj.isOrphaned && (
<span className="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider bg-amber-500/10 text-amber-400">
Orphaned
</span>
)}
</td>
<td className="px-4 py-3">
<button
onClick={() => setConfirmDelete(obj)}
disabled={deleting === obj.id}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{deleting === obj.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<TrashIcon className="h-3.5 w-3.5" />
)}
Delete
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{objects.length > 0 && (
<div className="flex items-center justify-between">
<p className="text-xs text-text/50">
Showing {offset + 1}{Math.min(offset + objects.length, total)} of {total}
</p>
<div className="flex items-center gap-2">
<button
onClick={() => setOffset((prev) => Math.max(0, prev - LIMIT))}
disabled={offset === 0 || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
<ChevronLeftIcon className="h-3.5 w-3.5" />
Previous
</button>
<button
onClick={() => setOffset((prev) => prev + LIMIT)}
disabled={!hasMore || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex items-center gap-1"
>
Next
<ChevronRightIcon className="h-3.5 w-3.5" />
</button>
</div>
</div>
)}
{confirmDelete && (
<ConfirmDialog
open={!!confirmDelete}
onClose={() => setConfirmDelete(null)}
onConfirm={() => handleDelete(confirmDelete)}
title="Delete Storage Object"
message={`Are you sure you want to delete "${confirmDelete.key}"? This will remove the file from R2 storage and the database record. This action cannot be undone.`}
confirmLabel="Delete"
variant="destructive"
loading={deleting === confirmDelete.id}
/>
)}
</div>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { SuggestionsClient } from "./suggestions-client"
export const metadata: Metadata = {
title: "Suggestions",
}
export default function SuggestionsPage() {
return <SuggestionsClient />
}
@@ -0,0 +1,383 @@
"use client"
import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { cn } from "@/lib/utils"
import { ConfirmDialog } from "@/components/ui/modal"
import {
Loader2,
SearchIcon,
Lightbulb,
ExternalLinkIcon,
CheckCircle2Icon,
XCircleIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
interface Suggestion {
id: string
gameId: string
gameTitle: string
fieldName: string
currentValue: string | null
proposedValue: string
reason: string | null
status: string
createdAt: string
userName: string | null
}
type ConfirmType = "approve" | "reject"
interface SuggestionsApiResponse {
data: Suggestion[]
total: number
limit: number
offset: number
}
const LIMIT = 50
function formatDate(value: string | Date | null | undefined) {
if (!value) return "—"
const d = typeof value === "string" ? new Date(value) : value
return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
}
export function SuggestionsClient() {
const [suggestions, setSuggestions] = useState<Suggestion[]>([])
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [total, setTotal] = useState(0)
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({})
const [confirmAction, setConfirmAction] = useState<{
type: ConfirmType
suggestion: Suggestion
} | null>(null)
const [activeTab, setActiveTab] = useState("all")
const statusTabs = [
{ label: "All", value: "all" },
{ label: "Pending", value: "pending" },
{ label: "Approved", value: "approved" },
{ label: "Rejected", value: "rejected" },
]
useEffect(() => {
let cancelled = false
const run = async () => {
try {
const res = await fetch(`/api/community-suggestions/admin?limit=${LIMIT}`)
if (res.ok && !cancelled) {
const json = (await res.json()) as SuggestionsApiResponse
setSuggestions(json.data)
setTotal(json.total)
}
} catch {
// ignore
} finally {
if (!cancelled) setLoading(false)
}
}
run()
return () => { cancelled = true }
}, [])
const filtered = useMemo(() => {
let result = suggestions
const term = search.trim().toLowerCase()
if (term) {
result = result.filter(
(s) =>
s.gameTitle?.toLowerCase().includes(term) ||
s.fieldName?.toLowerCase().includes(term) ||
s.proposedValue?.toLowerCase().includes(term) ||
s.userName?.toLowerCase().includes(term) ||
s.reason?.toLowerCase().includes(term)
)
}
if (activeTab !== "all") {
result = result.filter((s) => s.status === activeTab)
}
return result
}, [suggestions, search, activeTab])
const paginated = filtered.slice(offset, offset + LIMIT)
const hasMore = offset + LIMIT < total
const handlePrev = () => setOffset((prev) => Math.max(0, prev - LIMIT))
const handleNext = () => setOffset((prev) => prev + LIMIT)
const handleReview = async (
suggestion: Suggestion,
status: "approved" | "rejected"
) => {
setActionLoading((prev) => ({ ...prev, [suggestion.id]: true }))
try {
const res = await fetch(
`/api/community-suggestions/${suggestion.id}/review`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status }),
}
)
if (res.ok) {
setSuggestions((prev) =>
prev.filter((s) => s.id !== suggestion.id)
)
setConfirmAction(null)
}
} finally {
setActionLoading((prev) => ({ ...prev, [suggestion.id]: false }))
}
}
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center gap-2">
<Lightbulb className="h-5 w-5 text-text/50" />
<h2 className="text-lg font-semibold text-text">Suggestions</h2>
<span className="text-sm text-text/50">({filtered.length})</span>
</div>
{/* Search */}
<div className="relative">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text/40" />
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search suggestions..."
className="w-full pl-9 pr-4 py-2.5 rounded-lg bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
{/* Status Tabs */}
<div className="flex items-center gap-2">
{statusTabs.map((tab) => (
<button
key={tab.value}
onClick={() => setActiveTab(tab.value)}
className={cn(
"px-3 py-1.5 rounded-md text-xs font-medium transition-colors",
activeTab === tab.value
? "bg-primary/10 text-primary"
: "bg-text/5 text-text/60 hover:bg-text/10"
)}
>
{tab.label}
</button>
))}
</div>
{/* Suggestions List */}
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-primary" />
</div>
) : paginated.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-text/50">
<Lightbulb className="h-8 w-8 mb-2" />
<p className="text-sm">No suggestions found</p>
</div>
) : (
<div className="rounded-xl border border-border overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-text/[0.03]">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Game
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Field
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Current
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Proposed
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Reason
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
By
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Date
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Status
</th>
<th className="text-left px-4 py-3 text-xs font-medium uppercase tracking-wider text-text/50">
Actions
</th>
</tr>
</thead>
<tbody>
{paginated.map((suggestion) => (
<tr
key={suggestion.id}
className="border-t border-border hover:bg-text/[0.02] transition-colors"
>
<td className="px-4 py-3">
<p className="font-medium text-text truncate max-w-[200px]">
{suggestion.gameTitle}
</p>
</td>
<td className="px-4 py-3">
<span className="text-xs px-2 py-0.5 rounded-md bg-text/5 text-text/70">
{suggestion.fieldName}
</span>
</td>
<td className="px-4 py-3">
<p className="text-text/50 truncate max-w-[150px]">
{suggestion.currentValue || "—"}
</p>
</td>
<td className="px-4 py-3">
<p className="text-text truncate max-w-[150px]">
{suggestion.proposedValue}
</p>
</td>
<td className="px-4 py-3">
<p className="text-text/50 truncate max-w-[200px]">
{suggestion.reason || "—"}
</p>
</td>
<td className="px-4 py-3">
<p className="text-text/70 truncate max-w-[120px]">
{suggestion.userName || "Unknown"}
</p>
</td>
<td className="px-4 py-3">
<span className="text-xs text-text/50">
{formatDate(suggestion.createdAt)}
</span>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-medium uppercase tracking-wider ${
suggestion.status === "approved"
? "bg-green-500/10 text-green-400"
: suggestion.status === "rejected"
? "bg-red-500/10 text-red-400"
: "bg-yellow-500/10 text-yellow-400"
}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${
suggestion.status === "approved"
? "bg-green-400"
: suggestion.status === "rejected"
? "bg-red-400"
: "bg-yellow-400"
}`}
/>
{suggestion.status}
</span>
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
<Link
href={`/game/${suggestion.gameId}`}
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors cursor-pointer"
>
<ExternalLinkIcon className="h-3.5 w-3.5" />
View
</Link>
<button
onClick={() =>
setConfirmAction({ type: "approve", suggestion })
}
disabled={actionLoading[suggestion.id]}
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-green-500/10 text-green-400 hover:bg-green-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[suggestion.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<CheckCircle2Icon className="h-3.5 w-3.5" />
)}
Approve
</button>
<button
onClick={() =>
setConfirmAction({ type: "reject", suggestion })
}
disabled={actionLoading[suggestion.id]}
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer disabled:opacity-50"
>
{actionLoading[suggestion.id] ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<XCircleIcon className="h-3.5 w-3.5" />
)}
Reject
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* Pagination */}
{total > 0 && (
<div className="flex items-center justify-between">
<p className="text-xs text-text/50">
Showing {offset + 1}{Math.min(offset + paginated.length, total)} of{" "}
{total}
</p>
<div className="flex items-center gap-2">
<button
onClick={handlePrev}
disabled={offset === 0 || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
<ChevronLeftIcon className="h-3.5 w-3.5" />
Previous
</button>
<button
onClick={handleNext}
disabled={!hasMore || loading}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text hover:bg-text/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
Next
<ChevronRightIcon className="h-3.5 w-3.5" />
</button>
</div>
</div>
)}
{/* Confirm Dialog */}
<ConfirmDialog
open={!!confirmAction}
onClose={() => setConfirmAction(null)}
onConfirm={() => {
if (confirmAction) {
handleReview(
confirmAction.suggestion,
confirmAction.type === "approve" ? "approved" : "rejected"
)
}
}}
title={`Confirm ${confirmAction?.type === "approve" ? "Approval" : "Rejection"}`}
message={
confirmAction
? `Are you sure you want to ${confirmAction.type === "approve" ? "approve" : "reject"} the "${confirmAction.suggestion.fieldName}" suggestion for "${confirmAction.suggestion.gameTitle}"?`
: ""
}
confirmLabel={confirmAction?.type === "approve" ? "Approve" : "Reject"}
cancelLabel="Cancel"
variant={confirmAction?.type === "approve" ? "default" : "destructive"}
loading={confirmAction ? !!actionLoading[confirmAction.suggestion.id] : false}
/>
</div>
)
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next"
import { UsersClient } from "./users-client"
export const metadata: Metadata = {
title: "Users",
}
export default function UsersPage() {
return <UsersClient />
}
@@ -0,0 +1,276 @@
"use client"
import { useEffect, useMemo, useState } from "react"
import Image from "next/image"
import { authClient } from "@/lib/auth-client"
import { Loader2, SearchIcon, BanIcon, UserCheckIcon, UsersIcon } from "lucide-react"
type Role = "user" | "contributor" | "admin"
interface AdminUser {
id: string
name: string
email: string
emailVerified: boolean
image: string | null
createdAt: Date | string
role: Role
banned: boolean
}
const roles: Role[] = ["user", "contributor", "admin"]
function formatDate(value: Date | string | null | undefined) {
if (!value) return "—"
const d = typeof value === "string" ? new Date(value) : value
return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
}
function getInitial(name: string) {
return name?.charAt(0)?.toUpperCase() || "?"
}
export function UsersClient() {
const [users, setUsers] = useState<AdminUser[]>([])
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState("")
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({})
const [banTarget, setBanTarget] = useState<AdminUser | null>(null)
const [banReason, setBanReason] = useState("")
const [banExpiryDays, setBanExpiryDays] = useState("")
const [banFilter, setBanFilter] = useState<"all" | "banned" | "active">("all")
useEffect(() => {
const fetchUsers = async () => {
setLoading(true)
const res = await authClient.admin.listUsers({ query: { limit: 100 } })
if (res.data?.users) {
setUsers(res.data.users as AdminUser[])
}
setLoading(false)
}
fetchUsers()
}, [])
const filteredUsers = useMemo(() => {
let result = users
const term = search.trim().toLowerCase()
if (term) {
result = result.filter(
(u) => u.name?.toLowerCase().includes(term) || u.email?.toLowerCase().includes(term)
)
}
if (banFilter === "banned") result = result.filter((u) => u.banned)
if (banFilter === "active") result = result.filter((u) => !u.banned)
return result
}, [users, search, banFilter])
const handleRoleChange = async (userId: string, newRole: Role) => {
setActionLoading((prev) => ({ ...prev, [userId]: true }))
try {
await authClient.admin.setRole({ userId, role: newRole as "user" | "admin" })
setUsers((prev) =>
prev.map((u) => (u.id === userId ? { ...u, role: newRole } : u))
)
} finally {
setActionLoading((prev) => ({ ...prev, [userId]: false }))
}
}
const handleBan = async () => {
if (!banTarget) return
setActionLoading((prev) => ({ ...prev, [banTarget.id]: true }))
try {
await authClient.admin.banUser({
userId: banTarget.id,
banReason: banReason.trim() || undefined,
banExpires: banExpiryDays
? new Date(Date.now() + Number(banExpiryDays) * 24 * 60 * 60 * 1000)
: undefined,
} as any)
setUsers((prev) =>
prev.map((u) => (u.id === banTarget.id ? { ...u, banned: true } : u))
)
setBanTarget(null)
setBanReason("")
setBanExpiryDays("")
} finally {
setActionLoading((prev) => ({ ...prev, [banTarget.id]: false }))
}
}
const handleUnban = async (userId: string) => {
setActionLoading((prev) => ({ ...prev, [userId]: true }))
try {
await authClient.admin.unbanUser({ userId })
setUsers((prev) =>
prev.map((u) => (u.id === userId ? { ...u, banned: false } : u))
)
} finally {
setActionLoading((prev) => ({ ...prev, [userId]: false }))
}
}
return (
<div className="space-y-4">
{/* Header with count */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<UsersIcon className="h-5 w-5 text-text/50" />
<h2 className="text-lg font-semibold">Users</h2>
<span className="text-sm text-text/50">({filteredUsers.length})</span>
</div>
</div>
{/* Search */}
<div className="relative">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text/40" />
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search by name or email..."
className="w-full pl-9 pr-4 py-2.5 rounded-lg bg-text/5 border border-border text-sm text-text placeholder:text-text/40 focus:outline-none focus:border-primary/60 transition-colors"
/>
</div>
{/* Filter Tabs */}
<div className="flex gap-2">
{(["all", "active", "banned"] as const).map((f) => (
<button
key={f}
onClick={() => setBanFilter(f)}
className={`px-3 py-1 rounded-md text-xs font-medium transition-colors ${
banFilter === f ? "bg-primary/10 text-primary" : "text-text/50 hover:text-text/70"
}`}
>
{f === "all" ? "All" : f === "active" ? "Active" : "Banned"}
</button>
))}
</div>
{/* Users List */}
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-primary" />
</div>
) : filteredUsers.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-text/50">
<UsersIcon className="h-8 w-8 mb-2" />
<p className="text-sm">No users found</p>
</div>
) : (
<div className="space-y-2">
{filteredUsers.map((user) => (
<div
key={user.id}
className="flex items-center gap-4 p-4 rounded-xl border border-border bg-text/[0.02] hover:bg-text/[0.04] transition-colors"
>
{/* Avatar */}
{user.image ? (
<Image
src={user.image}
alt=""
width={40}
height={40}
className="h-10 w-10 rounded-full object-cover"
/>
) : (
<div className="h-10 w-10 rounded-full bg-text/10 flex items-center justify-center text-sm font-medium text-text/70">
{getInitial(user.name)}
</div>
)}
{/* User Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-medium text-text truncate">{user.name || "Unnamed"}</p>
{user.banned && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-red-500/10 text-red-400">
Banned
</span>
)}
</div>
<p className="text-xs text-text/50 truncate">{user.email}</p>
<p className="text-[11px] text-text/30 mt-0.5">Joined {formatDate(user.createdAt)}</p>
</div>
{/* Role Selector */}
<select
value={user.role || "user"}
onChange={(e) => handleRoleChange(user.id, e.target.value as Role)}
disabled={actionLoading[user.id]}
className="text-xs px-3 py-1.5 rounded-lg border border-border bg-text/5 text-text focus:outline-none focus:border-primary/60 transition-colors cursor-pointer disabled:opacity-50"
>
{roles.map((r) => (
<option key={r} value={r}>
{r.charAt(0).toUpperCase() + r.slice(1)}
</option>
))}
</select>
{/* Action Button */}
{actionLoading[user.id] ? (
<Loader2 className="h-4 w-4 animate-spin text-text/50" />
) : user.banned ? (
<button
onClick={() => handleUnban(user.id)}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-green-500/10 text-green-400 hover:bg-green-500/20 transition-colors cursor-pointer"
>
<UserCheckIcon className="h-3.5 w-3.5" />
Unban
</button>
) : (
<button
onClick={() => setBanTarget(user)}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors cursor-pointer"
>
<BanIcon className="h-3.5 w-3.5" />
Ban
</button>
)}
</div>
))}
</div>
)}
{/* Ban Modal */}
{banTarget && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60" onClick={() => setBanTarget(null)}>
<div className="bg-zinc-900 border border-zinc-800 rounded-xl p-6 w-full max-w-md space-y-4" onClick={(e) => e.stopPropagation()}>
<h3 className="font-semibold">Ban {banTarget.name || banTarget.email}</h3>
<div className="space-y-2">
<label className="text-xs text-text/60">Reason</label>
<textarea
value={banReason}
onChange={(e) => setBanReason(e.target.value)}
placeholder="Reason for ban..."
rows={3}
className="w-full px-3 py-2 rounded-lg border border-border bg-text/5 text-text text-sm placeholder:text-text/40 outline-none focus:border-primary resize-y"
/>
</div>
<div className="space-y-2">
<label className="text-xs text-text/60">Expiry (days, leave empty for permanent)</label>
<input
type="number"
value={banExpiryDays}
onChange={(e) => setBanExpiryDays(e.target.value)}
placeholder="e.g. 7"
min={1}
className="w-full px-3 py-2 rounded-lg border border-border bg-text/5 text-text text-sm placeholder:text-text/40 outline-none focus:border-primary"
/>
</div>
<div className="flex justify-end gap-2">
<button onClick={() => setBanTarget(null)} className="px-4 py-2 rounded-lg border border-border text-text/70 text-sm hover:bg-text/5 transition-colors">
Cancel
</button>
<button onClick={handleBan} disabled={actionLoading[banTarget.id]} className="px-4 py-2 rounded-lg bg-red-500 text-white text-sm font-semibold hover:bg-red-600 transition-colors disabled:opacity-50">
Ban User
</button>
</div>
</div>
</div>
)}
</div>
)
}