<template>
    <div class="message-video-container">
        <!-- PC 端：直接用原生 video 播放，不再套一层蒙层 -->
        <video v-if="isPC" class="message-video-inline" :src="videoContent.url" :poster="videoContent.snapshotUrl"
            controls preload="metadata" @loadedmetadata="handlePreviewLoaded" />

        <!-- Mobile 端：保留缩略图 + 全屏播放蒙层 -->
        <template v-else>
            <button class="message-video-preview" type="button" :style="previewStyle" @click="openFullscreen">
                <img v-if="videoContent.snapshotUrl" class="message-video-poster" :src="videoContent.snapshotUrl"
                    alt="video poster" @load="handlePreviewLoaded" />
                <div v-else class="message-video-fallback" />

                <div class="message-video-mask">
                    <img class="message-video-play-icon" :src="videoPlayIcon" alt="play" />
                </div>
            </button>

            <Teleport to="body">
                <div v-if="fullscreenVisible" class="message-video-player-mask" role="dialog" aria-modal="true"
                    @click="closeFullscreen">
                    <button class="message-video-player-close" type="button" :aria-label="t('关闭视频预览')"
                        @click.stop="closeFullscreen">
                        ×
                    </button>

                    <div class="message-video-player-wrapper" @click.stop>
                        <video ref="fullscreenVideoRef" class="message-video-player" :src="videoContent.url"
                            :poster="videoContent.snapshotUrl" controls playsinline webkit-playsinline autoplay />
                    </div>
                </div>
            </Teleport>
        </template>
    </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type CSSProperties } from 'vue'
import { useI18n } from 'vue-i18n'

import videoPlayIcon from '../../../assets/icons/videoPlay.svg'
import { isPC } from '../../../utils/env'

interface MessageVideoContent {
    url: string
    snapshotUrl: string
    snapshotWidth: number
    snapshotHeight: number
}

interface MessageVideoProps {
    videoContent: MessageVideoContent
    meidaMessageOnload: () => void
}

const props = defineProps<MessageVideoProps>()

const { t } = useI18n()

const fullscreenVisible = ref(false)
const fullscreenVideoRef = ref<HTMLVideoElement | null>(null)
const hasNotifiedLoaded = ref(false)

const previewStyle = computed<CSSProperties>(() => {
    const width = Number(props.videoContent.snapshotWidth) || 320
    const height = Number(props.videoContent.snapshotHeight) || 180

    return {
        aspectRatio: `${width} / ${height}`,
    }
})

const notifyLoaded = () => {
    if (hasNotifiedLoaded.value) {
        return
    }

    hasNotifiedLoaded.value = true
    props.meidaMessageOnload()
}

const handlePreviewLoaded = () => {
    notifyLoaded()
}

const openFullscreen = async () => {
    if (!props.videoContent.url) {
        return
    }

    fullscreenVisible.value = true
    await nextTick()

    try {
        await fullscreenVideoRef.value?.play()
    } catch {
    }
}

const closeFullscreen = () => {
    fullscreenVisible.value = false
    if (fullscreenVideoRef.value) {
        fullscreenVideoRef.value.pause()
        fullscreenVideoRef.value.currentTime = 0
    }
}

watch(fullscreenVisible, (visible) => {
    if (typeof document === 'undefined') {
        return
    }

    document.body.style.overflow = visible ? 'hidden' : ''
})

onMounted(() => {
    if (!props.videoContent.snapshotUrl) {
        nextTick(() => {
            notifyLoaded()
        })
    }
})

onUnmounted(() => {
    document.body.style.overflow = ''
})
</script>

<style scoped>
.message-video-container {
    position: relative;
    overflow: hidden;
}

/* PC 端内联播放器 */
.message-video-inline {
    display: block;
    max-width: min(calc(100vw - 180px), 400px);
    max-height: min(calc(100vw - 180px), 400px);
    width: inherit;
    height: inherit;
    border-radius: 10px;
    outline: none;
}

.message-video-preview {
    position: relative;
    display: block;
    width: min(calc(100vw - 180px), 400px);
    max-width: min(calc(100vw - 180px), 400px);
    padding: 0;
    border: none;
    border-radius: 10px;
    overflow: hidden;
    background: #111;
    cursor: pointer;
}

.message-video-poster,
.message-video-fallback {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.message-video-fallback {
    min-height: 180px;
    background: linear-gradient(180deg, #2d2d2d 0%, #121212 100%);
}

.message-video-mask {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.26);
}

.message-video-play-icon {
    width: 56px;
    height: 56px;
}

.message-video-player-mask {
    position: fixed;
    inset: 0;
    z-index: 20000;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.96);
}

.message-video-player-close {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 1;
    width: 32px;
    height: 32px;
    border: 0;
    padding: 0;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.14);
    color: #fff;
    font-size: 24px;
    line-height: 32px;
}

.message-video-player-wrapper {
    width: min(100vw, 960px);
    max-width: 100vw;
    max-height: 100vh;
    padding: 48px 16px 24px;
    box-sizing: border-box;
}

.message-video-player {
    display: block;
    width: 100%;
    max-height: calc(100vh - 72px);
    border-radius: 12px;
    background: #000;
}
</style>