<template>
  <div class="view">
    <div class="view-label">Internet Evidence → PDP Synthesis</div>
    <div class="view-header">
      <h1>Internet-sourced PDP and offer brief <span class="count-badge">{{ evidenceCount }}</span></h1>
      <p class="subtitle">This is the real project workflow: scraped/captured web evidence, Amazon marketplace signals, Reddit audience objections, source-backed claims, and product-page facts synthesised into PDP content and offer decisions.</p>
    </div>

    <div v-if="loading" class="loading">Loading internet evidence...</div>
    <div v-else-if="!content" class="empty">No content draft found for this SKU yet.</div>
    <template v-else>
      <section class="brief-grid">
        <article class="brief-card hero">
          <span class="eyebrow">Recommended PDP direction</span>
          <h2>{{ content.name }}</h2>
          <p>{{ content.metafields?.pdpWhoItsFor || 'No who-it-is-for draft yet.' }}</p>
          <div class="status-row">
            <span :class="['pill', statusClass(content.status)]">{{ content.status }}</span>
            <span :class="['pill', statusClass(content.approval?.compliance)]">Compliance: {{ content.approval?.compliance || 'missing' }}</span>
          </div>
        </article>

        <article class="brief-card">
          <span class="eyebrow">Offer angle</span>
          <h2>{{ offerAngle }}</h2>
          <p>{{ offerReason }}</p>
        </article>

        <article class="brief-card">
          <span class="eyebrow">Primary risk</span>
          <h2>{{ primaryRisk.title }}</h2>
          <p>{{ primaryRisk.detail }}</p>
        </article>
      </section>

      <section class="source-grid">
        <article v-for="source in sourceCards" :key="source.label" class="source-card" :class="source.state">
          <span class="eyebrow">{{ source.label }}</span>
          <strong>{{ source.value }}</strong>
          <p>{{ source.detail }}</p>
        </article>
      </section>

      <section class="two-col">
        <article class="panel">
          <h2>PDP content generated from evidence</h2>
          <div class="content-block">
            <span class="field-label">Who it's for</span>
            <p>{{ content.metafields?.pdpWhoItsFor }}</p>
          </div>
          <div class="content-block">
            <span class="field-label">Benefits</span>
            <ul><li v-for="benefit in content.metafields?.pdpProductBenefits || []" :key="benefit">{{ benefit }}</li></ul>
          </div>
          <div class="content-block">
            <span class="field-label">Key features</span>
            <ul><li v-for="feature in splitLines(content.metafields?.pdpKeyFeatures)" :key="feature">{{ feature }}</li></ul>
          </div>
        </article>

        <article class="panel">
          <h2>Offer and creative decisions</h2>
          <div class="decision" v-for="decision in decisions" :key="decision.title">
            <strong>{{ decision.title }}</strong>
            <p>{{ decision.detail }}</p>
          </div>
        </article>
      </section>

      <section class="panel">
        <h2>Evidence driving the synthesis</h2>
        <div class="evidence-tabs">
          <button v-for="tab in tabs" :key="tab.key" :class="{ active: activeTab === tab.key }" @click="activeTab = tab.key">{{ tab.label }} <span>{{ tab.rows.length }}</span></button>
        </div>
        <div class="evidence-list">
          <article v-for="row in activeRows" :key="row.source + row.title" class="evidence-row">
            <span class="source-type">{{ row.source }}</span>
            <div>
              <h3>{{ row.title }}</h3>
              <p>{{ row.detail }}</p>
              <small v-if="row.use">Use: {{ row.use }}</small>
              <a v-if="row.url" :href="row.url" target="_blank" rel="noopener">Open source</a>
            </div>
          </article>
        </div>
      </section>

      <section class="panel guardrail-panel">
        <h2>Guardrails before final PDP/export</h2>
        <ul>
          <li v-for="item in guardrails" :key="item">{{ item }}</li>
        </ul>
      </section>
    </template>
  </div>
</template>

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

