<template>
  <div
    class="eb-wrapper"
    :class="{ 'is-selected': selectedBlockId === block.id, 'eb-wrapper--nested': isNested }"
    :style="(block.styles?.marginTop || block.styles?.marginBottom) ? { margin: `${block.styles.marginTop||0}px ${block.styles.marginRight||0}px ${block.styles.marginBottom||0}px ${block.styles.marginLeft||0}px` } : {}"
    @click.stop="selectBlock(block.id)"
  >
    <!-- Block Tag (Type Label + Drag Handle) -->
    <div 
      class="eb-block-tag" 
      v-if="selectedBlockId === block.id"
      :style="isNested ? { top: '-18px', height: '18px', fontSize: '8px', padding: '0 6px', display: 'inline-flex', alignItems: 'center' } : {}"
    >
      <span class="eb-tag-text">{{ block.type.toUpperCase() }}</span>
      <span v-if="block.type !== 'footer'" style="opacity: 0.6; margin: 0 2px;">|</span>
      <div v-if="block.type !== 'footer'" class="eb-handle" style="display:inline-flex; align-items:center;" title="Drag to reorder">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" :width="isNested ? 9 : 11" :height="isNested ? 9 : 11">
          <path d="M7 2a1 1 0 11.001 2.001A1 1 0 017 2zm0 6a1 1 0 11.001 2.001A1 1 0 017 8zm0 6a1 1 0 11.001 2.001A1 1 0 017 14zm6-12a1 1 0 11.001 2.001A1 1 0 0113 2zm0 6a1 1 0 11.001 2.001A1 1 0 0113 8zm0 6a1 1 0 11.001 2.001A1 1 0 0113 14z"/>
        </svg>
      </div>
    </div>

    <!-- Actions floating panel (Move, Copy, Delete) -->
    <div 
      class="eb-actions-panel" 
      v-if="selectedBlockId === block.id"
      :style="isNested ? { right: '-36px' } : {}"
    >
      <div 
        v-if="block.type !== 'footer'" 
        class="eb-action-btn eb-handle" 
        title="Move block"
        :style="isNested ? { width: '28px', height: '28px' } : {}"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" :width="isNested ? 12 : 14" :height="isNested ? 12 : 14" class="lucide lucide-move">
          <path stroke-linecap="round" stroke-linejoin="round" d="m5 9-3 3 3 3M9 5l3-3 3 3M15 19l-3 3-3-3M19 9l3 3-3 3M2 12h20M12 2v20"/>
        </svg>
      </div>
      <div 
        v-if="block.type !== 'footer'" 
        class="eb-action-btn" 
        title="Copy block" 
        @click.stop="duplicateBlock(block.id)"
        :style="isNested ? { width: '28px', height: '28px' } : {}"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" :width="isNested ? 12 : 14" :height="isNested ? 12 : 14" class="lucide lucide-copy">
          <rect width="14" height="14" x="8" y="8" rx="2" ry="2"/>
          <path stroke-linecap="round" stroke-linejoin="round" d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>
        </svg>
      </div>
      <div 
        class="eb-action-btn" 
        title="Delete block" 
        @click.stop="deleteBlock(block.id)"
        :style="isNested ? { width: '28px', height: '28px' } : {}"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="#ef4444" :width="isNested ? 12 : 14" :height="isNested ? 12 : 14" class="lucide lucide-trash-2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2M10 11v6M14 11v6"/>
        </svg>
      </div>
    </div>

    <!-- Block content -->
    <div class="eb-content" :style="blockContentStyle(block)">
      
      <!-- ── Text Block ── -->
      <div v-if="block.type === 'text'">
        <template v-if="block.listType === 'bullet'">
          <ul 
            v-if="focusedTextId === block.id" 
            contenteditable="true" 
            :class="['eb-text', `eb-text-editable-${block.id}`]" 
            :style="textStyle(block)" 
            @blur="onListBlur(block, $event)" 
            @keydown.stop 
            :ref="el => initializeEditor(el, block)"
            style="list-style-type:disc !important; margin:0; padding-left:24px !important; cursor:text;"
          ></ul>
          <ul v-else :style="textStyle(block)" @click.stop="focusText(block.id)" style="list-style-type:disc !important; margin:0; padding-left:24px !important; cursor:text;">
            <li v-for="(line, idx) in splitLines(block.content)" :key="idx" style="margin-bottom:4px;">{{ line }}</li>
          </ul>
        </template>
        <template v-else-if="block.listType === 'numbered'">
          <ol 
            v-if="focusedTextId === block.id" 
            contenteditable="true" 
            :class="['eb-text', `eb-text-editable-${block.id}`]" 
            :style="textStyle(block)" 
            @blur="onListBlur(block, $event)" 
            @keydown.stop 
            :ref="el => initializeEditor(el, block)"
            style="list-style-type:decimal !important; margin:0; padding-left:24px !important; cursor:text;"
          ></ol>
          <ol v-else :style="textStyle(block)" @click.stop="focusText(block.id)" style="list-style-type:decimal !important; margin:0; padding-left:24px !important; cursor:text;">
            <li v-for="(line, idx) in splitLines(block.content)" :key="idx" style="margin-bottom:4px;">{{ line }}</li>
          </ol>
        </template>
        <template v-else>
          <div 
            v-if="focusedTextId === block.id" 
            contenteditable="true" 
            :class="['eb-text', `eb-text-editable-${block.id}`]" 
            :style="textStyle(block)" 
            @blur="onTextBlur(block, $event)" 
            @keydown.stop
            :ref="el => initializeEditor(el, block)"
          ></div>
          <div v-else :style="textStyle(block)" @click.stop="focusText(block.id)" style="white-space: pre-wrap; cursor: text;">{{ block.content || 'Your text here. Click to edit.' }}</div>
        </template>
      </div>

      <!-- ── Heading Block ── -->
      <div 
        v-else-if="block.type === 'heading'" 
        contenteditable="true" 
        :class="['eb-heading', `eb-heading-editable-${block.id}`]" 
        :style="headingStyle(block)" 
        @blur="updateContent(block.id, $event.target.innerText); saveHistory();" 
        @keydown.stop 
        v-text="block.content"
      ></div>

      <!-- ── Logo Block ── -->
      <div v-else-if="block.type === 'logo'" :style="{ textAlign: block.styles?.blockAlign || block.styles?.textAlign || 'center' }">
        <a v-if="block.link" :href="block.link" target="_blank" @click.prevent :style="{ display: 'inline-flex', alignItems: 'center', justifyContent: (block.styles?.blockAlign || block.styles?.textAlign || 'center') === 'left' ? 'flex-start' : ((block.styles?.blockAlign || block.styles?.textAlign || 'center') === 'right' ? 'flex-end' : 'center'), flexDirection: block.logoType === 'image-text-stacked' ? 'column' : 'row', gap: '12px', textDecoration: 'none', verticalAlign: 'middle' }">
          <img v-if="block.logoType !== 'text' && block.src" :src="block.src" :alt="block.alt" :style="{ maxWidth: '100%', width: (block.styles?.width ?? 50) + '%', display: 'inline-block', verticalAlign: 'middle' }" />
          <div v-else-if="block.logoType !== 'text'" class="eb-image-placeholder" @click.stop="selectBlock(block.id)" style="width: 120px; height: 60px; margin: 0;">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-diamond-icon lucide-diamond"><path d="M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z"/></svg>
            <span>Set logo</span>
          </div>
          <span v-if="block.logoType !== 'image'" :style="{ fontFamily: block.styles?.fontFamily || 'sans-serif', fontWeight: block.styles?.fontWeight || 'bold', fontSize: (block.styles?.fontSize || 24) + 'px', color: block.styles?.color || '#333333', lineHeight: 1, display: 'inline-block', verticalAlign: 'middle' }">{{ block.brandText || 'BrandName' }}</span>
        </a>
        <div v-else :style="{ display: 'inline-flex', alignItems: 'center', justifyContent: (block.styles?.blockAlign || block.styles?.textAlign || 'center') === 'left' ? 'flex-start' : ((block.styles?.blockAlign || block.styles?.textAlign || 'center') === 'right' ? 'flex-end' : 'center'), flexDirection: block.logoType === 'image-text-stacked' ? 'column' : 'row', gap: '12px', verticalAlign: 'middle' }">
          <img v-if="block.logoType !== 'text' && block.src" :src="block.src" :alt="block.alt" :style="{ maxWidth: '100%', width: (block.styles?.width ?? 50) + '%', display: 'inline-block', verticalAlign: 'middle' }" />
          <div v-else-if="block.logoType !== 'text'" class="eb-image-placeholder" @click.stop="selectBlock(block.id)" style="width: 120px; height: 60px; margin: 0;">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-diamond-icon lucide-diamond"><path d="M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z"/></svg>
            <span>Set logo</span>
          </div>
          <span v-if="block.logoType !== 'image'" :style="{ fontFamily: block.styles?.fontFamily || 'sans-serif', fontWeight: block.styles?.fontWeight || 'bold', fontSize: (block.styles?.fontSize || 24) + 'px', color: block.styles?.color || '#333333', lineHeight: 1, display: 'inline-block', verticalAlign: 'middle' }">{{ block.brandText || 'BrandName' }}</span>
        </div>
      </div>

      <!-- ── Image Block ── -->
      <div v-else-if="block.type === 'image'" :style="{ textAlign: block.styles?.blockAlign || block.styles?.textAlign || 'left' }">
        <img v-if="block.src" :src="block.src" :alt="block.alt" :style="{ maxWidth: '100%', width: block.styles?.width === 'auto' ? 'auto' : (block.styles?.width ?? 100) + '%', display: 'inline-block', verticalAlign: 'top' }" />
        <div v-else class="eb-image-placeholder" @click.stop="selectBlock(block.id)">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="28" height="28">
            <rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/>
          </svg>
          <span>Click to set image URL</span>
        </div>
      </div>

      <!-- ── Footer Block ── -->
      <div v-else-if="block.type === 'footer'" :style="{ textAlign: block.styles?.textAlign || 'center' }">
        <p :style="{ margin:'0 0 4px 0', fontSize: (block.styles?.fontSize || 11) + 'px', color: block.styles?.color || '#9ca3af', lineHeight: block.styles?.lineHeight || 1.8 }">{{ block.content || "You're receiving this email because you subscribed to our newsletter." }}</p>
        <p v-if="block.showUnsubscribe !== false || block.showPrivacy !== false" :style="{ margin:'0 0 4px 0', fontSize: (block.styles?.fontSize || 11) + 'px', color: '#4285f4', lineHeight: block.styles?.lineHeight || 1.8 }">
          <a v-if="block.showUnsubscribe !== false" href="#" style="color:#4285f4;text-decoration:none;" @click.prevent>Unsubscribe</a>
          <span v-if="(block.showUnsubscribe !== false) && (block.showPrivacy !== false)" style="color: #9ca3af; margin: 0 4px;">·</span>
          <a v-if="block.showPrivacy !== false" :href="block.privacyUrl || '#'" target="_blank" style="color:#4285f4;text-decoration:none;" @click.prevent="!block.privacyUrl ? $event.preventDefault() : null">Privacy Policy</a>
        </p>
        <p :style="{ margin:'0', fontSize: (block.styles?.fontSize || 11) + 'px', color: block.styles?.color || '#9ca3af', lineHeight: block.styles?.lineHeight || 1.8 }">{{ block.copyright || "© 2026 Your Company · All rights reserved" }}</p>
      </div>

      <!-- ── Button Block ── -->
      <div v-else-if="block.type === 'button'" :style="{ textAlign: block.styles?.blockAlign || block.styles?.textAlign || 'left' }">
        <span class="eb-button" :style="{ backgroundColor: block.styles?.backgroundColor, color: block.styles?.textColor, borderRadius: block.styles?.borderRadius + 'px', fontSize: block.styles?.fontSize + 'px', padding: '10px 24px', display: 'inline-block', fontWeight: 600 }">{{ block.text }}</span>
      </div>

      <!-- ── Divider Block ── -->
      <div v-else-if="block.type === 'divider'" :style="{ padding: `${block.styles?.paddingTop}px 0` }">
        <hr :style="{
          borderColor: block.styles?.borderColor || '#e5e7eb',
          borderTopWidth: (block.styles?.dividerThickness ?? 1) + 'px',
          borderStyle: block.styles?.borderStyle || 'solid',
          borderBottom: 'none',
          borderLeft: 'none',
          borderRight: 'none',
          margin: (block.styles?.blockAlign || block.styles?.textAlign || 'left') === 'center' ? '0 auto' : ((block.styles?.blockAlign || block.styles?.textAlign || 'left') === 'right' ? '0 0 0 auto' : '0 auto 0 0'),
          width: (block.styles?.width ?? 100) + '%'
        }" />
      </div>

      <!-- ── Spacer Block ── -->
      <div v-else-if="block.type === 'spacer'" :style="{ height: block.styles?.height + 'px' }"></div>

      <!-- ── Columns Block ── -->
      <div v-else-if="block.type === 'column'" class="eb-columns" :style="{ gridTemplateColumns: block.colWidths && block.colWidths.length ? block.colWidths.map(w => w + '%').join(' ') : `repeat(${block.columnCount || 2}, 1fr)` }">
        <div v-for="col in block.columns" :key="col.id" class="eb-col-slot">
          <draggable
            :model-value="col.blocks"
            @update:model-value="val => { col.blocks = val; saveHistory(); }"
            item-key="id"
            :group="{ name: 'email-blocks', pull: true, put: true }"
            :clone="makeBlock"
            :animation="150"
            ghost-class="eb-ghost"
            class="eb-col-draggable"
            @add="onColumnBlockAdded(col)"
            @start="onDragStart"
            @end="onDragEnd"
          >
            <template #item="{ element: nb }">
              <EmailBlock :block="nb" :is-nested="true" />
            </template>
          </draggable>
          <div v-if="!col.blocks.length" class="eb-col-drop-hint">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M12 5v14M5 12h14"/></svg>
            Drop here
          </div>
        </div>
      </div>

      <!-- ── Social Block ── -->
      <div v-else-if="block.type === 'social'" class="eb-social" :style="{ justifyContent: block.styles?.textAlign === 'center' ? 'center' : block.styles?.textAlign === 'right' ? 'flex-end' : 'flex-start', gap: (block.spaceBetween || 8) + 'px' }">
        <a v-for="link in block.links" :key="link.id || link.platform" href="#" class="eb-social-icon-wrap" :style="socialIconStyle(block, link)">
          <span v-html="socialIconSvg(block, link)" style="display:flex;align-items:center;justify-content:center;width:100%;height:100%"></span>
        </a>
      </div>

      <!-- ── HTML Block ── -->
      <div v-else-if="block.type === 'html'" class="eb-html-placeholder">
        <span>HTML Block</span>
        <code class="eb-html-code">{{ block.html || '<!-- HTML here -->' }}</code>
      </div>

      <!-- ── Video Block ── -->
      <div v-else-if="block.type === 'video'">
        <div v-if="block.url && isThirdPartyUrl(block.url)" class="eb-video-wrapper">
          <iframe :src="getVideoEmbedUrl(block.url)" frameborder="0" allowfullscreen style="width:100%;aspect-ratio:16/9;display:block;border:0"></iframe>
        </div>
        <video v-else-if="block.url" :src="block.url" controls style="width:100%;display:block;border-radius:4px"></video>
        <div v-else class="eb-image-placeholder" @click.stop="selectBlock(block.id)">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="28" height="28"><rect x="3" y="3" width="18" height="18" rx="2"/><path fill="currentColor" stroke="none" d="M9.5 8l7 4-7 4V8z"/></svg>
          <span>Click to add video</span>
        </div>
      </div>

      <!-- ── Default Fallback ── -->
      <div v-else class="eb-placeholder-block">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="20" height="20">
          <rect x="3" y="3" width="18" height="18" rx="2"/>
        </svg>
        <span>{{ blockTypeLabel(block.type) }} block</span>
      </div>

    </div>
  </div>
</template>

<script setup>
import { inject } from 'vue';
import draggable from 'vuedraggable';
import EmailBlock from './EmailBlock.vue';
import {
  splitLines,
  isThirdPartyUrl,
  getVideoEmbedUrl,
  blockContentStyle,
  textStyle,
  headingStyle,
  blockTypeLabel,
  socialIconStyle,
  socialIconSvg
} from './editorUtils';

const props = defineProps({
  block: {
    type: Object,
    required: true
  },
  isNested: {
    type: Boolean,
    default: false
  }
});

// Inject shared state and logic from EmailEditor wrapper
const {
  selectedBlockId,
  focusedTextId,
  selectBlock,
  duplicateBlock,
  deleteBlock,
  focusText,
  onTextBlur,
  onListBlur,
  onListInput,
  updateContent,
  saveHistory,
  makeBlock,
  onColumnBlockAdded,
  onDragStart,
  onDragEnd,
  getListHtml
} = inject('editorState');

function initializeEditor(el, block) {
  if (el && !el.__initialized) {
    el.__initialized = true;
    if (block.listType === 'bullet' || block.listType === 'numbered') {
      el.innerHTML = getListHtml(block.content);
    } else {
      el.innerText = block.content || '';
    }
  }
}
</script>
