<template>
  <div class="view">
    <div class="view-label">{{ label }}</div>
    <div class="view-header">
      <h1>{{ title }} <span v-if="count !== null" class="count-badge">{{ count }}</span></h1>
      <p class="subtitle">{{ subtitle }}</p>
    </div>

    <div v-if="loading" class="loading">Loading...</div>
    <div v-else-if="!data" class="empty">No {{ label.toLowerCase() }} data available for this product yet.</div>
    <template v-else>
      <div v-if="data.sourceStatus" class="source-strip">
        <span v-for="(value, key) in data.sourceStatus" :key="key" class="source-chip" :class="statusClass(value)">
          {{ humanize(key) }}: {{ value }}
        </span>
      </div>

      <slot :data="data" />
    </template>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const props = defineProps({
  viewName: { type: String, required: true },
  label: { type: String, required: true },
  title: { type: String, required: true },
  subtitle: { type: String, required: true },
  countKey: { type: String, default: '' }
})

const route = useRoute()
const data = ref(null)
const loading = ref(false)
const count = ref(null)

function humanize(value) {
  return String(value).replace(/([A-Z])/g, ' $1').replace(/[-_]/g, ' ').replace(/^./, c => c.toUpperCase())
}
function statusClass(value) {
  const v = String(value || '').toLowerCase()
  if (v.includes('available') || v.includes('complete')) return 'ok'
  if (v.includes('missing') || v.includes('not_ingested') || v.includes('blocked')) return 'bad'
  return 'pending'
}
async function load(sku) {
  if (!sku) return
  loading.value = true
  try {
    const res = await fetch(`/api/intelligence/${sku}/${props.viewName}`)
    data.value = res.ok ? await res.json() : null
    count.value = props.countKey && Array.isArray(data.value?.[props.countKey]) ? data.value[props.countKey].length : (data.value?.n ?? null)
  } finally {
    loading.value = false
  }
}

onMounted(() => load(route.params.sku))
watch(() => route.params.sku, load)
</script>

<style scoped src="../views/view.css" />
<style scoped>
.source-strip { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:14px; }
.source-chip { font-size:11px; padding:5px 10px; border-radius:999px; background:#f6f6f4; color:#555; font-weight:600; border:1px solid var(--border); }
.source-chip.ok { background:var(--positive-bg); color:var(--positive); }
.source-chip.bad { background:var(--negative-bg); color:var(--negative); }
.source-chip.pending { background:#fff7ed; color:#c2410c; }
</style>
