import { Ban, Check, Loader2, Lock, Share2, Star, UserCheck, UserPlus } from 'lucide-react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { fmtNumber, t } from '../../i18n' import { follow, getProfile, getProfileItems, getPublicProfile, PROFILE_ITEMS_PAGE, profileLink, unfollow, type Profile } from '../../lib/cloud/social' import { STATUSES, TOP_CATEGORIES } from '../../lib/constants' import { cx, formatRating } from '../../lib/utils' import { useMedia } from '../../store' import type { MediaItem, WatchStatus } from '../../types' import ConfirmDialog from '../ConfirmDialog' import ReportButton from '../moderation/ReportButton' import { blockUser, unblockUser, useBlocked } from '../../lib/cloud/moderation' import Poster from '../Poster' import { EmptyState, SectionTitle } from '../ui' import TopFive from '../TopFive' import Avatar from './Avatar' import Sheet from './Sheet' import { useSocial } from './SocialProvider' function PosterTile({ item, onOpen, caption }: { item: MediaItem; onOpen: () => void; caption?: string }) { return ( ) } function Stat({ value, label, onClick }: { value?: number; label: string; onClick?: () => void }) { const body = ( <> {value == null ? '—' : fmtNumber(value)} {label} ) return onClick ? ( ) : (
{body}
) } /** * Page de profil (la mienne ou celle d'un autre). * `guest` : ouverte sans compte depuis un lien bobinoo.org/@pseudo. Seulement la version publique du profil * (si la personne l'a activée), et chaque geste (suivre, voir la bibliothèque) propose de créer un compte. */ export default function ProfileView({ username, onClose, guest = false }: { username: string; onClose: () => void; guest?: boolean }) { const social = useSocial() const { settings, items: myItems, requestAccount } = useMedia() // Mon profil : affiché tout de suite avec ce qu'on a déjà, puis rechargé const [profile, setProfile] = useState(() => (social.me?.username === username ? social.me : undefined)) const [error, setError] = useState() const [tab, setTab] = useState<'profile' | 'top' | 'library'>('profile') const [busy, setBusy] = useState(false) const [confirmUnfollow, setConfirmUnfollow] = useState(false) const [toast, setToast] = useState() const [confirmBlock, setConfirmBlock] = useState(false) const { isBlocked } = useBlocked(!guest && !!profile && !profile.isMe) const blocked = !!profile && !profile.isMe && isBlocked(profile.id) /** `reload` : rechargement après une action (s'abonner, bloquer…) — en cas d'échec, on garde le profil affiché. */ const load = useCallback( async (reload = false) => { if (!reload) setError(undefined) try { const next = await (guest ? getPublicProfile(username) : getProfile(username)) if (reload) setError(undefined) setProfile(next) } catch (e) { if (reload) return setToast((e as Error).message) setError((e as Error).message) setProfile(null) } }, [username, guest], ) useEffect(() => { void load() }, [load]) // Mon profil a changé (modification) : on recharge useEffect(() => { if (profile?.isMe && social.me) setProfile(social.me) // eslint-disable-next-line react-hooks/exhaustive-deps }, [social.me]) useEffect(() => { if (!toast) return const timer = setTimeout(() => setToast(undefined), 2500) return () => clearTimeout(timer) }, [toast]) const owner = profile ? { username: profile.username, displayName: profile.displayName, avatarUrl: profile.avatarUrl } : undefined const openItem = (item: MediaItem) => social.openItem(item, profile?.isMe ? undefined : owner) const share = async () => { if (!profile) return const url = profileLink(profile.username) // Mon lien, pas encore public : il ne s'ouvrira que pour les membres connectés (on le dit, sans bloquer le partage) const membersOnly = profile.isMe && !profile.publicLink try { if (navigator.share && window.matchMedia?.('(pointer: coarse)').matches) { await navigator.share({ title: profile.displayName, url }) if (membersOnly) setToast(t('social.linkMembersOnly')) } else { await navigator.clipboard.writeText(url) setToast(membersOnly ? `${t('social.linkCopied')} ${t('social.linkMembersOnly')}` : t('social.linkCopied')) } } catch { /* partage annulé */ } } const toggleFollow = async () => { if (!profile) return if (profile.relation !== 'none') return setConfirmUnfollow(true) setBusy(true) try { await follow(profile.id) await load(true) void social.refresh() } catch (e) { setToast((e as Error).message) } finally { setBusy(false) } } const doUnfollow = async () => { if (!profile) return setConfirmUnfollow(false) setBusy(true) try { await unfollow(profile.id) await load(true) void social.refresh() } catch (e) { setToast((e as Error).message) } finally { setBusy(false) } } // Bloquer : il ne peut plus me suivre ni réagir à mes avis ; ses avis me sont masqués const doBlock = async () => { if (!profile) return setConfirmBlock(false) setBusy(true) try { await blockUser({ id: profile.id, username: profile.username, displayName: profile.displayName, avatarUrl: profile.avatarUrl }) await load(true) void social.refresh() setToast(t('block.done', { name: profile.displayName })) } catch (e) { setToast((e as Error).message) } finally { setBusy(false) } } const doUnblock = async () => { if (!profile) return setBusy(true) try { await unblockUser(profile.id) setToast(t('block.undone', { name: profile.displayName })) } catch (e) { setToast((e as Error).message) } finally { setBusy(false) } } const topByCategory = useMemo(() => { const out: { label: string; single: string; items: MediaItem[] }[] = [] // Mon profil : mes réglages locaux font foi tout de suite (même avant la synchro) const shown = profile?.isMe ? TOP_CATEGORIES.filter((c) => settings.topCategories.includes(c.value)) : TOP_CATEGORIES for (const c of shown) { // Mon profil : mes fiches locales (un Top 5 modifié se voit tout de suite) const source = profile?.isMe ? myItems.filter((i) => i.top) : (profile?.top ?? []) const list = source.filter((i) => i.top?.category === c.value).sort((a, b) => a.top!.rank - b.top!.rank) if (list.length) out.push({ label: c.plural, single: c.label, items: list }) } return out }, [profile, settings.topCategories, myItems]) // Mon profil : l'onglet Top 5 est toujours là (c'est ici qu'on le modifie) ; un autre : seulement s'il en a un const showTop = !!profile && (profile.isMe ? settings.topCategories.length > 0 : topByCategory.length > 0) // Sans compte : pas de bibliothèque complète (réservée aux membres) const tabs = (['profile', ...(showTop ? ['top'] : []), ...(guest ? [] : ['library'])] as ('profile' | 'top' | 'library')[]) return ( ) : undefined } > {profile === undefined ? (

{t('social.loading')}

) : profile === null ? (
{guest && !error ? ( <> ) : ( )}
) : ( <> {/* Bannière + photo */}
{profile.bannerUrl && }
{/* La photo chevauche la bannière ; les boutons restent en dessous (pt = partie de la photo posée sur la bannière + marge) */}
{profile.isMe ? ( ) : guest ? ( ) : (
{blocked ? ( ) : ( )} , label: t('block.unblock'), onClick: () => void doUnblock() } : { icon: , label: t('block.block'), onClick: () => setConfirmBlock(true) }, ]} />
)}