const route = useRoute()
const loading = ref(false)
const content = ref(null)
const publicEvidence = ref(null)
const amazon = ref(null)
const reddit = ref(null)
const blockers = ref(null)
const improvements = ref(null)
const claims = ref(null)
const market = ref(null)
const competitors = ref(null)
const activeTab = ref('all')

function splitLines(value) { return String(value || '').split('\n').map(v => v.trim()).filter(Boolean) }
function human(value) { return String(value || '').replace(/[-_]/g, ' ') }
function statusClass(value) {
  const v = String(value || '').toLowerCase()
  if (v.includes('draft') || v.includes('review')) return 'draft'
  if (v.includes('approved') || v.includes('ready')) return 'ready'
  if (v.includes('blocked') || v.includes('not_ready')) return 'blocked'
  return 'pending'
}
async function getJson(url) {
  const res = await fetch(url)
  return res.ok ? await res.json() : null
}
async function load(sku) {
  if (!sku) return
  loading.value = true
  try {
    const [c, p, a, r, b, i, cl, m, comp] = await Promise.all([
      getJson(`/api/content/products/${sku}`),
      getJson(`/api/intelligence/${sku}/public-internet-evidence`),
      getJson(`/api/intelligence/${sku}/amazon-reviews`),
      getJson(`/api/intelligence/${sku}/reddit-pulse`),
      getJson(`/api/intelligence/${sku}/conversion-blockers`),
      getJson(`/api/intelligence/${sku}/improvements`),
      getJson(`/api/intelligence/${sku}/claims-evidence`),
      getJson(`/api/intelligence/${sku}/market-insight-synthesis`),
      getJson(`/api/intelligence/${sku}/competitor-comparison`)
    ])
    content.value = c
    publicEvidence.value = p
    amazon.value = a
    reddit.value = r
    blockers.value = b
    improvements.value = i
    claims.value = cl
    market.value = m
    competitors.value = comp
  } finally { loading.value = false }
}

const officialRows = computed(() => [
  ...(publicEvidence.value?.facts || []).map((fact, index) => ({ source: 'Official PDP', title: `Product fact ${index + 1}`, detail: fact, url: publicEvidence.value?.url })),
  ...(publicEvidence.value?.reviewSignals || []).map(row => ({ source: 'Public reviews', title: row.theme, detail: row.evidence, use: row.use }))
])
const amazonRows = computed(() => (amazon.value?.themes || []).map(row => ({ source: 'Amazon', title: row.theme, detail: row.evidence || row.jvPublicSignal, use: row.contentUse || row.expectedAmazonCheck })))
const redditRows = computed(() => (reddit.value?.pulses || []).map(row => ({ source: 'Reddit', title: row.topic || row.theme, detail: row.evidence || row.whyItMatters, use: row.contentUse, url: row.sourceUrl })))
const blockerRows = computed(() => (blockers.value?.blockers || []).map(row => ({ source: 'Blocker', title: row.blocker, detail: row.evidence, use: row.fix })))
const improvementRows = computed(() => (improvements.value?.improvements || []).map(row => ({ source: 'Improvement', title: row.improvement, detail: row.evidence || row.productWeakness, use: row.expectedImpact ? `Expected impact: ${row.expectedImpact}` : '' })))
const claimRows = computed(() => (claims.value?.claims || []).map(row => ({ source: 'Claim evidence', title: row.heading, detail: row.description, url: row.citation?.url || row.citation?.source_url })))
const competitorRows = computed(() => [
  ...(market.value?.competitor?.signals || []).map((signal, index) => ({ source: 'Competitor', title: `${market.value.competitor.brand} signal ${index + 1}`, detail: signal, use: market.value.competitor.whitespace?.[index] || market.value.offer, url: market.value.competitor.url })),
  ...(competitors.value?.comparison || []).map(row => ({ source: 'Competitor comparison', title: row.attribute, detail: row.competitorEvidence || row.justVitamins, use: row.recommendation }))
])
const allRows = computed(() => [...officialRows.value, ...amazonRows.value, ...redditRows.value, ...competitorRows.value, ...blockerRows.value, ...improvementRows.value, ...claimRows.value])
const tabs = computed(() => [
  { key: 'all', label: 'All evidence', rows: allRows.value },
  { key: 'official', label: 'Official/PDP', rows: officialRows.value },
  { key: 'amazon', label: 'Amazon', rows: amazonRows.value },
  { key: 'reddit', label: 'Reddit', rows: redditRows.value },
  { key: 'competitors', label: 'Competitors', rows: competitorRows.value },
  { key: 'actions', label: 'Actions', rows: [...blockerRows.value, ...improvementRows.value] },
  { key: 'claims', label: 'Claims', rows: claimRows.value }
])
const activeRows = computed(() => tabs.value.find(t => t.key === activeTab.value)?.rows || [])
const evidenceCount = computed(() => allRows.value.length)

