<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <div>
        <NuxtLink to="/admin/book" class="text-sm text-white/40 hover:text-white/60 transition-colors">
          ← Chapitres
        </NuxtLink>
        <h1 class="font-display text-2xl font-bold text-white mt-1">
          {{ chapterTitle || slug }}
        </h1>
        <span class="text-xs text-white/30 font-mono">{{ slug }}</span>
      </div>
      <div class="flex items-center gap-3">
        <span v-if="wordCount" class="text-xs text-white/30">{{ wordCount }} mots</span>
        <AdminSaveButton :saving="saving" :saved="saved" @save="save" />
      </div>
    </div>

    <template v-if="chapter">
      <AdminFormSection title="Métadonnées">
        <div class="grid gap-3 sm:grid-cols-2">
          <div>
            <label class="field-label">Titre</label>
            <input v-model="title" class="field-input" placeholder="Titre du chapitre" />
          </div>
          <div>
            <label class="field-label">Temps de lecture</label>
            <input v-model="readingTime" class="field-input" placeholder="15 min" />
          </div>
          <div class="sm:col-span-2">
            <label class="field-label">Description</label>
            <input v-model="description" class="field-input" placeholder="Description courte pour le SEO" />
          </div>
        </div>
      </AdminFormSection>

      <AdminFormSection title="Contenu" open>
        <AdminMarkdownEditor v-model="body" :rows="35" />
      </AdminFormSection>
    </template>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'admin',
  middleware: 'admin',
})

const route = useRoute()
const slug = computed(() => route.params.slug as string)

const { data: chapter } = await useFetch(() => `/api/admin/chapters/${slug.value}`)

const title = ref('')
const description = ref('')
const readingTime = ref('')
const body = ref('')

const chapterTitle = computed(() => title.value)
const wordCount = computed(() => {
  if (!body.value) return 0
  return body.value.trim().split(/\s+/).filter(Boolean).length
})

watch(chapter, (val) => {
  if (val) {
    // Parse frontmatter fields
    const fm = val.frontmatter ?? ''
    title.value = extractFmField(fm, 'title')
    description.value = extractFmField(fm, 'description')
    readingTime.value = extractFmField(fm, 'readingTime')
    body.value = val.body ?? ''
  }
}, { immediate: true })

function extractFmField(fm: string, field: string): string {
  const match = fm.match(new RegExp(`^${field}:\\s*"?([^"\\n]*)"?`, 'm'))
  return match ? match[1].trim() : ''
}

const saving = ref(false)
const saved = ref(false)

async function save() {
  saving.value = true
  saved.value = false
  try {
    const order = chapter.value?.frontmatter?.match(/order:\s*(\d+)/)?.[1] ?? '1'
    const frontmatter = [
      `title: "${title.value}"`,
      `description: "${description.value}"`,
      `order: ${order}`,
      `readingTime: "${readingTime.value}"`,
    ].join('\n')

    await $fetch(`/api/admin/chapters/${slug.value}`, {
      method: 'PUT',
      body: { frontmatter, body: body.value },
    })
    saved.value = true
    setTimeout(() => { saved.value = false }, 2000)
  }
  finally {
    saving.value = false
  }
}
</script>

<style scoped>
.field-label {
  display: block;
  font-size: 0.75rem;
  color: hsl(20 8% 50%);
  margin-bottom: 0.25rem;
}

.field-input {
  width: 100%;
  padding: 0.5rem 0.625rem;
  border-radius: 0.375rem;
  border: 1px solid hsl(20 8% 18%);
  background: hsl(20 8% 6%);
  color: white;
  font-size: 0.85rem;
}

.field-input:focus {
  outline: none;
  border-color: hsl(12 76% 48% / 0.5);
}
</style>
