<template>
    <div class="bm-block-list">
        <header class="bm-block-list__header">
            <h2 class="bm-block-list__title">Blocks</h2>
            <button
                type="button"
                class="bm-button-primary"
                @click="$emit('open', null)"
            >+ New block</button>
        </header>

        <div v-if="loading" class="bm-block-list__status">Loading…</div>
        <div v-else-if="error" class="bm-block-list__status bm-block-list__status--error">{{ error }}</div>

        <div v-else-if="blocks.length === 0" class="bm-block-list__empty">
            No blocks yet. Click <strong>New block</strong> to compose your first one.
        </div>

        <div v-else class="bm-block-list__grid">
            <article
                v-for="block in blocks"
                :key="block.id"
                class="bm-block-card"
                @click="$emit('open', block.id)"
            >
                <div class="bm-block-card__icon">
                    <i v-if="block.icon" :class="['fa', block.icon]" aria-hidden="true"></i>
                    <span v-else aria-hidden="true">▢</span>
                </div>
                <div class="bm-block-card__body">
                    <h3 class="bm-block-card__name">{{ block.name }}</h3>
                    <p class="bm-block-card__slug">{{ block.slug }}</p>
                    <p v-if="block.description" class="bm-block-card__desc">{{ block.description }}</p>
                </div>
                <div class="bm-block-card__meta">
                    <span
                        v-if="block.last_shipped_at"
                        class="bm-block-card__badge bm-block-card__badge--shipped"
                    >Shipped</span>
                    <span v-else class="bm-block-card__badge">Draft</span>
                </div>
                <div class="bm-block-card__actions" @click.stop>
                    <button
                        type="button"
                        class="bm-instance__btn"
                        :disabled="busyId === block.id"
                        @click="duplicate(block)"
                    >Duplicate</button>
                    <button
                        type="button"
                        class="bm-instance__btn bm-instance__btn--danger"
                        :disabled="busyId === block.id"
                        @click="remove(block)"
                    >Delete</button>
                </div>
            </article>
        </div>
    </div>
</template>

<script>
const ENDPOINT = '/api/block-manager';

export default {
    name: 'BlockList',
    data() {
        return {
            blocks: [],
            loading: true,
            error: null,
            busyId: null,
        };
    },
    mounted() {
        this.load();
    },
    methods: {
        async load() {
            this.loading = true;
            this.error = null;
            try {
                const res = await fetch(ENDPOINT, {
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                    credentials: 'same-origin',
                });
                if (!res.ok) throw new Error(`status ${res.status}`);
                const { data } = await res.json();
                this.blocks = Array.isArray(data) ? data : [];
            } catch (err) {
                this.error = `Failed to load blocks: ${err.message}`;
            } finally {
                this.loading = false;
            }
        },
        async duplicate(block) {
            this.busyId = block.id;
            try {
                const res = await fetch(`${ENDPOINT}/${block.id}/duplicate`, {
                    method: 'POST',
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                    credentials: 'same-origin',
                });
                if (!res.ok) throw new Error(`status ${res.status}`);
                const { data } = await res.json();
                this.$emit('open', data.id);
            } catch (err) {
                this.error = `Duplicate failed: ${err.message}`;
            } finally {
                this.busyId = null;
            }
        },
        async remove(block) {
            const ok = window.confirm(`Delete block "${block.name}"? This cannot be undone.`);
            if (!ok) return;
            this.busyId = block.id;
            try {
                const res = await fetch(`${ENDPOINT}/${block.id}`, {
                    method: 'DELETE',
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                    credentials: 'same-origin',
                });
                if (!res.ok && res.status !== 204) throw new Error(`status ${res.status}`);
                this.blocks = this.blocks.filter((b) => b.id !== block.id);
            } catch (err) {
                this.error = `Delete failed: ${err.message}`;
            } finally {
                this.busyId = null;
            }
        },
    },
};
</script>
