import { useRef, useState } from 'react'
import { coverImageCdnUrl } from '~/lib/api-client'
import { resolvePdsUrl } from '~/lib/atproto'

interface CoverImageProps {
  did: string
  cid: string
  className?: string
  alt?: string
  thumbnail?: boolean
}

export default function CoverImage({ did, cid, className, alt = '', thumbnail = false }: CoverImageProps) {
  const [src, setSrc] = useState(() => coverImageCdnUrl(did, cid, thumbnail))
  const fallbackAttempted = useRef(false)

  function handleError() {
    if (fallbackAttempted.current) return
    fallbackAttempted.current = true
    resolvePdsUrl(did)
      .then((pdsUrl) => {
        setSrc(
          `${pdsUrl}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(did)}&cid=${encodeURIComponent(cid)}`,
        )
      })
      .catch(() => {})
  }

  return <img src={src} alt={alt} className={className} onError={handleError} />
}
