<template>
  <div>
    <div class="page-header">
      <h1>Slides</h1>
      <router-link to="/settings" class="btn btn-secondary">Back to Settings</router-link>
    </div>

    <div class="card">
      <div class="tabs">
        <button
          v-for="s in surfaces"
          :key="s.key"
          class="tab"
          :class="{ active: surface === s.key }"
          @click="switchSurface(s.key)"
        >{{ s.label }}</button>
      </div>

      <div class="toolbar">
        <label class="btn btn-primary upload-btn">
          {{ uploading ? 'Uploading...' : 'Upload Images' }}
          <input type="file" accept="image/*" multiple hidden :disabled="uploading" @change="onUpload" />
        </label>
        <button
          class="btn btn-danger"
          :disabled="!selected.length"
          @click="deleteSelected"
        >Delete Selected ({{ selected.length }})</button>
        <span class="hint">Order top-to-bottom is play order. Images show on the {{ surfaceLabel }}.</span>
      </div>

      <div v-if="loading" class="muted">Loading...</div>
      <div v-else-if="!slides.length" class="muted empty">No slides yet. Upload some images.</div>

      <div v-else class="slide-grid">
        <div v-for="(slide, idx) in slides" :key="slide.slideid" class="slide-tile">
          <label class="pick">
            <input type="checkbox" :value="slide.filename" v-model="selected" />
          </label>
          <img :src="slide.url" :alt="slide.filename" class="thumb" />
          <div class="slide-meta">
            <span class="fname" :title="slide.filename">{{ slide.filename }}</span>
            <div class="move">
              <button class="btn btn-sm btn-secondary" :disabled="idx === 0" @click="move(idx, -1)" title="Move up">&uarr;</button>
              <button class="btn btn-sm btn-secondary" :disabled="idx === slides.length - 1" @click="move(idx, 1)" title="Move down">&darr;</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const surfaces = [
  { key: 'lobby', label: 'Lobby Display' },
  { key: 'shopfloor', label: 'Shopfloor Screensaver' }
]
const surface = ref('lobby')
const slides = ref([])
const selected = ref([])
const loading = ref(true)
const uploading = ref(false)

const surfaceLabel = computed(() => surfaces.find(s => s.key === surface.value)?.label || surface.value)

async function load() {
  loading.value = true
  selected.value = []
  try {
    const response = await slidesApi.list(surface.value)
    slides.value = response.data.data || []
  } catch (err) {
    console.error('Error loading slides:', err)
  } finally {
    loading.value = false
  }
}

function switchSurface(key) {
  if (key === surface.value) return
  surface.value = key
  load()
}

async function onUpload(event) {
  const files = Array.from(event.target.files || [])
  if (!files.length) return
  uploading.value = true
  try {
    const formData = new FormData()
    files.forEach(f => formData.append('files', f))
    await slidesApi.upload(surface.value, formData)
    await load()
  } catch (err) {
    console.error('Upload failed:', err)
  } finally {
    uploading.value = false
    event.target.value = ''
  }
}

async function move(idx, delta) {
  const target = idx + delta
  if (target < 0 || target >= slides.value.length) return
  const arr = slides.value.slice()
  const [item] = arr.splice(idx, 1)
  arr.splice(target, 0, item)
  slides.value = arr
  try {
    await slidesApi.reorder(surface.value, arr.map(s => s.filename))
  } catch (err) {
    console.error('Reorder failed:', err)
    await load()
  }
}

async function deleteSelected() {
  if (!selected.value.length) return
  if (!confirm(`Delete ${selected.value.length} slide(s)?`)) return
  try {
    await slidesApi.remove(surface.value, selected.value)
    await load()
  } catch (err) {
    console.error('Delete failed:', err)
  }
}

onMounted(load)
</script>

<style scoped>
.tabs {
  display: flex;
  gap: 4px;
  border-bottom: 1px solid var(--border);
  margin-bottom: 16px;
}
.tab {
  padding: 10px 18px;
  border: none;
  background: none;
  color: var(--text-light);
  font-weight: 600;
  cursor: pointer;
  border-bottom: 3px solid transparent;
}
.tab.active {
  color: var(--text);
  border-bottom-color: var(--primary);
}
.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 18px;
  flex-wrap: wrap;
}
.upload-btn { position: relative; cursor: pointer; }
.hint { color: var(--text-light); font-size: 0.85rem; }
.muted { color: var(--text-light); }
.empty { padding: 30px 0; text-align: center; }

.slide-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 14px;
}
.slide-tile {
  position: relative;
  border: 1px solid var(--border);
  border-radius: 8px;
  overflow: hidden;
  background: var(--bg);
}
.slide-tile .pick {
  position: absolute;
  top: 6px;
  left: 6px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  padding: 2px 4px;
}
.thumb {
  width: 100%;
  height: 130px;
  object-fit: cover;
  display: block;
  background: #000;
}
.slide-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 6px;
  padding: 6px 8px;
}
.fname {
  font-size: 0.78rem;
  font-family: monospace;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.move { display: flex; gap: 4px; flex-shrink: 0; }
</style>
