'use client'

interface EmojiMediaProps {
  url: string
  alt: string
  className?: string
  fallbackClassName?: string
  autoPlay?: boolean
}

function isVideoUrl(url: string): boolean {
  const normalized = url.split('?')[0]?.toLowerCase() ?? ''
  return normalized.endsWith('.webm') || normalized.endsWith('.mp4') || normalized.endsWith('.mov')
}

const FALLBACK_DATA_URL =
  'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="100" height="100"%3E%3Crect fill="%23ddd" width="100" height="100"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="%23999"%3E?%3C/text%3E%3C/svg%3E'

export function EmojiMedia({
  url,
  alt,
  className,
  fallbackClassName,
  autoPlay = true,
}: EmojiMediaProps) {
  if (isVideoUrl(url)) {
    return (
      <video
        src={url}
        title={alt}
        className={className ? `${className} bg-slate-900` : 'bg-slate-900'}
        autoPlay={autoPlay}
        loop
        muted
        playsInline
        preload="metadata"
      />
    )
  }

  return (
    <img
      src={url}
      alt={alt}
      className={className}
      onError={e => {
        const target = e.target as HTMLImageElement
        target.src = FALLBACK_DATA_URL
        if (fallbackClassName) {
          target.className = fallbackClassName
        }
      }}
    />
  )
}
