<template>
  <div class="view">
    <div class="view-label">Product Content Editor</div>
    <div class="view-header">
      <h1>Matrixify PDP fields</h1>
      <p class="subtitle">Edit the 19 Shopify template metafields for this SKU. Every field now has review status, source citations, and a change trail before export approval.</p>
    </div>

    <div v-if="loading" class="loading">Loading...</div>
    <div v-else-if="!content" class="empty">No product-content record has been seeded for this SKU yet.</div>
    <template v-else>
      <div class="status-strip">
        <span v-for="(value, key) in content.approval" :key="key" class="status-chip" :class="statusClass(value)">{{ label(key) }}: {{ value }}</span>
        <button class="export-btn" @click="saveReviewEvent('review_note', null, 'Manual review note from content editor')">Log review note</button>
        <button class="export-btn primary" @click="save" :disabled="saving">{{ saving ? 'Saving...' : 'Save draft' }}</button>
      </div>

      <div v-if="saved" class="saved">Saved to data/content/products/{{ content.sku }}.json</div>

      <div class="editor-layout">
        <div class="editor-main">
          <div class="editor-grid">
            <section class="editor-card">
              <h2>References</h2>
              <FieldEditor v-for="field in referenceFields" :key="field.key" :field="field" :value="content.metafields[field.key]" :workflow="workflow?.fields?.[field.key]" :active="activeField === field.key" @focus="activeField = field.key" @approve="approveField(field.key)" @update="setField(field.key, $event)" />
            </section>

            <section class="editor-card wide">
              <h2>PDP copy</h2>
              <FieldEditor field-type="textarea" :field="{ key: 'pdpWhoItsFor', label: `Who it's for`, rows: 3 }" :value="content.metafields.pdpWhoItsFor" :workflow="workflow?.fields?.pdpWhoItsFor" :active="activeField === 'pdpWhoItsFor'" @focus="activeField = 'pdpWhoItsFor'" @approve="approveField('pdpWhoItsFor')" @update="setField('pdpWhoItsFor', $event)" />
              <FieldEditor field-type="textarea" :field="{ key: 'pdpProductBenefits', label: 'Product benefits (one per line)', rows: 4 }" :value="benefitsText" :workflow="workflow?.fields?.pdpProductBenefits" :active="activeField === 'pdpProductBenefits'" @focus="activeField = 'pdpProductBenefits'" @approve="approveField('pdpProductBenefits')" @update="benefitsText = $event" />
              <FieldEditor field-type="textarea" :field="{ key: 'pdpKeyFeatures', label: 'Key features', rows: 5 }" :value="content.metafields.pdpKeyFeatures" :workflow="workflow?.fields?.pdpKeyFeatures" :active="activeField === 'pdpKeyFeatures'" @focus="activeField = 'pdpKeyFeatures'" @approve="approveField('pdpKeyFeatures')" @update="setField('pdpKeyFeatures', $event)" />
            </section>

            <section class="editor-card">
              <h2>Image files</h2>
              <FieldEditor v-for="field in imageFields" :key="field.key" :field="field" :value="content.metafields[field.key]" :workflow="workflow?.fields?.[field.key]" :active="activeField === field.key" @focus="activeField = field.key" @approve="approveField(field.key)" @update="setField(field.key, $event)" />
            </section>

            <section class="editor-card wide">
              <h2>FAQs</h2>
              <FieldEditor v-for="field in faqFields" :key="field.key" :field="field" :field-type="field.type" :value="content.metafields[field.key]" :workflow="workflow?.fields?.[field.key]" :active="activeField === field.key" @focus="activeField = field.key" @approve="approveField(field.key)" @update="setField(field.key, $event)" />
            </section>
          </div>

          <section class="editor-card variants-card">
            <h2>Variant metafields</h2>
            <div class="variants-table">
              <div class="variant-row head"><span>SKU</span><span>Tag</span><span>Colour</span><span>Price per</span><span>Strapline</span></div>
              <div v-for="variant in content.variants" :key="variant.sku" class="variant-row">
                <span class="sku">{{ variant.sku }}</span>
                <input v-model="variant.pdpTag" />
                <input v-model="variant.pdpColour" />
                <input v-model="variant.pdpPricePer" placeholder="12p per capsule" />
                <input v-model="variant.pdpStrapline" />
              </div>
            </div>
          </section>
        </div>

        <aside class="review-panel">
          <section class="panel-card">
            <h2>Field source citations</h2>
            <p class="panel-sub">{{ activeField ? label(activeField) : 'Select a field' }}</p>
            <div v-if="activeWorkflow?.citations?.length" class="citation-list">
              <article v-for="citation in activeWorkflow.citations" :key="citation.path" class="citation-card">
                <strong>{{ citation.source }}</strong>
                <code>{{ citation.path }}</code>
                <p>{{ citation.note }}</p>
              </article>
            </div>
            <p v-else class="empty-small">No field selected or no citations recorded.</p>
          </section>

          <section class="panel-card">
            <h2>Draft diff</h2>
            <p class="panel-sub">Unsaved content changes since this view loaded.</p>
            <ul v-if="diffs.length" class="diff-list">
              <li v-for="diff in diffs" :key="diff.field"><strong>{{ label(diff.field) }}</strong><span>changed</span></li>
            </ul>
            <p v-else class="empty-small">No unsaved field changes.</p>
          </section>

          <section class="panel-card">
            <h2>Review log</h2>
            <div v-if="workflow?.events?.length" class="event-list">
              <article v-for="event in workflow.events.slice(0, 8)" :key="event.at + event.summary" class="event-card">
                <strong>{{ event.type }}</strong>
                <span>{{ formatDate(event.at) }}</span>
                <p>{{ event.summary }}</p>
              </article>
            </div>
            <p v-else class="empty-small">No review events yet.</p>
          </section>
        </aside>
      </div>

      <section class="source-card">
        <h2>Source trail</h2>
        <p v-for="(path, key) in content.sources" :key="key"><strong>{{ label(key) }}:</strong> {{ path }}</p>
        <ul><li v-for="note in content.notes" :key="note">{{ note }}</li></ul>
      </section>
    </template>
  </div>
