import type { Page } from '@/types/nostr'
import { Card } from './ui'
import { t } from '@/lib/i18n'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { useEffect, useState } from 'react'
import { objectCache } from '@/lib/objectCache'
import { ReadingMode } from './ReadingMode'
interface ArticlePagesProps {
pages: Page[]
articleId: string
}
export function ArticlePages({ pages, articleId }: ArticlePagesProps): React.ReactElement | null {
const { pubkey } = useNostrAuth()
const hasPurchased = useHasPurchasedArticle({ pubkey, articleId })
if (!pages || pages.length === 0) {
return null
}
if (!pubkey || !hasPurchased) {
return
}
return
}
function LockedPagesView({ pagesCount }: { pagesCount: number }): React.ReactElement {
return (
{t('article.pages.title')}
{t('article.pages.locked.title')}
{t('article.pages.locked.message', { count: pagesCount })}
)
}
function PurchasedPagesView({ pages }: { pages: Page[] }): React.ReactElement {
return (
{t('article.pages.title')}
{pages.map((page) => (
))}
)
}
function useHasPurchasedArticle({
pubkey,
articleId,
}: {
pubkey: string | null
articleId: string
}): boolean {
const [hasPurchased, setHasPurchased] = useState(false)
useEffect(() => {
if (!pubkey) {
return
}
const checkPurchase = async (): Promise => {
try {
const purchases = await objectCache.getAll('purchase')
const userPurchases = purchases.filter((p) => isUserPurchase({ p, pubkey, articleId }))
setHasPurchased(userPurchases.length > 0)
} catch (error) {
console.error('Error checking purchase status:', error)
setHasPurchased(false)
}
}
void checkPurchase()
}, [pubkey, articleId])
return hasPurchased
}
function isUserPurchase({
p,
pubkey,
articleId,
}: {
p: unknown
pubkey: string
articleId: string
}): boolean {
if (typeof p !== 'object' || p === null) {
return false
}
const purchase = p as { payerPubkey?: string; articleId?: string }
return purchase.payerPubkey === pubkey && purchase.articleId === articleId
}
function PageDisplay({ page }: { page: Page }): React.ReactElement {
return (
{t('page.number', { number: page.number })}
{t(`page.type.${page.type}`)}
{page.type === 'markdown' ? (
{page.content || {t('page.markdown.empty')}}
) : (
{page.content ? (

) : (
{t('page.image.empty')}
)}
)}
)
}