<template>
  <div class="view">
    <div class="view-label">Raw Evidence</div>
    <div class="view-header">
      <h1>Scraped source inspector <span class="count-badge">{{ availableSections }}</span></h1>
      <p class="subtitle">A focused source browser for raw files, extracted rows, and the exact material feeding research and PDP decisions.</p>
    </div>

    <div v-if="loading" class="loading">Loading raw source material...</div>
    <div v-else-if="!evidence" class="empty">No raw source material is available for this SKU yet.</div>
    <template v-else>
      <section class="hero">
        <div>
          <span class="eyebrow">{{ evidence.sku }}</span>
          <h2>Inspect source before synthesis</h2>
          <p>{{ evidence.note }}</p>
        </div>
        <div class="hero-stats">
          <div class="stat-card">
            <strong>{{ evidence.files?.length || 0 }}</strong>
            <span>raw files</span>
          </div>
          <div class="stat-card">
            <strong>{{ totalVisibleItems }}</strong>
            <span>visible rows</span>
          </div>
          <div class="stat-card">
            <strong>{{ current?.displayLimits?.itemLimit || 0 }}</strong>
            <span>row cap</span>
          </div>
        </div>
      </section>

      <section class="layout">
        <aside class="sidebar-panel">
          <div class="section-list">
            <button
              v-for="section in evidence.sections"
              :key="section.key"
              :class="['section-btn', { active: active === section.key }]"
              @click="active = section.key"
            >
              <div>
                <strong>{{ section.label }}</strong>
                <span>{{ human(section.status) }}</span>
              </div>
              <b>{{ (section.itemCount || 0) + (section.rawBlockCount || 0) }}</b>
            </button>
          </div>
        </aside>

        <section v-if="current" class="content-panel">
          <div class="section-head">
            <div>
              <h2>{{ current.label }}</h2>
              <p>Status: <strong>{{ human(current.status) }}</strong></p>
            </div>
            <button class="copy-btn" @click="copySection">Copy section JSON</button>
          </div>

          <div class="summary-strip">
            <div class="mini-stat">
              <strong>{{ current.itemCount || current.items?.length || 0 }}</strong>
              <span>rows found</span>
            </div>
            <div class="mini-stat">
              <strong>{{ current.rawBlockCount || current.rawBlocks?.length || 0 }}</strong>
              <span>raw blocks</span>
            </div>
            <div class="mini-stat">
              <strong>{{ current.displayLimits?.previewChars || 0 }}</strong>
              <span>preview chars</span>
            </div>
          </div>

          <div v-if="current.files?.length" class="panel-block">
            <h3>Source files</h3>
            <article v-for="file in current.files" :key="file.path" class="file-card">
              <div>
                <strong>{{ file.label }}</strong>
                <code>{{ file.path }}</code>
              </div>
              <small>{{ formatBytes(file.bytes) }} | {{ file.chars || 0 }} chars{{ file.clipped ? ' | clipped' : '' }}</small>
            </article>
          </div>

          <div v-if="current.items?.length" class="panel-block">
            <h3>Extracted rows</h3>
            <p class="limit-note">Showing {{ current.items.length }} of {{ current.itemCount || current.items.length }} rows.</p>
            <article v-for="(item, index) in current.items" :key="index" class="row-card">
              <div class="row-top">
                <strong>{{ item.title || item.post_title || item.topic || item.competitor || item.asin || `Raw item ${index + 1}` }}</strong>
                <span v-if="item.asin">{{ item.asin }}</span>
                <span v-else-if="item.sku">{{ item.sku }}</span>
              </div>
              <a v-if="item.url || item.sourceUrl" :href="item.url || item.sourceUrl" target="_blank" rel="noopener">{{ item.url || item.sourceUrl }}</a>
              <pre>{{ pretty(item) }}</pre>
            </article>
          </div>

          <div v-if="current.rawBlocks?.length" class="panel-block">
            <h3>Raw text previews</h3>
            <p class="limit-note">Showing {{ current.rawBlocks.length }} of {{ current.rawBlockCount || current.rawBlocks.length }} raw blocks.</p>
            <article v-for="block in current.rawBlocks" :key="block.title" class="block-card">
              <div class="row-top">
                <strong>{{ block.title }}</strong>
                <a v-if="block.url" :href="block.url" target="_blank" rel="noopener">Open source</a>
              </div>
              <small>{{ block.chars }} chars{{ block.clipped ? ' | clipped' : '' }}</small>
              <pre>{{ block.body }}</pre>
            </article>
          </div>
        </section>
      </section>
    </template>
  </div>
