import { t } from '../i18n' import { LanguageSelect } from '../i18n/react' import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, Import, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react' import { useEffect, useId, useRef, useState, type ReactNode } from 'react' import AccountSection from '../components/AccountSection' import ConfirmDialog from '../components/ConfirmDialog' import ImportWizard from '../components/ImportWizard' import { PageHeader, SectionTitle } from '../components/ui' import { exportBackup, parseBackupFile, type ParsedBackup } from '../lib/backup' import { testTmdbKey } from '../lib/catalogApi' import { checkTmdbProxy, type ProxyState } from '../lib/cloud/api' import { ALL_TOP_CATEGORIES, TOP_CATEGORIES } from '../lib/constants' import { THEME_MODES } from '../lib/theme' import { detectPlatform, useInstallPrompt } from '../lib/pwa' import { isAdmin } from '../lib/cloud/admin' import { cx } from '../lib/utils' import { useEscape } from '../lib/escape' import { useBackToClose } from '../lib/backNav' import { useScrollLock } from '../lib/scrollLock' import { useMedia } from '../store' import { BugReportRow } from '../components/moderation/BugReport' import { alertsSummary, useAdminAlerts } from '../components/moderation/useAdminAlerts' type Message = { kind: 'ok' | 'error'; text: string } function Row({ icon, title, hint, onClick, danger }: { icon: ReactNode; title: string; hint?: string; onClick: () => void; danger?: boolean }) { return ( ) } /** Bloque le défilement de la page tant qu'il est affiché (fenêtre d'installation). */ function ScrollLock() { useScrollLock() return null } export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { const { items, settings, updateSettings, importItems, clearAll, lists, mergeLists, account, guest, requestAccount } = useMedia() const { canInstall, installed, install } = useInstallPrompt() const [admin, setAdmin] = useState(false) // Une seule vérification par connexion (et pas à chaque changement d'état de la synchro) const signedIn = !!account useEffect(() => { // Réponse arrivée après une déconnexion (ou la fermeture de la page) : ignorée let alive = true if (signedIn) void isAdmin() .then((ok) => alive && setAdmin(ok)) .catch(() => alive && setAdmin(false)) else setAdmin(false) return () => { alive = false } }, [signedIn]) const adminHint = alertsSummary(useAdminAlerts(admin)) const fileRef = useRef(null) const [pending, setPending] = useState() const [message, setMessage] = useState() const [confirm, setConfirm] = useState(null) const [deleting, setDeleting] = useState(false) const [usage, setUsage] = useState() const [keyDraft, setKeyDraft] = useState(settings.tmdbKey ?? '') const [showKey, setShowKey] = useState(false) const [keyState, setKeyState] = useState<'idle' | 'testing' | 'ok' | 'bad'>(settings.tmdbKey ? 'ok' : 'idle') useEffect(() => { navigator.storage ?.estimate?.() .then(({ usage: u }) => u != null && setUsage(u < 1e6 ? t('common.kb', { n: Math.max(1, Math.round(u / 1e3)) }) : t('common.mb', { n: (u / 1e6).toFixed(1).replace('.', t('common.decimalSep')) }))) .catch(() => {}) }, [items.length]) // Avec un compte : vérifie que le proxy TMDB fonctionne vraiment const [proxy, setProxy] = useState('checking') const runProxyCheck = async () => { setProxy('checking') setProxy(await checkTmdbProxy()) } useEffect(() => { if (account) void runProxyCheck() // eslint-disable-next-line react-hooks/exhaustive-deps }, [!!account]) const saveKey = async () => { const key = keyDraft.trim() if (!key) { updateSettings({ tmdbKey: undefined }) setKeyState('idle') return } setKeyState('testing') const ok = await testTmdbKey(key) setKeyState(ok ? 'ok' : 'bad') if (ok) updateSettings({ tmdbKey: key }) } const onExport = async () => { try { const how = await exportBackup(items, settings, lists) setMessage({ kind: 'ok', text: how === 'shared' ? t('settings.backupShared') : t('settings.backupDownloaded') }) } catch (e) { if ((e as DOMException)?.name !== 'AbortError') setMessage({ kind: 'error', text: t('settings.exportFailed') }) } } const onFile = async (file?: File) => { if (fileRef.current) fileRef.current.value = '' if (!file) return try { const parsed = await parseBackupFile(file) if (!parsed.items.length) throw new Error(t('settings.noValidItems')) setPending(parsed) setMessage(undefined) } catch (e) { setMessage({ kind: 'error', text: (e as Error).message }) } } // Le message s'affiche en bas de l'écran puis disparaît (visible même en bas de page) useEffect(() => { if (!message) return const timer = setTimeout(() => setMessage(undefined), 3500) return () => clearTimeout(timer) }, [message]) const confirmImport = async (mode: 'merge' | 'replace') => { if (!pending) return setConfirm(null) try { await importItems(pending.items, mode) if (pending.settings) updateSettings(pending.settings) if (pending.lists) mergeLists(pending.lists, mode) setMessage({ kind: 'ok', text: pending.skipped ? t('settings.importedSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.imported', { count: pending.items.length }), }) setPending(undefined) } catch (e) { setMessage({ kind: 'error', text: (e as Error).message }) } } const onDeleteAccount = async () => { if (!account) return setConfirm(null) setDeleting(true) try { await account.deleteAccount() } catch (e) { setMessage({ kind: 'error', text: (e as Error).message }) setDeleting(false) } } const onReset = async () => { setConfirm(null) try { await clearAll() setMessage({ kind: 'ok', text: t('settings.cleared') }) } catch (e) { setMessage({ kind: 'error', text: (e as Error).message }) } } const [showImport, setShowImport] = useState(false) const [showInstall, setShowInstall] = useState(false) useEscape(() => setShowInstall(false), showInstall) useBackToClose(() => setShowInstall(false), showInstall) const installTitleId = useId() const platform = detectPlatform() const doNativeInstall = async () => { const ok = await install() setShowInstall(false) if (ok) setMessage({ kind: 'ok', text: t('settings.installed') }) } return ( <> {message && (

{message.text}

)} {account && setMessage({ kind, text })} />} {guest && ( <> {t('account.title')}

{t('guest.banner')}

)} {admin && ( <> {t('settings.admin')}
} title={t('admin.title')} hint={adminHint} onClick={onOpenAdmin} />
)} {t('settings.language')}

