<template>
  <div class="view">
    <div class="view-label">Research Workflow</div>
    <div class="view-header">
      <h1>Essential research profile <span class="count-badge">{{ totalSignals }}</span></h1>
      <p class="subtitle">Only the core inputs needed to move this project forward: product truth, scrape coverage, research signals, gaps, and the next PDP moves.</p>
    </div>

    <div v-if="loading" class="loading">Loading research profile...</div>
    <div v-else-if="!profile" class="empty">No research profile has been generated for this SKU yet.</div>
    <template v-else>
      <section class="hero">
        <div>
          <span class="eyebrow">{{ human(profile.status) }}</span>
          <h2>{{ productName }}</h2>
          <p>{{ mainAngle }}</p>
        </div>
        <div class="hero-stats">
          <div class="stat-card">
            <strong>{{ exactEvidence }}</strong>
            <span>exact evidence</span>
          </div>
          <div class="stat-card">
            <strong>{{ competitorEvidence }}</strong>
            <span>competitor context</span>
          </div>
          <div class="stat-card">
            <strong>{{ completeLanes }}</strong>
            <span>complete lanes</span>
          </div>
          <div class="stat-card">
            <strong>{{ missingLanes }}</strong>
            <span>gaps left</span>
          </div>
        </div>
      </section>

      <section class="decision-strip">
        <article>
          <span>Main angle</span>
          <strong>{{ mainAngle }}</strong>
        </article>
        <article>
          <span>Primary intent</span>
          <strong>{{ primaryIntent }}</strong>
        </article>
        <article>
          <span>Readiness</span>
          <strong>{{ readinessLabel }}</strong>
        </article>
      </section>

      <section class="grid">
        <article class="panel-card">
          <h2>Non-negotiable product truth</h2>
          <ul class="simple-list">
            <li v-for="item in truthItems" :key="item">{{ item }}</li>
          </ul>
        </article>

        <article class="panel-card">
          <h2>Claims to avoid</h2>
          <ul class="simple-list warning">
            <li v-for="item in claimsToAvoid" :key="item">{{ item }}</li>
          </ul>
        </article>
      </section>

      <section class="grid">
        <article class="panel-card">
          <h2>Questions and objections to answer</h2>
          <div class="signal-list">
            <div v-for="item in questionAndObjectionRows" :key="item.title" class="signal-row">
              <strong>{{ item.title }}</strong>
              <p>{{ item.body }}</p>
            </div>
          </div>
        </article>

        <article class="panel-card">
          <h2>PDP sections to build next</h2>
          <ul class="simple-list">
            <li v-for="item in recommendedSections" :key="item">{{ item }}</li>
          </ul>
          <h3 class="subhead">Image / proof direction</h3>
          <ul class="simple-list">
            <li v-for="item in imageBriefs" :key="item">{{ item }}</li>
          </ul>
        </article>
      </section>

      <section class="grid">
        <article class="panel-card">
          <h2>Source coverage</h2>
          <div class="lane-list">
            <div v-for="lane in lanes" :key="lane.key" class="lane-row" :class="lane.status">
              <span>{{ human(lane.status) }}</span>
              <div>
                <strong>{{ lane.label }}</strong>
                <p>{{ lane.evidence }}</p>
                <small>{{ lane.use }}</small>
              </div>
            </div>
          </div>
        </article>

        <article class="panel-card">
          <h2>Immediate next actions</h2>
          <ul class="simple-list">
            <li v-for="item in nextActions" :key="item">{{ item }}</li>
          </ul>
          <h3 class="subhead">Still missing</h3>
          <ul class="simple-list warning">
            <li v-for="item in missingItems" :key="item">{{ item }}</li>
          </ul>
        </article>
      </section>
    </template>
  </div>
</template>

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

const route = useRoute()
const profile = ref(null)
const loading = ref(false)

const totalSignals = computed(() => profile.value ? Object.values(profile.value.sourceCoverage || {}).reduce((sum, n) => sum + Number(n || 0), 0) : 0)
const productName = computed(() => profile.value?.productTruth?.productName || profile.value?.sku || 'Selected product')
const mainAngle = computed(() => profile.value?.pdpGenerationBrief?.mainOfferAngle || profile.value?.customerIntent?.primaryIntent || 'Build the PDP from verified source evidence')
const primaryIntent = computed(() => profile.value?.pdpGenerationBrief?.primaryIntent || profile.value?.customerIntent?.primaryIntent || 'Not set')
const readinessLabel = computed(() => human(profile.value?.scrapeCompleteness?.readiness || profile.value?.status || 'research profile'))
const completeLanes = computed(() => Number(profile.value?.scrapeCompleteness?.counts?.complete || 0))
const missingLanes = computed(() => Number(profile.value?.scrapeCompleteness?.counts?.missing || 0))
const exactEvidence = computed(() => Number(profile.value?.scrapeCompleteness?.exactProductEvidenceCount || 0))
const competitorEvidence = computed(() => Number(profile.value?.scrapeCompleteness?.competitorContextEvidenceCount || 0))
const lanes = computed(() => profile.value?.scrapeCompleteness?.lanes || [])