</template>

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

const route = useRoute()
const evidence = ref(null)
const loading = ref(false)
const active = ref('jv_truth')

const current = computed(() => evidence.value?.sections?.find(section => section.key === active.value) || evidence.value?.sections?.[0])
const availableSections = computed(() => (evidence.value?.sections || []).filter(section => section.status && section.status !== 'missing').length)
const totalVisibleItems = computed(() => (evidence.value?.sections || []).reduce((sum, section) => sum + (section.items?.length || 0), 0))

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

function pretty(value) {
  return JSON.stringify(value, null, 2)
}

function formatBytes(bytes) {
  const value = Number(bytes || 0)
  if (value > 1024 * 1024) return `${(value / 1024 / 1024).toFixed(1)} MB`
  if (value > 1024) return `${(value / 1024).toFixed(1)} KB`
  return `${value} B`
}

async function copySection() {
  if (!current.value) return
  await navigator.clipboard?.writeText(JSON.stringify(current.value, null, 2))
}

async function load(sku) {
  if (!sku) return
  loading.value = true
  try {
    const res = await fetch(`/api/raw-evidence/${sku}`)
    evidence.value = res.ok ? await res.json() : null
    if (evidence.value?.sections?.length && !evidence.value.sections.some(section => section.key === active.value)) {
      active.value = evidence.value.sections[0].key
    }
  } 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,#0f172a,#334155);color:#fff;border-radius:var(--radius-lg);padding:20px;margin-bottom:14px}.hero h2{font-size:24px;margin:4px 0 8px}.hero p{color:#dbeafe;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(3,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}.layout{display:grid;grid-template-columns:280px 1fr;gap:14px}.sidebar-panel,.content-panel{background:#fff;border:1px solid var(--border);border-radius:var(--radius-lg);padding:16px}.section-list{display:grid;gap:8px}.section-btn{display:grid;grid-template-columns:1fr auto;gap:10px;align-items:start;border:1px solid var(--border);border-radius:var(--radius);background:#fafafa;padding:12px;text-align:left}.section-btn strong{display:block;font-size:13px}.section-btn span{display:block;font-size:11px;color:var(--text-muted);margin-top:3px}.section-btn b{font-size:18px}.section-btn.active{border-color:var(--accent);background:var(--accent-light)}.section-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:14px}.section-head h2{font-size:18px;margin:0 0 4px}.section-head p{font-size:13px;color:var(--text-secondary)}.copy-btn{border:1px solid var(--border);background:#fff;border-radius:999px;padding:7px 12px;font-size:12px;cursor:pointer}.summary-strip{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-bottom:16px}.mini-stat{border:1px solid var(--border);border-radius:var(--radius);background:#fafafa;padding:10px}.mini-stat strong{display:block;font-size:18px}.mini-stat span{font-size:11px;color:var(--text-muted)}.panel-block + .panel-block{margin-top:16px}.panel-block h3{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin:0 0 8px}.limit-note{font-size:12px;color:var(--text-secondary);background:#f8fafc;border:1px solid var(--border);border-radius:8px;padding:8px 10px;margin:0 0 10px}.file-card,.row-card,.block-card{border:1px solid var(--border);border-radius:var(--radius);background:#fafafa;padding:12px}.file-card + .file-card,.row-card + .row-card,.block-card + .block-card{margin-top:10px}.file-card strong,.row-card strong,.block-card strong{font-size:13px;display:block}.file-card code{display:block;font-size:11px;color:var(--text-secondary);background:#fff;border:1px solid var(--border);padding:6px;border-radius:6px;margin:6px 0;word-break:break-all}.file-card small,.block-card small{font-size:11px;color:var(--text-muted)}.row-top{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}.row-top span{font-size:11px;background:var(--accent-light);color:var(--accent);border-radius:999px;padding:2px 7px;white-space:nowrap}.row-card a,.block-card a{font-size:12px;color:var(--accent);font-weight:600;word-break:break-all;display:inline-block;margin-top:6px}.row-card pre,.block-card pre{white-space:pre-wrap;word-break:break-word;max-height:420px;overflow:auto;background:#0b1220;color:#dbeafe;border-radius:8px;padding:12px;font-size:11px;line-height:1.45;margin:8px 0 0}@media(max-width:1000px){.hero,.layout,.hero-stats,.summary-strip{grid-template-columns:1fr}}
</style>
