<template>
  <div class="view">
    <div class="view-label">Image Audit</div>
    <div class="view-header">
      <h1>Objective feedback on your images</h1>
      <p class="subtitle">Scores across all {{ galleryUrls.length || data?.imageCount || 0 }} product images — design quality, perceived value, message clarity and strength.</p>
    </div>

    <div v-if="loading" class="loading">Loading…</div>
    <div v-else-if="!data" class="empty">No image audit data available for this product yet.</div>
    <template v-else>

      <!-- Overall score row -->
      <div class="section-title">Overall Image Score</div>
      <div class="score-row">
        <div class="main-score-card">
          <div class="main-score-num">{{ data.overallScore?.value?.toFixed(1) }}</div>
          <div class="main-score-label">out of {{ data.overallScore?.outOf || 5 }}</div>
          <div class="main-score-verdict">"{{ data.overallScore?.verdict }}"</div>
        </div>
        <div class="sub-scores-card">
          <div class="sub-score-row" v-for="axis in axisRows" :key="axis.key">
            <div class="sub-score-info">
              <span class="sub-score-name">{{ axis.label }}</span>
              <span class="sub-score-val">{{ axis.score?.toFixed(1) }} / {{ axis.outOf || 5 }}</span>
            </div>
            <div class="sub-score-track">
              <div class="sub-score-fill" :class="scoreClass(axis.score)" :style="{ width: ((axis.score||0)/(axis.outOf||5)*100)+'%' }"></div>
            </div>
            <div class="sub-score-verdict" :class="scoreClass(axis.score)">{{ axis.label_text }}</div>
          </div>
        </div>
      </div>

      <!-- Coverage map -->
      <div v-if="data.setAnalysis" class="section-title" style="margin-top:24px">Image Set Coverage</div>
      <div v-if="data.setAnalysis" class="coverage-row">
        <div v-for="(val, key) in data.setAnalysis.coverage" :key="key" class="coverage-badge" :class="val ? 'covered' : 'missing'">
          <span class="coverage-icon">{{ val ? '✓' : '✗' }}</span>
          <span class="coverage-label">{{ coverageLabel(key) }}</span>
        </div>
      </div>
      <div v-if="data.setAnalysis?.criticalGap" class="gap-banner">
        <span class="gap-icon">⚠</span>
        <span>{{ data.setAnalysis.criticalGap }}</span>
      </div>

      <!-- Per-image gallery with scores -->
      <div class="section-title" style="margin-top:24px">
        Product Images <span class="count-badge">{{ galleryUrls.length }}</span>
      </div>
      <div class="image-grid">
        <div
          v-for="(url, i) in galleryUrls"
          :key="i"
          class="image-card"
          :class="{ active: selected === i }"
          @click="selected = selected === i ? null : i"
        >
          <div class="image-wrap">
            <img :src="url" :alt="`Image ${i+1}`" class="gallery-img" />
            <div class="image-index">{{ imageForUrl(url)?.index || i+1 }}</div>
            <div v-if="imageForUrl(url)" class="image-score-badge" :class="scoreClass(imageForUrl(url).score)">
              {{ imageForUrl(url).score?.toFixed(1) }}
            </div>
          </div>
          <div class="image-role">{{ imageForUrl(url)?.role || '—' }}</div>
        </div>
      </div>

      <!-- Selected image detail -->
      <transition name="fade">
        <div v-if="selected !== null && selectedImage" class="image-detail-card">
          <div class="detail-header">
            <span class="detail-role">{{ selectedImage.role }}</span>
            <span class="detail-score" :class="scoreClass(selectedImage.score)">{{ selectedImage.score?.toFixed(1) }} / 5</span>
          </div>
          <p class="detail-desc">{{ selectedImage.description }}</p>
          <div class="detail-cols">
            <div class="detail-col">
              <div class="detail-col-title strength-title">Strengths</div>
              <ul class="detail-list">
                <li v-for="s in selectedImage.strengths" :key="s" class="strength-item">{{ s }}</li>
              </ul>
            </div>
            <div class="detail-col">
              <div class="detail-col-title weakness-title">Weaknesses</div>
              <ul class="detail-list">
                <li v-for="w in selectedImage.weaknesses" :key="w" class="weakness-item">{{ w }}</li>
              </ul>
            </div>
          </div>
        </div>
      </transition>

      <!-- Priority fixes -->
      <div class="section-title" style="margin-top:24px">Priority Fixes</div>
      <div class="fixes-list">
        <div v-for="(fix, i) in data.priorityFixes" :key="i" class="fix-item">
          <span class="fix-num">{{ i + 1 }}</span>
          <span class="fix-text">{{ fix }}</span>
        </div>
      </div>

      <!-- Competitor benchmark -->
      <div v-if="data.competitorBenchmark" class="benchmark-card">
        <div class="benchmark-title">Competitor Benchmark</div>
        <p v-for="(val, key) in data.competitorBenchmark" :key="key" class="benchmark-row">
          <template v-if="key !== 'verdict'"><strong>{{ benchmarkLabel(key) }}:</strong> {{ val }}</template>
          <em v-else>{{ val }}</em>
        </p>
      </div>

    </template>
  </div>
