import { locale, t } from '../i18n'
import { Check, Heart, ImagePlus, Loader2, MessagesSquare, Minus, Plus, Share2, Trash2, X } from 'lucide-react'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { CRITERIA, DEFAULT_FILM_MINUTES, MEDIA_TYPES, STATUSES, TYPE_BY_VALUE } from '../lib/constants'
import { canonicalGenre, canonicalSubtype, genreLabel, genreSuggestions as defaultGenres, subtypeLabel, subtypeSuggestions } from '../lib/genres'
import { fileToPosterDataURL } from '../lib/image'
import { getTmdbCredits, getTmdbExtras } from '../lib/catalogApi'
import { episodeCap, seasonPosition } from '../lib/franchise'
import { renderItemCard, slug } from '../lib/shareCard'
import { useScrollLock } from '../lib/scrollLock'
import { cx, formatDate, formatRating, todayISO } from '../lib/utils'
import { airedCount, nextAirDate, useAiringCache } from '../lib/airing'
import { useMedia } from '../store'
import type { MediaInput, MediaItem, RatingScale, WatchStatus } from '../types'
import { StatusDot } from './Badges'
import ConfirmDialog from './ConfirmDialog'
import SharePreview from './SharePreview'
import DatabaseSearch from './DatabaseSearch'
import EpisodeList from './EpisodeList'
import ItemHero, { type HeroAction } from './ItemHero'
import { useSocial } from './social/SocialProvider'
import { NewListForm } from './ListsView'
import Poster from './Poster'
import { RatingInput } from './Rating'
import TagInput from './TagInput'
const EMPTY: MediaInput = {
title: '',
type: 'film',
status: 'a_voir',
criteria: {},
episodesWatched: 0,
genres: [],
}
/** Champs « catalogue » qu'une recherche TMDB/AniList peut remplir. Le reste (statut, note, avis…) n'est jamais touché. */
const METADATA_KEYS = [
'title',
'originalTitle',
'type',
'subtype',
'year',
'overview',
'duration',
'episodesTotal',
'seasons',
'episodeDuration',
'poster',
'backdrop',
'externalId',
'countries',
'publicRating',
] as const
function Section({ title, children }: { title: string; children: ReactNode }) {
return (
{title && {title}
}
{children}
)
}
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
)
}
/** input number → nombre ou undefined si vide */
const toNum = (v: string) => (v === '' ? undefined : Math.max(0, Number(v)))
interface Props {
item?: MediaItem
onClose: () => void
onGoToSettings?: () => void
/** Ouvre une autre fiche (titre déjà dans la bibliothèque) */
onOpenItem?: (item: MediaItem) => void
}
/** « Moi vs le public » : ma note comparée à la moyenne TMDB / AniList. */
function PublicCompare({ mine, pub, scale, source }: { mine?: number; pub: number; scale: RatingScale; source: string }) {
const gap = mine != null ? mine - pub : undefined
const show = (v: number) => formatRating(v, scale) + (scale === '5' ? '/5' : '/10')
const gapText =
gap == null
? undefined
: Math.abs(gap) < 0.5
? t('public.agree')
: gap > 0
? t('public.more', { gap: formatRating(Math.abs(gap), scale) })
: t('public.less', { gap: formatRating(Math.abs(gap), scale) })
return (
{t('public.label')} {show(pub)} · {source}
{gapText && = 0.5 ? 'text-accent' : 'text-ink-3')}>{gapText}}
)
}
/** Liste des dates de revisionnage (films comme séries). */
function Rewatches({ dates, onChange }: { dates: string[]; onChange: (d: string[]) => void }) {
const [draft, setDraft] = useState(todayISO())
const add = () => {
if (!/^\d{4}-\d{2}-\d{2}$/.test(draft) || dates.length >= 100) return
onChange([...dates, draft].sort().reverse())
}
return (
{dates.length > 0 ? (
{dates.map((d, k) => (
-
{new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' })}
))}
) : (
{t('form.rewatchHint')}
)}
)
}
export default function MediaForm({ item, onClose, onGoToSettings, onOpenItem }: Props) {
const social = useSocial()
const { add, update, remove, items, settings, lists, patchMany } = useMedia()
const [form, setForm] = useState(() => {
if (!item) return EMPTY
const { id: _id, createdAt: _c, updatedAt: _u, ...rest } = item
return rest
})
const [saving, setSaving] = useState(false)
const [criteriaOpen] = useState(() => Object.keys(item?.criteria ?? {}).length > 0)
const [showSearch, setShowSearch] = useState(!item)
const [filledFrom, setFilledFrom] = useState()
const [posterError, setPosterError] = useState()
const fileRef = useRef(null)
const typeInfo = TYPE_BY_VALUE[form.type]
// Bloque le défilement de la page derrière la feuille
useScrollLock()
// Fiche TMDB ajoutée avant ces nouveautés : grande image et saisons récupérées en arrière-plan (et gardées)
const extId = form.externalId
useEffect(() => {
const key = settings.tmdbKey?.trim()
const isTv = extId?.startsWith('tmdb:tv:')
if (!extId?.startsWith('tmdb:') || !key || !navigator.onLine || (form.backdrop && (!isTv || form.seasons))) return
let alive = true
getTmdbExtras(extId, key)
.then(({ seasons, total, backdrop }) => {
if (!alive) return
const patch: Partial = {}
if (backdrop && !form.backdrop) patch.backdrop = backdrop
if (seasons && !form.seasons) {
patch.seasons = seasons
if ((total ?? 0) > (form.episodesTotal ?? 0)) patch.episodesTotal = total
}
if (!Object.keys(patch).length) return
setForm((f) => (f.externalId === extId ? { ...f, ...patch } : f))
if (item && item.externalId === extId) void patchMany([{ id: item.id, patch }])
})
.catch(() => {})
return () => {
alive = false
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [extId])
const [editInfo, setEditInfo] = useState(false)
/** En-tête façon plateforme : dès qu'un titre est lié à TMDB / AniList, ou pour une fiche existante */
const hasHero = !!form.title.trim() && (!!form.externalId || !!item)
/** Nouveaux épisodes vus : le statut et les dates suivent. */
const withEpisodes = (f: MediaInput, n: number, season?: number): MediaInput => {
const cap = episodeCap(f)
const watched = Math.max(0, cap ? Math.min(n, cap) : n)
const next: MediaInput = { ...f, episodesWatched: watched, season: f.seasons ? season ?? seasonPosition({ ...f, episodesWatched: watched, season: undefined })?.season : f.season }
if (watched > 0 && (f.status === 'a_voir' || f.status === 'pause')) {
next.status = 'en_cours'
next.startDate = f.startDate ?? todayISO()
}
if (cap && watched >= cap) {
next.status = 'termine'
next.endDate = f.endDate ?? todayISO()
} else if (f.status === 'termine' && watched < (f.episodesWatched ?? 0)) {
next.status = 'en_cours'
next.endDate = undefined
}
return next
}
/** Bouton principal de l'en-tête : épisode suivant (séries) ou « vu » (films). */
// Épisodes déjà sortis (fiche suivie) : on ne coche pas un épisode à venir
const airingCache = useAiringCache()
const aired = item ? airedCount({ id: item.id, type: form.type, externalId: form.externalId }, airingCache) : undefined
const primary: HeroAction = (() => {
if (typeInfo.episodic) {
const cap = episodeCap(form)
if (cap && form.episodesWatched >= cap) return { label: t('hero.allSeen'), done: true }
if (aired != null && form.episodesWatched >= aired) {
const date = item ? nextAirDate({ id: item.id, type: form.type, externalId: form.externalId }, airingCache) : undefined
return { label: date ? t('hero.nextOn', { date: formatDate(date) }) : t('hero.upToDate'), done: true }
}
const nextPos = seasonPosition({ ...form, episodesWatched: form.episodesWatched + 1, season: undefined })
const ep = t('episodes.short', { n: nextPos ? nextPos.episode : form.episodesWatched + 1 })
const label = t('hero.seenEp', { ep: nextPos ? `${t('episodes.seasonShort', { n: nextPos.season })} · ${ep}` : ep })
return { label, onClick: () => setForm((f) => withEpisodes(f, f.episodesWatched + 1)) }
}
if (form.status === 'termine') return { label: t('hero.seen'), done: true }
return { label: t('hero.markSeen'), onClick: () => setStatus('termine') }
})()
const set = (key: K, value: MediaInput[K]) => setForm((f) => ({ ...f, [key]: value }))
// Suggestions = listes par défaut + ce que j'ai déjà utilisé
const genreSuggestions = useMemo(() => [...new Set([...items.flatMap((i) => i.genres.map(genreLabel)), ...defaultGenres()])], [items])
/** Applique les infos trouvées en ligne sans écraser mon suivi (statut, note, épisodes vus, avis…). */
const applyMetadata = (data: Partial) => {
setForm((f) => {
const next: MediaInput = { ...f }
for (const key of METADATA_KEYS) {
if (data[key] !== undefined) (next as unknown as Record)[key] = data[key]
}
// Découpage par saison : celui de la nouvelle source (ou aucun)
next.seasons = data.seasons
next.backdrop = data.backdrop
if (data.type && data.type !== 'autre') next.subtype = undefined
if (data.genres?.length) next.genres = [...new Set([...f.genres, ...data.genres])]
if (data.platform && !f.platform) next.platform = data.platform
const cap = episodeCap(next)
if (cap && next.episodesWatched > cap) next.episodesWatched = cap
return next
})
setFilledFrom(data.externalId?.startsWith('anilist') ? 'AniList' : 'TMDB')
setShowSearch(false)
}
const setStatus = (status: WatchStatus) =>
setForm((f) => {
const next = { ...f, status }
// « À voir » : pas encore regardé, donc pas de dates
if (status === 'a_voir') {
next.startDate = undefined
next.endDate = undefined
}
if (status === 'en_cours' && !f.startDate) next.startDate = todayISO()
if (status === 'termine') {
if (!f.endDate) next.endDate = todayISO()
const cap = episodeCap(f)
if (cap && TYPE_BY_VALUE[f.type].episodic) next.episodesWatched = cap
}
return next
})
// Même règles que la liste d'épisodes : le statut et les dates suivent
const changeEpisodes = (delta: number) => setForm((f) => withEpisodes(f, f.episodesWatched + delta))
const onPickImage = async (file?: File) => {
if (!file) return
setPosterError(undefined)
try {
set('poster', await fileToPosterDataURL(file))
} catch (e) {
setPosterError((e as Error).message)
}
}
const submit = async () => {
if (!form.title.trim()) return
setSaving(true)
const clean: MediaInput = {
...form,
title: form.title.trim(),
originalTitle: form.originalTitle?.trim() || undefined,
subtype: form.type === 'autre' ? (form.subtype?.trim() ? canonicalSubtype(form.subtype) : undefined) : undefined,
platform: form.platform?.trim() || undefined,
notes: form.notes?.trim() || undefined,
poster: form.poster?.trim() || undefined,
overview: form.overview?.trim() || undefined,
}
const pos = seasonPosition(clean)
if (pos) clean.season = pos.season
try {
if (item) await update(item.id, clean)
else await add(clean)
onClose()
} finally {
setSaving(false)
}
}
const [confirmDelete, setConfirmDelete] = useState(false)
const [sharing, setSharing] = useState(false)
const [preview, setPreview] = useState<{ blob: Blob; filename: string }>()
const shareCard = async () => {
if (!item) return
setSharing(true)
try {
// Générique (réalisation, production, casting) depuis TMDB si possible
let credits
if (settings.tmdbKey && form.externalId?.startsWith('tmdb:') && navigator.onLine) {
credits = await getTmdbCredits(form.externalId, settings.tmdbKey).catch(() => undefined)
}
const blob = await renderItemCard({ ...item, ...form }, settings.ratingScale, credits)
setPreview({ blob, filename: `azuucine-${slug(form.title)}.png` })
} finally {
setSharing(false)
}
}
const onDelete = async () => {
if (!item) return
setConfirmDelete(false)
await remove(item.id)
onClose()
}
return (
{/* En-tête */}
{preview &&
setPreview(undefined)} />}
setConfirmDelete(false)}
/>
)
}