import { useCallback, useEffect, useState } from 'react'
import type { Series } from '@/types/nostr'
import { SeriesList } from './SeriesList'
import { SeriesStats } from './SeriesStats'
import { getSeriesByAuthor } from '@/lib/seriesQueries'
import { getSeriesAggregates } from '@/lib/seriesAggregation'
interface SeriesSectionProps {
authorPubkey: string
onSelect: (seriesId: string | undefined) => void
selectedId?: string | undefined
}
export function SeriesSection({ authorPubkey, onSelect, selectedId }: SeriesSectionProps) {
const [{ series, loading, error, aggregates }, load] = useSeriesData(authorPubkey)
if (loading) {
return
Chargement des séries...
}
if (error) {
return {error}
}
return (
)
}
function SeriesControls({
onSelect,
onReload,
}: {
onSelect: (id: string | undefined) => void
onReload: () => Promise
}) {
return (
)
}
function SeriesAggregatesList({
series,
aggregates,
}: {
series: Series[]
aggregates: Record
}) {
return (
<>
{series.map((s) => {
const agg = aggregates[s.id] ?? { sponsoring: 0, purchases: 0, reviewTips: 0 }
return (
)
})}
>
)
}
function useSeriesData(authorPubkey: string): [
{
series: Series[]
loading: boolean
error: string | null
aggregates: Record
},
() => Promise
] {
const [series, setSeries] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const [aggregates, setAggregates] = useState>({})
const load = useCallback(async () => {
setLoading(true)
setError(null)
try {
const { items, aggregates: agg } = await fetchSeriesAndAggregates(authorPubkey)
setSeries(items)
setAggregates(agg)
} catch (e) {
setError(e instanceof Error ? e.message : 'Erreur lors du chargement des séries')
} finally {
setLoading(false)
}
}, [authorPubkey])
useEffect(() => {
void load()
}, [load])
return [{ series, loading, error, aggregates }, load]
}
async function fetchSeriesAndAggregates(authorPubkey: string): Promise<{
items: Series[]
aggregates: Record
}> {
const items = await getSeriesByAuthor(authorPubkey)
const aggEntries = await Promise.all(
items.map(async (s) => {
const agg = await getSeriesAggregates({ authorPubkey, seriesId: s.id })
return [s.id, agg] as const
})
)
const aggMap: Record = {}
aggEntries.forEach(([id, agg]) => {
aggMap[id] = agg
})
return { items, aggregates: aggMap }
}