import { useMemo } from 'react' import { ActivityIndicator, Alert, FlatList, Pressable, RefreshControl, StyleSheet, TextInput, View, } from 'react-native' import type { NavigationProp, ParamListBase } from '@react-navigation/native' import { MetalCard, PhosphorText, Led, FilterChip, NativeThemeProvider, } from '@d3ro/ui-native' import { useI18n } from '@d3ro/i18n' import { useHistorySync } from '../features/history/use-history-sync' import type { HistoryFilter, HistoryListEntry } from '../features/history/history-service' import { useMobilePreferences } from '../lib/preferences-context' import { ScreenHeader } from '../components/ScreenHeader' import { useTabScreenBottomPadding } from '../navigation/tab-layout' interface HistoryScreenProps { navigation: NavigationProp } type GroupedItem = | { id: string; type: 'header'; label: string } | { id: string; type: 'entry'; entry: HistoryListEntry } export default function HistoryScreen({ navigation }: HistoryScreenProps): React.ReactElement { const bottomPadding = useTabScreenBottomPadding() const { t, formatTime, formatRelativeDate } = useI18n() const { palette } = useMobilePreferences() const styles = useMemo(() => createStyles(palette), [palette]) const history = useHistorySync() const grouped = useMemo( () => groupByDate(history.entries, formatRelativeDate), [formatRelativeDate, history.entries], ) const openDetail = (entry: HistoryListEntry): void => { // WORKS 허브에서 루트 스택으로 푸시된 경우 getParent()가 없으므로 // 현재 네비게이터(루트 스택) 자체로 HistoryDetail을 푸시한다. const target = navigation.getParent() ?? navigation target.navigate('HistoryDetail', { historyId: entry.id }) } const changeFavorite = async (entry: HistoryListEntry): Promise => { try { await history.toggleFavorite(entry) } catch { Alert.alert(t('mobile.auth.errorTitle'), t('mobile.hist.favoriteFailed')) } } const confirmDelete = (entry: HistoryListEntry): void => { Alert.alert( t('mobile.hist.deleteTitle'), t('mobile.hist.deleteBody'), [ { text: t('mobile.hist.cancel'), style: 'cancel' }, { text: t('mobile.hist.delete'), style: 'destructive', onPress: () => { void history.deleteEntry(entry).catch(() => { Alert.alert(t('mobile.auth.errorTitle'), t('mobile.hist.deleteFailed')) }) }, }, ], ) } if (history.loading) { return ( ) } return ( {t('mobile.hist.entries', { count: history.entries.length })} } testID="history-header" /> {history.offline && ( {t('mobile.hist.offline')} {history.staleAt !== null && ( {t('mobile.hist.cachedAt', { time: formatTime(new Date(history.staleAt).getTime()) })} )} )} {history.cacheWarning && !history.offline && ( {t('mobile.hist.cacheWarning')} )} {history.realtimeDisconnected && !history.offline && ( {t('mobile.hist.realtimeWaiting')} )} {history.error !== null && ( {t('mobile.hist.loadError')} { void history.refresh() }} style={styles.retryButton} testID="history-retry" > {t('mobile.hist.retry')} )} item.id} contentContainerStyle={history.entries.length === 0 ? [styles.emptyList, { paddingBottom: bottomPadding }] : [styles.listContent, { paddingBottom: bottomPadding }]} keyboardShouldPersistTaps="handled" refreshControl={ { void history.refresh() }} tintColor={palette.accent.main} /> } onEndReached={() => { void history.loadMore() }} onEndReachedThreshold={0.35} ListEmptyComponent={ history.error === null ? ( {history.search.trim().length > 0 || history.filter !== 'all' ? t('mobile.hist.emptySearch') : t('mobile.hist.empty')} ) : null } renderItem={({ item }) => { if (item.type === 'header') { return ( {item.label} ) } const entry = item.entry const isOld = !isToday(entry.created_at) const busy = history.isMutating(entry.id) return ( openDetail(entry)} style={styles.cardBody} > {formatTime(new Date(entry.created_at).getTime())} {entry.word_count > 0 && ( {t('mobile.hist.wordsShort', { count: entry.word_count })} )} {entry.title !== null && ( {entry.title} )} {entry.polished_text ?? entry.original_text} {entry.stt_model?.toUpperCase() ?? entry.mode.toUpperCase()} {entry.activeJob !== null && ( {t('mobile.hist.processingProgress', { progress: entry.activeJob.progress })} )} { void changeFavorite(entry) }} style={styles.cardAction} testID={`history-favorite-${entry.id}`} > {busy ? ( ) : ( {entry.is_favorite ? '★' : '☆'} )} confirmDelete(entry)} style={styles.cardAction} testID={`history-delete-${entry.id}`} > {t('mobile.hist.delete')} ) }} ListFooterComponent={history.loadingMore ? ( {t('mobile.hist.loadMore')} ) : null} /> ) } function HistoryFilterChip({ label, value, active, onChange, }: { label: string value: HistoryFilter active: HistoryFilter onChange: (filter: HistoryFilter) => void }): React.ReactElement { return onChange(value)} /> } function isToday(dateStr: string): boolean { const date = new Date(dateStr) const now = new Date() return date.toDateString() === now.toDateString() } export function groupByDate( entries: HistoryListEntry[], formatRelativeDate: (timestamp: number) => string, ): GroupedItem[] { const result: GroupedItem[] = [] let lastDate = '' for (const entry of entries) { const dateLabel = formatRelativeDate(new Date(entry.created_at).getTime()) if (dateLabel !== lastDate) { result.push({ id: `header-${entry.created_at.slice(0, 10)}`, type: 'header', label: dateLabel }) lastDate = dateLabel } result.push({ id: entry.id, type: 'entry', entry }) } return result } type Palette = ReturnType['palette'] function createStyles(palette: Palette) { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, center: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 32, backgroundColor: palette.bg.app }, searchRow: { paddingHorizontal: 20, paddingTop: 12 }, searchInput: { minHeight: 48, paddingHorizontal: 14, borderWidth: 1, borderColor: palette.border.default, borderRadius: 10, backgroundColor: palette.bg.inset, color: palette.text.primary, fontSize: 14, }, filters: { flexDirection: 'row', paddingHorizontal: 20, paddingVertical: 12, gap: 12, borderBottomWidth: 1, borderBottomColor: palette.border.subtle }, offlineBanner: { gap: 4, paddingHorizontal: 20, paddingVertical: 10, backgroundColor: palette.accent.dim }, warningBanner: { paddingHorizontal: 20, paddingVertical: 8 }, errorBanner: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12, paddingHorizontal: 20, paddingVertical: 10, backgroundColor: palette.bg.card, borderBottomWidth: 1, borderBottomColor: palette.tag.red }, retryButton: { minWidth: 72, minHeight: 48, alignItems: 'center', justifyContent: 'center' }, listContent: { padding: 20 }, emptyList: { flexGrow: 1, alignItems: 'center', justifyContent: 'center', padding: 32 }, emptyText: { textAlign: 'center' }, dateHeader: { letterSpacing: 3, marginBottom: 8, marginTop: 16 }, card: { marginBottom: 12, padding: 0 }, cardOld: { opacity: 0.82 }, cardBody: { minHeight: 48, padding: 16, paddingBottom: 10 }, cardHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }, cardHeaderLeft: { flexDirection: 'row', alignItems: 'center' }, timeLabel: { marginLeft: 8 }, wordBadge: { backgroundColor: palette.accent.dim, paddingHorizontal: 8, paddingVertical: 2, borderRadius: 4 }, entryTitle: { marginBottom: 6 }, transcriptText: { marginBottom: 8 }, cardMeta: { flexDirection: 'row', justifyContent: 'space-between', gap: 12 }, cardActions: { flexDirection: 'row', justifyContent: 'flex-end', borderTopWidth: 1, borderTopColor: palette.border.subtle }, cardAction: { minWidth: 64, minHeight: 48, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 12, borderLeftWidth: 1, borderLeftColor: palette.border.subtle }, loadingMore: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10, padding: 18 }, }) }