<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <div>
        <NuxtLink to="/admin/pages" class="text-sm text-white/40 hover:text-white/60 transition-colors">
          ← Pages
        </NuxtLink>
        <h1 class="font-display text-2xl font-bold text-white mt-1">
          Page : {{ pagePath }}
        </h1>
      </div>
      <AdminSaveButton :saving="saving" :saved="saved" @save="save" />
    </div>

    <div v-if="data" class="page-editor">
      <AdminFormSection title="Contenu YAML" open>
        <div class="yaml-editor-wrapper">
          <textarea
            v-model="yamlContent"
            class="yaml-textarea"
            rows="30"
            spellcheck="false"
          />
        </div>
      </AdminFormSection>
    </div>

    <p v-else-if="error" class="text-red-400">
      Erreur de chargement : {{ error.message }}
    </p>
  </div>
</template>

<script setup lang="ts">
import yaml from 'yaml'

definePageMeta({
  layout: 'admin',
  middleware: 'admin',
})

const route = useRoute()
const pagePath = computed(() => {
  const p = route.params.path
  return Array.isArray(p) ? p.join('/') : p
})

const { data, error } = await useFetch(() => `/api/content/pages/${pagePath.value}`)

const yamlContent = ref('')

watch(data, (val) => {
  if (val) {
    yamlContent.value = yaml.stringify(val, { lineWidth: 120 })
  }
}, { immediate: true })

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

async function save() {
  saving.value = true
  saved.value = false
  try {
    const parsed = yaml.parse(yamlContent.value)
    await $fetch(`/api/admin/content/pages/${pagePath.value}`, {
      method: 'PUT',
      body: parsed,
    })
    saved.value = true
    setTimeout(() => { saved.value = false }, 2000)
  }
  catch (e: any) {
    alert('Erreur YAML : ' + (e?.message ?? 'format invalide'))
  }
  finally {
    saving.value = false
  }
}
</script>

<style scoped>
.yaml-textarea {
  width: 100%;
  padding: 1rem;
  border: 1px solid hsl(var(--color-surface-light));
  border-radius: 0.5rem;
  background: hsl(var(--color-bg));
  color: hsl(var(--color-accent));
  font-family: var(--font-mono, monospace);
  font-size: 0.85rem;
  line-height: 1.7;
  resize: vertical;
  min-height: 20rem;
}

.yaml-textarea:focus {
  outline: none;
  border-color: hsl(var(--color-primary) / 0.5);
}
</style>
