<script setup>
import { computed, onMounted, onBeforeUnmount } from 'vue'
import { XMarkIcon, FilmIcon } from '@heroicons/vue/24/outline'

/**
 * Native HTML5 video player modal.
 *
 * Props:
 *   - show v-model:show
 *   - item current video item
 */
const props = defineProps({
    show: Boolean,
    item: Object,
})

const emit = defineEmits(['update:show'])

const videoSrc = computed(() =>
    props.item ? route('customer.files.download', { path: props.item.path }) : ''
)

const mimeFor = (name) => {
    const ext = (name || '').split('.').pop()?.toLowerCase()
    return {
        mp4: 'video/mp4',
        webm: 'video/webm',
        ogg: 'video/ogg',
        mov: 'video/quicktime',
        m4v: 'video/mp4',
    }[ext] || 'video/mp4'
}

const handleEsc = (e) => {
    if (props.show && e.key === 'Escape') emit('update:show', false)
}

onMounted(() => document.addEventListener('keydown', handleEsc))
onBeforeUnmount(() => document.removeEventListener('keydown', handleEsc))
</script>

<template>
    <Teleport to="body">
        <div v-if="show && item"
             class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/90 p-4"
             @click.self="emit('update:show', false)">
            <div class="flex w-full max-w-4xl flex-col overflow-hidden rounded-xl bg-slate-900 shadow-2xl">
                <div class="flex items-center justify-between border-b border-slate-700 px-4 py-2 text-white">
                    <div class="flex items-center gap-2 min-w-0">
                        <FilmIcon class="h-5 w-5 text-purple-400" />
                        <p class="truncate font-mono text-sm">{{ item.path }}</p>
                    </div>
                    <button @click="emit('update:show', false)"
                            class="rounded p-1.5 text-white hover:bg-white/10">
                        <XMarkIcon class="h-5 w-5" />
                    </button>
                </div>
                <div class="bg-black">
                    <video :key="item.path"
                           controls
                           autoplay
                           preload="metadata"
                           class="block max-h-[75vh] w-full">
                        <source :src="videoSrc" :type="mimeFor(item.name)" />
                        Tarayıcınız video etiketini desteklemiyor.
                    </video>
                </div>
            </div>
        </div>
    </Teleport>
</template>
