'use client' import Link from 'next/link' import { useCallback, useEffect, useRef, useState } from 'react' import { Alert, Box, Button, CircularProgress, Typography } from '@mui/material' import { ArrowUpRight, BookOpen, CalendarDays, Clock3, Database, Flame, Mic, RefreshCw, ShieldCheck, Star } from 'lucide-react' import type { D3roSupabaseClient } from '@d3ro/api-client' import { DoubleBezelCard, MetalCard, PhosphorText, PhysicalButton, StatRing, TactileBadge, TiltCard } from '@d3ro/ui/components/ds' import { d3roFontMono, d3roFontSans, d3roPalette } from '@d3ro/ui/theme' import { useAuth } from '@/components/providers/auth-provider' import { getSupabaseBrowserClient } from '@/lib/supabase-browser' import { DashboardClientError, loadDashboardSnapshot, type DashboardSnapshot } from '@/lib/dashboard-client' function dashboardMessage(error: unknown): string { if (error instanceof DashboardClientError) { if (error.code === 'auth') return '세션이 만료되었습니다. 다시 로그인해 주세요.' if (error.code === 'network') return '네트워크 연결을 확인한 뒤 다시 시도해 주세요.' if (error.code === 'not-initialized') return '계정 구독 정보가 아직 초기화되지 않았습니다.' if (error.code === 'invalid-response') return '서버 데이터 형식이 올바르지 않습니다.' } return '대시보드 데이터를 불러오지 못했습니다. 잠시 후 다시 시도해 주세요.' } function tierLabel(tier: DashboardSnapshot['subscription']['tier']): string { if (tier === 'pro_plus') return 'PRO+' return tier.toUpperCase() } function providerLabel(provider: DashboardSnapshot['subscription']['provider']): string { const labels: Record = { none: '미연결', stripe: 'Stripe (종료)', payple: '페이플', google_play: 'Google Play', app_store: 'App Store', admin: '관리자 부여' } return labels[provider] } function formatDuration(seconds: number): string { const total = Math.max(0, Math.floor(seconds)) const hours = Math.floor(total / 3600) const minutes = Math.floor((total % 3600) / 60) const remaining = total % 60 if (hours > 0) return `${hours}시간 ${minutes}분` if (minutes > 0) return `${minutes}분 ${remaining}초` return `${remaining}초` } export default function DashboardPage(): React.ReactElement { const { user, loading: authLoading } = useAuth() const userId = user?.id const [snapshot, setSnapshot] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const mountedRef = useRef(true) const requestSeqRef = useRef(0) useEffect(() => { mountedRef.current = true return () => { mountedRef.current = false } }, []) const load = useCallback(async (): Promise => { const seq = ++requestSeqRef.current const isStale = (): boolean => !mountedRef.current || requestSeqRef.current !== seq if (!userId) { if (!authLoading) { setSnapshot(null) setError('세션이 만료되었습니다. 다시 로그인해 주세요.') setLoading(false) } return } setLoading(true) setError(null) try { const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient const nextSnapshot = await loadDashboardSnapshot(client, userId) if (isStale()) return setSnapshot(nextSnapshot) } catch (requestError) { if (isStale()) return setSnapshot(null) setError(dashboardMessage(requestError)) } finally { if (!isStale()) { setLoading(false) } } }, [authLoading, userId]) useEffect(() => { void load() }, [load]) if (authLoading || loading) { return ( ) } if (error || !snapshot) { return ( } onClick={() => void load()}> 다시 시도 )} > {error ?? '대시보드 데이터를 불러오지 못했습니다.'} ) } const { stats, subscription } = snapshot const generatedAt = new Date(stats.generatedAt) const tiles = [ { label: '오늘 녹음 시간', value: formatDuration(stats.todayRecordingSeconds), icon: , ring: 'blue' as const }, { label: '전체 단어 수', value: stats.totalWordCount.toLocaleString(), icon: , ring: 'accent' as const }, { label: '오늘 세션', value: stats.todaySessions.toLocaleString(), icon: , ring: 'green' as const }, { label: '연속 사용', value: `${stats.streakDays}일`, icon: , ring: 'orange' as const } ] return ( SUPABASE SSOT RLS ACCOUNT DATA 갱신 {generatedAt.toLocaleString('ko-KR')} 내 음성 작업 현황 계정에 동기화된 완료 기록을 기준으로 집계합니다. }> 웹 녹음 시작 {[ { label: '전체 세션', value: stats.totalSessions.toLocaleString() }, { label: '전체 녹음', value: formatDuration(stats.totalRecordingSeconds) } ].map((item) => ( {item.label} {item.value} ))} {tiles.map((tile) => ( {tile.icon} {tile.label} {tile.value} ))} 동기화 기준 현재 구독 {tierLabel(subscription.tier)} {subscription.currentPeriodEnd && } {subscription.cancelAt && } 최근 전사 기록 {stats.recentHistory.length === 0 ? ( 아직 완료된 전사 기록이 없습니다. ) : ( {stats.recentHistory.map((entry) => ( {entry.title && {entry.title}} {entry.text} {new Date(entry.createdAt).toLocaleString('ko-KR')} {formatDuration(entry.durationSeconds)} ))} )} ) } function DataLine({ label, value }: { label: string; value: string }): React.ReactElement { return ( {label} {value} ) }