<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">{{ blockTypeLabel(block.type).toUpperCase() }}</span>
      <span v-if="block.type !== 'submit-button'" style="opacity: 0.6; margin: 0 2px;">|</span>
      <div v-if="block.type !== 'submit-button'" 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 -->
    <div class="eb-actions-panel" v-if="selectedBlockId === block.id" :style="isNested ? { right: '-36px' } : {}">
      <div v-if="block.type !== 'submit-button'" 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"><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 !== 'submit-button'" 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"><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"><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'" :style="textStyle(block)" style="white-space: pre-wrap;">{{ block.content }}</div>

      <!-- ── Heading Block ── -->
      <div v-else-if="block.type === 'heading'" :style="headingStyle(block)">{{ block.content }}</div>

      <!-- ── Logo Block ── -->
      <div v-else-if="block.type === 'logo'" :style="{ textAlign: block.styles?.blockAlign || 'center' }">
        <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' }" />
        <div v-else-if="block.logoType !== 'text'" class="eb-image-placeholder" @click.stop="selectBlock(block.id)" style="width: 120px; height: 60px; margin: 0 auto;">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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 || 22) + 'px', color: block.styles?.color || '#111827' }">{{ block.brandText || 'Your Brand' }}</span>
      </div>

      <!-- ── Image Block ── -->
      <div v-else-if="block.type === 'image'" :style="{ textAlign: block.styles?.blockAlign || block.styles?.textAlign || 'center' }">
        <img v-if="block.src" :src="block.src" :alt="block.alt" :style="{ maxWidth: '100%', width: (block.styles?.width ?? 100) + '%', display: 'inline-block' }" />
        <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>

      <!-- ── Link Button Block (decorative, not submit) ── -->
      <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 ?? 6) + 'px', fontSize: (block.styles?.fontSize ?? 15) + 'px', padding: '10px 24px', display: 'inline-block', fontWeight: 600 }">{{ block.text }}</span>
      </div>

      <!-- ── Submit Button Block (the real submit control) ── -->
      <div v-else-if="block.type === 'submit-button'" :style="{ textAlign: block.styles?.blockAlign || 'center' }">
        <span class="eb-button" :style="{ backgroundColor: block.styles?.backgroundColor || '#4285F4', color: block.styles?.textColor || '#fff', borderRadius: (block.styles?.borderRadius ?? 8) + 'px', fontSize: (block.styles?.fontSize ?? 15) + 'px', padding: '12px 24px', display: 'block', width: '100%', boxSizing: 'border-box', textAlign: 'center', fontWeight: 600 }">{{ block.text || 'Subscribe' }}</span>
      </div>

      <!-- ── Divider Block ── -->
      <div v-else-if="block.type === 'divider'">
        <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: 0, 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: 'form-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 }">
              <FormBlock :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>

      <!-- ── 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>

      <!-- ══════════════ Form Field Blocks ══════════════ -->
      <div v-else-if="isField(block.type)">
        <div v-if="block.type === 'field-hidden'" class="fb-field-label-row">
          <span class="fb-field-label">🔒 Hidden field: {{ block.label }}</span>
        </div>

        <div v-else-if="block.type === 'field-consent'">
          <label class="fb-checkbox-item" style="cursor:default">
            <div class="fb-checkbox-box"></div>
            <span>{{ block.label }}<span v-if="block.required" class="fb-field-required">*</span></span>
          </label>
          <div v-if="block.help" class="fb-field-help">{{ block.help }}</div>
        </div>

        <template v-else>
          <label class="fb-field-label" :style="{ color: block.styles?.color, display: 'block', marginBottom: '6px' }">
            {{ block.label }}<span v-if="block.required" class="fb-field-required">*</span>
          </label>

          <textarea v-if="block.type === 'field-textarea'" class="fb-textarea-preview" :style="fieldInputStyle(block)" :placeholder="block.placeholder" readonly></textarea>

          <div v-else-if="block.type === 'field-name'" style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
            <input class="fb-input-preview" :style="fieldInputStyle(block)" placeholder="First name" readonly>
            <input class="fb-input-preview" :style="fieldInputStyle(block)" placeholder="Last name" readonly>
          </div>

          <div v-else-if="block.type === 'field-dropdown'" class="fb-select-preview" :style="fieldInputStyle(block)">
            {{ block.placeholder || 'Select an option' }}
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /></svg>
          </div>

          <div v-else-if="block.type === 'field-radio' && block.displayAs === 'buttons'" style="display:flex;flex-direction:column;gap:8px">
            <div v-for="(opt, i) in block.options" :key="i" style="padding:12px 16px;border-radius:999px;background:var(--primary-preview,#374151);color:#fff;text-align:center;font-weight:600;font-size:13px" :style="{ background: block.styles?.color || '#374151' }">{{ opt }}</div>
          </div>
          <div v-else-if="block.type === 'field-radio'" class="fb-radio-group">
            <div class="fb-radio-item" v-for="(opt, i) in block.options" :key="i"><div class="fb-radio-dot"></div>{{ opt }}</div>
          </div>

          <div v-else-if="block.type === 'field-checkbox'" class="fb-checkbox-group">
            <div class="fb-checkbox-item" v-for="(opt, i) in block.options" :key="i"><div class="fb-checkbox-box"></div>{{ opt }}</div>
          </div>

          <div v-else-if="block.type === 'field-rating'" class="fb-rating-row">★★★☆☆</div>

          <input v-else :type="fieldInputType(block.type)" class="fb-input-preview" :style="fieldInputStyle(block)" :placeholder="block.placeholder" readonly>

          <div v-if="block.help" class="fb-field-help">{{ block.help }}</div>
        </template>
      </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 FormBlock from './FormBlock.vue';
import {
  blockContentStyle,
  textStyle,
  headingStyle,
  blockTypeLabel,
  fieldInputStyle,
  isFieldBlock,
} from './formEditorUtils';

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

const {
  selectedBlockId,
  selectBlock,
  duplicateBlock,
  deleteBlock,
  saveHistory,
  makeBlock,
  onColumnBlockAdded,
  onDragStart,
  onDragEnd,
} = inject('formEditorState');

function isField(type) {
  return isFieldBlock(type);
}

function fieldInputType(type) {
  return {
    'field-email': 'email',
    'field-phone': 'tel',
    'field-website': 'url',
    'field-number': 'number',
    'field-date': 'date',
  }[type] || 'text';
}
</script>
