<template>
  <div class="stream-player w-full">
    <!-- Loading State -->
    <div
      v-if="isLoading"
      class="flex items-center justify-center h-64 bg-gray-100 dark:bg-gray-800 rounded-lg"
    >
      <div class="text-center">
        <UIcon name="i-heroicons-arrow-path" class="w-8 h-8 animate-spin text-green-500" />
        <p class="mt-2 text-gray-600 dark:text-gray-400">Cargando stream...</p>
      </div>
    </div>

    <!-- No Stream Selected -->
    <div
      v-else-if="!streamUrl"
      class="flex items-center justify-center h-64 bg-gray-100 dark:bg-gray-800 rounded-lg"
    >
      <div class="text-center">
        <UIcon name="i-heroicons-video-camera-slash" class="w-12 h-12 text-gray-400" />
        <p class="mt-2 text-gray-600 dark:text-gray-400">Selecciona un stream para visualizar</p>
      </div>
    </div>

    <!-- Iframe Player (WebRTC/MSE) -->
    <iframe
      v-else-if="useIframe"
      :src="streamUrl"
      :key="streamUrl"
      class="w-full aspect-video rounded-lg border-0 bg-black"
      allow="autoplay; fullscreen"
      allowfullscreen
      @load="handleLoad"
      @error="handleError"
    />

    <!-- MJPEG usa img -->
    <img
      v-else-if="streamType === 'mjpeg'"
      :src="streamUrl"
      :key="streamUrl"
      class="w-full aspect-video rounded-lg object-contain bg-black"
      alt="Stream MJPEG"
      @load="handleLoad"
      @error="handleError"
    />

    <!-- Video nativo para MP4 y HLS -->
    <video
      v-else
      ref="videoRef"
      :src="streamUrl"
      :key="streamUrl"
      class="w-full aspect-video rounded-lg bg-black"
      controls
      autoplay
      muted
      playsinline
      @loadeddata="handleLoad"
      @error="handleError"
    />
  </div>
</template>

<script setup lang="ts">
import type { StreamType } from '~/composables/useStreams'

const props = defineProps<{
  streamUrl: string | null
  useIframe: boolean
  streamType: StreamType
  isLoading?: boolean
}>()

const emit = defineEmits<{
  (e: 'loaded'): void
  (e: 'error', message: string): void
}>()

const videoRef = ref<HTMLVideoElement | null>(null)

const handleLoad = () => {
  emit('loaded')
}

const handleError = () => {
  emit('error', 'Error al cargar el stream')
}
</script>

<style scoped>
.stream-player iframe,
.stream-player video,
.stream-player img {
  min-height: 200px;
  max-height: 400px;
}
</style>
