<template>
  <div class="view">
    <div class="view-label">Research Brief</div>
    <div class="view-header">
      <h1>Research command center <span class="count-badge">{{ evidenceCount }}</span></h1>
      <p class="subtitle">A focused brief for scraping, evidence review, and PDP build direction.</p>
    </div>

    <div v-if="loading" class="loading">Loading research brief...</div>
    <div v-else-if="error" class="empty">{{ error }}</div>
    <template v-else-if="profile">
      <section class="hero">
        <div>
          <span class="eyebrow">{{ productName }}</span>
          <h2>{{ mainAngle }}</h2>
          <p>{{ briefSummary }}</p>
        </div>
        <div class="hero-stats">
          <div class="stat-card strong">
            <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 PDP move</span>
          <strong>{{ primaryMove }}</strong>
        </article>
        <article>
          <span>Evidence rule</span>
          <strong>JV truth for facts. Scraped sources for language, objections, proof and positioning.</strong>
        </article>
        <article>
          <span>Main guardrail</span>
          <strong>{{ mainGuardrail }}</strong>
        </article>
      </section>

      <section class="grid">
        <article class="panel-card">
          <h3>What to build next</h3>
          <ul>
            <li v-for="item in nextBuildItems" :key="item">{{ item }}</li>
          </ul>
        </article>

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

      <section class="grid">
        <article class="panel-card">
          <h3>Source coverage</h3>
          <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>
              </div>
            </div>
          </div>
        </article>

        <article class="panel-card">
          <h3>Evidence inventory</h3>
          <div class="inventory-list">
            <div v-for="row in inventoryRows" :key="row.label" class="inventory-row">
              <div>
                <strong>{{ row.label }}</strong>
                <p>{{ row.status }}</p>
              </div>
              <b>{{ row.count }}</b>
            </div>
          </div>
        </article>
      </section>

      <section class="grid single">
        <article class="panel-card">
          <h3>Current strongest research signals</h3>
          <div class="signal-grid">
            <div v-for="item in strongestSignals" :key="item.id" class="signal-card">
              <span>{{ item.source }}</span>
              <strong>{{ item.title }}</strong>
              <p>{{ item.body }}</p>
              <a v-if="item.url" :href="item.url" target="_blank" rel="noopener">Open source</a>
            </div>
          </div>
        </article>
      </section>
    </template>
    <div v-else class="empty">No research profile is available for this SKU yet.</div>
  </div>
</template>

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

const route = useRoute()
const profile = ref(null)
const rawEvidence = ref(null)
const loading = ref(false)
const error = ref('')

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 briefSummary = computed(() => `Use the current scrape coverage to turn product truth, market language, and objections into a tighter PDP build brief for ${productName.value}.`)
const primaryMove = computed(() => firstText(profile.value?.pdpGenerationBrief?.recommendedPdpSections) || profile.value?.pdpGenerationBrief?.heroHeadline || mainAngle.value)
const mainGuardrail = computed(() => firstText(profile.value?.pdpGenerationBrief?.claimsToAvoid) || firstText(profile.value?.claimAndComplianceProfile?.claimsToAvoid) || 'Do not turn social or review language into product claims.')

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 evidencePool = computed(() => buildEvidencePool(rawEvidence.value, profile.value))
const evidenceCount = computed(() => evidencePool.value.length)

const nextBuildItems = computed(() => {
  const rows = []
  for (const item of profile.value?.pdpGenerationBrief?.recommendedPdpSections || []) rows.push(item)
  for (const item of profile.value?.offerArchitecture?.imageBriefs || []) if (rows.length < 6) rows.push(item)
  if (!rows.length) rows.push('Build the next PDP section from the strongest verified signal.')
  return rows.slice(0, 6)
})

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 inventoryRows = computed(() => {
  return (rawEvidence.value?.sections || []).map(section => ({
    label: section.label,
    status: human(section.status),
    count: (section.itemCount || 0) + (section.rawBlockCount || 0)
  }))
})

const strongestSignals = computed(() => evidencePool.value.slice(0, 9))

function firstText(value) {
  if (Array.isArray(value)) return value.map(String).find(Boolean) || ''
  return value ? String(value) : ''
}

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

function clip(value, limit = 220) {
  const text = String(value || '').replace(/\s+/g, ' ').trim()
  return text.length > limit ? `${text.slice(0, limit)}...` : text
}

