<template>
  <div class="home">
    <h1>Twitter/X Video Downloader</h1>
    <p class="subtitle">Paste a Twitter/X video link to download</p>

    <div class="input-group">
      <input v-model="url" placeholder="https://x.com/user/status/123..." @keyup.enter="parseUrl" :disabled="loading" />
      <button @click="parseUrl" :disabled="loading || !url.trim()">
        {{ loading ? '⏳ Parsing...' : '🔍 Parse' }}
      </button>
    </div>

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

    <div v-if="videoInfo" class="video-info">
      <img v-if="videoInfo.thumbnail" :src="videoInfo.thumbnail" class="thumbnail" />
      <h3>{{ videoInfo.title }}</h3>
      <p class="duration">Duration: {{ formatDuration(videoInfo.duration) }}</p>

      <div class="formats">
        <h4>Select Quality:</h4>
        <div v-for="fmt in videoInfo.formats" :key="fmt.format_id" class="format-item"
             :class="{ selected: selectedFormat === fmt.format_id }" @click="selectedFormat = fmt.format_id">
          <span class="quality">{{ fmt.quality }}</span>
          <span class="ext">{{ fmt.ext }}</span>
          <span v-if="fmt.filesize" class="size">~{{ humanSize(fmt.filesize) }}</span>
        </div>
      </div>

      <button class="download-btn" @click="startDownload" :disabled="downloading">
        {{ downloading ? '⏳ Downloading...' : '📥 Download' }}
      </button>
    </div>

    <div v-if="taskId" class="task-status">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: progress + '%' }"></div>
      </div>
      <p>{{ statusText }}</p>
      <a v-if="downloadReady" :href="downloadUrl" class="download-link" download>💾 Save to device</a>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const url = ref('')
const loading = ref(false)
const error = ref('')
const videoInfo = ref(null)
const selectedFormat = ref('best')
const downloading = ref(false)
const taskId = ref('')
const progress = ref(0)
const statusText = ref('')
const downloadReady = ref(false)
const downloadUrl = ref('')

function formatDuration(s) {
  if (!s) return 'N/A'
  const m = Math.floor(s / 60), sec = s % 60
  return `${m}:${String(sec).padStart(2, '0')}`
}

function humanSize(bytes) {
  for (const u of ['B', 'KB', 'MB', 'GB']) {
    if (bytes < 1024) return `${bytes.toFixed(1)} ${u}`
    bytes /= 1024
  }
  return `${bytes.toFixed(1)} TB`
}

async function parseUrl() {
  if (!url.value.trim()) return
  loading.value = true; error.value = ''; videoInfo.value = null; taskId.value = ''
  downloadReady.value = false
  try {
    const res = await axios.post('/api/parse', { url: url.value })
    videoInfo.value = res.data
    selectedFormat.value = 'best'
  } catch (e) {
    error.value = e.response?.data?.detail || 'Failed to parse URL'
  } finally {
    loading.value = false
  }
}

async function startDownload() {
  downloading.value = true; error.value = ''
  try {
    const res = await axios.post('/api/download', {
      url: url.value, format_id: selectedFormat.value, quality: selectedFormat.value
    })
    taskId.value = res.data.task_id
    statusText.value = 'Starting download...'
    pollStatus()
  } catch (e) {
    error.value = e.response?.data?.detail || 'Failed to start download'
    downloading.value = false
  }
}

async function pollStatus() {
  if (!taskId.value) return
  try {
    const res = await axios.get(`/api/download/${taskId.value}`)
    const d = res.data
    progress.value = d.progress
    if (d.status === 'done') {
      statusText.value = `✅ Done: ${d.title}`
      downloading.value = false
      downloadReady.value = true
      downloadUrl.value = `/api/file/task/${taskId.value}`
    } else if (d.status === 'error') {
      statusText.value = `❌ Error: ${d.error_message}`
      downloading.value = false
    } else {
      statusText.value = `⏳ ${d.status}... ${d.progress}%`
      setTimeout(pollStatus, 2000)
    }
  } catch {
    setTimeout(pollStatus, 3000)
  }
}
</script>

<style scoped>
.home { text-align: center; }
h1 { font-size: 2rem; margin-bottom: 0.5rem; }
.subtitle { color: #888; margin-bottom: 2rem; }
.input-group { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
.input-group input {
  flex: 1; padding: 0.8rem 1rem; border: 1px solid #444; border-radius: 8px;
  background: #1a1a2e; color: #fff; font-size: 1rem;
}
.input-group button, .download-btn {
  padding: 0.8rem 1.5rem; border: none; border-radius: 8px; cursor: pointer;
  background: #1da1f2; color: #fff; font-size: 1rem; font-weight: 600;
  transition: background 0.2s;
}
.input-group button:hover, .download-btn:hover { background: #1991db; }
.input-group button:disabled, .download-btn:disabled { background: #555; cursor: not-allowed; }
.error { color: #ff6b6b; margin: 1rem 0; padding: 0.8rem; background: #2a1515; border-radius: 8px; }
.video-info { text-align: left; background: #1a1a2e; border-radius: 12px; padding: 1.5rem; margin-top: 1.5rem; }
.thumbnail { width: 100%; max-height: 300px; object-fit: cover; border-radius: 8px; margin-bottom: 1rem; }
.video-info h3 { margin-bottom: 0.5rem; }
.duration { color: #888; margin-bottom: 1rem; }
.formats { margin: 1rem 0; }
.formats h4 { margin-bottom: 0.5rem; }
.format-item {
  display: flex; gap: 1rem; align-items: center; padding: 0.6rem 1rem;
  border: 1px solid #333; border-radius: 8px; margin-bottom: 0.4rem; cursor: pointer;
  transition: all 0.2s;
}
.format-item:hover { border-color: #1da1f2; }
.format-item.selected { border-color: #1da1f2; background: rgba(29, 161, 242, 0.1); }
.quality { font-weight: 600; min-width: 60px; }
.ext { color: #888; }
.size { color: #888; margin-left: auto; }
.download-btn { width: 100%; margin-top: 1rem; padding: 1rem; font-size: 1.1rem; }
.task-status { margin-top: 1.5rem; }
.progress-bar { height: 8px; background: #333; border-radius: 4px; overflow: hidden; margin-bottom: 0.5rem; }
.progress-fill { height: 100%; background: #1da1f2; transition: width 0.3s; }
.download-link {
  display: inline-block; margin-top: 0.5rem; padding: 0.8rem 2rem;
  background: #27ae60; color: #fff; border-radius: 8px; text-decoration: none; font-weight: 600;
}
</style>
