<template>
  <div class="queue-panel">
    <div class="queue-header">
      <div class="queue-title">
        <h3>Download Queue</h3>
        <span v-if="queue.worker_running" class="worker-indicator active" title="Worker is processing">
          <span class="pulse"></span> Active
        </span>
        <span v-else class="worker-indicator idle" title="Worker is idle">Idle</span>
      </div>
      <div class="queue-actions">
        <button
          v-if="queue.total_done > 0 || queue.total_failed > 0"
          @click="$emit('clear')"
          class="btn-clear"
          title="Clear completed tasks"
        >
          Clear
        </button>
        <button @click="$emit('refresh')" class="btn-refresh" title="Refresh">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.3"/>
          </svg>
        </button>
      </div>
    </div>

    <div class="queue-stats">
      <div class="stat">
        <span class="stat-value queued">{{ queue.total_queued }}</span>
        <span class="stat-label">Queued</span>
      </div>
      <div class="stat">
        <span class="stat-value downloading">{{ queue.total_downloading }}</span>
        <span class="stat-label">Active</span>
      </div>
      <div class="stat">
        <span class="stat-value done">{{ queue.total_done }}</span>
        <span class="stat-label">Done</span>
      </div>
      <div class="stat">
        <span class="stat-value failed">{{ queue.total_failed }}</span>
        <span class="stat-label">Failed</span>
      </div>
    </div>

    <div v-if="queue.estimated_queue_size_bytes > 0" class="queue-size">
      Est. queue size: {{ formatBytes(queue.estimated_queue_size_bytes) }}
    </div>

    <div class="queue-list" v-if="queue.tasks?.length">
      <div
        v-for="task in sortedTasks"
        :key="task.id"
        class="queue-item"
        :class="task.status"
      >
        <div class="task-main">
          <div class="task-info">
            <div class="task-anime">{{ task.anime_title }}</div>
            <div class="task-theme">
              <span class="theme-badge">{{ task.theme_name }}</span>
              <span v-if="task.song_title" class="song-name">{{ task.song_title }}</span>
            </div>
          </div>
          <div class="task-status">
            <span :class="'status-badge ' + task.status">{{ formatStatus(task.status) }}</span>
          </div>
        </div>

        <div v-if="isActive(task.status)" class="task-progress">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: task.progress_percent + '%' }"></div>
          </div>
          <span class="progress-text">{{ task.progress_percent }}%</span>
        </div>

        <div v-if="task.error_message" class="task-error">
          {{ task.error_message }}
        </div>

        <div class="task-actions">
          <button
            v-if="task.status === 'queued'"
            @click="$emit('cancel', task.id)"
            class="btn-action btn-cancel"
            title="Cancel"
          >
            Cancel
          </button>
          <button
            v-if="task.status === 'failed'"
            @click="$emit('retry', task.id)"
            class="btn-action btn-retry"
            title="Retry"
          >
            Retry
          </button>
          <span v-if="task.status === 'done'" class="task-size">
            {{ formatBytes(task.estimated_size_bytes) }}
          </span>
        </div>
      </div>
    </div>

    <div v-else class="queue-empty">
      No tasks in queue
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  queue: {
    type: Object,
    required: true,
  },
})

defineEmits(['cancel', 'retry', 'refresh', 'clear'])

const sortedTasks = computed(() => {
  if (!props.queue.tasks) return []
  // Sort: active first, then queued, then done/failed
  const order = {
    downloading: 0,
    converting: 0,
    uploading: 0,
    queued: 1,
    failed: 2,
    done: 3,
  }
  return [...props.queue.tasks].sort((a, b) => {
    const orderDiff = (order[a.status] || 4) - (order[b.status] || 4)
    if (orderDiff !== 0) return orderDiff
    // Within same status, sort by created_at desc
    return new Date(b.created_at) - new Date(a.created_at)
  })
})

function formatBytes(bytes) {
  if (!bytes) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let i = 0
  let value = bytes
  while (value >= 1024 && i < units.length - 1) {
    value /= 1024
    i++
  }
  return `${value.toFixed(1)} ${units[i]}`
}

function formatStatus(status) {
  const labels = {
    queued: 'Queued',
    downloading: 'Downloading',
    converting: 'Converting',
    uploading: 'Uploading',
    done: 'Done',
    failed: 'Failed',
  }
  return labels[status] || status
}

