import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ActivityIndicator, Alert, Pressable, ScrollView, Share, StyleSheet, TextInput, View, } from 'react-native' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { useSoundWithStates } from 'react-native-nitro-sound' import { MetalCard, NativeThemeProvider, PhosphorText, PhysicalButton, } from '@d3ro/ui-native' import { useI18n, type TranslationKey } from '@d3ro/i18n' import { formatBytes, formatDurationClockFromMs } from '@d3ro/core/format' import type { AudioFile, HistoryEntry } from '@d3ro/api-client' import { useAuth } from '../lib/auth-context' import { createAudioPlaybackUrl, deleteHistoryRevisionSafe, getHistoryDetail, HistoryServiceError, updateHistoryRevisionSafe, type HistoryDetail, } from '../features/history/history-service' import { loadHistoryCache } from '../features/history/history-cache' import { useMobilePreferences } from '../lib/preferences-context' const HISTORY_MODE_KEYS: Record = { dictation: 'mobile.hist.mode.dictation', translate: 'mobile.hist.mode.translate', command: 'mobile.hist.mode.command', caption: 'mobile.hist.mode.caption', 'file-transcription': 'mobile.hist.mode.fileTranscription', } const HISTORY_STATUS_KEYS: Record = { completed: 'mobile.hist.status.completed', cancelled: 'mobile.hist.status.cancelled', error: 'mobile.hist.status.error', } const AUDIO_STATUS_KEYS: Record = { pending: 'mobile.hist.audioStatus.pending', uploading: 'mobile.hist.audioStatus.uploading', uploaded: 'mobile.hist.audioStatus.uploaded', failed: 'mobile.hist.audioStatus.failed', deleted: 'mobile.hist.audioStatus.deleted', } const JOB_KIND_KEYS: Record = { transcription: 'mobile.hist.jobKind.transcription', summary: 'mobile.hist.jobKind.summary', minutes: 'mobile.hist.jobKind.minutes', diarization: 'mobile.hist.jobKind.diarization', export: 'mobile.hist.jobKind.export', } const JOB_STATUS_KEYS: Record = { queued: 'mobile.hist.jobStatus.queued', running: 'mobile.hist.jobStatus.running', succeeded: 'mobile.hist.jobStatus.succeeded', failed: 'mobile.hist.jobStatus.failed', cancelled: 'mobile.hist.jobStatus.cancelled', } interface HistoryDetailScreenProps { route: { params: { historyId: string } } navigation: { goBack: () => void } } export default function HistoryDetailScreen({ route, navigation, }: HistoryDetailScreenProps): React.ReactElement { const insets = useSafeAreaInsets() const { user } = useAuth() const { t, formatDate } = useI18n() const { palette } = useMobilePreferences() const styles = useMemo(() => createStyles(palette), [palette]) const player = useSoundWithStates() const playerRef = useRef(player) playerRef.current = player const mountedRef = useRef(true) const loadGenerationRef = useRef(0) const playbackGenerationRef = useRef(0) const [detail, setDetail] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [offline, setOffline] = useState(false) const [editing, setEditing] = useState(false) const [title, setTitle] = useState('') const [originalText, setOriginalText] = useState('') const [polishedText, setPolishedText] = useState('') const [saving, setSaving] = useState(false) const [conflict, setConflict] = useState(false) const [deleting, setDeleting] = useState(false) const [activeAudioId, setActiveAudioId] = useState(null) const [paused, setPaused] = useState(false) const [audioBusy, setAudioBusy] = useState(false) useEffect(() => { mountedRef.current = true return () => { mountedRef.current = false loadGenerationRef.current += 1 playbackGenerationRef.current += 1 void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined) } }, []) const applyEntry = useCallback((entry: HistoryEntry): void => { setTitle(entry.title ?? '') setOriginalText(entry.original_text) setPolishedText(entry.polished_text ?? '') }, []) const load = useCallback(async (): Promise => { const generation = ++loadGenerationRef.current if (user === null) { if (!mountedRef.current) return setError(t('mobile.account.loginRequired')) setLoading(false) return } setLoading(true) setError(null) try { const nextDetail = await getHistoryDetail(user.id, route.params.historyId) if (!mountedRef.current || loadGenerationRef.current !== generation) return setDetail(nextDetail) applyEntry(nextDetail.entry) setOffline(false) setConflict(false) } catch (requestError) { if (!mountedRef.current || loadGenerationRef.current !== generation) return if (requestError instanceof HistoryServiceError && requestError.code === 'network') { try { const cached = await loadHistoryCache(user.id) if (!mountedRef.current || loadGenerationRef.current !== generation) return const entry = cached?.entries.find((item) => item.id === route.params.historyId) if (entry !== undefined) { setDetail({ entry, audioFiles: [], jobs: [] }) applyEntry(entry) setOffline(true) return } } catch { // The request error below remains authoritative when secure cache access fails. } } if (!mountedRef.current || loadGenerationRef.current !== generation) return setError( requestError instanceof HistoryServiceError && requestError.code === 'not-found' ? t('mobile.hist.notFound') : t('mobile.hist.loadError'), ) } finally { if (mountedRef.current && loadGenerationRef.current === generation) { setLoading(false) } } }, [applyEntry, route.params.historyId, t, user]) useEffect(() => { void load() }, [load]) const cancelEdit = (): void => { if (detail !== null) applyEntry(detail.entry) setEditing(false) setConflict(false) setError(null) } const save = async (): Promise => { if (user === null || detail === null || saving) return const normalizedTitle = title.trim() const normalizedOriginal = originalText.trim() const normalizedPolished = polishedText.trim() if (normalizedTitle.length > 160) { setError(t('mobile.hist.validationTitle')) return } if (normalizedOriginal.length === 0) { setError(t('mobile.hist.validationOriginal')) return } const patch: { title?: string | null original_text?: string polished_text?: string | null } = {} if ((detail.entry.title ?? '') !== normalizedTitle) patch.title = normalizedTitle || null if (detail.entry.original_text !== normalizedOriginal) patch.original_text = normalizedOriginal if ((detail.entry.polished_text ?? '') !== normalizedPolished) { patch.polished_text = normalizedPolished || null } if (Object.keys(patch).length === 0) { setEditing(false) return } setSaving(true) setError(null) try { const updated = await updateHistoryRevisionSafe( user.id, detail.entry.id, detail.entry.revision, patch, ) if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, entry: updated }) applyEntry(updated) setEditing(false) setConflict(false) } catch (requestError) { if (!mountedRef.current) return if (requestError instanceof HistoryServiceError && requestError.code === 'conflict') { setConflict(true) setError(t('mobile.hist.conflict')) } else { setError(t('mobile.hist.editFailed')) } } finally { if (mountedRef.current) setSaving(false) } } const toggleFavorite = async (): Promise => { if (user === null || detail === null || saving) return const previous = detail.entry const optimistic = { ...previous, is_favorite: !previous.is_favorite } setDetail((current) => current === null ? null : { ...current, entry: optimistic }) setSaving(true) try { const updated = await updateHistoryRevisionSafe( user.id, previous.id, previous.revision, { is_favorite: optimistic.is_favorite }, ) if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, entry: updated }) } catch { if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, entry: previous }) setError(t('mobile.hist.favoriteFailed')) } finally { if (mountedRef.current) setSaving(false) } } const confirmDelete = (): void => { if (detail === null || deleting) return 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 deleteEntry() }, }, ], ) } const deleteEntry = async (): Promise => { if (user === null || detail === null || deleting) return setDeleting(true) setError(null) try { await deleteHistoryRevisionSafe(user.id, detail.entry.id, detail.entry.revision) if (!mountedRef.current) return navigation.goBack() } catch { if (!mountedRef.current) return setError(t('mobile.hist.deleteFailed')) setDeleting(false) } } const shareTranscript = async (): Promise => { if (detail === null) return const content = detail.entry.polished_text ?? detail.entry.original_text const summary = detail.entry.summary_text?.trim() const message = [detail.entry.title, content, summary].filter(Boolean).join('\n\n') try { await Share.share({ title: detail.entry.title ?? t('mobile.hist.detailTitle'), message, }) } catch { if (mountedRef.current) setError(t('mobile.hist.shareFailed')) } } const controlAudio = async (audioFile: AudioFile): Promise => { if (user === null || audioBusy) return const playbackGeneration = ++playbackGenerationRef.current setAudioBusy(true) setError(null) try { if (activeAudioId === audioFile.id && player.state.isPlaying) { await player.pausePlayer() if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(true) return } if (activeAudioId === audioFile.id && paused) { await player.resumePlayer() if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(false) return } if (activeAudioId !== null) { await player.stopPlayer() if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return } const signedUrl = await createAudioPlaybackUrl(user.id, audioFile) if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return await player.startPlayer(signedUrl) if (!mountedRef.current) { void Promise.resolve(player.stopPlayer()).catch(() => undefined) return } if (playbackGeneration !== playbackGenerationRef.current) return setActiveAudioId(audioFile.id) setPaused(false) } catch { if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return setActiveAudioId(null) setPaused(false) setError(t('mobile.hist.audioError')) } finally { if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { setAudioBusy(false) } } } const stopAudio = async (): Promise => { const playbackGeneration = ++playbackGenerationRef.current setAudioBusy(true) try { await player.stopPlayer() if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return setActiveAudioId(null) setPaused(false) } catch { if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { setError(t('mobile.hist.audioError')) } } finally { if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { setAudioBusy(false) } } } return ( ‹ {t('mobile.hist.back')} {t('mobile.hist.detailTitle').toUpperCase()} {loading ? ( {t('mobile.hist.detailLoading')} ) : detail === null ? ( {error ?? t('mobile.hist.notFound')} { void load() }} /> ) : ( {offline && ( {t('mobile.hist.offline')} )} {error !== null && ( {error} {conflict && ( { void load() }} style={styles.inlineButton} > {t('mobile.hist.reloadLatest')} )} )} { void toggleFavorite() }} style={styles.compactButton} testID="history-detail-favorite" > {detail.entry.is_favorite ? '★' : '☆'} setEditing(true)} style={styles.compactButton} testID="history-detail-edit" > {t('mobile.hist.edit')} { void shareTranscript() }} style={styles.compactButton} testID="history-detail-share" > {t('mobile.hist.share')} {editing ? ( ) : ( {detail.entry.title ?? '—'} )} {editing ? ( ) : ( {detail.entry.original_text} )} {editing ? ( ) : ( {detail.entry.polished_text ?? '—'} )} {editing && ( { void save() }} style={styles.flexButton} testID="history-detail-save" /> )} {detail.entry.summary_text !== null && (
{detail.entry.summary_text}
)}
{detail.audioFiles.length === 0 ? ( {t('mobile.hist.audioNone')} ) : detail.audioFiles.map((audioFile) => ( {audioFile.original_name ?? audioFile.mime_type} {formatBytes(audioFile.size_bytes)} · {formatDuration(audioFile.duration_ms ?? 0)} {audioFile.upload_status !== 'uploaded' && ( {t('mobile.hist.audioPending', { status: t(AUDIO_STATUS_KEYS[audioFile.upload_status]) })} )} { void controlAudio(audioFile) }} style={styles.compactButton} > {activeAudioId === audioFile.id && player.state.isPlaying ? t('mobile.hist.audioPause') : activeAudioId === audioFile.id && paused ? t('mobile.hist.audioResume') : t('mobile.hist.audioPlay')} ))} {activeAudioId !== null && ( {formatDuration(player.state.playback.position)} / {formatDuration(player.state.playback.duration)} { void stopAudio() }} disabled={audioBusy} style={styles.playbackButton} > {t('mobile.hist.audioStop')} )}
{detail.jobs.length === 0 ? ( {t('mobile.hist.jobsNone')} ) : detail.jobs.map((job) => ( ))}
)}
) } function FieldLabel({ label }: { label: string }): React.ReactElement { const styles = useHistoryDetailStyles() return {label} } function Section({ title, children }: { title: string; children: React.ReactNode }): React.ReactElement { const styles = useHistoryDetailStyles() return ( {title} {children} ) } function MetaRow({ label, value }: { label: string; value: string }): React.ReactElement { const styles = useHistoryDetailStyles() return ( {label} {value} ) } export { formatBytes } export function formatDuration(durationMs: number): string { return formatDurationClockFromMs(durationMs) } type Palette = ReturnType['palette'] function useHistoryDetailStyles(): ReturnType { const { palette } = useMobilePreferences() return useMemo(() => createStyles(palette), [palette]) } function createStyles(palette: Palette) { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 16, paddingBottom: 12, borderBottomWidth: 1, borderBottomColor: palette.border.subtle, }, headerButton: { minWidth: 80, minHeight: 48, justifyContent: 'center' }, headerTitle: { letterSpacing: 2 }, headerSpacer: { width: 80 }, center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 18, padding: 32 }, centerText: { textAlign: 'center' }, loadingText: { marginTop: 12 }, content: { padding: 20, gap: 14 }, offlineBanner: { padding: 12, borderRadius: 8, backgroundColor: palette.accent.dim, }, errorBanner: { padding: 12, gap: 10, borderRadius: 8, borderWidth: 1, borderColor: palette.tag.red, backgroundColor: palette.bg.card, }, inlineButton: { minHeight: 48, justifyContent: 'center' }, primaryCard: { gap: 8 }, actionRow: { flexDirection: 'row', justifyContent: 'flex-end', gap: 8, marginBottom: 4 }, compactButton: { minWidth: 48, minHeight: 48, paddingHorizontal: 12, alignItems: 'center', justifyContent: 'center', borderWidth: 1, borderColor: palette.border.default, borderRadius: 8, }, fieldLabel: { marginTop: 12, marginBottom: 4 }, fieldValue: { minHeight: 30 }, transcript: { lineHeight: 23 }, input: { minHeight: 48, paddingHorizontal: 12, paddingVertical: 10, borderWidth: 1, borderColor: palette.border.strong, borderRadius: 8, backgroundColor: palette.bg.inset, color: palette.text.primary, fontSize: 14, }, multiline: { minHeight: 140 }, editorActions: { flexDirection: 'row', gap: 10, marginTop: 12 }, flexButton: { flex: 1 }, section: { gap: 8 }, sectionTitle: { letterSpacing: 2, marginBottom: 8 }, metaRow: { flexDirection: 'row', justifyContent: 'space-between', gap: 16, paddingVertical: 6, borderBottomWidth: 1, borderBottomColor: palette.border.subtle, }, metaLabel: { flex: 1 }, metaValue: { flex: 2, textAlign: 'right' }, audioRow: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 6 }, audioInfo: { flex: 1, gap: 3 }, playbackRow: { flexDirection: 'row', justifyContent: 'space-between', paddingTop: 8 }, playbackButton: { minWidth: 48, minHeight: 48, alignItems: 'center', justifyContent: 'center' }, }) }