<template>
  <k-box>
    <k-button 
      theme="positive"
      icon="download" 
      :disabled="loading"
      @click="exportEpub"
    >
      Exporter en EPUB
    </k-button>

    <k-text v-if="loading">Génération en cours…</k-text>
    <k-text v-if="error" theme="negative">{{ error }}</k-text>
  </k-box>
</template>

<!-- <script>
  export default {
    props: {
      pageId: String
    },
    data() {
      return {
        loading: false,
        error: null,
      }
    },
    methods: {
    async exportEpub() {
      this.loading = true;
      this.error = null;

      try {
        const response = await this.$api.post(`epub-export/${this.pageId}`);
        const blob = await response.blob()
        
        

        // Télécharger le fichier
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = this.pageId + '.epub'
        a.click()

      } catch (e) {
        this.error = "Erreur : " + e.message
      } finally {
        this.loading = false
      }
    }
  }
}
</script> -->

<script setup>
import { ref } from 'vue'

// Props
const { pageId } = defineProps({
  pageId: String
})

// State
const loading = ref(false)
const error = ref(null)

// Methods
async function exportEpub() {
  loading.value = true
  error.value = null

  try {
    // Appel API
    const response = await $api.post(`epub-export/${pageId}`)
    const blob = await response.blob()

    // Création du téléchargement
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = pageId + '.epub'
    a.click()

  } catch (e) {
    error.value = 'Erreur : ' + e.message
  } finally {
    loading.value = false
  }
}
</script>