</template>

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

const route = useRoute()
const content = ref(null)
const original = ref(null)
const workflow = ref(null)
const loading = ref(false)
const saving = ref(false)
const saved = ref(false)
const activeField = ref('pdpWhoItsFor')

const referenceFields = [
  { key: 'filterDietaryTag', label: 'Dietary tags', list: true, placeholder: 'dietary_tag.vegan, dietary_tag.vegetarian' },
  { key: 'filterHealthGoals', label: 'Health goals', list: true, placeholder: 'health_goals.bone-health, health_goals.digestive-health' },
  { key: 'pdpKeyIngredients', label: 'Key ingredient' },
  { key: 'pdpBenefits', label: 'Benefits' },
  { key: 'pdpClinicallyShownTo', label: 'Clinically shown to', placeholder: 'blocked until claims-evidence.json exists' },
  { key: 'breadcrumbPrimaryCollection', label: 'Primary collection' },
  { key: 'filterStrength', label: 'Strength' }
]
const imageFields = [
  { key: 'pdpResults', label: 'Results', placeholder: 'filename in Shopify Files' },
  { key: 'pdpResultsMobile', label: 'Results mobile', placeholder: 'filename in Shopify Files' },
  { key: 'pdpHowWeCompare', label: 'How we compare', placeholder: 'filename in Shopify Files' }
]
const faqFields = [
  { key: 'faqHeadingOne', label: 'Heading one' },
  { key: 'faqAnswerOne', label: 'Answer one', type: 'textarea', rows: 3 },
  { key: 'faqHeadingTwo', label: 'Heading two' },
  { key: 'faqAnswerTwo', label: 'Answer two', type: 'textarea', rows: 3 },
  { key: 'faqHeadingThree', label: 'Heading three' },
  { key: 'faqAnswerThree', label: 'Answer three', type: 'textarea', rows: 3 }
]
const allFieldKeys = [...referenceFields, { key: 'pdpWhoItsFor' }, { key: 'pdpProductBenefits' }, { key: 'pdpKeyFeatures' }, ...imageFields, ...faqFields].map(f => f.key)

