<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="Morceaux associés">
        <p class="text-xs text-white/40 mb-3">
          Cliquez pour associer/dissocier. Cliquez sur l'étoile pour définir le morceau principal.
        </p>
        <div class="flex flex-wrap gap-2">
          <div
            v-for="song in allSongs"
            :key="song.id"
            class="song-tag"
            :class="{
              'song-tag--active': isLinked(song.id),
              'song-tag--primary': isPrimary(song.id),
            }"
          >
            <button
              v-if="isLinked(song.id)"
              class="song-star"
              :class="{ 'song-star--active': isPrimary(song.id) }"
              @click="setPrimary(song.id)"
              aria-label="Définir comme principal"
            >
              <div class="i-lucide-star h-3 w-3" />
            </button>
            <button class="song-tag-label" @click="toggleSong(song.id)">
              {{ song.title }}
            </button>
          </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 { data: bookConfig } = await useFetch<any>('/api/content/config')

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) {
    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() : ''
}

// ── Morceaux associés ──
const allSongs = computed(() => bookConfig.value?.songs ?? [])
const linkedSongIds = ref<Set<string>>(new Set())
const primarySongId = ref<string | null>(null)

watch(bookConfig, (val) => {
  if (!val) return
  const links = (val.chapterSongs ?? []).filter(
    (cs: any) => cs.chapterSlug === slug.value,
  )
  linkedSongIds.value = new Set(links.map((l: any) => l.songId))
  const primary = links.find((l: any) => l.primary)
  primarySongId.value = primary?.songId ?? null
}, { immediate: true })

function isLinked(songId: string) {
  return linkedSongIds.value.has(songId)
}

function isPrimary(songId: string) {
  return primarySongId.value === songId
}

function toggleSong(songId: string) {
  const next = new Set(linkedSongIds.value)
  if (next.has(songId)) {
    next.delete(songId)
    if (primarySongId.value === songId) primarySongId.value = null
  }
  else {
    next.add(songId)
    if (!primarySongId.value) primarySongId.value = songId
  }
  linkedSongIds.value = next
}

function setPrimary(songId: string) {
  if (!linkedSongIds.value.has(songId)) {
    const next = new Set(linkedSongIds.value)
    next.add(songId)
    linkedSongIds.value = next
  }
  primarySongId.value = songId
}

// ── Save ──
const saving = ref(false)
const saved = ref(false)

async function save() {
  saving.value = true
  saved.value = false
  try {
    // 1. Sauvegarder le contenu du chapitre
    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 },
    })

    // 2. Sauvegarder les liaisons morceaux dans la config
    if (bookConfig.value) {
      const otherLinks = (bookConfig.value.chapterSongs ?? []).filter(
        (cs: any) => cs.chapterSlug !== slug.value,
      )
      const newLinks = [...linkedSongIds.value].map(songId => ({
        chapterSlug: slug.value,
        songId,
        primary: songId === primarySongId.value,
      }))
      const updatedConfig = {
        ...bookConfig.value,
        chapterSongs: [...otherLinks, ...newLinks],
      }
      await $fetch('/api/admin/content/config', {
        method: 'PUT',
        body: updatedConfig,
      })
    }

    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(var(--color-text-muted));
  margin-bottom: 0.25rem;
}

.field-input {
  width: 100%;
  padding: 0.5rem 0.625rem;
  border-radius: 0.375rem;
  border: 1px solid hsl(var(--color-surface-light));
  background: hsl(var(--color-bg));
  color: hsl(var(--color-text));
  font-size: 0.85rem;
}

.field-input:focus {
  outline: none;
  border-color: hsl(var(--color-primary) / 0.5);
}

/* ── Song tags ── */
.song-tag {
  display: inline-flex;
  align-items: center;
  border-radius: 9999px;
  border: 1px solid hsl(var(--color-surface-light));
  transition: all 0.15s;
  overflow: hidden;
}

.song-tag:hover {
  border-color: hsl(var(--color-primary) / 0.4);
}

.song-tag--active {
  border-color: hsl(var(--color-primary) / 0.6);
  background: hsl(var(--color-primary) / 0.08);
}

.song-tag--primary {
  border-color: hsl(var(--color-accent));
  background: hsl(var(--color-accent) / 0.08);
}

.song-tag-label {
  padding: 0.375rem 0.75rem;
  background: none;
  border: none;
  color: hsl(var(--color-text-muted));
  font-size: 0.8rem;
  cursor: pointer;
  transition: color 0.15s;
}

.song-tag--active .song-tag-label {
  color: hsl(var(--color-primary));
}

.song-tag--primary .song-tag-label {
  color: hsl(var(--color-accent));
}

.song-tag-label:hover {
  color: hsl(var(--color-text));
}

.song-star {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.375rem 0 0.375rem 0.625rem;
  background: none;
  border: none;
  color: hsl(var(--color-text-muted));
  cursor: pointer;
  transition: color 0.15s;
}

.song-star:hover {
  color: hsl(var(--color-accent));
}

.song-star--active {
  color: hsl(var(--color-accent));
}
</style>
