<template>
    <div class="bm-structure__node">
        <div
            class="bm-structure__row"
            :class="{ 'is-selected': instance.instance_id === selectedId }"
            :style="{ paddingLeft: (8 + depth * 16) + 'px' }"
            @click="$emit('select', instance.instance_id)"
        >
            <span class="bm-structure__handle" aria-label="Drag to reorder" title="Drag to reorder">⋮⋮</span>
            <span class="bm-structure__type">{{ instance.element_type }}</span>
            <span class="bm-structure__variant">{{ instance.variant }}</span>
            <span class="bm-structure__name">{{ instance.field_name }}</span>
            <button
                type="button"
                class="bm-structure__delete"
                aria-label="Delete element"
                @click.stop="$emit('delete', instance.instance_id)"
            >×</button>
        </div>

        <!-- Container: recursive, drag-reorderable nested list -->
        <VueDraggable
            v-if="isContainer"
            :model-value="instance.children"
            :group="{ name: 'bm-structure' }"
            :animation="150"
            ghost-class="bm-structure__ghost"
            chosen-class="bm-structure__chosen"
            item-key="instance_id"
            handle=".bm-structure__handle"
            :empty-insert-threshold="40"
            class="bm-structure__children"
            @update:modelValue="(next) => $emit('children-input', instance.instance_id, next)"
        >
            <StructureNode
                v-for="child in instance.children"
                :key="child.instance_id"
                :instance="child"
                :selected-id="selectedId"
                :depth="depth + 1"
                @select="(id) => $emit('select', id)"
                @delete="(id) => $emit('delete', id)"
                @children-input="(cid, next) => $emit('children-input', cid, next)"
            />
            <p
                v-if="instance.children.length === 0"
                class="bm-structure__empty"
                :style="{ paddingLeft: (8 + (depth + 1) * 16) + 'px' }"
            >Empty container.</p>
        </VueDraggable>
    </div>
</template>

<script>
import { VueDraggable } from 'vue-draggable-plus';

export default {
    // `name` enables the recursive <StructureNode> self-reference below.
    name: 'StructureNode',
    components: { VueDraggable },
    props: {
        instance: { type: Object, required: true },
        selectedId: { type: String, default: null },
        depth: { type: Number, default: 0 },
    },
    computed: {
        isContainer() {
            return this.instance.children !== undefined;
        },
    },
};
</script>