</template>

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

const route = useRoute()
const data = ref(null)
const loading = ref(false)
const galleryUrls = ref([])
const selected = ref(null)

const axisRows = computed(() => {
  const axes = data.value?.axes || {}
  return [
    { key: 'designQuality',  label: 'Design & Image Quality', label_text: axes.designQuality?.label,  score: axes.designQuality?.score,  outOf: axes.designQuality?.outOf },
    { key: 'perceivedValue', label: 'Perceived Value',         label_text: axes.perceivedValue?.label, score: axes.perceivedValue?.score, outOf: axes.perceivedValue?.outOf },
    { key: 'messageClarity', label: 'Message Clarity',         label_text: axes.messageClarity?.label, score: axes.messageClarity?.score, outOf: axes.messageClarity?.outOf },
    { key: 'messageStrength',label: 'Message Strength',        label_text: axes.messageStrength?.label,score: axes.messageStrength?.score,outOf: axes.messageStrength?.outOf },
  ]
})

const selectedImage = computed(() => {
  if (selected.value === null) return null
  const url = galleryUrls.value[selected.value]
  return imageForUrl(url)
})

function imageForUrl(url) {
  if (!url || !data.value?.images) return null
  return data.value.images.find(img => img.url === url) || null
}

function scoreClass(v) {
  if (!v) return 'fair'
  if (v >= 4) return 'good'
  if (v >= 3) return 'okay'
  return 'fair'
}

function coverageLabel(key) {
  const map = {
    productIdentity: 'Product Identity',
    tabletSizeReference: 'Size Reference',
    socialProof: 'Social Proof',
    scienceDifferentiation: 'Science Story',
    brandTrust: 'Brand Trust',
    outcomeLifestyle: 'Outcome Lifestyle',
    timelineExpectation: 'Timeline Expectation',
    ingredientHeroShot: 'Ingredient Hero'
  }
  return map[key] || key
}

function benchmarkLabel(key) {
  const map = { hollandAndBarrett: 'H&B', naturesBest: "Nature's Best", wildNutrition: 'Wild Nutrition' }
  return map[key] || key
}

async function load(sku) {
  if (!sku) return
  loading.value = true
  selected.value = null
  try {
    const [auditRes, imgRes] = await Promise.all([
      fetch(`/api/intelligence/${sku}/image-audit`),
      fetch(`/api/product-images/${sku}`)
    ])
    data.value = auditRes.ok ? await auditRes.json() : null
    const imgData = imgRes.ok ? await imgRes.json() : null
    galleryUrls.value = imgData?.urls || []
  } finally { loading.value = false }
}

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

<style scoped src="../views/view.css" />
<style scoped>
.section-title { font-size: 18px; font-weight: 600; margin-bottom: 16px; }