{t('settings.languageHint')}

{t('settings.rating')}
{(['5', '10'] as const).map((scale) => ( ))}

{t('settings.ratingHint')}

{t('settings.appearance')}
{THEME_MODES.map(({ value, label }) => { const on = settings.themeMode === value return ( ) })}

{t('settings.appearanceHint')}

{t('settings.installApp')}
{installed ? (
{t('settings.installed')}
) : ( )}

{t('settings.installHint')}

{showInstall && (
setShowInstall(false)}>
e.stopPropagation()}>

{t('install.title')}

    {t(`install.${platform}`).split('\n').map((step, i) => (
  1. {i + 1} {step}
  2. ))}
{canInstall && ( )}
)} {t('settings.databases')}
AniList {t('settings.anilistActive')}

{t('settings.noConfig')}

{/* Mode découverte : TMDB passe par le serveur, rien à régler ici */} {guest ? null : account ? (
TMDB {proxy === 'ok' ? t('settings.tmdbActive') : proxy === 'checking' ? t('settings.checking') : proxy === 'offline' ? t('settings.offline') : proxy === 'missing-key' ? t('settings.proxyMissingKey') : proxy === 'not-deployed' ? t('settings.proxyNotDeployed') : t('settings.unavailable')}

{proxy === 'missing-key' ? t('settings.proxyMissingKeyHint') : proxy === 'not-deployed' ? t('settings.proxyNotDeployedHint') : proxy === 'error' ? t('settings.proxyErrorHint') : t('settings.proxyOkHint')}

{proxy !== 'ok' && proxy !== 'checking' && ( )}
) : (
TMDB {keyState === 'ok' ? t('settings.tmdbActive') : keyState === 'bad' ? t('settings.keyRefused') : keyState === 'testing' ? t('settings.checking') : t('settings.notConfigured')}

{t('settings.tmdbHelp')}

{ setKeyDraft(e.target.value) setKeyState('idle') }} placeholder={t('settings.tmdbKey')} autoComplete="off" autoCapitalize="off" spellCheck={false} />

{t('settings.keyLocal')}

)}
Top 5

{t('settings.topHint')}

{TOP_CATEGORIES.map((c) => { const on = settings.topCategories.includes(c.value) return ( ) })}
{settings.topCategories.length === 0 &&

{t('settings.topNone')}

} {t('settings.backup')}
} title={t('settings.export')} hint={t('settings.exportHint', { count: items.length })} onClick={onExport} /> } title={t('settings.import')} hint={t('settings.importHint')} onClick={() => fileRef.current?.click()} /> onFile(e.target.files?.[0])} /> } title={t('import.row')} hint={t('import.rowHint')} onClick={() => setShowImport(true)} />
{showImport && setShowImport(false)} />} {pending && (

{pending.format === 'legacy' && {t('settings.legacyDetected')}} {pending.skipped ? t('settings.foundSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.found', { count: pending.items.length })}

{t('settings.mergeHint')}

)} {t('settings.storage')}
{t('settings.used')} {usage ?? '—'}

{account ? t('settings.storageCloud') : t('settings.storageLocal')}

{t('settings.danger')}
} title={t('settings.clearAll')} hint={account ? t('settings.clearAllHintCloud', { count: items.length }) : t('settings.clearAllHint', { count: items.length })} onClick={() => setConfirm('reset')} danger /> {account && (
} title={deleting ? t('settings.deleting') : t('settings.deleteAccount')} hint={t('settings.deleteAccountHint')} onClick={() => !deleting && setConfirm('delete-account')} danger />
)}
{t('settings.about')}
{( [ ['/privacy.html', t('legal.privacy')], ['/legal.html#conditions', t('legal.terms')], ['/legal.html#mentions', t('legal.notice')], ['/legal.html#credits', t('legal.credits')], ] as const ).map(([href, label]) => ( {label} ))}

{t('legal.tmdb')}

Bobinoo v2.2 · {account ? t('settings.footerCloud') : t('settings.footerLocal')}

setConfirm(null)} /> setConfirm(null)} /> confirmImport('replace')} onCancel={() => setConfirm(null)} /> ) }