{profile.displayName}

@{profile.username} {profile.isPrivate && } {profile.followsMe && !profile.isMe && ( {t('social.followsYou')} )}

{profile.bio &&

{profile.bio}

} {blocked && (

{t('block.notice')}

)}
social.openFollowList(profile, 'followers') : undefined} /> social.openFollowList(profile, 'following') : undefined} />
{profile.isMe && social.requests.length > 0 && ( )} {!profile.visible ? (

{t('social.privateTitle')}

{t('social.privateText')}

) : ( <>
{tabs.map((v) => ( ))}
{tab === 'profile' ? ( <> {guest && (

{t('social.publicCtaTitle')}

{t('social.publicCtaText', { name: profile.displayName })}

)} ) : tab === 'top' ? ( ) : ( )} )}
)} {toast && (

{toast}

)} setConfirmBlock(false)} /> setConfirmUnfollow(false)} />
) } type TopGroup = { label: string; single: string; items: MediaItem[] } /** Onglet Profil : le n°1 de chaque Top 5, ce que je regarde, mes 5 derniers vus. */ function ProfileTab({ profile, topByCategory, onOpen }: { profile: Profile; topByCategory: TopGroup[]; onOpen: (i: MediaItem) => void }) { const firsts = topByCategory.flatMap((c) => (c.items[0]?.top?.rank === 1 ? [{ item: c.items[0], category: c.single }] : [])) const recent = profile.recent.slice(0, 5) return ( <> {firsts.length > 0 && ( <> {t('social.top1')}
{firsts.map(({ item, category }) => ( onOpen(item)} caption={category} /> ))}
)} {profile.watching.length > 0 && ( <> {t('social.watching')}
{profile.watching.map((item) => ( onOpen(item)} /> ))}
)} {t('social.recent')} {recent.length ? (
{recent.map((item) => ( onOpen(item)} /> ))}
) : (

{t('social.noRecent')}

)} ) } /** Onglet Top 5 : le même affichage que l'ancien accueil. Le mien se modifie ici ; celui d'un autre est en lecture seule. */ function TopTab({ profile, onOpen }: { profile: Profile; onOpen: (i: MediaItem) => void }) { return (
) } function LibraryTab({ profile, onOpen }: { profile: Profile; onOpen: (i: MediaItem) => void }) { const [status, setStatus] = useState('') const [list, setList] = useState([]) const [loading, setLoading] = useState(false) const [done, setDone] = useState(false) const request = useRef(0) // Lignes reçues du serveur (y compris celles écartées à la relecture) : décalage de la page suivante const received = useRef(0) const loadPage = useCallback( async (reset: boolean) => { // Une réponse arrivée après un changement de filtre ne doit pas écraser la nouvelle liste const id = ++request.current setLoading(true) if (reset) { setList([]) received.current = 0 } try { const page = await getProfileItems(profile.id, status || null, reset ? 0 : received.current) if (id !== request.current) return received.current += page.received setList((prev) => { // Sans doublon (une fiche ne peut apparaître qu'une fois : même clé React) const base = reset ? [] : prev const seen = new Set(base.map((i) => i.id)) return [...base, ...page.items.filter((i) => !seen.has(i.id) && !!seen.add(i.id))] }) setDone(page.received < PROFILE_ITEMS_PAGE) } catch { if (id === request.current) setDone(true) } finally { if (id === request.current) setLoading(false) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [profile.id, status], ) useEffect(() => { void loadPage(true) // eslint-disable-next-line react-hooks/exhaustive-deps }, [profile.id, status]) return (
{STATUSES.map((s) => ( ))}
{list.length ? (
{list.map((item) => ( onOpen(item)} /> ))}
) : ( !loading &&

{t('social.emptyLibrary')}

)} {loading && (

)} {!loading && !done && list.length > 0 && ( )}
) }