function pushEvidence(rows, item) {
  if (!item?.title && !item?.body) return
  rows.push({
    id: `${item.source}-${rows.length}`,
    source: item.sourceLabel || item.source,
    title: clip(item.title || 'Source item', 110),
    body: clip(item.body || item.text || item.preview, 220),
    url: item.url || null
  })
}

function buildEvidencePool(raw, profileData) {
  const rows = []
  const sections = Object.fromEntries((raw?.sections || []).map(section => [section.key, section]))

  for (const item of sections.jv_truth?.items || []) {
    pushEvidence(rows, { source: 'JV truth', title: item.title || item.sku || 'JV truth row', body: JSON.stringify(item) })
  }
  for (const item of sections.amazon?.items || []) {
    pushEvidence(rows, { source: 'Amazon', title: item.title || item.asin || 'Amazon row', body: JSON.stringify(item), url: item.url })
  }
  for (const item of sections.reddit?.items || []) {
    pushEvidence(rows, { source: 'Reddit', title: item.title || item.topic || 'Reddit snippet', body: item.text || item.body || JSON.stringify(item), url: item.url || item.sourceUrl })
  }
  for (const item of sections.apify_specialists?.items || []) {
    const row = item.item || item
    pushEvidence(rows, { source: `Apify ${item.job || 'specialist'}`, title: row.title || row.label || row.reviewTitle || 'Specialist capture', body: row.textPreview || row.reviewDescription || JSON.stringify(row), url: row.url || row.reviewUrl || row.loadedUrl })
  }
  for (const item of sections.apify_comprehensive?.items || []) {
    pushEvidence(rows, { source: 'Competitor', title: item.label || item.title || item.h1 || 'Page capture', body: item.textPreview || JSON.stringify(item), url: item.loadedUrl || item.requestedUrl })
  }

  if (!rows.length) {
    for (const item of profileData?.customerIntent?.redditLanguage || []) {
      pushEvidence(rows, { source: 'Research profile', title: item.topic, body: item.evidence, url: item.sourceUrl })
    }
  }
  return rows
}

async function load(sku) {
  if (!sku) return
  loading.value = true
  error.value = ''
  try {
    const [profileRes, rawRes] = await Promise.all([
      fetch(`/api/research-profile/${sku}`),
      fetch(`/api/raw-evidence/${sku}`)
    ])
    profile.value = profileRes.ok ? await profileRes.json() : null
    rawEvidence.value = rawRes.ok ? await rawRes.json() : null
    if (!profile.value) error.value = 'No research brief is available for this SKU yet.'
  } catch (_) {
    error.value = 'Failed to load research brief.'
  } 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.15fr .85fr;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:22px;display:block}.stat-card span{font-size:11px;color:#d1d5db}.stat-card.strong{background:rgba(99,102,241,.18)}.decision-strip{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-bottom:14px}.decision-strip article{background:#fff;border:1px solid var(--border);border-radius:var(--radius);padding:12px}.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}.grid.single{grid-template-columns:1fr}.panel-card{background:#fff;border:1px solid var(--border);border-radius:var(--radius-lg);padding:16px}.panel-card h3{font-size:16px;margin:0 0 10px}.panel-card ul{padding-left:18px}.panel-card li{margin:0 0 6px;color:var(--text-secondary);font-size:13px;line-height:1.5}.evidence-list,.inventory-list,.lane-list,.signal-grid{display:grid;gap:10px}.evidence-item,.inventory-row,.lane-row,.signal-card{border:1px solid var(--border);border-radius:var(--radius);background:#fafafa;padding:12px}.evidence-item strong,.inventory-row strong,.lane-row strong,.signal-card strong{font-size:13px;display:block}.evidence-item p,.inventory-row p,.lane-row p,.signal-card p{font-size:12px;color:var(--text-secondary);line-height:1.5;margin-top:4px}.inventory-row,.lane-row{display:grid;grid-template-columns:1fr auto;gap:10px;align-items:start}.inventory-row b{font-size:18px}.lane-row span,.signal-card span{font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted)}.lane-row.complete span{color:var(--positive)}.lane-row.partial span{color:#c2410c}.lane-row.missing span{color:var(--negative)}.signal-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.signal-card a{display:inline-block;margin-top:8px;font-size:12px;color:var(--accent);font-weight:600}@media(max-width:1000px){.hero,.decision-strip,.grid,.signal-grid{grid-template-columns:1fr}}
</style>
