<template>
  <div class="cw-canvas-inner-draggable">
    <div v-if="displayBlocks.length === 0" class="cw-drop-hint" @dragover.prevent @drop.prevent="handleDrop">
      <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 email</p>
    </div>

    <draggable
      v-model="displayBlocks"
      :group="{ name: 'email-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 }">
        <EmailBlock :block="block" />
      </template>
    </draggable>

    <!-- Footer -->
    <div v-if="!hasFooterBlock" class="eb-footer">
      <p>You're receiving this email because you subscribed to our newsletter.</p>
      <p><a href="#" @click.prevent>Unsubscribe</a> · <a href="#" @click.prevent>Privacy Policy</a></p>
      <p>© {{ new Date().getFullYear() }} Your Company · All rights reserved</p>
    </div>
  </div>
</template>

<script setup>
import { computed, inject } from 'vue';
import draggable from 'vuedraggable';
import EmailBlock from './EmailBlock.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');
    const newList = bodyBlock ? [bodyBlock, ...val] : val;
    emit('update:modelValue', newList);
  }
});

// Inject shared state and logic from EmailEditor wrapper
const {
  onBlockAdded,
  onDragStart,
  onDragEnd,
  handleDrop
} = inject('editorState');

const hasFooterBlock = computed(() => {
  return props.modelValue.some(b => {
    if (b.type === 'footer') return true;
    if (b.type === 'column' && b.columns) {
      return b.columns.some(col => col.blocks?.some(nb => nb.type === 'footer'));
    }
    return false;
  });
});
</script>