/* Score row */
.score-row { display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap; align-items: stretch; }
.main-score-card {
  background: #fff; border: 1px solid var(--border); border-radius: var(--radius-lg);
  padding: 32px 36px; text-align: center; min-width: 180px;
  display: flex; flex-direction: column; justify-content: center;
}
.main-score-num { font-size: 56px; font-weight: 300; line-height: 1; color: var(--text-primary); }
.main-score-label { font-size: 13px; color: var(--text-muted); margin-top: 4px; }
.main-score-verdict { font-size: 11px; color: var(--text-muted); margin-top: 10px; font-style: italic; line-height: 1.4; }
.sub-scores-card {
  flex: 1; background: #fff; border: 1px solid var(--border); border-radius: var(--radius-lg);
  padding: 20px 24px; display: flex; flex-direction: column; gap: 16px; min-width: 260px;
}
.sub-score-row { display: flex; flex-direction: column; gap: 4px; }
.sub-score-info { display: flex; justify-content: space-between; align-items: baseline; }
.sub-score-name { font-size: 12px; font-weight: 500; color: var(--text-primary); }
.sub-score-val  { font-size: 12px; color: var(--text-muted); }
.sub-score-track { height: 6px; background: var(--border); border-radius: 3px; overflow: hidden; }
.sub-score-fill { height: 100%; border-radius: 3px; transition: width 0.5s; background: #e5e7eb; }
.sub-score-fill.good { background: var(--positive); }
.sub-score-fill.okay { background: #f59e0b; }
.sub-score-fill.fair { background: var(--negative); }
.sub-score-verdict { font-size: 11px; }
.sub-score-verdict.good { color: var(--positive); }
.sub-score-verdict.okay { color: #f59e0b; }
.sub-score-verdict.fair { color: var(--negative); }

/* Coverage */
.coverage-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
.coverage-badge {
  display: flex; align-items: center; gap: 5px;
  padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 500;
}
.coverage-badge.covered { background: var(--positive-bg); color: var(--positive); }
.coverage-badge.missing  { background: var(--negative-bg); color: var(--negative); }
.coverage-icon { font-size: 10px; }
.gap-banner {
  display: flex; align-items: flex-start; gap: 10px;
  background: #fff7ed; border: 1px solid #fed7aa; border-radius: var(--radius-lg);
  padding: 12px 16px; font-size: 13px; color: #c2410c; margin-bottom: 24px; line-height: 1.5;
}
.gap-icon { font-size: 14px; flex-shrink: 0; margin-top: 1px; }

/* Image grid */
.image-grid { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
.image-card {
  width: 148px; border: 2px solid var(--border); border-radius: var(--radius-lg);
  overflow: hidden; background: #fff; cursor: pointer; transition: border-color 0.15s;
}
.image-card:hover { border-color: var(--accent); }
.image-card.active { border-color: var(--accent); }
.image-wrap { position: relative; }
.gallery-img { width: 100%; height: 148px; object-fit: contain; display: block; padding: 8px; }
.image-index {
  position: absolute; top: 6px; left: 6px; width: 20px; height: 20px;
  background: rgba(0,0,0,0.45); color: #fff; border-radius: 50%;
  font-size: 10px; font-weight: 600; display: flex; align-items: center; justify-content: center;
}
.image-score-badge {
  position: absolute; top: 6px; right: 6px;
  padding: 2px 7px; border-radius: 10px; font-size: 11px; font-weight: 700;
}
.image-score-badge.good { background: var(--positive-bg); color: var(--positive); }
.image-score-badge.okay { background: #fef9c3; color: #a16207; }
.image-score-badge.fair { background: var(--negative-bg); color: var(--negative); }
.image-role { font-size: 11px; color: var(--text-muted); padding: 6px 8px 8px; text-align: center; line-height: 1.3; }

/* Image detail */
.image-detail-card {
  background: #fff; border: 1px solid var(--border); border-radius: var(--radius-lg);
  padding: 20px 24px; margin-bottom: 24px;
}
.detail-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.detail-role { font-size: 13px; font-weight: 600; color: var(--text-primary); }
.detail-score { font-size: 14px; font-weight: 700; }
.detail-score.good { color: var(--positive); }
.detail-score.okay { color: #f59e0b; }
.detail-score.fair { color: var(--negative); }
.detail-desc { font-size: 12px; color: var(--text-secondary); line-height: 1.5; margin-bottom: 16px; }
.detail-cols { display: flex; gap: 20px; }
.detail-col { flex: 1; }
.detail-col-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 8px; }
.strength-title { color: var(--positive); }
.weakness-title { color: var(--negative); }
.detail-list { padding-left: 16px; }
.detail-list li { font-size: 12px; line-height: 1.5; margin-bottom: 4px; }
.strength-item { color: var(--text-secondary); }
.weakness-item { color: var(--text-secondary); }

/* Fixes */
.fixes-list { background: #fff; border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 8px 0; margin-bottom: 24px; }
.fix-item { display: flex; align-items: flex-start; gap: 14px; padding: 12px 22px; border-bottom: 1px solid var(--border); }
.fix-item:last-child { border-bottom: none; }
.fix-num {
  width: 22px; height: 22px; background: var(--accent-light); color: var(--accent);
  border-radius: 50%; display: flex; align-items: center; justify-content: center;
  font-size: 11px; font-weight: 700; flex-shrink: 0; margin-top: 1px;
}
.fix-text { font-size: 13px; color: var(--text-primary); line-height: 1.5; }

/* Benchmark */
.benchmark-card { background: #fff; border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 18px 22px; }
.benchmark-title { font-size: 13px; font-weight: 600; margin-bottom: 10px; }
.benchmark-row { font-size: 12px; color: var(--text-secondary); line-height: 1.5; margin: 0 0 6px; }

/* Fade transition */
.fade-enter-active, .fade-leave-active { transition: opacity 0.2s; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
</style>
