<template>
  <div class="cw-canvas-inner-draggable">
    <div v-if="displayBlocks.length === 0" class="cw-drop-hint" @dragover.prevent @drop.prevent>
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="32" height="32">
        <path d="M12 5v14M5 12l7 7 7-7"/>
      </svg>
      <p>Drag blocks here to build your form</p>
    </div>

    <draggable
      v-model="displayBlocks"
      :group="{ name: 'form-blocks', pull: true, put: true }"
      item-key="id"
      handle=".eb-handle"
      :animation="150"
      ghost-class="eb-ghost"
      class="cw-canvas-draggable"
      @add="onBlockAdded"
      @start="onDragStart"
      @end="onDragEnd"
    >
      <template #item="{ element: block }">
        <FormBlock :block="block" />
      </template>
    </draggable>
  </div>
</template>

<script setup>
import { computed, inject } from 'vue';
import draggable from 'vuedraggable';
import FormBlock from './FormBlock.vue';

const props = defineProps({
  modelValue: { type: Array, required: true },
});

const emit = defineEmits(['update:modelValue']);

const displayBlocks = computed({
  get: () => props.modelValue.filter((b) => b.type !== 'body'),
  set: (val) => {
    const bodyBlock = props.modelValue.find((b) => b.type === 'body');
    emit('update:modelValue', bodyBlock ? [bodyBlock, ...val] : val);
  },
});

const { onBlockAdded, onDragStart, onDragEnd } = inject('formEditorState');
</script>

<style scoped>
.cw-canvas-inner-draggable {
  min-height: 200px;
  padding: 8px;
}
.cw-canvas-draggable {
  min-height: 120px;
}
</style>
