<template>
  <!-- Renders nothing when everything is healthy — the daily answer to
       "does anything need me?" should be silence, not an empty card. -->
  <FailingSourcesCard
    v-if="failing.length"
    class="mb-4"
    :sources="failing"
    :retrying-ids="sourcesStore.checkingIds"
    :retrying-all="retryingAll"
    @retry="onRetry"
    @retry-all="onRetryAll"
    @view-logs="onViewLogs"
  />
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'

import { toast } from '../../utils/toast.js'
import FailingSourcesCard from './FailingSourcesCard.vue'
import { useDownloadsStore } from '../../stores/downloads.js'
import { useSourcesStore } from '../../stores/sources.js'

// The needs-attention strip on the Subscriptions LANDING tab (2026-07-02):
// failing sources used to live below the fold of the Downloads tab, so a
// broken subscription was invisible unless you went looking. Retry logic is
// shared with the Downloads maintenance menu via the downloads store.
const store = useDownloadsStore()
const sourcesStore = useSourcesStore()
const router = useRouter()
const { failing } = storeToRefs(store)
const retryingAll = ref(false)
let pollId = null

async function onRetry(source) {
  try {
    const res = await store.retrySource(source)
    toast(res === 'queued'
      ? { text: `Retry queued for ${source.artist_name || source.platform}`, type: 'success' }
      : { text: 'Already running — check Downloads', type: 'info' })
  } catch (e) {
    toast({ text: `Retry failed: ${e?.detail || e?.message || e}`, type: 'error' })
  }
}

async function onRetryAll(sources) {
  retryingAll.value = true
  try {
    const t = await store.retryAllFailing(sources)
    const parts = []
    if (t.ok) parts.push(`${t.ok} queued`)
    if (t.deferred) parts.push(`${t.deferred} deferred (cooldown)`)
    if (t.conflict) parts.push(`${t.conflict} already running`)
    toast({ text: parts.join(', ') || 'Nothing to retry', type: 'info' })
  } finally {
    retryingAll.value = false
  }
}

function onViewLogs(source) {
  // The Downloads tab owns the log/detail surface — deep-link into it
  // pre-filtered to this source (it watches ?source_id).
  router.push({ path: '/subscriptions', query: { tab: 'downloads', source_id: source.id } })
}

onMounted(() => {
  store.loadFailing()
  pollId = setInterval(() => { if (!document.hidden) store.loadFailing() }, 60000)
})
onUnmounted(() => { if (pollId) clearInterval(pollId) })
</script>
