<template>
    <div class="bm-designer__picker">
        <!-- Grid view: pick an element to work with (mirrors the Blocks tab). -->
        <template v-if="!selectedType">
            <header class="bm-block-list__header">
                <h2 class="bm-block-list__title">Elements</h2>
            </header>

            <p v-if="errorMessage" class="bm-designer__msg">{{ errorMessage }}</p>
            <div v-if="elements.length === 0 && !errorMessage" class="bm-designer__placeholder">
                Loading elements…
            </div>

            <div v-else class="bm-element-grid">
                <article
                    v-for="el in elements"
                    :key="el.type"
                    class="bm-element-card"
                    role="button"
                    tabindex="0"
                    @click="selectType(el.type)"
                    @keydown.enter.prevent="selectType(el.type)"
                    @keydown.space.prevent="selectType(el.type)"
                >
                    <div class="bm-element-card__icon">
                        <i v-if="el.icon" :class="['fa', el.icon]" aria-hidden="true"></i>
                        <span v-else aria-hidden="true">▢</span>
                    </div>
                    <div class="bm-element-card__body">
                        <h3 class="bm-element-card__name">{{ el.label }}</h3>
                        <p class="bm-element-card__slug">{{ el.type }}</p>
                    </div>
                    <div class="bm-element-card__meta">
                        <span class="bm-element-card__badge">
                            {{ (el.variants || []).length }} {{ (el.variants || []).length === 1 ? 'variant' : 'variants' }}
                        </span>
                        <span v-if="el.accepts_children" class="bm-element-card__badge bm-element-card__badge--layout">
                            Layout
                        </span>
                    </div>
                </article>
            </div>
        </template>

        <!-- Detail view: chosen element — open an existing draft or create one. -->
        <template v-else>
            <header class="bm-designer__picker-head">
                <button type="button" class="bm-back-button" @click="clearSelection">← All elements</button>
                <h2 class="bm-admin__title">{{ selectedLabel }} <span class="bm-designer__picker-type">{{ selectedType }}</span></h2>
            </header>

        <div class="bm-designer__picker-tabs">
            <button
                type="button"
                class="bm-rail-tab"
                :class="{ 'is-active': pickerMode === 'open' }"
                @click="pickerMode = 'open'"
            >Open existing</button>
            <button
                type="button"
                class="bm-rail-tab"
                :class="{ 'is-active': pickerMode === 'create' }"
                @click="pickerMode = 'create'"
            >Create new</button>
        </div>

        <div v-if="pickerMode === 'open'" class="bm-designer__picker-list">
            <p v-if="loadingDrafts" class="bm-designer__placeholder">Loading drafts…</p>
            <p v-else-if="filteredDrafts.length === 0" class="bm-designer__placeholder">
                No drafts yet for "{{ selectedType }}". Create one.
            </p>
            <ul v-else class="bm-designer__draft-list">
                <li
                    v-for="d in filteredDrafts"
                    :key="d.id"
                    class="bm-designer__draft-row"
                    @click="open(d.id)"
                >
                    <strong>{{ d.label || d.variant_slug }}</strong>
                    <span class="bm-designer__draft-slug">{{ d.variant_slug }}</span>
                </li>
            </ul>
        </div>

        <form v-if="pickerMode === 'create'" class="bm-designer__picker-form" @submit.prevent="create">
            <label class="bm-designer__field">
                <span class="bm-designer__field-label">Variant slug</span>
                <input
                    v-model="newSlug"
                    type="text"
                    class="bm-designer__input"
                    placeholder="e.g. primary-pill"
                    required
                />
            </label>
            <label class="bm-designer__field">
                <span class="bm-designer__field-label">Label</span>
                <input
                    v-model="newLabel"
                    type="text"
                    class="bm-designer__input"
                    placeholder="e.g. Primary Pill"
                />
            </label>
            <button
                type="submit"
                class="bm-button-primary"
                :disabled="creating || !newSlug.trim()"
            >{{ creating ? 'Creating…' : 'Create draft' }}</button>
            <span v-if="errorMessage" class="bm-designer__msg">{{ errorMessage }}</span>
        </form>
        </template>
    </div>
</template>

<script>
const VARIANTS_ENDPOINT = '/api/block-manager/variants';
const ELEMENTS_ENDPOINT = '/api/block-manager/elements';

export default {
    name: 'ElementVariantPicker',
    data() {
        return {
            elements: [],
            selectedType: '',
            pickerMode: 'open',
            drafts: [],
            loadingDrafts: false,
            newSlug: '',
            newLabel: '',
            creating: false,
            errorMessage: '',
        };
    },
    computed: {
        filteredDrafts() {
            return this.drafts.filter((d) => d.element_type === this.selectedType);
        },
        selectedLabel() {
            const el = this.elements.find((e) => e.type === this.selectedType);
            return el ? el.label : this.selectedType;
        },
    },
    watch: {
        selectedType(next) {
            if (next) this.loadDrafts(next);
        },
    },
    async mounted() {
        await this.loadElements();
    },
    methods: {
        async loadElements() {
            try {
                const r = await fetch(ELEMENTS_ENDPOINT);
                const j = await r.json();
                this.elements = j.data || [];
            } catch (err) {
                this.errorMessage = `Element load failed: ${err.message}`;
            }
        },
        async loadDrafts(elementType) {
            this.loadingDrafts = true;
            try {
                const r = await fetch(`${VARIANTS_ENDPOINT}?element_type=${encodeURIComponent(elementType)}`);
                const j = await r.json();
                this.drafts = j.data || [];
            } catch (err) {
                this.errorMessage = `Draft load failed: ${err.message}`;
            } finally {
                this.loadingDrafts = false;
            }
        },
        selectType(type) {
            // The selectedType watcher loads this element's drafts.
            this.selectedType = type;
            this.pickerMode = 'open';
            this.errorMessage = '';
        },
        clearSelection() {
            this.selectedType = '';
            this.pickerMode = 'open';
            this.newSlug = '';
            this.newLabel = '';
            this.errorMessage = '';
        },
        open(id) {
            window.location.href = `/admin/block-manager/elements/${id}`;
        },
        async create() {
            this.creating = true;
            this.errorMessage = '';
            try {
                const r = await fetch(VARIANTS_ENDPOINT, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    body: JSON.stringify({
                        element_type: this.selectedType,
                        variant_slug: this.newSlug.trim(),
                        label: this.newLabel.trim() || null,
                    }),
                    credentials: 'same-origin',
                });
                if (!r.ok) {
                    const body = await r.text();
                    throw new Error(`${r.status} ${body.slice(0, 200)}`);
                }
                const { data } = await r.json();
                this.open(data.id);
            } catch (err) {
                this.errorMessage = `Create failed: ${err.message}`;
            } finally {
                this.creating = false;
            }
        },
    },
};
</script>