const offerAngle = computed(() => {
  if (market.value?.offer) return market.value.offer
  const sku = content.value?.sku || ''
  if (sku.includes('D1000')) return 'Make the format the offer: a daily Vitamin D drink, not another tablet'
  if (sku.includes('VISISOFT')) return 'Make the stack and normal-vision claim clear without promising treatment'
  if (sku.includes('TURMERIC')) return 'Make strength and standardisation the trust-builder'
  return 'Use evidence-backed benefits, not generic supplement copy'
})
const offerReason = computed(() => {
  if (market.value?.synthesis?.pdpDecisions?.length) return market.value.synthesis.pdpDecisions.join(' ')
  const a = amazon.value?.themes?.[1]?.contentUse || amazon.value?.themes?.[0]?.contentUse
  const r = reddit.value?.pulses?.[0]?.contentUse
  return [a, r].filter(Boolean).join(' ')
})
const primaryRisk = computed(() => {
  const blocker = blockers.value?.blockers?.find(b => /contamination|wrong|claim|disease|not confirmed|format/i.test(`${b.blocker} ${b.evidence} ${b.fix}`)) || blockers.value?.blockers?.[0]
  return blocker ? { title: blocker.blocker, detail: blocker.fix || blocker.evidence } : { title: 'Human approval still required', detail: 'The synthesis is ready for review, but compliance/content/image/export approval remains gated.' }
})
const sourceCards = computed(() => [
  { label: 'Official PDP', value: publicEvidence.value?.facts?.length ? `${publicEvidence.value.facts.length} facts` : 'Missing', detail: publicEvidence.value?.url || 'No public PDP capture loaded.', state: publicEvidence.value ? 'ready' : 'blocked' },
  { label: 'Amazon', value: amazon.value?.n != null ? `${amazon.value.n} signals` : 'Missing', detail: human(amazon.value?.coverage || 'No Amazon evidence loaded.'), state: amazon.value ? 'ready' : 'blocked' },
  { label: 'Reddit', value: reddit.value?.n != null ? `${reddit.value.n} signals` : 'Missing', detail: human(reddit.value?.coverage || 'No Reddit evidence loaded.'), state: reddit.value ? 'ready' : 'blocked' },
  { label: 'Claims', value: claims.value?.claims?.length ? `${claims.value.claims.length} source-backed claim` : 'Needs review', detail: claims.value?.complianceGate || 'No claims evidence loaded.', state: claims.value?.claims?.length ? 'draft' : 'blocked' }
  ,{ label: 'Competitor scrape', value: market.value?.competitor?.apifyCaptured ? 'Apify captured' : (market.value?.competitor ? 'Fallback web evidence' : 'Missing'), detail: market.value?.competitor ? `${market.value.competitor.brand}: ${market.value.competitor.source}` : 'No competitor synthesis loaded.', state: market.value?.competitor?.apifyCaptured ? 'ready' : (market.value?.competitor ? 'draft' : 'blocked') }
])
const decisions = computed(() => [
  { title: 'Hero / above-the-fold', detail: content.value?.metafields?.pdpWhoItsFor || 'Use the internet evidence to define the buyer and situation.' },
  { title: 'Comparison image', detail: splitLines(content.value?.metafields?.pdpKeyFeatures).slice(0, 2).join(' / ') || 'No image direction yet.' },
  { title: 'FAQ strategy', detail: [content.value?.metafields?.faqHeadingOne, content.value?.metafields?.faqHeadingTwo, content.value?.metafields?.faqHeadingThree].filter(Boolean).join(' | ') || 'No FAQs yet.' },
  { title: 'Offer proof', detail: market.value?.competitor?.signals?.[0] || amazon.value?.themes?.[0]?.evidence || 'Use marketplace and public review evidence as proof context, not fabricated claims.' }
])
const guardrails = computed(() => [
  ...(publicEvidence.value?.contaminationExclusions || []),
  ...(amazon.value?.themes || []).filter(t => /guardrail|contamination|not confirmed|do not/i.test(`${t.status} ${t.theme}`)).map(t => `${t.theme}: ${t.contentUse || t.evidence}`),
  ...(reddit.value?.pulses || []).filter(t => /guardrail|objection|market/i.test(`${t.status}`)).map(t => `${t.topic}: ${t.contentUse || t.evidence}`),
  'Do not export until human content, compliance, image, and final export approvals are recorded.'
])

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

