<template>
  <div class="view">
    <div class="view-label">Approval Queue</div>
    <div class="view-header">
      <h1>Review readiness by SKU</h1>
      <p class="subtitle">Single queue for Umar/content/compliance/image sign-off before any Matrixify export is sent to Lewis. Approval actions update product content, workflow events, and the workflow index.</p>
    </div>

    <div class="toolbar">
      <button v-for="option in filters" :key="option.value" class="filter" :class="{ active: filter === option.value }" @click="filter = option.value">{{ option.label }} <span>{{ count(option.value) }}</span></button>
    </div>

    <div v-if="loading" class="loading">Loading...</div>
    <div v-else class="table-wrap">
      <table class="data-table">
        <thead><tr><th>SKU</th><th>Name</th><th>Stage</th><th>Content</th><th>Compliance</th><th>Images</th><th>Blocked fields</th><th>Actions</th><th>Last event</th><th>Blockers</th></tr></thead>
        <tbody>
          <tr v-for="p in filteredRows" :key="p.sku">
            <td class="sku">{{ p.sku }}</td>
            <td>{{ p.name }}</td>
            <td><Badge :value="p.workflow?.stage || 'missing'" /></td>
            <td><Badge :value="p.approval?.content" /></td>
            <td><Badge :value="p.approval?.compliance" /></td>
            <td><Badge :value="p.approval?.images" /></td>
            <td>{{ blockedFieldCount(p.workflow) }}</td>
            <td class="actions">
              <button :disabled="approving || p.approval?.content === 'approved' || p.status === 'pending_intelligence'" @click="updateApproval(p, 'content', 'approved')">Approve content</button>
              <button :disabled="approving || imageBlockers(p).length || p.approval?.images === 'ready'" @click="updateApproval(p, 'images', 'ready')">Images ready</button>
              <button :disabled="approving || hardBlockers(p).length || p.approval?.export === 'ready'" @click="updateApproval(p, 'export', 'ready')">Export ready</button>
            </td>
            <td class="event-cell">{{ p.workflow?.events?.[0]?.summary || '—' }}</td>
            <td>{{ blockers(p).join('; ') || '—' }}</td>
          </tr>
          <tr v-if="!filteredRows.length"><td colspan="10" class="empty-row">No products match this filter.</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
const products = ref([])
const workflows = ref({})
const loading = ref(false)
const approving = ref(false)
const filter = ref('blocked')
const filters = [
  { value: 'blocked', label: 'Blocked' },
  { value: 'draft', label: 'Drafts' },
  { value: 'pending', label: 'Pending intel' },
  { value: 'approved', label: 'Approved content' },
  { value: 'all', label: 'All' }
]
const rows = computed(() => products.value.map(p => ({ ...p, workflow: workflows.value[p.sku] })))
const filteredRows = computed(() => rows.value.filter(row => {
  if (filter.value === 'all') return true
  if (filter.value === 'pending') return row.status === 'pending_intelligence'
  if (filter.value === 'approved') return row.approval?.content === 'approved'
  if (filter.value === 'draft') return row.status !== 'pending_intelligence' && row.approval?.content !== 'approved'
  return blockers(row).length > 0
}))
function count(value) {
  if (value === 'all') return rows.value.length
  return rows.value.filter(row => {
    if (value === 'pending') return row.status === 'pending_intelligence'
    if (value === 'approved') return row.approval?.content === 'approved'
    if (value === 'draft') return row.status !== 'pending_intelligence' && row.approval?.content !== 'approved'
    return blockers(row).length > 0
  }).length
}
function imageBlockers(p) { const m=p.metafields||{}; return [!m.pdpResults&&'results image', !m.pdpResultsMobile&&'mobile image', !m.pdpHowWeCompare&&'compare image'].filter(Boolean) }
function hardBlockers(p) { return blockers(p).filter(b => b !== 'content approval') }
function blockers(p) { const m=p.metafields||{}; return [p.status === 'pending_intelligence'&&'needs intelligence', !m.pdpClinicallyShownTo&&'claims', ...imageBlockers(p), p.approval?.content !== 'approved'&&'content approval', p.approval?.compliance !== 'approved'&&'compliance approval'].filter(Boolean) }
function blockedFieldCount(workflow) { return Object.values(workflow?.fields || {}).filter(f => String(f.status || '').startsWith('blocked')).length }
async function load(){
  loading.value=true
  try{
    const res=await fetch('/api/content/products')
    products.value=res.ok?await res.json():[]
    const pairs = await Promise.all(products.value.map(async p => {
      const w = await fetch(`/api/content/workflow/${p.sku}`)
      return [p.sku, w.ok ? await w.json() : null]
    }))
    workflows.value = Object.fromEntries(pairs)
  } finally{ loading.value=false }
}
async function updateApproval(product, area, status) {
  approving.value = true
  try {
    const previous = product.approval?.[area]
    const res = await fetch(`/api/content/products/${product.sku}/approval`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ area, status, from: previous, actor: 'dashboard', summary: `${area} approval changed from ${previous || 'missing'} to ${status}` })
    })
    if (!res.ok) throw new Error(await res.text())
    await load()
  } finally { approving.value = false }
}
onMounted(load)
</script>
<script>export default { components:{ Badge:{ props:['value'], template:`<span class="badge" :class="String(value)">{{ value || 'missing' }}</span>` } } }</script>
<style scoped src="../views/view.css" />
<style scoped>
.toolbar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px}.filter{border:1px solid var(--border);background:#fff;border-radius:999px;padding:7px 11px;font-size:12px;cursor:pointer}.filter.active{background:var(--text-primary);border-color:var(--text-primary);color:#fff}.filter span{opacity:.7;margin-left:4px}.sku{font-family:monospace;font-size:12px}.badge{padding:2px 8px;border-radius:999px;font-size:11px;background:#f3f4f6;color:#555}.badge.approved,.badge.ready,.badge.reviewed{background:var(--positive-bg);color:var(--positive)}.badge.blocked,.badge.needed,.badge.not_ready,.badge.blocked_asset,.badge.blocked_compliance{background:var(--negative-bg);color:var(--negative)}.badge.draft,.badge.content_draft,.badge.needs_intelligence{background:#fff7ed;color:#c2410c}.event-cell{font-size:12px;color:var(--text-secondary);max-width:260px}.actions{display:flex;gap:6px;flex-wrap:wrap;min-width:210px}.actions button{border:1px solid var(--border);border-radius:999px;background:#fff;padding:4px 8px;font-size:11px;cursor:pointer;color:var(--text-secondary)}.actions button:disabled{opacity:.4;cursor:not-allowed}.actions button:not(:disabled):hover{border-color:var(--accent);color:var(--accent)}.empty-row{text-align:center;color:var(--text-muted);padding:28px!important}</style>
