<template>
  <div class="mt-6">
    <button
        class="px-4 py-2 bg-red-600 text-white rounded inline-flex items-center"
        @click="confirmDelete"
        :disabled="loading"
    >
      <svg
          v-if="loading"
          class="animate-spin h-5 w-5 mr-2"
          viewBox="0 0 24 24"
      >
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
      </svg>
      {{ loading ? (i18n.deleting) : i18n.delete_my_data }}
    </button>
    <InfoModal
        :show="showInfoModal"
        :message="infoMessage"
        :i18n="i18n"
        @close="handleModalClose"
    />
  </div>
</template>

<script>
import InfoModal from './modals/InfoModal.vue';

export default {
  name: 'DeleteDataButton',
  components: { InfoModal },
  props: { i18n: { type: Object, required: true } },
  data() {
    return { loading: false, showInfoModal: false, infoMessage: '', infoModalCallback: null };
  },
  methods: {
    confirmDelete() {
      if (!confirm(this.i18n.confirm_delete_data)) return;
      this.loading = true;
      fetch(`${window.BookaroData.rest_url}bookaro/v1/personal-data`, {
        method: 'DELETE',
        headers: { 'X-WP-Nonce': window.BookaroData.rest_nonce }
      })
        .then(r => r.json())
        .then(() => {
          this.infoMessage = this.i18n.data_deleted;
          this.infoModalCallback = () => window.location.reload();
          this.showInfoModal = true;
        })
        .catch(() => {
          this.infoMessage = this.i18n.delete_failed;
          this.showInfoModal = true;
        })
        .finally(() => { this.loading = false; });
    },
    handleModalClose() {
      this.showInfoModal = false;
      if (this.infoModalCallback) {
        this.infoModalCallback();
        this.infoModalCallback = null;
      }
    }
  }
};
</script>
