<template>
  <div class="tv-dashboard">
    <div class="slideshow-container">
      <div
        v-for="(slide, idx) in slides"
        :key="slide.filename"
        class="slide"
        :class="{ active: idx === currentSlide }"
      >
        <img :src="basePath + slide.filename" :alt="slide.filename" />
      </div>

      <div v-if="error" class="error-message">
        <h2>Display Error</h2>
        <p>{{ error }}</p>
      </div>

      <div v-if="!slides.length && !error" class="error-message">
        <h2>No Slides</h2>
        <p>No slides configured for display</p>
      </div>
    </div>

    <div class="progress-bar" :style="progressStyle"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import api from '@/api'

const INTERVAL = 10 // seconds between slides

const slides = ref([])
const basePath = ref('/static/slides/')
const currentSlide = ref(0)
const error = ref('')
const progress = ref(0)

let slideTimer = null
let progressTimer = null
let refreshTimer = null

const progressStyle = computed(() => ({
  width: `${progress.value}%`,
  transition: progress.value === 0 ? 'none' : `width ${INTERVAL}s linear`
}))

onMounted(async () => {
  await fetchSlides()

  // Start slideshow if we have slides
  if (slides.value.length > 1) {
    startSlideshow()
  }

  // Refresh slide list every 60 seconds
  refreshTimer = setInterval(fetchSlides, 60000)
})

onUnmounted(() => {
  if (slideTimer) clearTimeout(slideTimer)
  if (progressTimer) clearTimeout(progressTimer)
  if (refreshTimer) clearInterval(refreshTimer)
})

async function fetchSlides() {
  try {
    const response = await api.get('/slides')
    const data = response.data

    if (data.success && data.data?.slides?.length > 0) {
      slides.value = data.data.slides
      basePath.value = data.data.basepath || '/static/slides/'
      error.value = ''

      // Restart slideshow if slides changed
      if (slides.value.length > 1 && !slideTimer) {
        startSlideshow()
      }
    } else {
      error.value = data.message || 'No slides found'
    }
  } catch (err) {
    console.error('Error fetching slides:', err)
    error.value = 'Unable to load slides'
  }
}

function startSlideshow() {
  scheduleNextSlide()
}

function scheduleNextSlide() {
  // Reset progress bar
  progress.value = 0

  // Start progress animation after a small delay
  progressTimer = setTimeout(() => {
    progress.value = 100
  }, 50)

  // Schedule next slide
  slideTimer = setTimeout(() => {
    nextSlide()
    scheduleNextSlide()
  }, INTERVAL * 1000)
}

function nextSlide() {
  if (slides.value.length === 0) return
  currentSlide.value = (currentSlide.value + 1) % slides.value.length
}
</script>

<style scoped>
.tv-dashboard {
  background: #000;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.slideshow-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 1s ease-in-out;
  display: flex;
  align-items: center;
  justify-content: center;
}

.slide.active {
  opacity: 1;
}

.slide img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.progress-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  height: 4px;
  background: #4181ff;
  z-index: 100;
}

.error-message {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  font-size: 24px;
}

.error-message h2 {
  color: #ff4444;
  margin-bottom: 20px;
}
</style>