const truthItems = computed(() => ([
  ...(profile.value?.productTruth?.ingredientsAndDose || []),
  ...(profile.value?.productTruth?.nonNegotiableFacts || [])
]).slice(0, 8))

const claimsToAvoid = computed(() => (profile.value?.pdpGenerationBrief?.claimsToAvoid || profile.value?.claimAndComplianceProfile?.claimsToAvoid || []).slice(0, 8))
const recommendedSections = computed(() => (profile.value?.pdpGenerationBrief?.recommendedPdpSections || profile.value?.offerArchitecture?.recommendedSections || []).slice(0, 8))
const imageBriefs = computed(() => (profile.value?.offerArchitecture?.imageBriefs || []).slice(0, 8))

const questionAndObjectionRows = computed(() => {
  const rows = []
  for (const q of profile.value?.customerIntent?.topSearchQuestions || []) {
    rows.push({ title: q, body: 'High-intent customer question that should be answered clearly in the PDP.' })
  }
  for (const obj of profile.value?.objectionAndAnxietyMap || []) {
    rows.push({ title: obj.objection, body: obj.response || obj.evidence })
  }
  return rows.slice(0, 8)
})

const missingItems = computed(() => {
  const rows = []
  for (const lane of profile.value?.scrapeCompleteness?.lanes || []) {
    if (lane.status !== 'complete') rows.push(`${lane.label}: ${lane.evidence}`)
  }
  return rows.slice(0, 8)
})

const nextActions = computed(() => {
  const actions = []
  if (recommendedSections.value.length) actions.push(`Build PDP sections from the current brief: ${recommendedSections.value[0]}`)
  if (imageBriefs.value.length) actions.push(`Generate or refine image assets around: ${imageBriefs.value[0]}`)
  if (missingItems.value.length) actions.push(`Close the highest-priority gap: ${missingItems.value[0]}`)
  actions.push('Keep JV database truth separate from internet language and competitor positioning.')
  return actions
})

function human(value) {
  return String(value || '')
    .replace(/_/g, ' ')
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    .replace(/^./, c => c.toUpperCase())
}

async function load(sku) {
  if (!sku) return
  loading.value = true
  try {
    const res = await fetch(`/api/research-profile/${sku}`)
    profile.value = res.ok ? await res.json() : null
  } finally { loading.value = false }
}

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

<style scoped src="../views/view.css" />
<style scoped>
.hero{display:grid;grid-template-columns:1.05fr 1fr;gap:16px;background:linear-gradient(135deg,#111827,#1f2937);color:#fff;border-radius:var(--radius-lg);padding:20px;margin-bottom:14px}.hero h2{font-size:24px;margin:4px 0 8px}.hero p{color:#d1d5db;line-height:1.5}.eyebrow{font-size:10px;letter-spacing:.08em;text-transform:uppercase;color:#93c5fd;font-weight:700}.hero-stats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.stat-card{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.14);border-radius:var(--radius);padding:10px}.stat-card strong{font-size:20px;display:block}.stat-card span{font-size:11px;color:#d1d5db}.decision-strip{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-bottom:14px}.decision-strip article,.panel-card{background:#fff;border:1px solid var(--border);border-radius:var(--radius-lg);padding:16px;box-shadow:var(--shadow-sm)}.decision-strip span{display:block;font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:6px}.decision-strip strong{font-size:13px;line-height:1.45}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;margin-top:14px}.panel-card h2{font-size:16px;margin:0 0 10px}.subhead{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin:14px 0 8px}.simple-list{padding-left:18px}.simple-list li{margin:0 0 6px;color:var(--text-secondary);font-size:13px;line-height:1.5}.simple-list.warning li{color:var(--negative)}.signal-list,.lane-list{display:grid;gap:10px}.signal-row,.lane-row{border:1px solid var(--border);border-radius:var(--radius);padding:12px;background:#fafaf9}.signal-row strong,.lane-row strong{font-size:13px;display:block}.signal-row p,.lane-row p,.lane-row small{font-size:12px;line-height:1.5;color:var(--text-secondary);margin-top:4px}.lane-row{display:grid;grid-template-columns:92px 1fr;gap:10px}.lane-row>span{font-size:10px;text-transform:uppercase;font-weight:800;letter-spacing:.06em}.lane-row.complete>span{color:var(--positive)}.lane-row.partial>span{color:#c2410c}.lane-row.missing>span{color:var(--negative)}@media(max-width:1000px){.hero,.decision-strip,.grid{grid-template-columns:1fr}}
</style>
