<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <div>
        <NuxtLink to="/admin" class="text-sm text-white/40 hover:text-white/60 transition-colors">
          ← Dashboard
        </NuxtLink>
        <h1 class="font-display text-2xl font-bold text-white mt-1">
          Page : {{ pageName }}
        </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 pageName = computed(() => route.params.name as string)

const { data, error } = await useFetch(() => `/api/content/pages/${pageName.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/${pageName.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(20 8% 18%);
  border-radius: 0.5rem;
  background: hsl(20 8% 4%);
  color: hsl(36 80% 76%);
  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(12 76% 48% / 0.5);
}
</style>
