'use client' import Link from 'next/link' import { useParams, useRouter } from 'next/navigation' import React, { useCallback, useEffect, useState } from 'react' import { Alert, Box, Button, CircularProgress, IconButton, Stack, TextField, Tooltip, Typography } from '@mui/material' import { ArrowLeft, Check, Copy, RefreshCw, Save, Star, Trash2 } from 'lucide-react' import type { D3roSupabaseClient, HistoryEntry } from '@d3ro/api-client' import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds' import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme' import { getSupabaseBrowserClient } from '@/lib/supabase-browser' import { deleteHistoryEntryRevisionSafe, getHistoryEntry, HistoryClientError, updateHistoryEntryRevisionSafe } from '@/lib/history-client' function asApiClient(): D3roSupabaseClient { return getSupabaseBrowserClient() as unknown as D3roSupabaseClient } async function requireCurrentUser(client: D3roSupabaseClient): Promise { const { data, error } = await client.auth.getUser() if (error || !data.user) { throw new HistoryClientError('auth', error?.message ?? 'Authenticated session is required') } return data.user.id } function historyMessage(error: unknown): string { if (error instanceof HistoryClientError) { if (error.code === 'auth') return '세션이 만료되었습니다. 다시 로그인해 주세요.' if (error.code === 'not-found') return '이 전사 기록을 찾을 수 없습니다.' if (error.code === 'conflict') return '다른 기기에서 변경되었습니다. 최신 기록을 다시 불러와 주세요.' if (error.code === 'network') return '네트워크 연결을 확인한 뒤 다시 시도해 주세요.' } return '전사 기록을 처리하지 못했습니다. 잠시 후 다시 시도해 주세요.' } export default function HistoryDetailPage(): React.ReactElement { const params = useParams<{ id: string }>() const router = useRouter() const entryId = params.id const [entry, setEntry] = useState(null) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [deleting, setDeleting] = useState(false) const [editing, setEditing] = useState(false) const [copied, setCopied] = useState(false) const [error, setError] = useState(null) const [title, setTitle] = useState('') const [originalText, setOriginalText] = useState('') const [polishedText, setPolishedText] = useState('') const applyEntry = (next: HistoryEntry): void => { setEntry(next) setTitle(next.title ?? '') setOriginalText(next.original_text) setPolishedText(next.polished_text ?? '') } const loadEntry = useCallback(async (): Promise => { setLoading(true) setError(null) try { const client = asApiClient() const userId = await requireCurrentUser(client) applyEntry(await getHistoryEntry(client, userId, entryId)) } catch (requestError) { setEntry(null) setError(historyMessage(requestError)) } finally { setLoading(false) } }, [entryId]) useEffect(() => { void loadEntry() }, [loadEntry]) const cancelEdit = (): void => { if (!entry) return setTitle(entry.title ?? '') setOriginalText(entry.original_text) setPolishedText(entry.polished_text ?? '') setEditing(false) setError(null) } const saveEntry = async (): Promise => { if (!entry || saving) return if (originalText.trim().length === 0) { setError('원본 전사는 비워 둘 수 없습니다.') return } setSaving(true) setError(null) try { const client = asApiClient() const userId = await requireCurrentUser(client) const updated = await updateHistoryEntryRevisionSafe( client, userId, entry.id, entry.revision, { title: title.trim() || null, original_text: originalText.trim(), polished_text: polishedText.trim() || null } ) applyEntry(updated) setEditing(false) } catch (requestError) { setError(historyMessage(requestError)) } finally { setSaving(false) } } const toggleFavorite = async (): Promise => { if (!entry || saving) return const previous = entry setSaving(true) setError(null) setEntry({ ...previous, is_favorite: !previous.is_favorite, revision: previous.revision + 1 }) try { const client = asApiClient() const userId = await requireCurrentUser(client) applyEntry(await updateHistoryEntryRevisionSafe( client, userId, previous.id, previous.revision, { is_favorite: !previous.is_favorite } )) } catch (requestError) { applyEntry(previous) setError(historyMessage(requestError)) } finally { setSaving(false) } } const deleteEntry = async (): Promise => { if (!entry || deleting) return if (!window.confirm('이 전사 기록을 영구 삭제할까요?')) return setDeleting(true) setError(null) try { const client = asApiClient() const userId = await requireCurrentUser(client) await deleteHistoryEntryRevisionSafe(client, userId, entry.id, entry.revision) router.push('/history') router.refresh() } catch (requestError) { setError(historyMessage(requestError)) setDeleting(false) } } const copyTranscript = async (): Promise => { if (!entry) return try { await navigator.clipboard.writeText(entry.polished_text ?? entry.original_text) setCopied(true) window.setTimeout(() => setCopied(false), 2000) } catch { setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.') } } return ( {loading ? ( ) : entry === null ? ( {error ?? '전사 기록을 불러오지 못했습니다.'} ) : ( TRANSCRIPTION DETAIL {new Date(entry.created_at).toLocaleString('ko-KR')} · REV {entry.revision} void toggleFavorite()} sx={{ color: entry.is_favorite ? 'var(--d3-status-warning)' : 'var(--d3-text-label)' }}> void copyTranscript()} sx={{ color: copied ? 'var(--d3-tag-green)' : 'var(--d3-text-label)' }}> {copied ? : } {error && ( void loadEntry()}>최신 내용 불러오기} > {error} )} {editing ? ( setTitle(event.target.value)} inputProps={{ maxLength: 160 }} /> ) : ( {entry.title ?? '제목 없음'} )} {editing ? ( setOriginalText(event.target.value)} /> ) : ( {entry.original_text} )} {editing ? ( setPolishedText(event.target.value)} /> ) : ( {entry.polished_text ?? '다듬은 전사가 없습니다.'} )} {editing ? ( <> ) : ( )} {entry.summary_text && ( SUMMARY {entry.summary_text} )} METADATA )} ) } function HistoryField({ label, children }: { label: string; children: React.ReactNode }): React.ReactElement { return ( {label.toUpperCase()} {children} ) } function Metadata({ label, value }: { label: string; value: string }): React.ReactElement { return ( {label} {value} ) } function formatDuration(durationSeconds: number): string { const totalSeconds = Number.isFinite(durationSeconds) ? Math.max(0, Math.floor(durationSeconds)) : 0 const hours = Math.floor(totalSeconds / 3600) const minutes = Math.floor((totalSeconds % 3600) / 60) const seconds = totalSeconds % 60 if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` return `${minutes}:${String(seconds).padStart(2, '0')}` }