import { Check, Loader2, LogOut, Pencil, Plus, Search, Trash2, UserPlus, Users, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { locale, t } from '../../i18n'
import {
addSharedListItem,
createSharedList,
deleteSharedList,
getSharedList,
getSharedLists,
inviteCandidates,
inviteToSharedList,
leaveSharedList,
removeSharedListItem,
removeSharedListMember,
renameSharedList,
respondToInvite,
SHARED_LIST_NAME_MAX,
SharedListsUnavailable,
snapshotOf,
type SharedList,
type SharedListCard,
type SharedListInvite,
type SharedListItem,
} from '../../lib/cloud/sharedLists'
import type { ProfileCard } from '../../lib/cloud/social'
import { TYPE_BY_VALUE } from '../../lib/constants'
import { cx, normalizeText } from '../../lib/utils'
import { useMedia } from '../../store'
import { TypeBadge } from '../Badges'
import ConfirmDialog from '../ConfirmDialog'
import Poster from '../Poster'
import { EmptyState } from '../ui'
import ReportButton from '../moderation/ReportButton'
import Avatar from './Avatar'
import PersonRow from './PersonRow'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
/** Mosaïque 2×2 des dernières affiches d'une liste partagée. */
function PosterMosaic({ posters }: { posters: string[] }) {
return (
{[0, 1, 2, 3].map((i) =>
posters[i] ? (

) : (
),
)}
)
}
/** Champ « nom de liste » + bouton (création, renommage). */
function NameForm({ initial = '', submitLabel, onSubmit, onCancel, autoFocus }: { initial?: string; submitLabel: string; onSubmit: (name: string) => Promise; onCancel?: () => void; autoFocus?: boolean }) {
const [name, setName] = useState(initial)
const [busy, setBusy] = useState(false)
const [err, setErr] = useState()
const submit = async () => {
if (!name.trim() || busy) return
setBusy(true)
setErr(undefined)
try {
await onSubmit(name.trim())
setName('')
} catch (e) {
setErr((e as Error).message)
} finally {
setBusy(false)
}
}
return (
setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
void submit()
}
if (e.key === 'Escape' && onCancel) {
e.stopPropagation()
onCancel()
}
}}
placeholder={t('shared.namePh')}
autoFocus={autoFocus}
enterKeyHint="done"
aria-label={t('shared.namePh')}
/>
{err && (
{err}
)}
)
}
// ════════════════════════ Section « Listes partagées » (onglet Listes) ════════════════════════
export function SharedListsSection() {
const social = useSocial()
const [data, setData] = useState<{ lists: SharedListCard[]; invites: SharedListInvite[] }>()
const [unavailable, setUnavailable] = useState(false)
const [creating, setCreating] = useState(false)
const [busyInvite, setBusyInvite] = useState()
useEffect(() => {
if (!social.enabled) return
let alive = true
getSharedLists()
.then((d) => alive && setData(d))
.catch((e) => {
if (!alive) return
if (e instanceof SharedListsUnavailable) setUnavailable(true)
else setData((prev) => prev ?? { lists: [], invites: [] })
})
return () => {
alive = false
}
}, [social.enabled, social.sharedTick])
// Sans compte, ou serveur pas encore à jour : la section n'existe pas
if (!social.enabled || unavailable) return null
const respond = async (inv: SharedListInvite, accept: boolean) => {
setBusyInvite(inv.id)
try {
await respondToInvite(inv.id, accept)
social.bumpShared()
if (accept) social.openSharedList(inv.id)
} catch {
/* l'invitation reste affichée */
} finally {
setBusyInvite(undefined)
}
}
return (
{t('shared.title')}
{t('shared.hint')}
{creating ? (
setCreating(false)}
onSubmit={async (name) => {
const id = await createSharedList(name)
setCreating(false)
social.bumpShared()
social.openSharedList(id)
}}
/>
) : (
)}
{/* Invitations reçues */}
{data && data.invites.length > 0 && (
{data.invites.map((inv) => (
-
{inv.owner?.displayName ?? t('notif.someone')} {t('shared.invitesYou')} {inv.name}
))}
)}
{data === undefined ? (
{t('social.loading')}
) : data.lists.length === 0 ? (
{t('shared.none')}
) : (
{data.lists.map((l) => (
))}
)}
)
}
// ════════════════════════ Une liste partagée (plein écran) ════════════════════════
export function SharedListSheet({ id, onClose }: { id: string; onClose: () => void }) {
const social = useSocial()
const [list, setList] = useState()
const [error, setError] = useState()
const [renaming, setRenaming] = useState(false)
const [editing, setEditing] = useState(false)
const [confirm, setConfirm] = useState<'delete' | 'leave' | null>(null)
const [busyKey, setBusyKey] = useState()
const [reload, setReload] = useState(0)
useEffect(() => {
let alive = true
getSharedList(id)
.then((l) => alive && setList(l))
.catch((e) => alive && (setError((e as Error).message), setList(null)))
return () => {
alive = false
}
}, [id, reload, social.sharedTick])
const refresh = () => setReload((n) => n + 1)
const act = async (key: string, fn: () => Promise) => {
setBusyKey(key)
setError(undefined)
try {
await fn()
refresh()
social.bumpShared()
} catch (e) {
setError((e as Error).message)
} finally {
setBusyKey(undefined)
}
}
const accepted = list?.members.filter((m) => m.status === 'accepted') ?? []
const ownerId = list?.members.find((m) => m.isOwner)?.id
const pending = list?.members.filter((m) => m.status === 'pending') ?? []
return (
{list === undefined ? (
) : list === null ? (
) : (
{/* Nom + compteurs */}
{renaming ? (
setRenaming(false)}
onSubmit={async (name) => {
await renameSharedList(list.id, name)
setRenaming(false)
refresh()
social.bumpShared()
}}
/>
) : (
{t('shared.badge')}
{list.name}
{t('account.nTitles', { count: list.items.length })} · {t('shared.nMembers', { count: accepted.length })}
)}
{!list.isOwner && ownerId &&
}
{list.isOwner && !renaming && (
)}
{/* Membres */}
{t('shared.members')}
{list.isOwner && (
)}
{[...accepted, ...pending].map((m) => (
-
{list.isOwner && !m.isOwner && (
)}
))}
{error && (
{error}
)}
{/* Titres */}
{editing &&
}
{list.items.length === 0 ? (
) : (
{list.items.map((it) => (
social.openTitle(it)}
onRemove={() => void act(`i:${it.externalId}`, () => removeSharedListItem(list.id, it.externalId))}
/>
))}
)}
{/* Quitter / supprimer */}
{list.isOwner ? (
) : (
)}
)}
setConfirm(null)}
onConfirm={async () => {
if (!list) return
const kind = confirm
setConfirm(null)
try {
if (kind === 'delete') await deleteSharedList(list.id)
else await leaveSharedList(list.id)
social.bumpShared()
onClose()
} catch (e) {
setError((e as Error).message)
}
}}
/>
)
}
function SharedItemCard({ item, editing, busy, onOpen, onRemove }: { item: SharedListItem; editing: boolean; busy: boolean; onOpen: () => void; onRemove: () => void }) {
return (
{item.addedBy && (
{t('shared.addedBy', { name: item.addedBy.displayName })}
)}
{editing && (
)}
)
}
/** Ajouter / retirer des titres de ma bibliothèque (ceux qui ont une référence TMDB / AniList). */
function LibraryPicker({ list, onChanged }: { list: SharedList; onChanged: () => void }) {
const { items } = useMedia()
const social = useSocial()
const [query, setQuery] = useState('')
const [busy, setBusy] = useState()
const [err, setErr] = useState()
const inList = useMemo(() => new Set(list.items.map((i) => i.externalId)), [list.items])
const candidates = useMemo(() => {
const q = normalizeText(query)
return items
.filter((i) => i.externalId && (!q || normalizeText(`${i.title} ${i.originalTitle ?? ''}`).includes(q)))
.sort((a, b) => a.title.localeCompare(b.title, locale()))
.slice(0, 60)
}, [items, query])
const toggle = async (item: (typeof items)[number]) => {
const snap = snapshotOf(item)
if (!snap) return
setBusy(item.id)
setErr(undefined)
try {
if (inList.has(snap.externalId)) await removeSharedListItem(list.id, snap.externalId)
else await addSharedListItem(list.id, snap)
onChanged()
social.bumpShared()
} catch (e) {
setErr((e as Error).message)
} finally {
setBusy(undefined)
}
}
return (
setQuery(e.target.value)} placeholder={t('lists.searchLibrary')} className="field ps-10" aria-label={t('lists.searchLibrary')} />
{err && (
{err}
)}
{candidates.map((item) => {
const on = inList.has(item.externalId!)
return (
-
)
})}
{candidates.length === 0 && - {t('shared.noCandidates')}
}
)
}
// ════════════════════════ Inviter des membres ════════════════════════
export function InvitePeople({ listId, listName, onClose }: { listId: string; listName: string; onClose: () => void }) {
const social = useSocial()
const [q, setQ] = useState('')
const [people, setPeople] = useState()
const [invited, setInvited] = useState>(new Set())
const [busy, setBusy] = useState()
const [err, setErr] = useState()
useEffect(() => {
let alive = true
const timer = setTimeout(
() => {
inviteCandidates(listId, q)
.then((r) => alive && setPeople(r))
.catch((e) => alive && (setPeople([]), setErr((e as Error).message)))
},
q ? 250 : 0,
)
return () => {
alive = false
clearTimeout(timer)
}
}, [listId, q])
const invite = async (p: ProfileCard) => {
setBusy(p.id)
setErr(undefined)
try {
await inviteToSharedList(listId, p.id)
setInvited((s) => new Set(s).add(p.id))
social.bumpShared()
} catch (e) {
setErr((e as Error).message)
} finally {
setBusy(undefined)
}
}
return (
{t('shared.inviteHint', { name: listName })}
setQ(e.target.value)} placeholder={t('shared.searchPeople')} className="field ps-10" autoFocus aria-label={t('shared.searchPeople')} />
{err && (
{err}
)}
{people === undefined ? (
) : people.length === 0 ? (
{t('shared.noPeople')}
) : (
{people.map((p) => (
void invite(p)}
disabled={busy === p.id || invited.has(p.id)}
className={cx(
'flex h-8 shrink-0 items-center gap-1 rounded-md px-3 text-xs font-semibold transition active:scale-95',
invited.has(p.id) ? 'border border-line-strong text-ink-2' : 'bg-accent-fill text-on-accent',
)}
>
{busy === p.id ? : invited.has(p.id) ? : }
{invited.has(p.id) ? t('shared.invited') : t('shared.inviteShort')}
}
/>
))}
)}
)
}