'use client'

import Image from 'next/image'
import { forwardRef, useCallback, useState } from 'react'

/** public/images/loading.mp4 */
export const LIVE_STREAM_LOADING_VIDEO_SRC = '/images/loading.mp4'
/** public/images/loading.png（mp4 無法播放時的替代圖） */
export const LIVE_STREAM_LOADING_IMAGE_SRC = '/images/loading.png'

type Props = {
    /** loop：載入中循環播放；still：僅顯示首幀（未開播畫面） */
    variant?: 'loop' | 'still'
    className?: string
}

const LiveStreamLoadingMedia = forwardRef<HTMLVideoElement, Props>(function LiveStreamLoadingMedia(
    { variant = 'loop', className = 'absolute inset-0 h-full w-full object-cover' },
    ref
) {
    const [useImageFallback, setUseImageFallback] = useState(false)
    const onVideoError = useCallback(() => setUseImageFallback(true), [])

    if (useImageFallback) {
        return (
            <Image
                src={LIVE_STREAM_LOADING_IMAGE_SRC}
                alt=""
                fill
                className={className}
                draggable={false}
                unoptimized
                priority
            />
        )
    }

    if (variant === 'still') {
        return (
            <video
                ref={ref}
                src={LIVE_STREAM_LOADING_VIDEO_SRC}
                muted
                playsInline
                preload="metadata"
                className={className}
                onError={onVideoError}
                onLoadedData={(e) => {
                    const v = e.currentTarget
                    try {
                        v.currentTime = 0
                        v.pause()
                    } catch {
                        // ignore
                    }
                }}
                onPlay={(e) => {
                    const v = e.currentTarget
                    try {
                        v.pause()
                        v.currentTime = 0
                    } catch {
                        // ignore
                    }
                }}
            />
        )
    }

    return (
        <video
            ref={ref}
            src={LIVE_STREAM_LOADING_VIDEO_SRC}
            autoPlay
            loop
            muted
            playsInline
            className={className}
            onError={onVideoError}
        />
    )
})

export default LiveStreamLoadingMedia