function isActive(status) {
  return ['downloading', 'converting', 'uploading'].includes(status)
}
</script>

<style scoped>
.queue-panel {
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  padding: 1rem;
  max-height: 500px;
  display: flex;
  flex-direction: column;
}

.queue-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.queue-title {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.queue-title h3 {
  margin: 0;
  color: #fff;
}

.queue-actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.worker-indicator {
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.worker-indicator.active {
  background: rgba(0, 255, 136, 0.15);
  color: #00ff88;
}

.worker-indicator.idle {
  background: rgba(136, 136, 136, 0.15);
  color: #888;
}

.pulse {
  width: 8px;
  height: 8px;
  background: #00ff88;
  border-radius: 50%;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.5; transform: scale(0.8); }
}

.btn-clear {
  background: rgba(255, 170, 0, 0.2);
  border: 1px solid rgba(255, 170, 0, 0.3);
  border-radius: 4px;
  padding: 0.4rem 0.75rem;
  color: #ffaa00;
  font-size: 0.8rem;
  cursor: pointer;
  transition: background 0.2s, border-color 0.2s;
}

.btn-clear:hover {
  background: rgba(255, 170, 0, 0.3);
  border-color: #ffaa00;
}

.btn-refresh {
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  padding: 0.5rem;
  color: #888;
  cursor: pointer;
  transition: color 0.2s, border-color 0.2s;
}

.btn-refresh:hover {
  color: #00d4ff;
  border-color: #00d4ff;
}

/* Stats */
.queue-stats {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: bold;
}

.stat-value.queued {
  color: #ffaa00;
}

.stat-value.downloading {
  color: #00d4ff;
}

.stat-value.done {
  color: #00ff88;
}

.stat-value.failed {
  color: #ff4444;
}

.stat-label {
  font-size: 0.75rem;
  color: #888;
  text-transform: uppercase;
}

.queue-size {
  text-align: center;
  color: #888;
  font-size: 0.85rem;
  margin-bottom: 1rem;
}

/* Queue List */
.queue-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.queue-item {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  padding: 0.75rem;
  border-left: 3px solid transparent;
}

.queue-item.queued {
  border-left-color: #ffaa00;
}

.queue-item.downloading,
.queue-item.converting,
.queue-item.uploading {
  border-left-color: #00d4ff;
}

.queue-item.done {
  border-left-color: #00ff88;
}

.queue-item.failed {
  border-left-color: #ff4444;
}

.task-main {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
}

.task-info {
  flex: 1;
  min-width: 0;
}

.task-anime {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.task-theme {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.25rem;
}

.theme-badge {
  font-size: 0.75rem;
  padding: 0.125rem 0.5rem;
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
  border-radius: 4px;
}

.song-name {
  font-size: 0.85rem;
  color: #888;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.task-status {
  flex-shrink: 0;
}

.status-badge {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
}

.status-badge.queued {
  background: rgba(255, 170, 0, 0.2);
  color: #ffaa00;
}

.status-badge.downloading,
.status-badge.converting,
.status-badge.uploading {
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
}

.status-badge.done {
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
}

.status-badge.failed {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

/* Progress */
.task-progress {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.task-progress .progress-bar {
  flex: 1;
  height: 4px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
  overflow: hidden;
}

.task-progress .progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00d4ff, #00ff88);
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 0.75rem;
  color: #00d4ff;
  min-width: 36px;
  text-align: right;
}

/* Error */
.task-error {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background: rgba(255, 68, 68, 0.1);
  border-radius: 4px;
  color: #ff4444;
  font-size: 0.8rem;
  word-break: break-word;
}

/* Actions */
.task-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.btn-action {
  padding: 0.25rem 0.75rem;
  border: none;
  border-radius: 4px;
  font-size: 0.8rem;
  cursor: pointer;
  transition: opacity 0.2s;
}

.btn-action:hover {
  opacity: 0.8;
}

.btn-cancel {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.btn-retry {
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
}

.task-size {
  font-size: 0.8rem;
  color: #00ff88;
}

/* Empty */
.queue-empty {
  text-align: center;
  padding: 2rem;
  color: #666;
}
</style>