const benefitsText = computed({
  get: () => (content.value?.metafields?.pdpProductBenefits || []).join('\n'),
  set: value => { content.value.metafields.pdpProductBenefits = value.split('\n').map(v => v.trim()).filter(Boolean) }
})
const activeWorkflow = computed(() => workflow.value?.fields?.[activeField.value] || null)
const diffs = computed(() => {
  if (!content.value || !original.value) return []
  return allFieldKeys.filter(field => JSON.stringify(content.value.metafields?.[field] ?? '') !== JSON.stringify(original.value.metafields?.[field] ?? '')).map(field => ({ field }))
})

function parseList(value) {
  if (Array.isArray(value)) return value.map(v => String(v).trim()).filter(Boolean)
  return String(value || '').split(',').map(v => v.trim()).filter(Boolean)
}
function setField(field, value) {
  const config = [...referenceFields, ...imageFields, ...faqFields].find(item => item.key === field)
  content.value.metafields[field] = config?.list ? parseList(value) : value
}
function label(value) { return String(value).replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase()) }
function statusClass(value) {
  if (value === 'approved' || value === 'ready' || value === 'reviewed') return 'ok'
  if (String(value).startsWith('blocked') || value === 'needed' || value === 'not_ready') return 'blocked'
  return 'draft'
}
function formatDate(value) { return value ? new Date(value).toLocaleString() : '' }

async function load(sku) {
  if (!sku) return
  loading.value = true
  saved.value = false
  try {
    const [contentRes, workflowRes] = await Promise.all([
      fetch(`/api/content/products/${sku}`),
      fetch(`/api/content/workflow/${sku}`)
    ])
    content.value = contentRes.ok ? await contentRes.json() : null
    original.value = content.value ? JSON.parse(JSON.stringify(content.value)) : null
    workflow.value = workflowRes.ok ? await workflowRes.json() : null
  } finally { loading.value = false }
}
async function save() {
  saving.value = true
  saved.value = false
  try {
    const changed = diffs.value.map(d => d.field)
    const res = await fetch(`/api/content/products/${content.value.sku}`, {
      method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(content.value)
    })
    if (!res.ok) throw new Error(await res.text())
    if (changed.length) await saveReviewEvent('draft_saved', null, `Saved draft changes: ${changed.map(label).join(', ')}`)
    original.value = JSON.parse(JSON.stringify(content.value))
    saved.value = true
  } finally { saving.value = false }
}
async function approveField(field) {
  await saveReviewEvent('field_reviewed', field, `${label(field)} marked reviewed`, 'reviewed')
  await load(content.value.sku)
}
async function saveReviewEvent(type, field, summary, status = null) {
  if (!content.value) return
  const res = await fetch(`/api/content/workflow/${content.value.sku}`, {
    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type, field, summary, status, actor: 'dashboard' })
  })
  if (!res.ok) throw new Error(await res.text())
  const latest = await fetch(`/api/content/workflow/${content.value.sku}`)
  workflow.value = latest.ok ? await latest.json() : workflow.value
}

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

<script>
export default {
  components: {
    FieldEditor: {
      props: ['field', 'value', 'workflow', 'active', 'fieldType'],
      emits: ['update', 'focus', 'approve'],
      computed: {
        renderedValue: {
          get() { return Array.isArray(this.value) ? this.value.join(', ') : this.value },
          set(value) { this.$emit('update', this.field.list ? String(value).split(',').map(v => v.trim()).filter(Boolean) : value) }
        },
        statusClass() {
          const value = this.workflow?.status || 'missing'
          if (value === 'reviewed' || value === 'approved') return 'ok'
          if (String(value).startsWith('blocked')) return 'blocked'
          return 'draft'
        }
      },
      template: `<label class="field" :class="{ active }" @focusin="$emit('focus')">
        <span class="field-head"><span>{{ field.label }}</span><button type="button" class="mini-approve" @click.prevent="$emit('approve')">Mark reviewed</button></span>
        <textarea v-if="fieldType === 'textarea' || field.type === 'textarea'" :rows="field.rows || 3" :value="renderedValue" :placeholder="field.placeholder" @input="renderedValue = $event.target.value" />
        <input v-else :value="renderedValue" :placeholder="field.placeholder" @input="renderedValue = $event.target.value" />
        <small :class="statusClass">{{ workflow?.status || 'missing status' }}</small>
      </label>`
    }
  }
}
</script>

