'use client' import { useCallback, useEffect, useRef, useState } from 'react' import { Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, IconButton, InputAdornment, InputLabel, MenuItem, Select, TextField, Tooltip, Typography } from '@mui/material' import { Download, Pencil, Plus, RefreshCw, Search, Trash2, Upload } from 'lucide-react' import type { D3roSupabaseClient, DictionaryEntry } from '@d3ro/api-client' import { MetalCard, PhosphorText, PhysicalButton, TactileBadge } from '@d3ro/ui/components/ds' import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme' import { useAuth } from '@/components/providers/auth-provider' import { getSupabaseBrowserClient } from '@/lib/supabase-browser' import { createDictionaryEntry, deleteDictionaryEntry, DictionaryClientError, importDictionaryFile, listDictionaryPage, normalizeDictionaryDraft, sanitizeDictionarySearch, serializeDictionary, updateDictionaryEntry, type DictionaryCategory, type DictionaryCursor, type DictionaryDraft, type DictionaryFilter } from '@/lib/dictionary-client' const PAGE_SIZE = 20 const SEARCH_DELAY_MS = 300 function downloadText(filename: string, text: string, mime: string): void { const blob = new Blob([text], { type: mime }) const url = URL.createObjectURL(blob) const anchor = document.createElement('a') anchor.href = url anchor.download = filename document.body.appendChild(anchor) anchor.click() document.body.removeChild(anchor) URL.revokeObjectURL(url) } const CATEGORY_LABELS: Record = { user: '사용자', technical: '기술', auto: '자동' } function dictionaryMessage(error: unknown): string { if (error instanceof DictionaryClientError) { if (error.code === 'auth') return '세션이 만료되었습니다. 다시 로그인해 주세요.' if (error.code === 'conflict') return '다른 기기에서 변경된 단어입니다. 목록을 새로고침한 뒤 다시 시도해 주세요.' if (error.code === 'duplicate') return '같은 분류에 동일한 단어가 이미 있습니다.' if (error.code === 'network') return '네트워크 연결을 확인한 뒤 다시 시도해 주세요.' if (error.code === 'validation') return error.message } return '사전을 처리하지 못했습니다. 잠시 후 다시 시도해 주세요.' } function sortDictionary(entries: DictionaryEntry[]): DictionaryEntry[] { return [...entries].sort((left, right) => { const byDate = right.updated_at.localeCompare(left.updated_at) return byDate !== 0 ? byDate : right.id.localeCompare(left.id) }) } function matchesView(entry: DictionaryEntry, category: DictionaryFilter, search: string): boolean { if (category !== 'all' && entry.category !== category) return false const normalized = sanitizeDictionarySearch(search).toLocaleLowerCase() if (!normalized) return true return entry.word.toLocaleLowerCase().includes(normalized) || (entry.pronunciation?.toLocaleLowerCase().includes(normalized) ?? false) } export default function DictionaryPage(): React.ReactElement { const { user, loading: authLoading } = useAuth() const [entries, setEntries] = useState([]) const [searchInput, setSearchInput] = useState('') const [search, setSearch] = useState('') const [category, setCategory] = useState('all') const [nextCursor, setNextCursor] = useState(null) const [total, setTotal] = useState(0) const [loading, setLoading] = useState(true) const [loadingMore, setLoadingMore] = useState(false) const [error, setError] = useState(null) const [dialogOpen, setDialogOpen] = useState(false) const [editing, setEditing] = useState(null) const [draft, setDraft] = useState({ word: '', pronunciation: null, category: 'user' }) const [saving, setSaving] = useState(false) const [mutatingIds, setMutatingIds] = useState>(() => new Set()) const [ioBusy, setIoBusy] = useState(false) const [notice, setNotice] = useState(null) const requestGeneration = useRef(0) const fileInputRef = useRef(null) useEffect(() => { const timer = window.setTimeout(() => setSearch(searchInput), SEARCH_DELAY_MS) return () => window.clearTimeout(timer) }, [searchInput]) const loadFirstPage = useCallback(async (): Promise => { const generation = ++requestGeneration.current if (!user) { if (!authLoading) { setLoading(false) setError('세션이 만료되었습니다. 다시 로그인해 주세요.') } return } setLoading(true) setError(null) try { const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient const result = await listDictionaryPage(client, { userId: user.id, search, category, pageSize: PAGE_SIZE, cursor: null }) if (generation !== requestGeneration.current) return setEntries(result.entries) setNextCursor(result.nextCursor) setTotal(result.total) } catch (requestError) { if (generation !== requestGeneration.current) return setEntries([]) setNextCursor(null) setTotal(0) setError(dictionaryMessage(requestError)) } finally { if (generation === requestGeneration.current) setLoading(false) } }, [authLoading, category, search, user]) useEffect(() => { void loadFirstPage() }, [loadFirstPage]) const loadMore = async (): Promise => { if (!user || loading || loadingMore || !nextCursor) return const generation = requestGeneration.current setLoadingMore(true) setError(null) try { const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient const result = await listDictionaryPage(client, { userId: user.id, search, category, pageSize: PAGE_SIZE, cursor: nextCursor }) if (generation !== requestGeneration.current) return setEntries((current) => { const rows = new Map(current.map((entry) => [entry.id, entry])) for (const entry of result.entries) rows.set(entry.id, entry) return sortDictionary([...rows.values()]) }) setNextCursor(result.nextCursor) } catch (requestError) { if (generation === requestGeneration.current) setError(dictionaryMessage(requestError)) } finally { if (generation === requestGeneration.current) setLoadingMore(false) } } const openAdd = (): void => { setEditing(null) setDraft({ word: '', pronunciation: null, category: 'user' }) setDialogOpen(true) } const openEdit = (entry: DictionaryEntry): void => { setEditing(entry) setDraft({ word: entry.word, pronunciation: entry.pronunciation, category: entry.category }) setDialogOpen(true) } const save = async (): Promise => { if (!user || saving) return let normalized: DictionaryDraft try { normalized = normalizeDictionaryDraft(draft) } catch (requestError) { setError(dictionaryMessage(requestError)) return } setSaving(true) setError(null) const now = new Date().toISOString() const original = editing const optimisticId = original?.id ?? crypto.randomUUID() const optimistic: DictionaryEntry = { id: optimisticId, user_id: user.id, word: normalized.word, pronunciation: normalized.pronunciation, category: normalized.category, usage_count: original?.usage_count ?? 0, last_used_at: original?.last_used_at ?? null, created_at: original?.created_at ?? now, updated_at: now } const wasVisible = original ? matchesView(original, category, search) : false const willBeVisible = matchesView(optimistic, category, search) setEntries((current) => { if (original) { const without = current.filter((entry) => entry.id !== original.id) return willBeVisible ? sortDictionary([optimistic, ...without]) : without } return willBeVisible ? sortDictionary([optimistic, ...current]) : current }) if (!original && willBeVisible) setTotal((value) => value + 1) if (original && wasVisible && !willBeVisible) setTotal((value) => Math.max(0, value - 1)) if (original && !wasVisible && willBeVisible) setTotal((value) => value + 1) setDialogOpen(false) try { const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient const saved = original ? await updateDictionaryEntry(client, user.id, original, normalized) : await createDictionaryEntry(client, user.id, normalized) setEntries((current) => { const without = current.filter((entry) => entry.id !== optimisticId && entry.id !== saved.id) return matchesView(saved, category, search) ? sortDictionary([saved, ...without]) : without }) } catch (requestError) { setEntries((current) => { const withoutOptimistic = current.filter((entry) => entry.id !== optimisticId) return original && wasVisible ? sortDictionary([original, ...withoutOptimistic]) : withoutOptimistic }) if (!original && willBeVisible) setTotal((value) => Math.max(0, value - 1)) if (original && wasVisible && !willBeVisible) setTotal((value) => value + 1) if (original && !wasVisible && willBeVisible) setTotal((value) => Math.max(0, value - 1)) setError(dictionaryMessage(requestError)) } finally { setSaving(false) } } const remove = async (entry: DictionaryEntry): Promise => { if (!user || mutatingIds.has(entry.id)) return if (!window.confirm(`“${entry.word}” 단어를 삭제할까요?`)) return setMutatingIds((current) => new Set(current).add(entry.id)) setError(null) const index = Math.max(0, entries.findIndex((candidate) => candidate.id === entry.id)) setEntries((current) => current.filter((candidate) => candidate.id !== entry.id)) setTotal((value) => Math.max(0, value - 1)) try { const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient await deleteDictionaryEntry(client, user.id, entry) } catch (requestError) { setEntries((current) => { if (current.some((candidate) => candidate.id === entry.id)) return current const restored = [...current] restored.splice(Math.min(index, restored.length), 0, entry) return restored }) setTotal((value) => value + 1) setError(dictionaryMessage(requestError)) } finally { setMutatingIds((current) => { const next = new Set(current) next.delete(entry.id) return next }) } } const emptyMessage = search || category !== 'all' ? '조건에 맞는 사전 단어가 없습니다.' : '등록된 사전 단어가 없습니다.' const collectAllEntries = async (): Promise => { if (!user) return [] const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient const all: DictionaryEntry[] = [] let cursor: DictionaryCursor | null = null for (let guard = 0; guard < 200; guard += 1) { const page = await listDictionaryPage(client, { userId: user.id, search: '', category: 'all', pageSize: 50, cursor }) all.push(...page.entries) if (!page.nextCursor) break cursor = page.nextCursor } return all } const handleExport = async (format: 'json' | 'csv'): Promise => { if (!user || ioBusy) return setIoBusy(true) setError(null) setNotice(null) try { const all = await collectAllEntries() const visible = all.filter((entry) => matchesView(entry, category, search)) const stamp = new Date().toISOString().slice(0, 10) downloadText( `d3ro-dictionary-${stamp}.${format}`, serializeDictionary(visible, format), format === 'csv' ? 'text/csv;charset=utf-8' : 'application/json' ) setNotice(`사전 ${visible.length}개를 내보냈습니다.`) } catch (requestError) { setError(dictionaryMessage(requestError)) } finally { setIoBusy(false) } } const handleImportFile = async (file: File): Promise => { if (!user) return const format = file.name.toLowerCase().endsWith('.csv') ? 'csv' : 'json' setIoBusy(true) setError(null) setNotice(null) try { const raw = await file.text() const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient const result = await importDictionaryFile(client, user.id, raw, format) await loadFirstPage() setNotice(`가져오기 ${result.imported}건, 건너뜀 ${result.skipped}건`) } catch (requestError) { setError(dictionaryMessage(requestError)) } finally { setIoBusy(false) } } return ( CUSTOM DICTIONARY {total} ENTRIES · ACCOUNT SYNC void handleExport('json')} sx={{ color: 'var(--d3-text-label)' }}> void handleExport('csv')} sx={{ color: 'var(--d3-text-label)' }}> fileInputRef.current?.click()} sx={{ color: 'var(--d3-text-label)' }}> { const file = event.target.files?.[0] event.target.value = '' if (file) void handleImportFile(file) }} /> }> 단어 추가 {notice && ( setNotice(null)}> {notice} )} setSearchInput(event.target.value)} placeholder="단어 또는 발음 검색..." size="small" inputProps={{ 'aria-label': '커스텀 사전 검색', maxLength: 100 }} InputProps={{ startAdornment: , sx: { bgcolor: 'var(--d3-bg-inset)', borderRadius: '12px', border: '1px solid var(--d3-border-default)', color: 'var(--d3-text-secondary)', '& fieldset': { border: 'none' } } }} sx={{ flex: 1, minWidth: 260 }} /> {(['all', 'user', 'technical', 'auto'] as const).map((value) => ( setCategory(value)} sx={{ cursor: 'pointer', height: 36, px: 1.5 }} > {value === 'all' ? '전체' : CATEGORY_LABELS[value]} ))} {error && ( } onClick={() => void loadFirstPage()}>새로고침} sx={{ mb: 3 }} > {error} )} {authLoading || loading ? ( ) : entries.length === 0 ? ( {emptyMessage} ) : ( {entries.map((entry) => { const busy = mutatingIds.has(entry.id) return ( {entry.word} {entry.pronunciation && [{entry.pronunciation}]} {CATEGORY_LABELS[entry.category]} {entry.usage_count}회 사용 openEdit(entry)} sx={{ color: 'var(--d3-text-label)' }}> void remove(entry)} sx={{ color: 'var(--d3-text-label)', '&:hover': { color: 'var(--d3-status-danger)' } }}> ) })} )} {!loading && nextCursor && ( )} { if (!saving) setDialogOpen(false) }} maxWidth="xs" fullWidth PaperProps={{ sx: { bgcolor: 'var(--d3-bg-card)', border: '1px solid var(--d3-border-default)', borderRadius: '16px', p: 1 } }} > {editing ? '단어 편집' : '새 단어 추가'} setDraft((current) => ({ ...current, word: event.target.value }))} inputProps={{ maxLength: 120 }} fullWidth autoFocus size="small" sx={{ mt: 1 }} /> setDraft((current) => ({ ...current, pronunciation: event.target.value }))} inputProps={{ maxLength: 200 }} fullWidth size="small" helperText="예: 디쓰리오" /> 분류 setDialogOpen(false)}>취소 void save()}> {saving ? '저장 중...' : '저장'} ) }