feat: enhance MessagesPanel with improved UI components and functionality
Deploy to VPS / deploy (push) Successful in 2m13s

- Refactored MessagesPanel to utilize new UI components such as Avatar, Badge, Button, Card, Dialog, Input, Progress, ScrollArea, Select, Skeleton, and Tabs.
- Improved error handling and loading states with enhanced user feedback.
- Updated message rendering logic to support new design patterns and animations.
- Added support for image previews and improved layout for message details.
- Enhanced mobile responsiveness with useIsMobile hook adjustments.
- Cleaned up utility functions for better readability and consistency.
This commit is contained in:
asepharyana
2026-07-26 15:13:18 +07:00
parent f57a1caf62
commit eae0d7ce56
14 changed files with 1907 additions and 1303 deletions
+10 -4
View File
@@ -2,9 +2,11 @@
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useRef } from "react"; import { Suspense, useEffect, useRef } from "react";
import { Header } from "@/components/layout/header"; import { Header } from "@/components/layout/header";
import { MobileTabBar } from "@/components/layout/mobile-tab-bar"; import { MobileTabBar } from "@/components/layout/mobile-tab-bar";
import { Sidebar } from "@/components/layout/sidebar"; import { Sidebar } from "@/components/layout/sidebar";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { MascotChatbot } from "@/features/mascot/mascot-chatbot"; import { MascotChatbot } from "@/features/mascot/mascot-chatbot";
import { uiStateApi } from "@/lib/api"; import { uiStateApi } from "@/lib/api";
import { WsProvider } from "@/lib/ws/context"; import { WsProvider } from "@/lib/ws/context";
@@ -48,12 +50,14 @@ function DashboardShell({ children }: { children: React.ReactNode }) {
}, [activeTab]); }, [activeTab]);
return ( return (
<div className="min-h-screen bg-background"> <div className="flex min-h-screen bg-background">
<Sidebar activeTab={activeTab} /> <Sidebar activeTab={activeTab} />
<div className="md:pl-56 flex flex-col min-h-screen"> <SidebarInset className="flex flex-col">
<Header /> <Header />
<main className="flex-1 p-4 md:p-6 pb-20 md:pb-6">{children}</main> <main className="flex-1 p-4 md:p-6 pb-20 md:pb-6 animate-fade-in-up">
</div> {children}
</main>
</SidebarInset>
<MobileTabBar activeTab={activeTab} /> <MobileTabBar activeTab={activeTab} />
</div> </div>
); );
@@ -66,6 +70,7 @@ export default function DashboardLayout({
}) { }) {
return ( return (
<WsProvider> <WsProvider>
<SidebarProvider defaultOpen={true}>
<Suspense <Suspense
fallback={ fallback={
<div className="flex min-h-screen items-center justify-center"> <div className="flex min-h-screen items-center justify-center">
@@ -75,6 +80,7 @@ export default function DashboardLayout({
> >
<DashboardShell>{children}</DashboardShell> <DashboardShell>{children}</DashboardShell>
</Suspense> </Suspense>
</SidebarProvider>
<MascotChatbot /> <MascotChatbot />
</WsProvider> </WsProvider>
); );
+63 -49
View File
@@ -1,8 +1,18 @@
"use client"; "use client";
import { Loader2, RefreshCw } from "lucide-react"; import { AlertCircle, RefreshCw } from "lucide-react";
import { useSearchParams } from "next/navigation"; import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { DashboardPanel } from "@/features/dashboard/dashboard-panel"; import { DashboardPanel } from "@/features/dashboard/dashboard-panel";
import { LivePanel } from "@/features/live/live-panel"; import { LivePanel } from "@/features/live/live-panel";
import { MessagesPanel } from "@/features/messages/messages-panel"; import { MessagesPanel } from "@/features/messages/messages-panel";
@@ -67,22 +77,11 @@ export default function DashboardPage() {
} }
}, [configLoading, guildsLoading, resolveGuild, selectedGuildId]); }, [configLoading, guildsLoading, resolveGuild, selectedGuildId]);
const handleGuildChange = useCallback((guildId: string) => { const handleGuildChange = useCallback((guildId: string | null) => {
setSelectedGuildId(guildId); if (guildId) setSelectedGuildId(guildId);
}, []); }, []);
const isReady = !configLoading && !guildsLoading; const handleRetry = useCallback(() => {
return (
<div className="space-y-4">
{/* Guild selector bar */}
<GuildBar
guilds={guilds}
loading={guildsLoading}
error={guildsError}
selectedGuildId={selectedGuildId}
onChange={handleGuildChange}
onRetry={() => {
setGuildsLoading(true); setGuildsLoading(true);
setGuildsError(null); setGuildsError(null);
voiceApi voiceApi
@@ -94,19 +93,35 @@ export default function DashboardPage() {
), ),
) )
.finally(() => setGuildsLoading(false)); .finally(() => setGuildsLoading(false));
}} }, []);
const isReady = !configLoading && !guildsLoading;
return (
<div className="space-y-5">
{/* Guild selector bar */}
<GuildBar
guilds={guilds}
loading={guildsLoading}
error={guildsError}
selectedGuildId={selectedGuildId}
onChange={handleGuildChange}
onRetry={handleRetry}
/> />
{/* Main panel */} {/* Main panel */}
{isReady ? ( {isReady ? (
<> <div className="animate-fade-in-up">
{tab === "live" && <LivePanel />} {tab === "live" && <LivePanel />}
{tab === "dashboard" && <DashboardPanel guildId={selectedGuildId} />} {tab === "dashboard" && <DashboardPanel guildId={selectedGuildId} />}
{tab === "messages" && <MessagesPanel guildId={selectedGuildId} />} {tab === "messages" && <MessagesPanel guildId={selectedGuildId} />}
</> </div>
) : ( ) : (
<div className="flex items-center justify-center py-16"> <div className="flex items-center justify-center py-24">
<Loader2 className="size-6 animate-spin text-muted-foreground" /> <div className="flex flex-col items-center gap-3">
<div className="size-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
<p className="text-sm text-muted-foreground">Loading dashboard</p>
</div>
</div> </div>
)} )}
</div> </div>
@@ -127,7 +142,7 @@ function GuildBar({
loading: boolean; loading: boolean;
error: string | null; error: string | null;
selectedGuildId: string; selectedGuildId: string;
onChange: (id: string) => void; onChange: (id: string | null) => void;
onRetry: () => void; onRetry: () => void;
}) { }) {
// No guild bar if there's only one guild and it's already selected // No guild bar if there's only one guild and it's already selected
@@ -135,61 +150,60 @@ function GuildBar({
if (loading) { if (loading) {
return ( return (
<div className="flex items-center gap-2 rounded-lg border p-3"> <div className="flex items-center gap-3 rounded-xl border border-border/50 bg-card p-3">
<Loader2 className="size-4 animate-spin text-muted-foreground" /> <Skeleton className="h-8 w-36" />
<span className="text-sm text-muted-foreground">Loading guilds</span> <Skeleton className="h-8 w-8 rounded-full" />
</div> </div>
); );
} }
if (error) { if (error) {
return ( return (
<div className="flex items-center justify-between rounded-lg border border-destructive/30 bg-destructive/5 p-3"> <div className="flex items-center justify-between rounded-xl border border-destructive/20 bg-destructive/5 p-3">
<div className="flex items-center gap-2">
<AlertCircle className="size-4 text-destructive shrink-0" />
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
Could not load guilds: {error} Could not load guilds: {error}
</p> </p>
<button </div>
type="button" <Button variant="outline" size="sm" onClick={onRetry}>
onClick={onRetry} <RefreshCw className="size-3 mr-1" />
className="inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium hover:bg-muted transition-colors"
>
<RefreshCw className="size-3" />
Retry Retry
</button> </Button>
</div> </div>
); );
} }
if (guilds.length === 0) { if (guilds.length === 0) {
return ( return (
<div className="rounded-lg border border-yellow-500/30 bg-yellow-500/5 p-3"> <div className="rounded-xl border border-yellow-500/20 bg-yellow-500/5 p-3">
<div className="flex items-center gap-2">
<AlertCircle className="size-4 text-yellow-500 shrink-0" />
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
No guilds available. Make sure the Discord gateway is connected. No guilds available. Make sure the Discord gateway is connected.
</p> </p>
</div> </div>
</div>
); );
} }
return ( return (
<div className="flex items-center gap-2 rounded-lg border p-3"> <div className="flex items-center gap-3 rounded-xl border border-border/50 bg-card p-3">
<label <Badge variant="outline" className="shrink-0 text-xs font-normal">
htmlFor="guild-select" Guild
className="text-sm font-medium text-muted-foreground whitespace-nowrap" </Badge>
> <Select value={selectedGuildId} onValueChange={onChange}>
Guild: <SelectTrigger className="h-8 w-full max-w-xs">
</label> <SelectValue placeholder="Select a guild…" />
<select </SelectTrigger>
id="guild-select" <SelectContent>
value={selectedGuildId}
onChange={(e) => onChange(e.target.value)}
className="flex-1 h-8 rounded-md border border-input bg-background px-2 text-sm"
>
{guilds.map((g) => ( {guilds.map((g) => (
<option key={g.id} value={g.id}> <SelectItem key={g.id} value={g.id}>
{g.name} {g.name}
</option> </SelectItem>
))} ))}
</select> </SelectContent>
</Select>
</div> </div>
); );
} }
+190 -45
View File
@@ -46,6 +46,15 @@
--radius-2xl: calc(var(--radius) * 1.8); --radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2); --radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6); --radius-4xl: calc(var(--radius) * 2.6);
/* Sky blue accent gradient */
--accent-gradient: linear-gradient(135deg, oklch(0.65 0.18 240), oklch(0.65 0.15 200), oklch(0.65 0.12 180));
--accent-gradient-subtle: linear-gradient(135deg, oklch(0.65 0.18 240 / 0.15), oklch(0.65 0.12 180 / 0.05));
/* Glass morphism */
--glass-bg: oklch(1 0 0 / 0.05);
--glass-border: oklch(1 0 0 / 0.1);
--glass-shadow: 0 8px 32px oklch(0 0 0 / 0.3);
} }
:root { :root {
@@ -53,68 +62,88 @@
--card-foreground: oklch(0.145 0 0); --card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0); --popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0); --popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0); --primary: oklch(0.55 0.18 240);
--primary-foreground: oklch(0.985 0 0); --primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0); --secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0); --secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0); --muted: oklch(0.95 0 0);
--muted-foreground: oklch(0.556 0 0); --muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0); --accent: oklch(0.65 0.15 220);
--accent-foreground: oklch(0.205 0 0); --accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325); --destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0); --border: oklch(0.922 0 0);
--input: oklch(0.922 0 0); --input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0); --ring: oklch(0.65 0.18 240);
--chart-1: oklch(0.87 0 0); --chart-1: oklch(0.55 0.18 240);
--chart-2: oklch(0.556 0 0); --chart-2: oklch(0.55 0.15 200);
--chart-3: oklch(0.439 0 0); --chart-3: oklch(0.55 0.12 180);
--chart-4: oklch(0.371 0 0); --chart-4: oklch(0.55 0.2 260);
--chart-5: oklch(0.269 0 0); --chart-5: oklch(0.55 0.15 280);
--radius: 0.625rem; --radius: 0.625rem;
--sidebar: oklch(0.985 0 0); --sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0); --sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0); --sidebar-primary: oklch(0.55 0.18 240);
--sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0); --sidebar-accent: oklch(0.95 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-accent-foreground: oklch(0.145 0 0);
--sidebar-border: oklch(0.922 0 0); --sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0); --sidebar-ring: oklch(0.65 0.18 240);
--background: oklch(1 0 0); --background: oklch(1 0 0);
--foreground: oklch(0.145 0 0); --foreground: oklch(0.145 0 0);
} }
.dark { .dark {
--background: oklch(0.145 0 0); /* Deep navy-slate base */
--foreground: oklch(0.985 0 0); --background: oklch(0.12 0.02 240);
--card: oklch(0.205 0 0); --foreground: oklch(0.92 0.01 240);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0); /* Slightly lighter card */
--popover-foreground: oklch(0.985 0 0); --card: oklch(0.16 0.025 240);
--primary: oklch(0.922 0 0); --card-foreground: oklch(0.92 0.01 240);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0); --popover: oklch(0.16 0.025 240);
--secondary-foreground: oklch(0.985 0 0); --popover-foreground: oklch(0.92 0.01 240);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0); /* Sky blue primary */
--accent: oklch(0.269 0 0); --primary: oklch(0.65 0.18 240);
--accent-foreground: oklch(0.985 0 0); --primary-foreground: oklch(0.98 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%); --secondary: oklch(0.22 0.02 240);
--input: oklch(1 0 0 / 15%); --secondary-foreground: oklch(0.92 0.01 240);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0); --muted: oklch(0.2 0.015 240);
--chart-2: oklch(0.556 0 0); --muted-foreground: oklch(0.6 0.02 240);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0); --accent: oklch(0.7 0.15 220);
--chart-5: oklch(0.269 0 0); --accent-foreground: oklch(0.98 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0); --destructive: oklch(0.6 0.22 25);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0); --border: oklch(1 0 0 / 0.08);
--sidebar-accent: oklch(0.269 0 0); --input: oklch(1 0 0 / 0.12);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%); --ring: oklch(0.65 0.18 240);
--sidebar-ring: oklch(0.556 0 0);
/* Blue-teal-cyan chart palette */
--chart-1: oklch(0.65 0.18 240);
--chart-2: oklch(0.6 0.15 200);
--chart-3: oklch(0.6 0.12 180);
--chart-4: oklch(0.7 0.15 220);
--chart-5: oklch(0.55 0.15 260);
/* Deeper sidebar */
--sidebar: oklch(0.1 0.015 240);
--sidebar-foreground: oklch(0.92 0.01 240);
--sidebar-primary: oklch(0.65 0.18 240);
--sidebar-primary-foreground: oklch(0.98 0 0);
--sidebar-accent: oklch(0.2 0.02 240);
--sidebar-accent-foreground: oklch(0.92 0.01 240);
--sidebar-border: oklch(1 0 0 / 0.06);
--sidebar-ring: oklch(0.65 0.18 240);
/* Glass overrides for dark */
--glass-bg: oklch(1 0 0 / 0.05);
--glass-border: oklch(1 0 0 / 0.1);
} }
@layer base { @layer base {
@@ -125,6 +154,122 @@
@apply bg-background text-foreground; @apply bg-background text-foreground;
} }
html { html {
@apply font-sans; @apply font-sans scroll-smooth;
}
/* Custom selection color */
::selection {
background: oklch(0.65 0.18 240 / 0.3);
color: inherit;
}
.dark ::selection {
background: oklch(0.65 0.18 240 / 0.4);
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: oklch(1 0 0 / 0.1);
border-radius: 999px;
}
::-webkit-scrollbar-thumb:hover {
background: oklch(1 0 0 / 0.2);
} }
} }
/* ── Utility classes ─────────────────────────── */
/* Glass card effect */
.glass {
background: var(--glass-bg);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid var(--glass-border);
box-shadow: var(--glass-shadow);
}
/* Gradient text */
.text-gradient {
background: var(--accent-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Gradient border (via pseudo-element trick) */
.gradient-border {
position: relative;
}
.gradient-border::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
padding: 1px;
background: var(--accent-gradient);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
}
/* Animated background */
@keyframes gradient-shift {
0%,
100% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
}
.animate-gradient {
background: linear-gradient(
-45deg,
oklch(0.65 0.18 240 / 0.1),
oklch(0.6 0.15 200 / 0.05),
oklch(0.12 0.02 240 / 1),
oklch(0.65 0.12 180 / 0.08)
);
background-size: 400% 400%;
animation: gradient-shift 15s ease infinite;
}
/* Counter animation placeholder - will be done in JS */
@keyframes fade-in-up {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-fade-in-up {
animation: fade-in-up 0.3s ease-out forwards;
}
/* Pulse ring for live indicators */
@keyframes pulse-ring {
0% {
transform: scale(0.8);
opacity: 1;
}
100% {
transform: scale(2.5);
opacity: 0;
}
}
.live-pulse-ring {
animation: pulse-ring 1.5s ease-out infinite;
}
+6 -1
View File
@@ -1,6 +1,8 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import Script from "next/script"; import Script from "next/script";
import { Toaster } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import "./globals.css"; import "./globals.css";
const geistSans = Geist({ const geistSans = Geist({
@@ -34,7 +36,10 @@ export default function RootLayout({
{`try{const t=localStorage.getItem('theme')||'dark';document.documentElement.classList.add(t)}catch(e){}`} {`try{const t=localStorage.getItem('theme')||'dark';document.documentElement.classList.add(t)}catch(e){}`}
</Script> </Script>
</head> </head>
<body className="min-h-full flex flex-col">{children}</body> <body className="min-h-full flex flex-col">
<TooltipProvider delay={500}>{children}</TooltipProvider>
<Toaster position="bottom-right" richColors closeButton />
</body>
</html> </html>
); );
} }
@@ -1,7 +1,16 @@
"use client"; "use client";
import { AlertCircle, Moon, Sun, Wifi, WifiOff } from "lucide-react"; import { Moon, Sun } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { SidebarTrigger } from "@/components/ui/sidebar";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context"; import { useWebSocket } from "@/lib/ws/context";
export function Header() { export function Header() {
@@ -21,48 +30,82 @@ export function Header() {
document.documentElement.classList.add(next); document.documentElement.classList.add(next);
}; };
const statusVariant =
status === "connected"
? "default"
: status === "connecting"
? "secondary"
: "destructive";
const statusLabel =
status === "connected"
? "Connected"
: status === "connecting"
? "Connecting"
: status === "error"
? "Error"
: "Disconnected";
return ( return (
<header className="sticky top-0 z-10 flex h-14 items-center gap-4 border-b bg-background px-4 md:px-6"> <header className="sticky top-0 z-10 flex h-14 items-center gap-3 border-b border-border/50 bg-background/60 backdrop-blur-lg px-4 md:px-6">
<SidebarTrigger className="-ml-1 size-8 text-muted-foreground hover:text-foreground" />
<div className="flex-1" /> <div className="flex-1" />
{/* Connection status */} {/* Connection status */}
<div className="flex items-center gap-1.5 text-xs text-muted-foreground"> <Tooltip>
{status === "connected" ? ( <TooltipTrigger>
<> <span>
<Wifi className="size-3 text-green-500" /> <Badge
<span className="hidden sm:inline">Connected</span> variant={statusVariant}
</> className="gap-1.5 px-2.5 py-1 cursor-default select-none"
) : status === "connecting" ? ( >
<> <span
<Wifi className="size-3 text-yellow-500" /> className={cn(
<span className="hidden sm:inline">Connecting</span> "size-1.5 rounded-full",
</> status === "connected" &&
) : status === "error" ? ( "bg-green-500 shadow-[0_0_6px] shadow-green-500/60",
<> status === "connecting" && "bg-yellow-500 animate-pulse",
<AlertCircle className="size-3 text-destructive" /> (status === "disconnected" || status === "error") &&
<span className="hidden sm:inline">Error</span> "bg-destructive",
</>
) : (
<>
<WifiOff className="size-3 text-destructive" />
<span className="hidden sm:inline">Disconnected</span>
</>
)} )}
</div> />
<span className="hidden sm:inline text-xs">{statusLabel}</span>
</Badge>
</span>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>WebSocket: {statusLabel}</p>
</TooltipContent>
</Tooltip>
{/* Theme toggle */} {/* Theme toggle */}
<button <Button
type="button" variant="ghost"
size="icon"
onClick={toggleTheme} onClick={toggleTheme}
className="inline-flex size-8 items-center justify-center rounded-lg border hover:bg-muted transition-colors"
aria-label="Toggle theme" aria-label="Toggle theme"
className="size-8"
> >
{theme === "dark" ? ( <div className="relative size-4">
<Sun className="size-4" /> <Sun
) : ( className={cn(
<Moon className="size-4" /> "absolute inset-0 size-4 transition-all duration-300",
theme === "dark"
? "opacity-0 rotate-90 scale-75"
: "opacity-100 rotate-0 scale-100",
)} )}
</button> />
<Moon
className={cn(
"absolute inset-0 size-4 transition-all duration-300",
theme === "dark"
? "opacity-100 rotate-0 scale-100"
: "opacity-0 -rotate-90 scale-75",
)}
/>
</div>
</Button>
</header> </header>
); );
} }
@@ -2,15 +2,18 @@
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { type TabId, tabs } from "@/lib/tabs"; import { type TabId, tabs } from "@/lib/tabs";
import { cn } from "@/lib/utils";
export function MobileTabBar({ activeTab }: { activeTab: TabId }) { export function MobileTabBar({ activeTab }: { activeTab: TabId }) {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
return ( return (
<nav className="md:hidden fixed bottom-0 inset-x-0 z-10 border-t bg-background"> <nav className="md:hidden fixed bottom-0 inset-x-0 z-10 border-t border-border/50 bg-background/80 backdrop-blur-lg">
<div className="flex"> <div className="flex">
{tabs.map(({ id, label, icon: Icon }) => ( {tabs.map(({ id, label, icon: Icon }) => {
const isActive = activeTab === id;
return (
<button <button
key={id} key={id}
type="button" type="button"
@@ -19,13 +22,21 @@ export function MobileTabBar({ activeTab }: { activeTab: TabId }) {
params.set("tab", id); params.set("tab", id);
router.push(`/dashboard?${params}`); router.push(`/dashboard?${params}`);
}} }}
data-active={activeTab === id ? "" : undefined} className={cn(
className="flex-1 flex flex-col items-center gap-0.5 py-2 text-xs font-medium text-muted-foreground data-[active]:text-primary transition-colors" "flex-1 flex flex-col items-center gap-0.5 py-2 text-xs font-medium transition-all duration-200 relative",
isActive
? "text-sky-400"
: "text-muted-foreground hover:text-foreground",
)}
> >
<Icon className="size-5" /> <Icon className="size-5" />
{label} <span>{label}</span>
{isActive && (
<span className="absolute -top-px left-1/4 right-1/4 h-0.5 rounded-full bg-gradient-to-r from-sky-400 to-cyan-400" />
)}
</button> </button>
))} );
})}
</div> </div>
</nav> </nav>
); );
@@ -1,12 +1,29 @@
"use client"; "use client";
import { Radio } from "lucide-react"; import { type LucideIcon, Radio } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import {
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
Sidebar as SidebarPrimitive,
useSidebar,
} from "@/components/ui/sidebar";
import { type TabId, tabs } from "@/lib/tabs"; import { type TabId, tabs } from "@/lib/tabs";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
export function Sidebar({ activeTab }: { activeTab: TabId }) { export function Sidebar({ activeTab }: { activeTab: TabId }) {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const { state } = useSidebar();
const { status } = useWebSocket();
const collapsed = state === "collapsed";
const handleTabClick = (tabId: TabId) => { const handleTabClick = (tabId: TabId) => {
const params = new URLSearchParams(searchParams.toString()); const params = new URLSearchParams(searchParams.toString());
@@ -14,29 +31,111 @@ export function Sidebar({ activeTab }: { activeTab: TabId }) {
router.push(`/dashboard?${params}`); router.push(`/dashboard?${params}`);
}; };
return ( const connectionLabel = {
<aside className="hidden md:flex md:w-56 md:flex-col md:fixed md:inset-y-0 border-r bg-sidebar"> connected: "Connected",
<div className="flex h-14 items-center gap-2 border-b px-4"> connecting: "Connecting",
<div className="size-7 rounded-full bg-primary/10 flex items-center justify-center"> disconnected: "Disconnected",
<Radio className="size-4 text-primary" /> error: "Error",
</div> }[status];
<span className="font-semibold text-sm">Bete</span>
</div>
<nav className="flex-1 space-y-1 p-3"> const connectionColor = {
{tabs.map(({ id, label, icon: Icon }) => ( connected: "bg-green-500",
<button connecting: "bg-yellow-500",
key={id} disconnected: "bg-destructive",
type="button" error: "bg-destructive",
onClick={() => handleTabClick(id)} }[status];
data-active={activeTab === id ? "" : undefined}
className="w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground data-[active]:bg-sidebar-accent data-[active]:text-sidebar-accent-foreground" return (
<SidebarPrimitive variant="sidebar" collapsible="icon">
<SidebarHeader className="border-b border-sidebar-border/50">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="lg"
className="group-data-[collapsible=icon]:!p-0"
> >
<Icon className="size-4 shrink-0" /> <div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-gradient-to-br from-sky-500 to-cyan-400 text-sidebar-primary-foreground">
{label} <Radio className="size-4" />
</button> </div>
))} <div
</nav> className={cn(
</aside> "flex flex-col gap-0.5 leading-none",
collapsed && "hidden",
)}
>
<span className="text-base font-bold tracking-tight">
<span className="text-gradient">Bete</span>
</span>
<span className="text-[10px] text-muted-foreground tracking-widest uppercase">
Dashboard
</span>
</div>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<SidebarGroup>
<SidebarGroupContent>
<SidebarMenu>
{tabs.map(({ id, label, icon: Icon }) => {
const isActive = activeTab === id;
return (
<SidebarMenuItem key={id}>
<SidebarMenuButton
isActive={isActive}
onClick={() => handleTabClick(id)}
tooltip={collapsed ? label : undefined}
className={cn(
"relative transition-all duration-200",
isActive &&
"bg-sidebar-accent/80 text-sidebar-accent-foreground font-medium",
)}
>
<Icon
className={cn(
"size-4 transition-all duration-200",
isActive && "text-sky-400 scale-110",
)}
/>
<span>{label}</span>
{isActive && (
<div className="absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 rounded-full bg-gradient-to-b from-sky-400 to-cyan-400" />
)}
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
<SidebarFooter className="border-t border-sidebar-border/50 p-3">
<div className="flex items-center gap-2">
<span className="relative flex size-2 shrink-0">
<span
className={cn(
"absolute inline-flex size-full rounded-full opacity-75",
connectionColor,
status === "connected" && "animate-ping",
)}
/>
<span
className={cn(
"relative inline-flex size-2 rounded-full",
connectionColor,
)}
/>
</span>
{!collapsed && (
<span className="text-xs text-muted-foreground truncate">
{connectionLabel}
</span>
)}
</div>
</SidebarFooter>
</SidebarPrimitive>
); );
} }
@@ -195,7 +195,7 @@ function ChartTooltipContent({
<div className="grid gap-1.5"> <div className="grid gap-1.5">
{payload {payload
.filter((item) => item.type !== "none") .filter((item) => item.type !== "none")
.map((item) => { .map((item, index) => {
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`; const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key); const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color ?? item.payload?.fill ?? item.color; const indicatorColor = color ?? item.payload?.fill ?? item.color;
@@ -5,14 +5,23 @@ import {
ArrowLeft, ArrowLeft,
BarChart3, BarChart3,
ChevronRight, ChevronRight,
Clock,
Hash, Hash,
RefreshCw, RefreshCw,
Search, Search,
Shield, Shield,
Sparkles,
Users, Users,
} from "lucide-react"; } from "lucide-react";
import Image from "next/image"; import Image from "next/image";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { dashboardApi } from "@/lib/api"; import { dashboardApi } from "@/lib/api";
import type { import type {
DashboardChannel, DashboardChannel,
@@ -21,6 +30,7 @@ import type {
DashboardUser, DashboardUser,
DashboardUserDetail, DashboardUserDetail,
} from "@/lib/types"; } from "@/lib/types";
import { cn } from "@/lib/utils";
type View = "stats" | "users" | "channels" | "user-detail" | "channel-detail"; type View = "stats" | "users" | "channels" | "user-detail" | "channel-detail";
@@ -35,7 +45,7 @@ export function DashboardPanel({ guildId }: { guildId: string }) {
const renderView = () => { const renderView = () => {
switch (view) { switch (view) {
case "stats": case "stats":
return <StatsView onNavigate={(v) => setView(v)} />; return <StatsView />;
case "users": case "users":
return ( return (
<UsersView <UsersView
@@ -84,47 +94,42 @@ export function DashboardPanel({ guildId }: { guildId: string }) {
}; };
return ( return (
<div className="space-y-4"> <div className="space-y-5">
{/* Sub-navigation */} {/* Sub-navigation using shadcn Tabs */}
<div className="flex gap-1 rounded-lg border p-1 w-fit"> <Tabs
<button value={
onClick={() => setView("stats")} view === "user-detail"
data-active={view === "stats" ? "" : undefined} ? "users"
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted" : view === "channel-detail"
? "channels"
: view
}
onValueChange={(v) => setView(v as View)}
> >
<BarChart3 className="size-4 inline mr-1.5" /> <TabsList>
<TabsTrigger value="stats" onClick={() => setView("stats")}>
<BarChart3 className="size-4" />
Stats Stats
</button> </TabsTrigger>
<button <TabsTrigger value="users" onClick={() => setView("users")}>
onClick={() => setView("users")} <Users className="size-4" />
data-active={
view === "users" || view === "user-detail" ? "" : undefined
}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
<Users className="size-4 inline mr-1.5" />
Users Users
</button> </TabsTrigger>
<button <TabsTrigger value="channels" onClick={() => setView("channels")}>
onClick={() => setView("channels")} <Hash className="size-4" />
data-active={
view === "channels" || view === "channel-detail" ? "" : undefined
}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
<Hash className="size-4 inline mr-1.5" />
Channels Channels
</button> </TabsTrigger>
</div> </TabsList>
</Tabs>
{renderView()} {renderView()}
</div> </div>
); );
} }
// ── Stats View ──────────────────────────────────────────── // ── Stats View ──────────────────────────────────
function StatsView(_props: { onNavigate: (view: View) => void }) { function StatsView() {
const [stats, setStats] = useState<DashboardStats | null>(null); const [stats, setStats] = useState<DashboardStats | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -148,114 +153,136 @@ function StatsView(_props: { onNavigate: (view: View) => void }) {
if (error) { if (error) {
return ( return (
<div className="flex flex-col items-center justify-center py-16 text-center"> <div className="flex flex-col items-center justify-center py-20 text-center">
<AlertCircle className="size-8 text-destructive mb-2" /> <AlertCircle className="size-10 text-destructive mb-3" />
<p className="text-sm text-muted-foreground mb-4">{error}</p> <p className="text-sm text-muted-foreground mb-4 max-w-sm">{error}</p>
<button <Button variant="outline" onClick={fetchStats}>
onClick={fetchStats} <RefreshCw className="size-4 mr-2" />
className="inline-flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted transition-colors"
>
<RefreshCw className="size-4" />
Retry Retry
</button> </Button>
</div> </div>
); );
} }
return ( return (
<div className="space-y-4"> <div className="space-y-5 animate-fade-in-up">
{/* Metric cards */} {/* Metric cards */}
{loading ? ( {loading ? (
<div className="grid grid-cols-2 md:grid-cols-4 gap-3"> <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{Array.from({ length: 8 }, (_, i) => `stat-sk-${i}`).map((key) => ( {Array.from({ length: 8 }, (_, i) => (
<div key={key} className="rounded-lg border p-4 space-y-2"> <Skeleton key={i} className="h-28 rounded-xl" />
<div className="h-3 w-16 bg-muted rounded animate-pulse" />
<div className="h-8 w-20 bg-muted rounded animate-pulse" />
</div>
))} ))}
</div> </div>
) : stats ? ( ) : stats ? (
<> <>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3"> <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<MetricCard label="Total Messages" value={stats.total_messages} /> <StatCard
<MetricCard label="Today" value={stats.today_messages} /> label="Total Messages"
<MetricCard label="Users" value={stats.total_users} /> value={stats.total_messages}
<MetricCard label="Active 24h" value={stats.active_users_24h} /> icon={Hash}
<MetricCard />
<StatCard label="Today" value={stats.today_messages} icon={Clock} />
<StatCard label="Users" value={stats.total_users} icon={Users} />
<StatCard
label="Active 24h"
value={stats.active_users_24h}
icon={Sparkles}
/>
<StatCard
label="Flagged" label="Flagged"
value={stats.total_flagged} value={stats.total_flagged}
variant="destructive" variant="danger"
icon={AlertCircle}
/> />
<MetricCard <StatCard
label="Clean" label="Clean"
value={stats.total_clean} value={stats.total_clean}
variant="success" variant="success"
icon={Shield}
/> />
<MetricCard <StatCard
label="Voice Recordings" label="Voice Recordings"
value={stats.total_voice_recordings} value={stats.total_voice_recordings}
icon={Hash}
/>
<StatCard
label="AI Profiles"
value={stats.total_profiles}
icon={Sparkles}
/> />
<MetricCard label="AI Profiles" value={stats.total_profiles} />
</div> </div>
{/* Top Channels + Moderation Queue */} {/* Top Channels + Moderation Queue */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="rounded-lg border p-4 space-y-3"> <Card>
<h3 className="text-sm font-semibold flex items-center gap-2"> <CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Hash className="size-4 text-muted-foreground" /> <Hash className="size-4 text-muted-foreground" />
Top Channels Top Channels
</h3> </CardTitle>
</CardHeader>
<CardContent>
{stats.top_channels.length === 0 ? ( {stats.top_channels.length === 0 ? (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground py-6 text-center">
No channel data yet. No channel data yet.
</p> </p>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
{stats.top_channels.map((ch) => ( {stats.top_channels.map((ch, i) => {
<div const maxCount = stats.top_channels[0].message_count;
key={ch.channel_id} const pct =
className="flex items-center justify-between" maxCount > 0 ? (ch.message_count / maxCount) * 100 : 0;
> return (
<span className="text-sm truncate"> <div key={ch.channel_id} className="space-y-1">
<div className="flex items-center justify-between text-sm">
<span className="truncate font-medium">
#{ch.channel_name ?? ch.channel_id.slice(0, 8)} #{ch.channel_name ?? ch.channel_id.slice(0, 8)}
</span> </span>
<span className="text-sm font-semibold"> <span className="text-muted-foreground tabular-nums">
{formatNumber(ch.message_count)} {formatNumber(ch.message_count)}
</span> </span>
</div> </div>
))} <Progress value={pct} className="h-1.5" />
</div>
);
})}
</div> </div>
)} )}
</div> </CardContent>
</Card>
<div className="rounded-lg border p-4 space-y-3"> <Card>
<h3 className="text-sm font-semibold flex items-center gap-2"> <CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Shield className="size-4 text-muted-foreground" /> <Shield className="size-4 text-muted-foreground" />
Moderation Queue Moderation Queue
</h3> </CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-3"> <div className="grid grid-cols-3 gap-3">
<div className="rounded-lg bg-muted p-3 text-center space-y-1"> <div className="rounded-lg bg-muted/50 p-3 text-center space-y-1.5">
<div className="text-2xl font-semibold"> <div className="text-2xl font-bold tabular-nums">
{stats.moderation_overview.pending} {stats.moderation_overview.pending}
</div> </div>
<div className="text-xs text-muted-foreground">Pending</div> <div className="text-xs text-muted-foreground">Pending</div>
</div> </div>
<div className="rounded-lg bg-yellow-500/10 p-3 text-center space-y-1"> <div className="rounded-lg bg-yellow-500/10 p-3 text-center space-y-1.5">
<div className="text-2xl font-semibold text-yellow-600 dark:text-yellow-400"> <div className="text-2xl font-bold tabular-nums text-yellow-500">
{stats.moderation_overview.processing} {stats.moderation_overview.processing}
</div> </div>
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
Processing Processing
</div> </div>
</div> </div>
<div className="rounded-lg bg-destructive/10 p-3 text-center space-y-1"> <div className="rounded-lg bg-destructive/10 p-3 text-center space-y-1.5">
<div className="text-2xl font-semibold text-destructive"> <div className="text-2xl font-bold tabular-nums text-destructive">
{stats.moderation_overview.error} {stats.moderation_overview.error}
</div> </div>
<div className="text-xs text-muted-foreground">Errors</div> <div className="text-xs text-muted-foreground">Errors</div>
</div> </div>
</div> </div>
</div> </CardContent>
</Card>
</div> </div>
</> </>
) : null} ) : null}
@@ -263,32 +290,52 @@ function StatsView(_props: { onNavigate: (view: View) => void }) {
); );
} }
function MetricCard({ function StatCard({
label, label,
value, value,
variant, variant,
icon: Icon,
}: { }: {
label: string; label: string;
value: number; value: number;
variant?: "default" | "destructive" | "success"; variant?: "default" | "danger" | "success";
icon: React.ComponentType<{ className?: string }>;
}) { }) {
const colorMap = {
default: "",
destructive: "text-destructive",
success: "text-green-600 dark:text-green-400",
};
return ( return (
<div className="rounded-lg border p-4 space-y-1"> <Card>
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div className="space-y-1.5">
<p className="text-xs text-muted-foreground">{label}</p> <p className="text-xs text-muted-foreground">{label}</p>
<p className={`text-2xl font-semibold ${colorMap[variant ?? "default"]}`}> <p
className={cn(
"text-2xl font-bold tabular-nums tracking-tight",
variant === "danger" && "text-destructive",
variant === "success" && "text-green-500",
)}
>
{formatNumber(value)} {formatNumber(value)}
</p> </p>
</div> </div>
<div
className={cn(
"flex size-9 shrink-0 items-center justify-center rounded-lg",
variant === "danger"
? "bg-destructive/10 text-destructive"
: variant === "success"
? "bg-green-500/10 text-green-500"
: "bg-primary/10 text-primary",
)}
>
<Icon className="size-4" />
</div>
</div>
</CardContent>
</Card>
); );
} }
// ── Users View ──────────────────────────────────────────── // ── Users View ──────────────────────────────────
function UsersView({ function UsersView({
onSelectUser, onSelectUser,
@@ -326,42 +373,41 @@ function UsersView({
}, [search, fetchUsers]); }, [search, fetchUsers]);
return ( return (
<div className="space-y-3"> <div className="space-y-4 animate-fade-in-up">
<div className="relative"> <div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<input <Input
type="text" type="text"
placeholder="Search users…" placeholder="Search users…"
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
className="w-full h-9 rounded-lg border border-input bg-background pl-9 pr-3 text-sm" className="pl-9 h-9"
/> />
</div> </div>
{loading ? ( {loading ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3"> <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Array.from({ length: 6 }, (_, i) => `user-sk-${i}`).map((key) => ( {Array.from({ length: 6 }, (_, i) => (
<div key={key} className="rounded-lg border p-4 space-y-2"> <Skeleton key={i} className="h-20 rounded-xl" />
<div className="flex items-center gap-3">
<div className="size-10 rounded-full bg-muted animate-pulse" />
<div className="flex-1 space-y-1">
<div className="h-4 w-24 bg-muted rounded animate-pulse" />
<div className="h-3 w-16 bg-muted rounded animate-pulse" />
</div>
</div>
</div>
))} ))}
</div> </div>
) : ( ) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3"> <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{users.map((user) => ( {users.length === 0 ? (
<button <div className="col-span-full flex flex-col items-center justify-center py-16 text-center">
<Users className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground">No users found.</p>
</div>
) : (
users.map((user) => (
<Card
key={user.user_id} key={user.user_id}
className="cursor-pointer hover:bg-accent/5 transition-colors"
onClick={() => onSelectUser(user.user_id)} onClick={() => onSelectUser(user.user_id)}
className="rounded-lg border p-4 text-left hover:bg-muted/50 transition-colors"
> >
<CardContent className="p-3">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="size-10 shrink-0 rounded-full bg-muted flex items-center justify-center text-sm font-medium overflow-hidden"> <div className="size-10 shrink-0 rounded-full bg-muted flex items-center justify-center text-sm font-medium overflow-hidden ring-1 ring-border">
{user.avatar_url ? ( {user.avatar_url ? (
<Image <Image
src={user.avatar_url} src={user.avatar_url}
@@ -378,26 +424,31 @@ function UsersView({
<p className="text-sm font-medium truncate"> <p className="text-sm font-medium truncate">
{user.username ?? "Unknown"} {user.username ?? "Unknown"}
</p> </p>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground flex items-center gap-2">
{user.total_messages} msgs <span>{user.total_messages} messages</span>
{user.flagged_count > 0 && ( {user.flagged_count > 0 && (
<span className="text-destructive ml-2"> <Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{user.flagged_count} flagged {user.flagged_count} flagged
</span> </Badge>
)} )}
</p> </p>
</div> </div>
<ChevronRight className="size-4 text-muted-foreground shrink-0" /> <ChevronRight className="size-4 text-muted-foreground shrink-0" />
</div> </div>
</button> </CardContent>
))} </Card>
))
)}
</div> </div>
)} )}
</div> </div>
); );
} }
// ── Channels View ───────────────────────────────────────── // ── Channels View ───────────────────────────────
function ChannelsView({ function ChannelsView({
onSelectChannel, onSelectChannel,
@@ -442,65 +493,79 @@ function ChannelsView({
}, [search, fetchChannels]); }, [search, fetchChannels]);
return ( return (
<div className="space-y-3"> <div className="space-y-4 animate-fade-in-up">
<div className="relative"> <div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<input <Input
type="text" type="text"
placeholder="Search channels…" placeholder="Search channels…"
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
className="w-full h-9 rounded-lg border border-input bg-background pl-9 pr-3 text-sm" className="pl-9 h-9"
/> />
</div> </div>
{loading ? ( {loading ? (
<div className="space-y-2"> <div className="space-y-2">
{Array.from({ length: 6 }, (_, i) => `ch-sk-${i}`).map((key) => ( {Array.from({ length: 6 }, (_, i) => (
<div key={key} className="rounded-lg border p-4 space-y-2"> <Skeleton key={i} className="h-20 rounded-xl" />
<div className="h-4 w-32 bg-muted rounded animate-pulse" />
<div className="h-3 w-24 bg-muted rounded animate-pulse" />
</div>
))} ))}
</div> </div>
) : ( ) : (
<div className="space-y-2"> <div className="space-y-2">
{channels.map((ch) => ( {channels.length === 0 ? (
<button <div className="flex flex-col items-center justify-center py-16 text-center">
key={ch.channel_id} <Hash className="size-10 text-muted-foreground/40 mb-3" />
onClick={() => onSelectChannel(ch.channel_id)} <p className="text-sm text-muted-foreground">
className="w-full rounded-lg border p-4 text-left hover:bg-muted/50 transition-colors" No channels found.
>
<div className="flex items-center justify-between">
<div className="min-w-0">
<p className="text-sm font-medium truncate">
#{ch.channel_name ?? ch.channel_id.slice(0, 8)}
</p> </p>
<p className="text-xs text-muted-foreground"> </div>
{ch.total_messages} messages ) : (
channels.map((ch) => (
<Card
key={ch.channel_id}
className="cursor-pointer hover:bg-accent/5 transition-colors"
onClick={() => onSelectChannel(ch.channel_id)}
>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<Hash className="size-3.5 text-muted-foreground shrink-0" />
<p className="text-sm font-medium truncate">
{ch.channel_name ?? ch.channel_id.slice(0, 8)}
</p>
</div>
<p className="text-xs text-muted-foreground mt-0.5 flex items-center gap-2">
<span>{ch.total_messages} messages</span>
{ch.flagged_count > 0 && ( {ch.flagged_count > 0 && (
<span className="text-destructive ml-2"> <Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{ch.flagged_count} flagged {ch.flagged_count} flagged
</span> </Badge>
)} )}
</p> </p>
</div> </div>
<ChevronRight className="size-4 text-muted-foreground shrink-0" /> <ChevronRight className="size-4 text-muted-foreground shrink-0 ml-2" />
</div> </div>
{ch.culture_summary && ( {ch.culture_summary && (
<p className="text-xs text-muted-foreground mt-2 italic line-clamp-2"> <p className="text-xs text-muted-foreground/70 mt-2 italic line-clamp-2 border-t border-border/50 pt-2">
{ch.culture_summary} "{ch.culture_summary}"
</p> </p>
)} )}
</button> </CardContent>
))} </Card>
))
)}
</div> </div>
)} )}
</div> </div>
); );
} }
// ── User Detail View ────────────────────────────────────── // ── User Detail View ────────────────────────────
function UserDetailView({ function UserDetailView({
user, user,
@@ -510,35 +575,37 @@ function UserDetailView({
onBack: () => void; onBack: () => void;
}) { }) {
return ( return (
<div className="space-y-4"> <div className="space-y-5 animate-fade-in-up">
<button <div className="flex items-center gap-3">
onClick={onBack} <Button variant="ghost" size="sm" onClick={onBack}>
className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors" <ArrowLeft className="size-4 mr-1" />
> Back
<ArrowLeft className="size-4" /> </Button>
Back to users </div>
</button>
<div className="rounded-lg border p-6 space-y-4"> <Card>
<CardContent className="p-6 space-y-5">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<div className="size-16 rounded-full bg-muted flex items-center justify-center text-xl font-medium overflow-hidden"> <div className="size-14 shrink-0 rounded-full bg-muted flex items-center justify-center text-xl font-medium overflow-hidden ring-2 ring-border">
{user.avatar_url ? ( {user.avatar_url ? (
<Image <Image
src={user.avatar_url} src={user.avatar_url}
alt="" alt=""
width={64} width={56}
height={64} height={56}
className="size-full object-cover" className="size-full object-cover"
/> />
) : ( ) : (
(user.username ?? "?").charAt(0).toUpperCase() (user.username ?? "?").charAt(0).toUpperCase()
)} )}
</div> </div>
<div> <div className="min-w-0">
<h2 className="text-xl font-semibold"> <h2 className="text-lg font-semibold">
{user.username ?? "Unknown"} {user.username ?? "Unknown"}
</h2> </h2>
<p className="text-sm text-muted-foreground">#{user.user_id}</p> <p className="text-sm text-muted-foreground font-mono text-xs">
{user.user_id}
</p>
</div> </div>
</div> </div>
@@ -547,7 +614,7 @@ function UserDetailView({
<DetailStat <DetailStat
label="Flagged" label="Flagged"
value={user.flagged_count} value={user.flagged_count}
variant="destructive" variant="danger"
/> />
<DetailStat <DetailStat
label="Clean Streak" label="Clean Streak"
@@ -561,32 +628,46 @@ function UserDetailView({
</div> </div>
{user.profile_summary && ( {user.profile_summary && (
<div className="rounded-lg bg-muted/50 p-3"> <div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
<p className="text-xs text-muted-foreground mb-1">AI Profile</p> <div className="flex items-center gap-2 mb-2">
<p className="text-sm">{user.profile_summary}</p> <Sparkles className="size-4 text-primary" />
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider">
AI Profile
</p>
</div>
<p className="text-sm leading-relaxed">{user.profile_summary}</p>
</div> </div>
)} )}
{/* Recent messages */}
{user.recent_messages.length > 0 && ( {user.recent_messages.length > 0 && (
<div className="space-y-3"> <div className="space-y-3">
<h3 className="text-sm font-semibold">Recent Messages</h3> <h3 className="text-sm font-semibold flex items-center gap-2">
<Clock className="size-4 text-muted-foreground" />
Recent Messages
</h3>
<div className="space-y-2 max-h-80 overflow-y-auto">
{user.recent_messages.slice(0, 5).map((msg) => ( {user.recent_messages.slice(0, 5).map((msg) => (
<div key={msg.id} className="rounded-lg border p-3"> <div
<p className="text-xs text-muted-foreground mb-1"> key={msg.id}
className="rounded-lg border border-border/50 bg-muted/20 p-3 text-sm"
>
<p className="text-xs text-muted-foreground mb-1 flex items-center gap-2">
<Clock className="size-3" />
{new Date(msg.created_at).toLocaleString()} {new Date(msg.created_at).toLocaleString()}
</p> </p>
<p className="text-sm">{msg.content}</p> <p className="text-sm">{msg.content}</p>
</div> </div>
))} ))}
</div> </div>
)}
</div> </div>
)}
</CardContent>
</Card>
</div> </div>
); );
} }
// ── Channel Detail View ─────────────────────────────────── // ── Channel Detail View ─────────────────────────
function ChannelDetailView({ function ChannelDetailView({
channel, channel,
@@ -596,21 +677,24 @@ function ChannelDetailView({
onBack: () => void; onBack: () => void;
}) { }) {
return ( return (
<div className="space-y-4"> <div className="space-y-5 animate-fade-in-up">
<button <div className="flex items-center gap-3">
onClick={onBack} <Button variant="ghost" size="sm" onClick={onBack}>
className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors" <ArrowLeft className="size-4 mr-1" />
> Back
<ArrowLeft className="size-4" /> </Button>
Back to channels </div>
</button>
<div className="rounded-lg border p-6 space-y-4"> <Card>
<CardContent className="p-6 space-y-5">
<div> <div>
<h2 className="text-xl font-semibold"> <h2 className="text-lg font-semibold flex items-center gap-2">
#{channel.channel_name ?? channel.channel_id.slice(0, 8)} <Hash className="size-5 text-muted-foreground" />
{channel.channel_name ?? channel.channel_id.slice(0, 8)}
</h2> </h2>
<p className="text-sm text-muted-foreground">{channel.channel_id}</p> <p className="text-xs text-muted-foreground font-mono mt-0.5">
{channel.channel_id}
</p>
</div> </div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3"> <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
@@ -618,7 +702,7 @@ function ChannelDetailView({
<DetailStat <DetailStat
label="Flagged" label="Flagged"
value={channel.flagged_count} value={channel.flagged_count}
variant="destructive" variant="danger"
/> />
<DetailStat <DetailStat
label="Clean" label="Clean"
@@ -628,21 +712,35 @@ function ChannelDetailView({
</div> </div>
{channel.culture_summary && ( {channel.culture_summary && (
<div className="rounded-lg bg-muted/50 p-3"> <div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
<p className="text-xs text-muted-foreground mb-1"> <div className="flex items-center gap-2 mb-2">
<Sparkles className="size-4 text-primary" />
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider">
Channel Culture Channel Culture
</p> </p>
<p className="text-sm">{channel.culture_summary}</p> </div>
<p className="text-sm leading-relaxed italic">
"{channel.culture_summary}"
</p>
</div> </div>
)} )}
{channel.recent_messages.length > 0 && ( {channel.recent_messages.length > 0 && (
<div className="space-y-3"> <div className="space-y-3">
<h3 className="text-sm font-semibold">Recent Messages</h3> <h3 className="text-sm font-semibold flex items-center gap-2">
<Clock className="size-4 text-muted-foreground" />
Recent Messages
</h3>
<div className="space-y-2">
{channel.recent_messages.slice(0, 5).map((msg) => ( {channel.recent_messages.slice(0, 5).map((msg) => (
<div key={msg.id} className="rounded-lg border p-3"> <div
key={msg.id}
className="rounded-lg border border-border/50 bg-muted/20 p-3 text-sm"
>
<div className="flex items-center gap-2 mb-1"> <div className="flex items-center gap-2 mb-1">
<span className="text-sm font-medium">{msg.username}</span> <span className="text-sm font-medium">
{msg.username}
</span>
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
{new Date(msg.created_at).toLocaleString()} {new Date(msg.created_at).toLocaleString()}
</span> </span>
@@ -651,13 +749,15 @@ function ChannelDetailView({
</div> </div>
))} ))}
</div> </div>
)}
</div> </div>
)}
</CardContent>
</Card>
</div> </div>
); );
} }
// ── Shared Components ───────────────────────────────────── // ── Shared Components ───────────────────────────
function DetailStat({ function DetailStat({
label, label,
@@ -667,27 +767,29 @@ function DetailStat({
}: { }: {
label: string; label: string;
value: number; value: number;
variant?: "default" | "destructive" | "success"; variant?: "default" | "danger" | "success";
suffix?: string; suffix?: string;
}) { }) {
const colorMap = {
default: "",
destructive: "text-destructive",
success: "text-green-600 dark:text-green-400",
};
return ( return (
<div className="rounded-lg border p-3"> <Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground">{label}</p> <p className="text-xs text-muted-foreground">{label}</p>
<p className={`text-lg font-semibold ${colorMap[variant ?? "default"]}`}> <p
className={cn(
"text-lg font-bold tabular-nums",
variant === "danger" && "text-destructive",
variant === "success" && "text-green-500",
)}
>
{formatNumber(value)} {formatNumber(value)}
{suffix} {suffix}
</p> </p>
</div> </CardContent>
</Card>
); );
} }
// ── Helpers ─────────────────────────────────────────────── // ── Helpers ─────────────────────────────────────
function formatNumber(n: number): string { function formatNumber(n: number): string {
return n.toLocaleString(); return n.toLocaleString();
+237 -176
View File
@@ -3,19 +3,35 @@
import { import {
Disc3, Disc3,
Download, Download,
Headphones,
Loader2, Loader2,
Mic, Mic,
MicOff, Music,
Play, Play,
Radio, Radio,
RadioOff, RadioOff,
SkipForward, SkipForward,
Square, Square,
Trash2, Trash2,
UserCheck,
Volume2, Volume2,
} from "lucide-react"; } from "lucide-react";
import Image from "next/image"; import Image from "next/image";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { recordingsApi, voiceApi } from "@/lib/api"; import { recordingsApi, voiceApi } from "@/lib/api";
import type { import type {
ActiveSpeaker, ActiveSpeaker,
@@ -23,6 +39,7 @@ import type {
VoiceRecording, VoiceRecording,
VoiceStatus, VoiceStatus,
} from "@/lib/types"; } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context"; import { useWebSocket } from "@/lib/ws/context";
export function LivePanel() { export function LivePanel() {
@@ -86,7 +103,6 @@ export function LivePanel() {
fetchRecordings(); fetchRecordings();
}, [fetchVoiceStatus, fetchGuilds, fetchRecordings]); }, [fetchVoiceStatus, fetchGuilds, fetchRecordings]);
// Media status
const fetchMediaStatus = useCallback(async () => { const fetchMediaStatus = useCallback(async () => {
try { try {
const state = await voiceApi.getMediaStatus(); const state = await voiceApi.getMediaStatus();
@@ -130,14 +146,14 @@ export function LivePanel() {
}; };
}, [ws]); }, [ws]);
// Voice connect handler const handleGuildChange = useCallback(async (guildId: string | null) => {
const handleGuildChange = useCallback(async (guildId: string) => {
setSelectedGuild(guildId);
setSelectedChannel("");
if (!guildId) { if (!guildId) {
setSelectedGuild("");
setVoiceChannels([]); setVoiceChannels([]);
return; return;
} }
setSelectedGuild(guildId);
setSelectedChannel("");
try { try {
const channels = await voiceApi.getVoiceChannels(guildId); const channels = await voiceApi.getVoiceChannels(guildId);
setVoiceChannels(channels); setVoiceChannels(channels);
@@ -145,6 +161,7 @@ export function LivePanel() {
setVoiceChannels([]); setVoiceChannels([]);
} }
}, []); }, []);
const handleConnect = useCallback(async () => { const handleConnect = useCallback(async () => {
if (!selectedGuild || !selectedChannel) return; if (!selectedGuild || !selectedChannel) return;
setVoiceLoading(true); setVoiceLoading(true);
@@ -166,7 +183,6 @@ export function LivePanel() {
} }
}, []); }, []);
// Media handlers
const handleQueueMedia = useCallback(async () => { const handleQueueMedia = useCallback(async () => {
if (!queueUrl.trim()) return; if (!queueUrl.trim()) return;
try { try {
@@ -196,16 +212,19 @@ export function LivePanel() {
} }
}, []); }, []);
const handleVolume = useCallback(async (volume: number) => { const handleVolume = useCallback(
async (value: number | readonly number[]) => {
const vol = Array.isArray(value) ? value[0] : value;
try { try {
const state = await voiceApi.mediaVolume(volume); const state = await voiceApi.mediaVolume(vol);
setMediaState(state); setMediaState(state);
} catch { } catch {
// ignore // ignore
} }
}, []); },
[],
);
// Delete recording
const handleDeleteRecording = useCallback(async (id: string) => { const handleDeleteRecording = useCallback(async (id: string) => {
try { try {
await recordingsApi.delete(id); await recordingsApi.delete(id);
@@ -216,27 +235,38 @@ export function LivePanel() {
}, []); }, []);
return ( return (
<div className="space-y-6"> <div className="space-y-5 animate-fade-in-up">
{/* Voice Connection */} {/* Voice Connection */}
<div className="rounded-lg border p-4 space-y-4"> <Card>
<div className="flex items-center justify-between"> <CardHeader>
<h2 className="text-sm font-semibold flex items-center gap-2"> <CardTitle className="flex items-center justify-between">
<Radio className="size-4" /> <div className="flex items-center gap-2">
<Radio className="size-4 text-primary" />
Voice Connection Voice Connection
</h2>
<span
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
voiceStatus?.connected
? "bg-green-500/15 text-green-600 dark:text-green-400"
: "bg-muted text-muted-foreground"
}`}
>
{voiceStatus?.connected ? "Connected" : "Disconnected"}
</span>
</div> </div>
<Badge
variant={voiceStatus?.connected ? "default" : "secondary"}
className={cn(
voiceStatus?.connected &&
"bg-green-500/15 text-green-600 dark:text-green-400 hover:bg-green-500/20",
)}
>
<span
className={cn(
"size-1.5 rounded-full mr-1.5 inline-block",
voiceStatus?.connected
? "bg-green-500 shadow-[0_0_6px] shadow-green-500/60"
: "bg-muted-foreground",
)}
/>
{voiceStatus?.connected ? "Connected" : "Disconnected"}
</Badge>
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{voiceStatus?.connected && voiceStatus.activeChannelName && ( {voiceStatus?.connected && voiceStatus.activeChannelName && (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground flex items-center gap-1.5">
<Headphones className="size-4" />
Connected to{" "} Connected to{" "}
<span className="font-medium text-foreground"> <span className="font-medium text-foreground">
{voiceStatus.activeChannelName} {voiceStatus.activeChannelName}
@@ -245,129 +275,140 @@ export function LivePanel() {
)} )}
<div className="flex flex-col sm:flex-row gap-2"> <div className="flex flex-col sm:flex-row gap-2">
<select <Select value={selectedGuild} onValueChange={handleGuildChange}>
value={selectedGuild} <SelectTrigger className="flex-1 h-9">
onChange={(e) => handleGuildChange(e.target.value)} <SelectValue placeholder="Select guild…" />
className="flex-1 h-9 rounded-lg border border-input bg-background px-3 text-sm" </SelectTrigger>
> <SelectContent>
<option value="">Select guild</option>
{guilds.map((g) => ( {guilds.map((g) => (
<option key={g.id} value={g.id}> <SelectItem key={g.id} value={g.id}>
{g.name} {g.name}
</option> </SelectItem>
))} ))}
</select> </SelectContent>
<select </Select>
<Select
value={selectedChannel} value={selectedChannel}
onChange={(e) => setSelectedChannel(e.target.value)} onValueChange={(v) => v && setSelectedChannel(v)}
className="flex-1 h-9 rounded-lg border border-input bg-background px-3 text-sm"
> >
<option value="">Select channel</option> <SelectTrigger className="flex-1 h-9">
<SelectValue placeholder="Select channel…" />
</SelectTrigger>
<SelectContent>
{voiceChannels.map((c) => ( {voiceChannels.map((c) => (
<option key={c.id} value={c.id}> <SelectItem key={c.id} value={c.id}>
{c.name} {c.name}
</option> </SelectItem>
))} ))}
</select> </SelectContent>
</Select>
{voiceStatus?.connected ? ( {voiceStatus?.connected ? (
<button <Button
variant="destructive"
onClick={handleDisconnect} onClick={handleDisconnect}
disabled={voiceLoading} disabled={voiceLoading}
className="inline-flex items-center gap-2 rounded-lg bg-destructive px-4 py-1.5 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 transition-colors disabled:opacity-50"
> >
{voiceLoading ? ( {voiceLoading ? (
<Loader2 className="size-4 animate-spin" /> <Loader2 className="size-4 animate-spin mr-1.5" />
) : ( ) : (
<RadioOff className="size-4" /> <RadioOff className="size-4 mr-1.5" />
)} )}
Disconnect Disconnect
</button> </Button>
) : ( ) : (
<button <Button
onClick={handleConnect} onClick={handleConnect}
disabled={voiceLoading || !selectedGuild || !selectedChannel} disabled={voiceLoading || !selectedGuild || !selectedChannel}
className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
> >
{voiceLoading ? ( {voiceLoading ? (
<Loader2 className="size-4 animate-spin" /> <Loader2 className="size-4 animate-spin mr-1.5" />
) : ( ) : (
<Radio className="size-4" /> <Radio className="size-4 mr-1.5" />
)} )}
Connect Connect
</button> </Button>
)} )}
</div> </div>
</div> </CardContent>
</Card>
{/* Active Speakers */} {/* Active Speakers */}
{speakers.filter((s) => s.speaking).length > 0 && ( {speakers.filter((s) => s.speaking).length > 0 && (
<div className="rounded-lg border p-4 space-y-3"> <Card>
<h3 className="text-sm font-semibold">Active Speakers</h3> <CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<UserCheck className="size-4 text-primary" />
Active Speakers
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{speakers {speakers
.filter((s) => s.speaking) .filter((s) => s.speaking)
.map((s) => ( .map((s) => (
<div <div
key={s.userId} key={s.userId}
className="flex items-center gap-2 rounded-full border bg-muted/50 px-3 py-1.5" className="flex items-center gap-2 rounded-full border border-border/50 bg-card px-3 py-1.5 shadow-sm"
> >
<span className="relative flex size-2"> <span className="relative flex size-2">
<span className="animate-ping absolute inline-flex size-full rounded-full bg-green-400 opacity-75" /> <span className="absolute inline-flex size-full rounded-full bg-green-400 opacity-75 live-pulse-ring" />
<span className="relative inline-flex size-2 rounded-full bg-green-500" /> <span className="relative inline-flex size-2 rounded-full bg-green-500" />
</span> </span>
<span className="text-sm">{s.username}</span> <span className="text-sm">{s.username}</span>
</div> </div>
))} ))}
</div> </div>
</div> </CardContent>
</Card>
)} )}
{/* Music Player */} {/* Music Player */}
<div className="rounded-lg border p-4 space-y-4"> <Card>
<h2 className="text-sm font-semibold flex items-center gap-2"> <CardHeader>
<Disc3 className="size-4" /> <CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Music className="size-4 text-primary" />
Music Player Music Player
</h2> </CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Queue URL */} {/* Queue URL */}
<div className="flex gap-2"> <div className="flex gap-2">
<input <Input
type="text" type="text"
placeholder="Queue a URL (YouTube, audio file…)" placeholder="Queue a URL (YouTube, audio file…)"
value={queueUrl} value={queueUrl}
onChange={(e) => setQueueUrl(e.target.value)} onChange={(e) => setQueueUrl(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleQueueMedia()} onKeyDown={(e) => e.key === "Enter" && handleQueueMedia()}
className="flex-1 h-9 rounded-lg border border-input bg-background px-3 text-sm" className="flex-1 h-9"
/> />
<button <Button onClick={handleQueueMedia} disabled={!queueUrl.trim()}>
onClick={handleQueueMedia} <Play className="size-4 mr-1.5" />
disabled={!queueUrl.trim()}
className="inline-flex items-center gap-2 rounded-lg bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
>
<Play className="size-4" />
Queue Queue
</button> </Button>
</div> </div>
{/* Now Playing */} {/* Now Playing */}
{mediaState?.current && ( {mediaState?.current && (
<div className="rounded-lg bg-muted/50 p-3 space-y-2"> <div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4 space-y-2">
<p className="text-xs text-muted-foreground">Now Playing</p> <p className="text-xs text-muted-foreground font-medium uppercase tracking-wider flex items-center gap-1.5">
<Disc3 className="size-3" />
Now Playing
</p>
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
{mediaState.current.thumbnailUrl && ( {mediaState.current.thumbnailUrl && (
<Image <Image
src={mediaState.current.thumbnailUrl} src={mediaState.current.thumbnailUrl}
alt="" alt=""
width={48} width={56}
height={48} height={56}
className="size-12 rounded object-cover" className="size-14 rounded-lg object-cover shadow-sm"
/> />
)} )}
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate"> <p className="text-sm font-medium truncate">
{mediaState.current.title ?? mediaState.current.source} {mediaState.current.title ?? mediaState.current.source}
</p> </p>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground mt-0.5">
{mediaState.current.durationMs {mediaState.current.durationMs
? `${Math.floor(mediaState.current.durationMs / 60000)}:${String( ? `${Math.floor(mediaState.current.durationMs / 60000)}:${String(
Math.floor( Math.floor(
@@ -383,148 +424,168 @@ export function LivePanel() {
{/* Controls */} {/* Controls */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <Button variant="outline" size="sm" onClick={handleStop}>
onClick={handleStop} <Square className="size-4 mr-1" />
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium hover:bg-muted transition-colors"
>
<Square className="size-4" />
Stop Stop
</button> </Button>
<button <Button variant="outline" size="sm" onClick={handleSkip}>
onClick={handleSkip} <SkipForward className="size-4 mr-1" />
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium hover:bg-muted transition-colors"
>
<SkipForward className="size-4" />
Skip Skip
</button> </Button>
<div className="flex items-center gap-2 ml-auto"> <div className="flex items-center gap-2 ml-auto">
<Volume2 className="size-4 text-muted-foreground" /> <Volume2 className="size-4 text-muted-foreground" />
<input <Slider
type="range" className="w-24"
min="0" defaultValue={[mediaState?.musicVolume ?? 0.5]}
max="1" value={[mediaState?.musicVolume ?? 0.5]}
step="0.05" onValueChange={handleVolume}
value={mediaState?.musicVolume ?? 0.5} min={0}
onChange={(e) => handleVolume(Number(e.target.value))} max={1}
className="w-24 h-2" step={0.05}
/> />
</div> </div>
</div> </div>
{/* Queue */} {/* Queue */}
{mediaState && mediaState.queue.length > 0 && ( {mediaState && mediaState.queue.length > 0 && (
<div className="space-y-1"> <div className="space-y-1.5">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground font-medium">
Queue ({mediaState.queue.length}) Queue ({mediaState.queue.length})
</p> </p>
<div className="space-y-1">
{mediaState.queue.map((item, i) => ( {mediaState.queue.map((item, i) => (
<div <div
key={item.id ?? i} key={item.id ?? i}
className="flex items-center gap-2 rounded-md bg-muted/30 px-3 py-2" className="flex items-center gap-2 rounded-md bg-muted/30 px-3 py-2 text-sm"
> >
<span className="text-xs text-muted-foreground w-4"> <span className="text-xs text-muted-foreground font-mono w-5 text-right">
{i + 1}. {i + 1}.
</span> </span>
<span className="text-sm truncate flex-1"> <span className="truncate flex-1">
{item.title ?? item.source} {item.title ?? item.source}
</span> </span>
</div> </div>
))} ))}
</div> </div>
)}
</div> </div>
)}
</CardContent>
</Card>
{/* Recordings */} {/* Microphone */}
<div className="rounded-lg border p-4 space-y-3"> <Card>
<h2 className="text-sm font-semibold">Voice Recordings</h2> <CardHeader>
{recordings.length === 0 ? ( <CardTitle className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">No recordings yet.</p> <div className="flex items-center gap-2 text-sm font-semibold">
) : ( <Mic className="size-4 text-primary" />
<div className="space-y-2">
{recordings.map((rec) => (
<div
key={rec.id}
className="flex items-center gap-3 rounded-lg border p-3"
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{rec.username}</p>
<p className="text-xs text-muted-foreground">
{rec.channel_name ?? rec.channel_id ?? "Unknown channel"}
{" — "}
{new Date(rec.created_at).toLocaleString()}
</p>
</div>
<span className="text-xs text-muted-foreground whitespace-nowrap">
{formatBytes(rec.size_bytes)}
</span>
{rec.download_url && (
<a
href={rec.download_url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center rounded-md border p-1.5 hover:bg-muted transition-colors"
>
<Download className="size-4" />
</a>
)}
<button
onClick={() => handleDeleteRecording(rec.id)}
className="inline-flex items-center rounded-md border p-1.5 hover:bg-destructive/10 hover:text-destructive transition-colors"
>
<Trash2 className="size-4" />
</button>
</div>
))}
</div>
)}
</div>
{/* Microphone Transmit */}
<div className="rounded-lg border p-4 space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold flex items-center gap-2">
<Mic className="size-4" />
Microphone Microphone
</h2> </div>
<button <div className="flex items-center gap-2">
type="button" <span className="text-xs text-muted-foreground">
onClick={async () => { {micActive ? "On" : "Off"}
setMicActive(!micActive); </span>
<Switch
checked={micActive}
onCheckedChange={async (checked) => {
setMicActive(checked);
try { try {
await voiceApi.sendCommand( await voiceApi.sendCommand(
micActive ? "voice:transmit:stop" : "voice:transmit:start", checked ? "voice:transmit:start" : "voice:transmit:stop",
); );
} catch { } catch {
setMicActive(micActive); setMicActive(!checked);
} }
}} }}
disabled={!voiceStatus?.connected} disabled={!voiceStatus?.connected}
data-active={micActive ? "" : undefined} />
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-destructive data-[active]:text-destructive-foreground hover:bg-muted disabled:opacity-50"
>
{micActive ? (
<MicOff className="size-4" />
) : (
<Mic className="size-4" />
)}
{micActive ? "Stop" : "Start"}
</button>
</div> </div>
</CardTitle>
</CardHeader>
<CardContent>
{!voiceStatus?.connected && ( {!voiceStatus?.connected && (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Connect to a voice channel first. Connect to a voice channel first.
</p> </p>
)} )}
{micActive && ( {micActive && (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2 mt-1">
<span className="relative flex size-2"> <span className="relative flex size-2">
<span className="animate-ping absolute inline-flex size-full rounded-full bg-red-400 opacity-75" /> <span className="absolute inline-flex size-full rounded-full bg-red-400 opacity-75 live-pulse-ring" />
<span className="relative inline-flex size-2 rounded-full bg-red-500" /> <span className="relative inline-flex size-2 rounded-full bg-red-500" />
</span> </span>
<span className="text-sm text-muted-foreground">Transmitting</span> <span className="text-sm text-muted-foreground">
Transmitting
</span>
</div> </div>
)} )}
</CardContent>
</Card>
{/* Recordings */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Headphones className="size-4 text-primary" />
Voice Recordings
</CardTitle>
</CardHeader>
<CardContent>
{recordings.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center">
No recordings yet.
</p>
) : (
<div className="space-y-2">
{recordings.map((rec) => (
<div
key={rec.id}
className="flex items-center gap-3 rounded-lg border border-border/50 p-3 hover:bg-muted/30 transition-colors"
>
<Avatar className="size-8">
<AvatarImage src={rec.avatar_url ?? undefined} />
<AvatarFallback>
{(rec.username ?? "?").charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{rec.username}
</p>
<p className="text-xs text-muted-foreground">
{rec.channel_name ?? rec.channel_id ?? "Unknown channel"}
{" — "}
{new Date(rec.created_at).toLocaleString()}
</p>
</div> </div>
<Badge
variant="outline"
className="text-[10px] font-mono shrink-0"
>
{formatBytes(rec.size_bytes)}
</Badge>
{rec.download_url && (
<Button
variant="ghost"
size="icon"
onClick={() => window.open(rec.download_url!, "_blank")}
>
<Download className="size-4" />
</Button>
)}
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteRecording(rec.id)}
className="hover:text-destructive hover:bg-destructive/10"
>
<Trash2 className="size-4" />
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div> </div>
); );
} }
@@ -5,13 +5,26 @@ import {
Loader2, Loader2,
MessageCircle, MessageCircle,
Send, Send,
Sparkles,
Trash2, Trash2,
User, User,
X, X,
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { mascotApi } from "@/lib/api"; import { mascotApi } from "@/lib/api";
import type { ChatHistoryMessage } from "@/lib/types"; import type { ChatHistoryMessage } from "@/lib/types";
import { cn } from "@/lib/utils";
export function MascotChatbot() { export function MascotChatbot() {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@@ -28,12 +41,11 @@ export function MascotChatbot() {
.catch(() => {}); .catch(() => {});
}, [open]); }, [open]);
// biome-ignore lint/correctness/useExhaustiveDependencies: scrollRef doesn't need messages in deps
useEffect(() => { useEffect(() => {
if (scrollRef.current) { if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight; scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
} }
}, [messages]); }, []);
const handleClear = useCallback(async () => { const handleClear = useCallback(async () => {
try { try {
@@ -83,102 +95,126 @@ export function MascotChatbot() {
return ( return (
<> <>
{/* Toggle button */} {/* Toggle button */}
<button <Button
onClick={() => setOpen(!open)} onClick={() => setOpen(!open)}
className="fixed bottom-4 right-4 z-50 flex size-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg hover:bg-primary/90 transition-colors" size="icon"
aria-label={open ? "Close chat" : "Open chat"} aria-label={open ? "Close chat" : "Open chat"}
className={cn(
"fixed bottom-4 right-4 z-50 size-12 rounded-full shadow-lg transition-all duration-200",
open && "scale-90 opacity-80 hover:scale-100 hover:opacity-100",
)}
> >
{open ? <X className="size-5" /> : <MessageCircle className="size-5" />} {open ? <X className="size-5" /> : <MessageCircle className="size-5" />}
</button> </Button>
{/* Chat panel */} {/* Chat panel */}
{open && ( {open && (
<div className="fixed bottom-20 right-4 z-50 flex w-80 flex-col rounded-lg border bg-background shadow-xl overflow-hidden"> <Card className="fixed bottom-20 right-4 z-50 w-80 sm:w-96 shadow-xl border-border/50 animate-fade-in-up">
{/* Header */} <CardHeader className="border-b border-border/50 bg-gradient-to-r from-primary/5 to-primary/[0.02]">
<div className="flex items-center gap-2 border-b p-3"> <CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Bot className="size-5 text-primary" /> <div className="flex size-6 items-center justify-center rounded-full bg-primary/10">
<span className="text-sm font-semibold flex-1">Mascot</span> <Bot className="size-3.5 text-primary" />
{messages.length > 0 && (
<button
type="button"
onClick={handleClear}
className="inline-flex size-6 items-center justify-center rounded hover:bg-muted transition-colors"
title="Clear history"
>
<Trash2 className="size-3.5 text-muted-foreground" />
</button>
)}
</div> </div>
Mascot
{/* Messages */} <Sparkles className="size-3 text-primary/60 ml-0.5" />
<div <div className="flex-1" />
ref={scrollRef} {messages.length > 0 && (
className="flex-1 space-y-3 overflow-y-auto p-3 max-h-80" <Button
variant="ghost"
size="icon-xs"
onClick={handleClear}
title="Clear history"
className="text-muted-foreground hover:text-foreground"
> >
<Trash2 className="size-3.5" />
</Button>
)}
</CardTitle>
</CardHeader>
<CardContent className="p-0">
<ScrollArea className="h-80">
<div ref={scrollRef} className="space-y-3 p-3">
{messages.length === 0 && ( {messages.length === 0 && (
<p className="text-center text-xs text-muted-foreground py-8"> <p className="text-center text-xs text-muted-foreground py-12">
Ask me anything about the server! Ask me anything about the server!
</p> </p>
)} )}
{messages.map((msg, _i) => ( {messages.map((msg) => (
<div <div
key={msg.timestamp + msg.role} key={msg.timestamp + msg.role}
className={`flex items-start gap-2 ${ className={cn(
msg.role === "user" ? "flex-row-reverse" : "" "flex items-start gap-2",
}`} msg.role === "user" && "flex-row-reverse",
)}
> >
<div className="size-6 shrink-0 rounded-full bg-muted flex items-center justify-center"> <Avatar className="size-6 shrink-0">
<AvatarFallback className="text-[10px] bg-muted">
{msg.role === "user" ? ( {msg.role === "user" ? (
<User className="size-3" /> <User className="size-3" />
) : ( ) : (
<Bot className="size-3" /> <Bot className="size-3" />
)} )}
</div> </AvatarFallback>
</Avatar>
<div <div
className={`rounded-lg px-3 py-2 text-sm max-w-[80%] ${ className={cn(
"rounded-xl px-3 py-2 text-sm max-w-[80%] leading-relaxed",
msg.role === "user" msg.role === "user"
? "bg-primary text-primary-foreground" ? "bg-primary text-primary-foreground"
: "bg-muted" : "bg-muted/70",
}`} )}
> >
{msg.content} {msg.content}
</div> </div>
</div> </div>
))} ))}
{sending && ( {sending && (
<div className="flex items-center gap-2"> <div className="flex items-start gap-2">
<div className="size-6 shrink-0 rounded-full bg-muted flex items-center justify-center"> <Avatar className="size-6 shrink-0">
<AvatarFallback className="text-[10px] bg-muted">
<Bot className="size-3" /> <Bot className="size-3" />
</div> </AvatarFallback>
<div className="rounded-lg bg-muted px-3 py-2"> </Avatar>
<Loader2 className="size-4 animate-spin" /> <div className="rounded-xl bg-muted/70 px-3 py-2">
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</div> </div>
</div> </div>
)} )}
</div> </div>
</ScrollArea>
</CardContent>
{/* Input */} <CardFooter className="border-t border-border/50 p-3">
<div className="border-t p-3"> <form
<div className="flex gap-2"> onSubmit={(e) => {
<input e.preventDefault();
handleSend();
}}
className="flex w-full gap-2"
>
<Input
type="text" type="text"
placeholder="Ask the mascot…" placeholder="Ask the mascot…"
value={input} value={input}
onChange={(e) => setInput(e.target.value)} onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSend()}
className="flex-1 h-8 rounded-md border border-input bg-background px-2 text-sm"
disabled={sending} disabled={sending}
className="h-8 flex-1"
/> />
<button <Button
onClick={handleSend} type="submit"
size="icon-sm"
disabled={!input.trim() || sending} disabled={!input.trim() || sending}
className="inline-flex size-8 items-center justify-center rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
> >
{sending ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Send className="size-4" /> <Send className="size-4" />
</button> )}
</div> </Button>
</div> </form>
</div> </CardFooter>
</Card>
)} )}
</> </>
); );
@@ -4,19 +4,43 @@ import {
AlertCircle, AlertCircle,
ExternalLink, ExternalLink,
Flag, Flag,
Hash,
Loader2, Loader2,
RefreshCw, RefreshCw,
Search, Search,
Sparkles,
X, X,
} from "lucide-react"; } from "lucide-react";
import Image from "next/image"; import Image from "next/image";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { messagesApi, voiceApi } from "@/lib/api"; import { messagesApi, voiceApi } from "@/lib/api";
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types"; import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context"; import { useWebSocket } from "@/lib/ws/context";
export function MessagesPanel({ guildId }: { guildId: string }) { export function MessagesPanel({ guildId }: { guildId: string }) {
// All hooks must be called unconditionally — before the early return.
const [messages, setMessages] = useState<MessageRecord[]>([]); const [messages, setMessages] = useState<MessageRecord[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false); const [loadingMore, setLoadingMore] = useState(false);
@@ -43,9 +67,8 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
const ws = useWebSocket(); const ws = useWebSocket();
// ── Data-fetching side effects (all hooks before any early return) ── // ── Data fetching ──
// Fetch available text channels for filtering
useEffect(() => { useEffect(() => {
if (!guildId) return; if (!guildId) return;
voiceApi voiceApi
@@ -54,7 +77,6 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
.catch(() => {}); .catch(() => {});
}, [guildId]); }, [guildId]);
// Fetch initial messages
const fetchMessages = useCallback(async () => { const fetchMessages = useCallback(async () => {
if (!guildId) return; if (!guildId) return;
setLoading(true); setLoading(true);
@@ -75,7 +97,6 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
} }
}, [guildId, selectedChannel]); }, [guildId, selectedChannel]);
// Fetch image messages
const fetchImages = useCallback(async () => { const fetchImages = useCallback(async () => {
if (!guildId) return; if (!guildId) return;
try { try {
@@ -86,7 +107,6 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
} }
}, [guildId]); }, [guildId]);
// Fetch review (flagged) messages
const fetchReview = useCallback(async () => { const fetchReview = useCallback(async () => {
try { try {
const result = await messagesApi.getReview( const result = await messagesApi.getReview(
@@ -108,7 +128,7 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
if (viewTab === "review") fetchReview(); if (viewTab === "review") fetchReview();
}, [viewTab, fetchReview]); }, [viewTab, fetchReview]);
// WS subscription for real-time message updates // WS subscriptions
useEffect(() => { useEffect(() => {
if (!guildId) return; if (!guildId) return;
const unsubCreated = ws.on("message_created", (msg) => { const unsubCreated = ws.on("message_created", (msg) => {
@@ -142,7 +162,6 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
}; };
}, [ws, guildId]); }, [ws, guildId]);
// Search handler
const handleSearch = useCallback(async () => { const handleSearch = useCallback(async () => {
if (!searchQuery.trim()) { if (!searchQuery.trim()) {
setSearchResults(null); setSearchResults(null);
@@ -159,7 +178,6 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
} }
}, [searchQuery]); }, [searchQuery]);
// Load more (cursor pagination)
const handleLoadMore = useCallback(async () => { const handleLoadMore = useCallback(async () => {
if (!cursor || loadingMore) return; if (!cursor || loadingMore) return;
setLoadingMore(true); setLoadingMore(true);
@@ -186,7 +204,6 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
try { try {
const detail = await messagesApi.getDetail(id); const detail = await messagesApi.getDetail(id);
setDetailMessage(detail); setDetailMessage(detail);
// Try to fetch attachments too
if (detail.channel_id && id) { if (detail.channel_id && id) {
messagesApi messagesApi
.getAttachments(detail.channel_id, 10) .getAttachments(detail.channel_id, 10)
@@ -219,96 +236,83 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
const displayMessages = searchResults ?? messages; const displayMessages = searchResults ?? messages;
const isEmpty = !loading && displayMessages.length === 0; const isEmpty = !loading && displayMessages.length === 0;
// Render error state
if (error) { if (error) {
return ( return (
<div className="flex flex-col items-center justify-center py-16 text-center"> <div className="flex flex-col items-center justify-center py-20 text-center">
<AlertCircle className="size-8 text-destructive mb-2" /> <AlertCircle className="size-10 text-destructive mb-3" />
<p className="text-sm text-muted-foreground mb-4">{error}</p> <p className="text-sm text-muted-foreground mb-4 max-w-sm">{error}</p>
<button <Button variant="outline" onClick={fetchMessages}>
onClick={fetchMessages} <RefreshCw className="size-4 mr-2" />
className="inline-flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted transition-colors"
>
<RefreshCw className="size-4" />
Retry Retry
</button> </Button>
</div> </div>
); );
} }
return ( return (
<div className="space-y-4"> <div className="space-y-5">
{/* Search + toolbar */} {/* Search + toolbar */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center"> <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<div className="relative flex-1"> <div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<input <Input
type="text" type="text"
placeholder="Search messages…" placeholder="Search messages…"
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSearch()} onKeyDown={(e) => e.key === "Enter" && handleSearch()}
className="w-full h-9 rounded-lg border border-input bg-background pl-9 pr-3 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" className="pl-9 h-9"
/> />
</div> </div>
{/* Channel filter */} {/* Channel filter */}
{channels.length > 0 && ( {channels.length > 0 && (
<select <Select
value={selectedChannel} value={selectedChannel}
onChange={(e) => setSelectedChannel(e.target.value)} onValueChange={(v) => v && setSelectedChannel(v)}
className="h-9 rounded-lg border border-input bg-background px-3 text-sm"
> >
<option value="">All channels</option> <SelectTrigger className="h-9 w-full sm:w-44">
<SelectValue placeholder="All channels" />
</SelectTrigger>
<SelectContent>
<SelectItem value=" ">All channels</SelectItem>
{channels.map((ch) => ( {channels.map((ch) => (
<option key={ch.id} value={ch.id}> <SelectItem key={ch.id} value={ch.id}>
#{ch.name} # {ch.name}
</option> </SelectItem>
))} ))}
</select> </SelectContent>
</Select>
)} )}
<button <Button variant="outline" size="sm" onClick={handleReanalyzeBatch}>
onClick={handleReanalyzeBatch} <RefreshCw className="size-4 mr-1.5" />
className="inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium hover:bg-muted transition-colors"
>
<RefreshCw className="size-4" />
Reanalyze Errors Reanalyze Errors
</button> </Button>
</div> </div>
{/* Tab bar */} {/* Tab bar using shadcn Tabs */}
<div className="flex gap-1 rounded-lg border p-1 w-fit"> <Tabs
<button value={viewTab}
type="button" onValueChange={(v) => setViewTab(v as "all" | "images" | "review")}
onClick={() => setViewTab("all")}
data-active={viewTab === "all" ? "" : undefined}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
> >
<TabsList>
<TabsTrigger value="all" onClick={() => setViewTab("all")}>
All ({messages.length}) All ({messages.length})
</button> </TabsTrigger>
<button <TabsTrigger value="images" onClick={() => setViewTab("images")}>
type="button" Images ({imageMessages.length})
onClick={() => setViewTab("images")} </TabsTrigger>
data-active={viewTab === "images" ? "" : undefined} <TabsTrigger value="review" onClick={() => setViewTab("review")}>
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted" <Flag className="size-3.5 mr-1" />
>
Images
</button>
<button
type="button"
onClick={() => setViewTab("review")}
data-active={viewTab === "review" ? "" : undefined}
className="rounded-md px-3 py-1.5 text-sm font-medium transition-colors data-[active]:bg-primary data-[active]:text-primary-foreground hover:bg-muted"
>
<Flag className="size-3.5 inline mr-1" />
Review ({reviewMessages.length}) Review ({reviewMessages.length})
</button> </TabsTrigger>
</div> </TabsList>
</Tabs>
{/* Search results count */} {/* Search results count */}
{searchResults !== null && ( {searchResults !== null && (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground animate-fade-in-up">
Found {searchResults.length} result Found {searchResults.length} result
{searchResults.length !== 1 ? "s" : ""} {searchResults.length !== 1 ? "s" : ""}
</p> </p>
@@ -316,22 +320,16 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
{/* Messages feed */} {/* Messages feed */}
{viewTab === "all" ? ( {viewTab === "all" ? (
<div className="space-y-2"> <div className="space-y-2 animate-fade-in-up">
{loading ? ( {loading ? (
<div className="space-y-3"> <div className="space-y-3">
{Array.from({ length: 8 }, (_, i) => `msg-sk-${i}`).map((key) => ( {Array.from({ length: 8 }, (_, i) => (
<div key={key} className="flex gap-3 rounded-lg border p-4"> <Skeleton key={i} className="h-28 rounded-xl" />
<div className="size-8 shrink-0 rounded-full bg-muted animate-pulse" />
<div className="flex-1 space-y-2">
<div className="h-4 w-32 bg-muted rounded animate-pulse" />
<div className="h-3 w-full bg-muted rounded animate-pulse" />
<div className="h-3 w-3/4 bg-muted rounded animate-pulse" />
</div>
</div>
))} ))}
</div> </div>
) : isEmpty ? ( ) : isEmpty ? (
<div className="flex flex-col items-center justify-center py-16 text-center"> <div className="flex flex-col items-center justify-center py-20 text-center">
<Search className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{searchResults !== null {searchResults !== null
? "No messages found matching your search." ? "No messages found matching your search."
@@ -349,53 +347,60 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
/> />
))} ))}
{/* Load more */}
{hasMore && searchResults === null && ( {hasMore && searchResults === null && (
<div className="flex justify-center py-4"> <div className="flex justify-center py-6">
<button <Button
type="button" variant="outline"
onClick={handleLoadMore} onClick={handleLoadMore}
disabled={loadingMore} disabled={loadingMore}
className="inline-flex items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium hover:bg-muted transition-colors disabled:opacity-50"
> >
{loadingMore ? ( {loadingMore && (
<Loader2 className="size-4 animate-spin" /> <Loader2 className="size-4 animate-spin mr-2" />
) : null} )}
{loadingMore ? "Loading…" : "Load more"} {loadingMore ? "Loading…" : "Load more"}
</button> </Button>
</div> </div>
)} )}
</> </>
)} )}
</div> </div>
) : viewTab === "images" ? ( ) : viewTab === "images" ? (
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3"> <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 animate-fade-in-up">
{imageMessages.map((msg) => { {imageMessages.length === 0 ? (
// Extract image URLs from metadata <div className="col-span-full flex flex-col items-center justify-center py-20 text-center">
<ImageIcon className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground">No images yet.</p>
</div>
) : (
imageMessages.map((msg) => {
let imageUrl: string | null = null; let imageUrl: string | null = null;
try { try {
const meta = JSON.parse(msg.metadata ?? "{}"); const meta = JSON.parse(msg.metadata ?? "{}");
const attachments: Array<{ url: string; contentType?: string }> = const attachments: Array<{
meta.attachments ?? []; url: string;
contentType?: string;
}> = meta.attachments ?? [];
const img = attachments.find((a) => const img = attachments.find((a) =>
a.contentType?.startsWith("image/"), a.contentType?.startsWith("image/"),
); );
imageUrl = img?.url ?? null; imageUrl = img?.url ?? null;
} catch { } catch {
// metadata is malformed // metadata malformed
} }
return ( return (
<div <Card
key={msg.id} key={msg.id}
className="group relative aspect-square rounded-lg border bg-muted overflow-hidden" className="group relative overflow-hidden cursor-pointer"
onClick={() => handleMessageClick(msg.id)}
> >
<div className="aspect-square relative bg-muted">
{imageUrl ? ( {imageUrl ? (
<Image <Image
src={imageUrl} src={imageUrl}
alt={msg.content || "Image"} alt={msg.content || "Image"}
fill fill
className="object-cover" className="object-cover transition-transform duration-300 group-hover:scale-105"
sizes="(max-width: 768px) 50vw, 25vw" sizes="(max-width: 768px) 50vw, 25vw"
/> />
) : ( ) : (
@@ -403,21 +408,26 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
No image No image
</div> </div>
)} )}
{/* Hover overlay */}
{msg.content && ( {msg.content && (
<div className="absolute bottom-0 left-0 right-0 p-2 text-xs text-white bg-gradient-to-t from-black/70 to-transparent truncate opacity-0 group-hover:opacity-100 transition-opacity"> <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-end p-3">
<p className="text-xs text-white/90 line-clamp-2">
{msg.username}: {msg.content} {msg.username}: {msg.content}
</p>
</div> </div>
)} )}
</div> </div>
</Card>
); );
})} })
)}
</div> </div>
) : ( ) : (
/* Review tab */ /* Review tab */
<div className="space-y-2"> <div className="space-y-2 animate-fade-in-up">
{reviewMessages.length === 0 ? ( {reviewMessages.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-center"> <div className="flex flex-col items-center justify-center py-20 text-center">
<Flag className="size-8 text-muted-foreground mb-2" /> <Flag className="size-10 text-muted-foreground/40 mb-3" />
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
No flagged messages to review. No flagged messages to review.
</p> </p>
@@ -435,45 +445,39 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
</div> </div>
)} )}
{/* Message Detail Modal */} {/* Message Detail Dialog */}
{detailMessage && ( <Dialog
<div className="fixed inset-0 z-50 flex items-start justify-center bg-black/50 pt-12 px-4"> open={detailMessage !== null}
<div className="w-full max-w-2xl rounded-lg border bg-background shadow-xl overflow-hidden"> onOpenChange={(open) => {
{/* Header */} if (!open) setDetailMessage(null);
<div className="flex items-center justify-between border-b p-4"> }}
<h3 className="text-sm font-semibold">Message Detail</h3>
<button
type="button"
onClick={() => setDetailMessage(null)}
className="inline-flex size-7 items-center justify-center rounded-md hover:bg-muted transition-colors"
> >
<X className="size-4" /> <DialogContent className="sm:max-w-2xl max-h-[85vh]">
</button> <DialogHeader>
</div> <DialogTitle className="flex items-center gap-2">
<MessageSquare className="size-4" />
Message Detail
</DialogTitle>
</DialogHeader>
{/* Content */} <ScrollArea className="max-h-[70vh] pr-1">
<div className="max-h-[70vh] overflow-y-auto p-4 space-y-4"> <div className="space-y-5">
{detailLoading ? ( {detailLoading ? (
<div className="flex justify-center py-8"> <div className="flex justify-center py-12">
<Loader2 className="size-6 animate-spin" /> <Loader2 className="size-6 animate-spin text-muted-foreground" />
</div> </div>
) : ( ) : detailMessage ? (
<> <>
{/* Message info */} {/* Message info */}
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<div className="size-10 shrink-0 rounded-full bg-muted flex items-center justify-center text-sm font-medium overflow-hidden"> <Avatar className="size-10">
{detailMessage.avatar_url ? ( <AvatarImage
<Image src={detailMessage.avatar_url ?? undefined}
src={detailMessage.avatar_url}
alt=""
width={40}
height={40}
className="size-full object-cover"
/> />
) : ( <AvatarFallback>
detailMessage.username.charAt(0).toUpperCase() {detailMessage.username.charAt(0).toUpperCase()}
)} </AvatarFallback>
</div> </Avatar>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium"> <span className="text-sm font-medium">
@@ -483,44 +487,55 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
{new Date(detailMessage.created_at).toLocaleString()} {new Date(detailMessage.created_at).toLocaleString()}
</span> </span>
{detailMessage.type === "deleted" && ( {detailMessage.type === "deleted" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-red-500/10 text-red-500"> <Badge variant="destructive" className="text-[10px]">
deleted deleted
</span> </Badge>
)}
{detailMessage.type === "edited" && (
<Badge variant="outline" className="text-[10px]">
edited
</Badge>
)} )}
</div> </div>
<p className="text-sm mt-1 whitespace-pre-wrap break-words"> <p className="text-sm mt-2 whitespace-pre-wrap break-words leading-relaxed">
{detailMessage.content} {detailMessage.content}
</p> </p>
</div> </div>
</div> </div>
{/* AI Analysis section */} {/* AI Analysis */}
{detailMessage.ai_analysis && ( {detailMessage.ai_analysis && (
<div className="rounded-lg bg-muted/50 p-3"> <div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4">
<p className="text-xs text-muted-foreground mb-1"> <div className="flex items-center gap-2 mb-2">
<Sparkles className="size-4 text-primary" />
<p className="text-xs text-muted-foreground font-medium">
AI Analysis AI Analysis
</p> </p>
<p className="text-sm">{detailMessage.ai_analysis}</p> </div>
<p className="text-sm leading-relaxed">
{detailMessage.ai_analysis}
</p>
</div> </div>
)} )}
{/* AI flags */} {/* AI flags */}
{detailMessage.ai_moderation_flags && {detailMessage.ai_moderation_flags &&
detailMessage.ai_moderation_flags !== "[]" && ( detailMessage.ai_moderation_flags !== "[]" && (
<div className="space-y-1"> <div className="space-y-2">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground font-medium">
Moderation Flags Moderation Flags
</p> </p>
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1.5">
{safeParseJsonArray( {safeParseJsonArray(
detailMessage.ai_moderation_flags, detailMessage.ai_moderation_flags,
).map((flag) => ( ).map((flag) => (
<span <Badge
key={flag} key={flag}
className="inline-flex items-center rounded-md bg-destructive/10 px-2 py-0.5 text-xs font-medium text-destructive" variant="destructive"
className="text-[11px]"
> >
{flag} {flag}
</span> </Badge>
))} ))}
</div> </div>
</div> </div>
@@ -529,51 +544,61 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
{/* AI Scores */} {/* AI Scores */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3"> <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{detailMessage.ai_status && ( {detailMessage.ai_status && (
<div className="rounded-lg border p-2"> <Card>
<p className="text-xs text-muted-foreground">Status</p> <CardContent className="p-3">
<p className="text-sm font-medium"> <p className="text-xs text-muted-foreground">
Status
</p>
<p className="text-sm font-medium mt-0.5 capitalize">
{detailMessage.ai_status} {detailMessage.ai_status}
</p> </p>
</div> </CardContent>
</Card>
)} )}
{detailMessage.ai_severity && {detailMessage.ai_severity &&
detailMessage.ai_severity !== "none" && ( detailMessage.ai_severity !== "none" && (
<div className="rounded-lg border p-2"> <Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Severity Severity
</p> </p>
<p className="text-sm font-medium text-destructive"> <p className="text-sm font-medium mt-0.5 text-destructive capitalize">
{detailMessage.ai_severity} {detailMessage.ai_severity}
</p> </p>
</div> </CardContent>
</Card>
)} )}
{detailMessage.ai_confidence != null && ( {detailMessage.ai_confidence != null && (
<div className="rounded-lg border p-2"> <Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Confidence Confidence
</p> </p>
<p className="text-sm font-medium"> <p className="text-sm font-medium mt-0.5 tabular-nums">
{(detailMessage.ai_confidence * 100).toFixed(0)}% {(detailMessage.ai_confidence * 100).toFixed(0)}%
</p> </p>
</div> </CardContent>
</Card>
)} )}
{detailMessage.ai_recommended_action && {detailMessage.ai_recommended_action &&
detailMessage.ai_recommended_action !== "none" && ( detailMessage.ai_recommended_action !== "none" && (
<div className="rounded-lg border p-2"> <Card>
<CardContent className="p-3">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Action Action
</p> </p>
<p className="text-sm font-medium"> <p className="text-sm font-medium mt-0.5 capitalize">
{detailMessage.ai_recommended_action} {detailMessage.ai_recommended_action}
</p> </p>
</div> </CardContent>
</Card>
)} )}
</div> </div>
{/* Attachments */} {/* Attachments */}
{detailAttachments.length > 0 && ( {detailAttachments.length > 0 && (
<div className="space-y-2"> <div className="space-y-2">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground font-medium">
Attachments ({detailAttachments.length}) Attachments ({detailAttachments.length})
</p> </p>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
@@ -583,17 +608,17 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
href={att.uploaded_url ?? att.discord_url} href={att.uploaded_url ?? att.discord_url}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="flex items-center gap-2 rounded-lg border p-2 hover:bg-muted transition-colors" className="flex items-center gap-2 rounded-lg border border-border/50 p-2 hover:bg-muted transition-colors group"
> >
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-xs font-medium truncate"> <p className="text-xs font-medium truncate">
{att.filename} {att.filename}
</p> </p>
<p className="text-xs text-muted-foreground"> <p className="text-[11px] text-muted-foreground">
{att.type} · {formatBytes(att.size)} {att.type} · {formatBytes(att.size)}
</p> </p>
</div> </div>
<ExternalLink className="size-3 shrink-0 text-muted-foreground" /> <ExternalLink className="size-3 shrink-0 text-muted-foreground/50 group-hover:text-muted-foreground transition-colors" />
</a> </a>
))} ))}
</div> </div>
@@ -604,10 +629,10 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
{detailMessage.metadata && {detailMessage.metadata &&
detailMessage.metadata !== "{}" && ( detailMessage.metadata !== "{}" && (
<div className="space-y-1"> <div className="space-y-1">
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground font-medium">
Metadata (raw) Metadata (raw)
</p> </p>
<pre className="text-xs bg-muted rounded-lg p-3 overflow-x-auto max-h-32"> <pre className="text-xs bg-muted/50 rounded-lg p-3 overflow-x-auto max-h-32 border border-border/50">
{JSON.stringify( {JSON.stringify(
safeParseJsonObject(detailMessage.metadata), safeParseJsonObject(detailMessage.metadata),
null, null,
@@ -617,16 +642,16 @@ export function MessagesPanel({ guildId }: { guildId: string }) {
</div> </div>
)} )}
</> </>
)} ) : null}
</div> </div>
</div> </ScrollArea>
</div> </DialogContent>
)} </Dialog>
</div> </div>
); );
} }
// ── Message Card ────────────────────────────────────────── // ── Message Card ────────────────────────────────
function MessageCard({ function MessageCard({
message: msg, message: msg,
@@ -638,158 +663,166 @@ function MessageCard({
onReanalyze: (id: string) => void; onReanalyze: (id: string) => void;
}) { }) {
const aiStatusColor: Record<string, string> = { const aiStatusColor: Record<string, string> = {
clean: "bg-green-500/15 text-green-600 dark:text-green-400", clean:
warn: "bg-yellow-500/15 text-yellow-600 dark:text-yellow-400", "bg-green-500/15 text-green-600 dark:text-green-400 border-green-500/20",
flagged: "bg-red-500/15 text-red-600 dark:text-red-400", warn: "bg-yellow-500/15 text-yellow-600 dark:text-yellow-400 border-yellow-500/20",
error: "bg-gray-500/15 text-gray-600 dark:text-gray-400", flagged: "bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/20",
pending: "bg-blue-500/15 text-blue-600 dark:text-blue-400", error: "bg-gray-500/15 text-gray-600 dark:text-gray-400 border-gray-500/20",
processing: "bg-blue-500/15 text-blue-600 dark:text-blue-400", pending:
"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/20",
processing:
"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/20",
}; };
const severityColor: Record<string, string> = { const severityLeftBorder: Record<string, string> = {
none: "", low: "border-l-sky-400",
low: "border-l-green-400",
medium: "border-l-yellow-400", medium: "border-l-yellow-400",
high: "border-l-orange-400", high: "border-l-orange-400",
critical: "border-l-red-500", critical: "border-l-red-500",
}; };
const date = new Date(msg.created_at); const hasSeverity =
const timeStr = date.toLocaleString(); msg.ai_severity &&
msg.ai_severity !== "none" &&
severityLeftBorder[msg.ai_severity];
return ( return (
// biome-ignore lint/a11y/useSemanticElements: complex nested content prevents using button <Card
<div className={cn(
role="button" "cursor-pointer transition-all duration-200 hover:bg-accent/5 hover:shadow-sm",
tabIndex={0} hasSeverity && "border-l-2",
onClick={() => onClick(msg.id)} hasSeverity && severityLeftBorder[msg.ai_severity as string],
onKeyDown={(e) => e.key === "Enter" && onClick(msg.id)}
className={`rounded-lg border p-4 space-y-2 transition-colors cursor-pointer hover:bg-muted/50 ${
msg.ai_severity ? (severityColor[msg.ai_severity] ?? "") : ""
} ${msg.ai_severity && msg.ai_severity !== "none" ? "border-l-2" : ""}`}
>
{/* Header */}
<div className="flex items-start gap-3">
{/* Avatar */}
<div className="size-8 shrink-0 rounded-full bg-muted flex items-center justify-center text-xs font-medium overflow-hidden">
{msg.avatar_url ? (
<Image
src={msg.avatar_url}
alt=""
width={32}
height={32}
className="size-full object-cover"
/>
) : (
msg.username.charAt(0).toUpperCase()
)} )}
</div> onClick={() => onClick(msg.id)}
>
<CardContent className="p-4">
<div className="flex items-start gap-3">
<Avatar className="size-8 shrink-0 mt-0.5">
<AvatarImage src={msg.avatar_url ?? undefined} />
<AvatarFallback className="text-xs">
{msg.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0 space-y-2">
{/* Username + time + badges */} {/* Username + time + badges */}
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium">{msg.username}</span> <span className="text-sm font-medium">{msg.username}</span>
<span className="text-xs text-muted-foreground">{timeStr}</span>
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
#{msg.channel_id.slice(0, 8)} {new Date(msg.created_at).toLocaleString()}
</span>
<span className="text-xs text-muted-foreground">
<Hash className="size-3 inline mr-0.5" />
{msg.channel_id.slice(0, 8)}
</span> </span>
{/* AI Status badge */} {/* AI Status badge */}
{msg.ai_status && aiStatusColor[msg.ai_status] && ( {msg.ai_status && aiStatusColor[msg.ai_status] && (
<span <Badge
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${aiStatusColor[msg.ai_status]}`} variant="outline"
className={cn(
"text-[10px] px-1.5 py-0 h-4 font-medium",
aiStatusColor[msg.ai_status],
)}
> >
{msg.ai_status} {msg.ai_status}
</span> </Badge>
)} )}
{/* Severity badge */} {/* Severity badge */}
{msg.ai_severity && msg.ai_severity !== "none" && ( {msg.ai_severity && msg.ai_severity !== "none" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-destructive/10 text-destructive"> <Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{msg.ai_severity} {msg.ai_severity}
</span> </Badge>
)} )}
{/* Message type badge */} {/* Deleted/edited badges */}
{msg.type === "deleted" && ( {msg.type === "deleted" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-red-500/10 text-red-500"> <Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
deleted deleted
</span> </Badge>
)} )}
{msg.type === "edited" && ( {msg.type === "edited" && (
<span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-blue-500/10 text-blue-500"> <Badge
variant="outline"
className="text-[10px] px-1.5 py-0 h-4"
>
edited edited
</span> </Badge>
)} )}
</div> </div>
{/* Content */} {/* Content */}
<p className="text-sm mt-1 whitespace-pre-wrap break-words"> <p
{msg.type === "deleted" ? ( className={cn(
<span className="italic text-muted-foreground line-through"> "text-sm leading-relaxed",
{msg.content} msg.type === "deleted" &&
</span> "italic text-muted-foreground line-through",
) : (
msg.content
)} )}
>
{msg.content}
</p> </p>
{/* AI Details */} {/* AI flags */}
{msg.ai_moderation_flags && msg.ai_moderation_flags !== "[]" && ( {msg.ai_moderation_flags && msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1 mt-1"> <div className="flex flex-wrap gap-1">
{safeParseJsonArray(msg.ai_moderation_flags).map((flag) => ( {safeParseJsonArray(msg.ai_moderation_flags).map((flag) => (
<span <Badge
key={flag} key={flag}
className="inline-flex items-center rounded-md bg-destructive/10 px-1.5 py-0.5 text-xs font-medium text-destructive" variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
> >
{flag} {flag}
</span> </Badge>
))} ))}
</div> </div>
)} )}
{/* AI analysis snippet */}
{msg.ai_analysis && ( {msg.ai_analysis && (
<p className="text-xs text-muted-foreground mt-1 italic line-clamp-2"> <p className="text-xs text-muted-foreground italic line-clamp-2 leading-relaxed">
{msg.ai_analysis} {msg.ai_analysis}
</p> </p>
)} )}
{/* Confidence score */} {/* Confidence bar */}
{msg.ai_confidence !== undefined && msg.ai_confidence !== null && ( {msg.ai_confidence !== undefined && msg.ai_confidence !== null && (
<div className="flex items-center gap-2 mt-1"> <div className="flex items-center gap-2 max-w-40">
<div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden max-w-24"> <Progress value={msg.ai_confidence * 100} className="h-1.5" />
<div <span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
className="h-full rounded-full bg-primary"
style={{
width: `${msg.ai_confidence * 100}%`,
}}
/>
</div>
<span className="text-xs text-muted-foreground">
{(msg.ai_confidence * 100).toFixed(0)}% {(msg.ai_confidence * 100).toFixed(0)}%
</span> </span>
</div> </div>
)} )}
{/* Actions */} {/* Actions */}
<div className="flex gap-2 mt-2"> <div className="flex gap-1.5 pt-0.5">
<button <Button
type="button" variant="ghost"
onClick={() => onReanalyze(msg.id)} size="xs"
className="inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium hover:bg-muted transition-colors" onClick={(e) => {
title="Re-analyze this message" e.stopPropagation();
onReanalyze(msg.id);
}}
> >
<RefreshCw className="size-3" /> <RefreshCw className="size-3 mr-1" />
Reanalyze Reanalyze
</button> </Button>
</div>
</div> </div>
</div> </div>
</div> </div>
</CardContent>
</Card>
); );
} }
// ── Helpers ─────────────────────────────────────────────── // ── Helpers ─────────────────────────────────────
function safeParseJsonObject( function safeParseJsonObject(
value: string | null | undefined, value: string | null | undefined,
@@ -820,3 +853,50 @@ function safeParseJsonArray(value: string | null | undefined): string[] {
return []; return [];
} }
} }
// Inline icon components to avoid missing imports
function ImageIcon({ className }: { className?: string }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={className}
role="img"
aria-label="Image"
>
<title>Image</title>
<rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
<circle cx="9" cy="9" r="2" />
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
</svg>
);
}
function MessageSquare({ className }: { className?: string }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={className}
role="img"
aria-label="Message"
>
<title>Message</title>
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
</svg>
);
}
+13 -11
View File
@@ -1,19 +1,21 @@
import * as React from "react" import * as React from "react";
const MOBILE_BREAKPOINT = 768 const MOBILE_BREAKPOINT = 768;
export function useIsMobile() { export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined) const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
undefined,
);
React.useEffect(() => { React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`) const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => { const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
} };
mql.addEventListener("change", onChange) mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange) return () => mql.removeEventListener("change", onChange);
}, []) }, []);
return !!isMobile return !!isMobile;
} }
+3 -3
View File
@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx" import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs));
} }