<style scoped src="../views/view.css" />
<style scoped>
.status-strip { display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-bottom:16px; }
.status-strip .export-btn.primary { margin-left:auto; }
.status-chip { padding:4px 9px; border-radius:999px; font-size:11px; font-weight:600; background:#f3f4f6; color:#555; }
.status-chip.ok { background:var(--positive-bg); color:var(--positive); }
.status-chip.blocked { background:var(--negative-bg); color:var(--negative); }
.status-chip.draft { background:#fff7ed; color:#c2410c; }
.saved { margin-bottom:12px; color:var(--positive); font-size:12px; }
.editor-layout { display:grid; grid-template-columns:minmax(0, 1fr) 320px; gap:16px; align-items:start; }
.editor-grid { display:grid; grid-template-columns: repeat(2, minmax(280px, 1fr)); gap:16px; }
.editor-card, .source-card, .panel-card { background:#fff; border:1px solid var(--border); border-radius:var(--radius-lg); padding:18px; }
.editor-card h2, .source-card h2, .panel-card h2 { margin:0 0 12px; font-size:16px; }
.field { display:flex; flex-direction:column; gap:5px; margin-bottom:12px; font-size:12px; color:var(--text-secondary); font-weight:600; border:1px solid transparent; border-radius:var(--radius); padding:4px; }
.field.active { border-color:var(--accent); background:var(--accent-light); }
.field-head { display:flex; justify-content:space-between; gap:8px; align-items:center; }
.mini-approve { font-size:10px; border:1px solid var(--border); background:#fff; border-radius:999px; padding:2px 7px; cursor:pointer; color:var(--text-secondary); }
input, textarea { width:100%; box-sizing:border-box; border:1px solid var(--border); border-radius:var(--radius); padding:8px 10px; font:inherit; color:var(--text-primary); background:#fff; }
textarea { resize:vertical; line-height:1.45; }
.field small { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.04em; }
.field small.ok { color:var(--positive); }
.field small.blocked { color:var(--negative); }
.field small.draft { color:#c2410c; }
.variants-card { margin-top:16px; }
.variants-table { display:flex; flex-direction:column; gap:6px; }
.variant-row { display:grid; grid-template-columns: 150px 1fr 110px 150px 1.4fr; gap:8px; align-items:center; }
.variant-row.head { font-size:11px; color:var(--text-muted); text-transform:uppercase; font-weight:700; }
.sku { font-family:monospace; font-size:12px; color:var(--text-secondary); }
.review-panel { display:flex; flex-direction:column; gap:12px; position:sticky; top:16px; }
.panel-sub, .empty-small { font-size:12px; color:var(--text-muted); margin:0 0 10px; }
.citation-list, .event-list { display:flex; flex-direction:column; gap:8px; }
.citation-card, .event-card { border:1px solid var(--border); border-radius:var(--radius); padding:10px; background:#fafafa; }
.citation-card strong, .event-card strong { display:block; font-size:12px; }
.citation-card code { display:block; margin:4px 0; font-size:11px; color:var(--accent); white-space:pre-wrap; }
.citation-card p, .event-card p { margin:4px 0 0; font-size:11px; line-height:1.4; color:var(--text-secondary); }
.event-card span { font-size:10px; color:var(--text-muted); }
.diff-list { margin:0; padding-left:18px; font-size:12px; }
.diff-list li { margin:6px 0; }
.diff-list span { color:var(--text-muted); margin-left:5px; }
.source-card { margin-top:16px; font-size:12px; color:var(--text-secondary); line-height:1.5; }
@media (max-width: 1100px) { .editor-layout { grid-template-columns:1fr; } .review-panel { position:static; } }
@media (max-width: 900px) { .editor-grid { grid-template-columns: 1fr; } .variant-row { grid-template-columns: 1fr; } }
</style>