<style scoped src="../views/view.css" />
<style scoped>
.brief-grid{display:grid;grid-template-columns:1.4fr 1fr 1fr;gap:14px;margin-bottom:14px}.brief-card,.source-card,.panel{background:#fff;border:1px solid var(--border);border-radius:var(--radius-lg);padding:18px}.brief-card.hero{background:linear-gradient(135deg,#111827,#1f2937);color:#fff}.brief-card h2{font-size:18px;margin:4px 0 8px}.brief-card p{font-size:13px;line-height:1.55;margin:0;color:var(--text-secondary)}.brief-card.hero p{color:#d1d5db}.eyebrow,.field-label,.source-type{display:block;font-size:10px;letter-spacing:.08em;text-transform:uppercase;color:var(--text-muted);font-weight:700}.status-row{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}.pill{font-size:11px;border-radius:999px;padding:4px 9px;background:#f3f4f6;color:#555}.pill.ready{background:var(--positive-bg);color:var(--positive)}.pill.draft{background:#fff7ed;color:#c2410c}.pill.blocked{background:var(--negative-bg);color:var(--negative)}.source-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px;margin-bottom:14px}.source-card.ready{border-color:#bbf7d0}.source-card.draft{border-color:#fed7aa}.source-card.blocked{border-color:#fecaca}.source-card strong{display:block;font-size:18px;margin:4px 0}.source-card p{font-size:12px;line-height:1.45;color:var(--text-secondary);margin:0}.two-col{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px}.panel h2{font-size:17px;margin:0 0 12px}.content-block{border-top:1px solid var(--border);padding-top:12px;margin-top:12px}.content-block p,.content-block li,.decision p,.guardrail-panel li{font-size:13px;line-height:1.5;color:var(--text-secondary)}.decision{border-left:3px solid var(--accent);padding-left:12px;margin:12px 0}.evidence-tabs{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:12px}.evidence-tabs button{border:1px solid var(--border);background:#fff;border-radius:999px;padding:7px 11px;font-size:12px;cursor:pointer}.evidence-tabs button.active{background:var(--text-primary);color:#fff;border-color:var(--text-primary)}.evidence-tabs span{opacity:.7;margin-left:4px}.evidence-list{display:grid;gap:10px}.evidence-row{display:grid;grid-template-columns:110px 1fr;gap:12px;border:1px solid var(--border);border-radius:var(--radius);padding:12px;background:#fafafa}.evidence-row h3{font-size:14px;margin:0 0 4px}.evidence-row p{font-size:12px;line-height:1.5;color:var(--text-secondary);margin:0}.evidence-row small{display:block;margin-top:6px;color:var(--accent);font-size:12px}.evidence-row a{display:inline-block;margin-top:6px;color:var(--accent);font-size:12px;font-weight:600}.guardrail-panel{margin-top:14px;background:#fff7ed;border-color:#fed7aa}@media (max-width:1100px){.brief-grid,.two-col{grid-template-columns:1fr}.evidence-row{grid-template-columns:1fr}}
</style>
