import { ArrowLeft, Check, ChevronDown, FileUp, Loader2, X } from 'lucide-react' import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react' import { t, type TKey } from '../i18n' import { useBackToClose } from '../lib/backNav' import ImportTextReview from './ImportTextReview' import { useEscape } from '../lib/escape' import { ImportFileError, readImportFile, type TextFile } from '../lib/import/files' import { buildImportPlan, countByKind, type ImportPlan } from '../lib/import/merge' import { CancelledError, fetchAniListUser, isAniListUserName, resolveEntries, resolveTextEntries, withProgress, type CancelToken, type Match, type Progress } from '../lib/import/resolve' import { parseTextList, TEXT_MAX_CHARS, type TextEntry } from '../lib/import/textList' import { letterboxdRole, parseLetterboxd, parseMal, parseTvTime, type ImportEntry, type ImportSource } from '../lib/import/sources' import { useScrollLock } from '../lib/scrollLock' import { LIMITS } from '../lib/security' import { cx } from '../lib/utils' import { useMedia } from '../store' /** * Assistant « Importer depuis une autre app » : Letterboxd, TV Time, MyAnimeList, AniList. * Source → fichier (ou nom d'utilisateur) → recherche des fiches → aperçu → fusion → résumé. * Tout se passe sur l'appareil ; la synchro existante enverra ensuite les fiches au compte. */ type Step = 'source' | 'input' | 'working' | 'review' | 'preview' | 'done' const SOURCES: { id: ImportSource; name: string; mark: string; accept?: string; multiple?: boolean }[] = [ { id: 'text', name: '', mark: 'Aa' }, { id: 'letterboxd', name: 'Letterboxd', mark: 'Lb', accept: '.zip,.csv,application/zip,text/csv', multiple: true }, { id: 'tvtime', name: 'TV Time', mark: 'TV', accept: '.zip,.csv,application/zip,text/csv', multiple: true }, { id: 'mal', name: 'MyAnimeList', mark: 'MAL', accept: '.xml,.gz,application/xml,text/xml,application/gzip' }, { id: 'anilist', name: 'AniList', mark: 'AL' }, ] const NEEDS_TMDB: ImportSource[] = ['text', 'letterboxd', 'tvtime'] const sourceName = (s: { id: ImportSource; name: string }) => (s.id === 'text' ? t('import.text.name') : s.name) /** Message lisible pour une erreur de lecture / de réseau. */ function errorText(e: unknown): string { if (e instanceof ImportFileError) { const k = `import.err.${e.message}` as TKey return ['tooBig', 'badZip', 'encrypted', 'unsupported'].includes(e.message) ? t(k) : t('import.err.read') } const msg = (e as Error)?.message if (msg === 'anilist-user') return t('import.err.user') if (msg === 'rate') return t('err.anilistRate') if (!navigator.onLine) return t('search.offline') return msg || t('import.err.read') } async function readEntries(source: ImportSource, files: File[]): Promise { const texts: TextFile[] = [] for (const f of files.slice(0, 40)) { const keep = source === 'letterboxd' ? (p: string) => !!letterboxdRole(p) : source === 'mal' ? (p: string) => /\.xml$/.test(p) : (p: string) => /\.csv$/.test(p) texts.push(...(await readImportFile(f, keep, LIMITS.importFileBytes))) } if (source === 'letterboxd') return parseLetterboxd(texts) if (source === 'tvtime') return parseTvTime(texts) const xml = texts.find((x) => x.text.includes('')) if (!xml) throw new ImportFileError('read') return parseMal(xml.text) } export default function ImportWizard({ onClose }: { onClose: () => void }) { const { items, settings, importItems } = useMedia() const [step, setStep] = useState('source') const [source, setSource] = useState() const [userName, setUserName] = useState('') const [error, setError] = useState() const [phase, setPhase] = useState<'reading' | 'resolving' | 'saving'>('reading') const [progress, setProgress] = useState({ done: 0, total: 0 }) const [entries, setEntries] = useState([]) const [matches, setMatches] = useState>(new Map()) const [includeUnmatched, setIncludeUnmatched] = useState(false) const [showMissing, setShowMissing] = useState(false) const [result, setResult] = useState<{ added: number; updated: number; unchanged: number; notFound: number }>() const [dragging, setDragging] = useState(false) // Liste collée const [pasted, setPasted] = useState('') const [defaultStatus, setDefaultStatus] = useState<'termine' | 'a_voir'>('termine') const [unsure, setUnsure] = useState>(new Set()) const [excluded, setExcluded] = useState>(new Set()) const [now, setNow] = useState(Date.now()) const token = useRef({ cancelled: false }) const fileRef = useRef(null) const close = () => { token.current.cancelled = true onClose() } useScrollLock() useEscape(close) useBackToClose(close) // Fermeture de l'assistant : la recherche en cours s'arrête useEffect(() => () => void (token.current.cancelled = true), []) // Compte à rebours pendant une pause imposée par la limite de débit useEffect(() => { if (!progress.waitUntil) return const id = setInterval(() => setNow(Date.now()), 500) return () => clearInterval(id) }, [progress.waitUntil]) const info = SOURCES.find((s) => s.id === source) const hasTmdb = !!settings.tmdbKey?.trim() const plan: ImportPlan | undefined = useMemo(() => { if (step !== 'preview') return undefined // Liste collée : seulement les lignes gardées, avec la progression « S3E12 » convertie en épisodes const list = source === 'text' ? (entries as TextEntry[]).filter((e) => !excluded.has(e.key) && matches.has(e.key)).map((e) => withProgress(e, matches.get(e.key))) : entries return buildImportPlan(list, matches, items, { includeUnmatched: source === 'text' ? false : includeUnmatched }) }, [step, source, entries, matches, items, includeUnmatched, excluded]) const run = async (load: () => Promise) => { const tk = { cancelled: false } token.current = tk setError(undefined) setStep('working') setPhase('reading') setProgress({ done: 0, total: 0 }) try { const list = await load() if (tk.cancelled) return if (!list.length) throw new Error(t('import.err.empty')) setEntries(list) setPhase('resolving') const found = await resolveEntries(list, { tmdbKey: settings.tmdbKey, token: tk, onProgress: (p) => !tk.cancelled && setProgress(p) }) if (tk.cancelled) return setMatches(found) setShowMissing(false) setIncludeUnmatched(false) setStep('preview') } catch (e) { if (e instanceof CancelledError || tk.cancelled) return setError(errorText(e)) setStep('input') } } const onFiles = (list: FileList | null | undefined) => { const files = Array.from(list ?? []) if (fileRef.current) fileRef.current.value = '' if (!files.length || !source || source === 'anilist' || source === 'text') return void run(() => readEntries(source, files)) } const onText = () => { const list = parseTextList(pasted, { defaultStatus }) if (!list.length) return setError(t('import.err.empty')) const tk = { cancelled: false } token.current = tk setError(undefined) setEntries(list) setStep('working') setPhase('resolving') setProgress({ done: 0, total: list.length }) resolveTextEntries(list, { tmdbKey: settings.tmdbKey, token: tk, onProgress: (p) => !tk.cancelled && setProgress(p) }) .then(({ found, unsure }) => { if (tk.cancelled) return setEntries([...list]) setMatches(found) setUnsure(unsure) setExcluded(new Set()) setStep('review') }) .catch((e) => { if (e instanceof CancelledError || tk.cancelled) return setError(errorText(e)) setStep('input') }) } const onAniList = () => { const name = userName.trim() if (!isAniListUserName(name)) return setError(t('import.err.user')) void run(async () => (await fetchAniListUser(name)).entries) } const cancelWork = () => { token.current.cancelled = true setStep('input') } const confirm = async () => { if (!plan) return setStep('working') setPhase('saving') try { await importItems([...plan.added, ...plan.updated], 'merge') setResult({ added: plan.added.length, updated: plan.updated.length, unchanged: plan.unchanged, notFound: includeUnmatched || source === 'text' ? 0 : plan.notFound.length }) setStep('done') } catch (e) { setError(errorText(e)) setStep('preview') } } const onDrop = (e: DragEvent) => { e.preventDefault() setDragging(false) onFiles(e.dataTransfer?.files) } const back = () => { setError(undefined) setStep(step === 'preview' ? (source === 'text' ? 'review' : 'input') : step === 'review' ? 'input' : 'source') } const pct = progress.total ? Math.round((progress.done / progress.total) * 100) : 0 const wait = progress.waitUntil ? Math.max(0, Math.ceil((progress.waitUntil - now) / 1000)) : 0 const kinds = plan ? countByKind(plan.added) : undefined return (
{step === 'input' || step === 'review' || step === 'preview' ? ( ) : ( )}

{info && step !== 'source' ? sourceName(info) : t('import.title')}

{step === 'source' && ( <>

{t('import.chooseSource')}

{SOURCES.map((s) => ( ))}

{t('import.mergeHint')}

)} {step === 'input' && info && ( <> {t('import.how')}
    {t(`import.steps.${info.id}` as TKey) .split('\n') .map((line, i) => (
  1. {i + 1} {line}
  2. ))}
{NEEDS_TMDB.includes(info.id) && !hasTmdb && (

{t('import.noTmdb')}

)} {info.id === 'text' ? (