<template>
    <a href="#"
       class="siteMenuAdmin__status"
       :class="isPublished ? 'siteMenuAdmin__status--active' : 'siteMenuAdmin__status--inactive'"
       :title="isPublished ? 'Click to deactivate' : 'Click to activate'"
       @click.prevent="toggle">
        <span class="siteMenuAdmin__dot"></span>
        <i v-if="loading" class="fa fa-spinner fa-spin"></i>
        <span v-else>{{ isPublished ? 'Active' : 'Inactive' }}</span>
    </a>
</template>

<script>
/**
 * Reactive publish toggle for a Site Menu item. Hits the publish route via AJAX
 * (JSON) and flips its own state without a page reload.
 */
export default {
    name: 'site-menu-status',
    props: {
        base: { type: String, required: true },
        itemId: { type: [String, Number], required: true },
        published: { type: Boolean, default: false },
    },
    data() {
        return { isPublished: this.published, loading: false };
    },
    watch: {
        published(value) { this.isPublished = value; },
    },
    methods: {
        toggle() {
            if (this.loading) { return; }
            this.loading = true;
            const url = this.base + '/publish/' + this.itemId + '/' + (this.isPublished ? 0 : 1);
            fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' })
                .then(response => response.json())
                .then(data => { if (data.success) { this.isPublished = data.published; } })
                .catch(() => {})
                .finally(() => { this.loading = false; });
        },
    },
};
</script>
