"use client"

import { useState, useEffect } from "react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { db } from "@/lib/db"

interface AvatarDisplayProps {
  imageId?: string
  fallbackUrl?: string
  fallbackText?: string
  className?: string
}

export function AvatarDisplay({ imageId, fallbackUrl, fallbackText, className }: AvatarDisplayProps) {
  const [blobUrl, setBlobUrl] = useState<string | undefined>(undefined)

  useEffect(() => {
    if (imageId) {
      db.images.get(imageId).then((image) => {
        if (image) {
          const url = URL.createObjectURL(image.blob)
          setBlobUrl(url)
          return () => URL.revokeObjectURL(url)
        }
      })
    } else {
      setBlobUrl(undefined)
    }
  }, [imageId])

  return (
    <Avatar className={className}>
      <AvatarImage src={blobUrl || fallbackUrl || "/placeholder.svg"} />
      <AvatarFallback className="text-lg font-serif bg-muted">{fallbackText}</AvatarFallback>
    </Avatar>
  )
}
