<template>
  <div style="display:flex; flex-direction:column; height:100%; overflow:hidden;">
    <!-- Tabs Header -->
    <div class="cw-lp-tabs">
      <button 
        type="button" 
        class="cw-lp-tab" 
        :class="{ 'is-active': activeTab === 'blocks' }" 
        @click="activeTab = 'blocks'"
      >
        Blocks
      </button>
      <button 
        type="button" 
        class="cw-lp-tab" 
        :class="{ 'is-active': activeTab === 'sections' }" 
        @click="activeTab = 'sections'"
      >
        Sections
      </button>
      <button 
        type="button" 
        class="cw-lp-tab" 
        :class="{ 'is-active': activeTab === 'templates' }" 
        @click="activeTab = 'templates'"
      >
        Templates
      </button>
      <button 
        type="button" 
        class="cw-lp-tab" 
        :class="{ 'is-active': activeTab === 'design' }" 
        @click="activeTab = 'design'"
      >
        Design
      </button>
    </div>

    <!-- TAB 1: BLOCKS -->
    <div v-show="activeTab === 'blocks'" class="cw-lp-content" style="flex: 1; overflow-y: auto; overflow-x: hidden; padding: 14px 12px;">
      <draggable
        :list="PALETTE_ITEMS"
        :group="{ name: 'email-blocks', pull: 'clone', put: false }"
        :clone="makeBlock"
        item-key="type"
        class="cw-block-grid"
        @start="onDragStart"
        @end="onDragEnd"
      >
        <template #item="{ element: item }">
          <div 
            class="cw-block-card"
            :class="{ 'is-disabled': item.type === 'footer' && hasFooterBlock }"
            :style="item.type === 'footer' && hasFooterBlock ? { opacity: 0.4, pointerEvents: 'none' } : {}"
          >
            <div class="cw-block-card-dots">⠿</div>
            <div class="cw-block-card-icon" v-html="item.icon"></div>
            <div class="cw-block-card-label">{{ item.label }}</div>
          </div>
        </template>
      </draggable>
    </div>

    <!-- TAB 2: SECTIONS -->
    <div v-show="activeTab === 'sections'" class="cw-lp-content cw-sec-panel" style="flex: 1; overflow-y: auto; overflow-x: hidden; padding: 0;">
      <!-- Categories scroll bar -->
      <div class="cw-sec-cats">
        <button
          v-for="cat in SECTION_CATEGORIES"
          :key="cat"
          type="button"
          class="cw-sec-cat-btn"
          :class="{ 'is-active': sectionCategory === cat }"
          @click="sectionCategory = cat"
        >
          {{ cat }}
        </button>
      </div>

      <!-- Sections Grid -->
      <div class="cw-sec-grid">
        <div 
          v-for="sec in filteredSections" 
          :key="sec.id" 
          class="cw-sec-card" 
          @click="insertSection(sec)"
          :title="`Click to add ${sec.label}`"
        >
          <div class="cw-sec-thumb" v-html="sec.thumb"></div>
          <div class="cw-sec-card-lbl">{{ sec.label }}</div>
        </div>
      </div>
    </div>

    <!-- TAB 3: TEMPLATES -->
    <div v-show="activeTab === 'templates'" class="cw-lp-content cw-templates-panel" style="flex: 1; overflow-y: auto; overflow-x: hidden; padding: 14px 12px;">
      <div v-if="templates.length === 0" style="text-align:center; padding: 20px; color:#9ca3af; font-size:13px;">
        No templates found.
      </div>
      <div v-else class="cw-templates-list" style="display:flex; flex-direction:column; gap:8px;">
        <div 
          v-for="tpl in templates" 
          :key="tpl.id" 
          class="cw-template-item"
          @click="importTemplate(tpl)"
        >
          <!-- Mini Layout Preview -->
          <div class="cw-template-preview">
            <div 
              v-for="b in (tpl.email_body || [])" 
              :key="b.id" 
              class="cw-mini-block"
              :style="getMiniBlockStyle(b)"
            >
              <!-- Heading -->
              <div v-if="b.type === 'heading'" class="cw-mini-heading" :style="{ width: '70%', background: '#4b5563', height: '4px', borderRadius: '1px', margin: (b.styles?.textAlign || 'center') === 'left' ? '0' : ((b.styles?.textAlign || 'center') === 'right' ? '0 0 0 auto' : '0 auto') }"></div>
              
              <!-- Text -->
              <div v-else-if="b.type === 'text'" class="cw-mini-text-lines" style="display:flex; flex-direction:column; gap:2px; width:90%; margin:0 auto;">
                <div style="height:2px; background:#9ca3af; border-radius:1px; width:100%;"></div>
                <div style="height:2px; background:#9ca3af; border-radius:1px; width:80%;"></div>
              </div>
              
              <!-- Logo -->
              <div v-else-if="b.type === 'logo'" class="cw-mini-logo" style="display:flex; align-items:center; justify-content:center; gap:3px;">
                <div style="width:4px; height:4px; background:#6366f1; border-radius:1px;"></div>
                <div style="height:3px; background:#6366f1; border-radius:1px; width:12px;"></div>
              </div>
              
              <!-- Button -->
              <div v-else-if="b.type === 'button'" class="cw-mini-button" :style="{ height: '8px', background: b.styles?.backgroundColor || '#6366f1', borderRadius: '2px', width: '40%', margin: (b.styles?.blockAlign || 'center') === 'left' ? '0' : ((b.styles?.blockAlign || 'center') === 'right' ? '0 0 0 auto' : '0 auto') }"></div>
              
              <!-- Divider -->
              <div v-else-if="b.type === 'divider'" class="cw-mini-divider" style="height:1px; background:#e5e7eb; width:100%;"></div>
              
              <!-- Spacer -->
              <div v-else-if="b.type === 'spacer'" :style="{ height: Math.min((b.styles?.height || 20) / 4, 8) + 'px' }"></div>
              
              <!-- Social -->
              <div v-else-if="b.type === 'social'" class="cw-mini-social" style="display:flex; justify-content:center; gap:3px;">
                <div v-for="l in (b.links || [])" :key="l.id || l.platform" style="width:6px; height:6px; background:#9ca3af; border-radius:50%;"></div>
              </div>
              
              <!-- Image -->
              <div v-else-if="b.type === 'image'" class="cw-mini-image" style="height:22px; background:#e5e7eb; border-radius:3px; display:flex; align-items:center; justify-content:center; color:#9ca3af;">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" width="8" height="8">
                  <rect width="18" height="18" x="3" y="3" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.08-3.08a2 2 0 0 0-2.82 0L6 21"/>
                </svg>
              </div>
              
              <!-- Footer -->
              <div v-else-if="b.type === 'footer'" class="cw-mini-footer" style="display:flex; flex-direction:column; gap:2px; width:70%; margin:0 auto;">
                <div style="height:2px; background:#d1d5db; border-radius:1px; width:100%;"></div>
                <div style="height:2px; background:#d1d5db; border-radius:1px; width:60%; margin:0 auto;"></div>
              </div>
              
              <!-- Column -->
              <div v-else-if="b.type === 'column'" class="cw-mini-column" style="display:flex; gap:4px; width:100%;">
                <div v-for="col in (b.columns || [])" :key="col.id" style="flex:1; background:#f9fafb; border:0.5px dashed #cbd5e1; border-radius:2px; padding:2px; display:flex; flex-direction:column; gap:1.5px; min-height:10px;">
                  <div v-for="cb in (col.blocks || [])" :key="cb.id" style="height:2px; background:#cbd5e1; border-radius:0.5px;"></div>
                </div>
              </div>
            </div>
          </div>
          
          <div style="font-weight:600; font-size:13px; color:#374151; margin-top:4px;">{{ tpl.title }}</div>
          <div v-if="tpl.email_subject" style="font-size:11px; color:#9ca3af; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:2px;">
            Subject: {{ tpl.email_subject }}
          </div>
        </div>
      </div>
    </div>

    <!-- TAB 4: DESIGN / BODY SETTINGS -->
    <div v-show="activeTab === 'design'" class="cw-lp-content cw-design-panel" style="flex: 1; overflow-y: auto; overflow-x: hidden; padding: 14px 12px;">
      <div v-if="bodyBlock" class="cw-design-settings">
        <!-- Outer Background Group -->
        <div class="cw-design-section" style="margin-bottom: 20px;">
          <div style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; margin-bottom: 10px;">Outer Page Background</div>
          
          <div style="display: flex; flex-direction: column; gap: 12px;">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <span style="font-size: 13px; color: #374151;">Color</span>
              <CwColorPicker v-model="bodyBlock.bgColor" />
            </div>
          </div>
        </div>

        <hr style="border: 0; border-top: 1px solid #e5e7eb; margin: 20px 0;" />

        <!-- Inner Content Background Group -->
        <div class="cw-design-section" style="margin-bottom: 20px;">
          <div style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: #6b7280; letter-spacing: 0.05em; margin-bottom: 10px;">Email Container (Inner Body)</div>
          
          <div style="display: flex; flex-direction: column; gap: 12px;">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <span style="font-size: 13px; color: #374151;">Color</span>
              <CwColorPicker v-model="bodyBlock.contentBgColor" />
            </div>

            <!-- Email Container Width -->
            <div>
              <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
                <span style="font-size: 13px; color: #374151;">Width</span>
                <span style="font-size: 12px; font-weight: 600; color: #4f46e5;">{{ bodyBlock.contentWidth || 600 }}px</span>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <input 
                  type="range" 
                  min="480" 
                  max="800" 
                  step="10" 
                  v-model.number="bodyBlock.contentWidth" 
                  style="flex: 1; height: 6px; border-radius: 3px; accent-color: #6366f1;"
                  @input="saveHistory"
                />
              </div>
            </div>

            <!-- Pattern selection -->
            <div>
              <span style="font-size: 13px; color: #374151; display: block; margin-bottom: 6px;">Background Pattern</span>
              <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px;">
                <button 
                  v-for="p in PATTERNS" 
                  :key="p.id" 
                  type="button" 
                  @click="setPattern(p.id)"
                  style="height: 38px; border: 1px solid #e5e7eb; border-radius: 6px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 500; transition: all 0.2s;"
                  :style="bodyBlock.bgPattern === p.id && !bodyBlock.bgImage ? { borderColor: '#6366f1', background: '#eef2ff', color: '#4338ca' } : { background: '#ffffff', color: '#4b5563' }"
                >
                  {{ p.label }}
                </button>
              </div>
            </div>

            <!-- Custom background image upload -->
            <div>
              <span style="font-size: 13px; color: #374151; display: block; margin-bottom: 6px;">Background Image</span>
              
              <div style="display: flex; gap: 6px; align-items: center;">
                <input 
                  type="text" 
                  class="cw-field-input" 
                  v-model="bodyBlock.bgImage" 
                  placeholder="https://image-url.com/..." 
                  style="flex: 1; height: 32px; font-size: 12px; border: 1px solid #d1d5db; border-radius: 6px; padding: 0 8px;"
                  @change="saveHistory"
                />
                <button 
                  type="button" 
                  class="btn btn-outline btn-xs" 
                  @click="openLibrary(bodyBlock, 'bgImage')"
                  style="padding: 0 10px; height: 32px; font-size: 12px; display: inline-flex; align-items: center; justify-content: center;"
                >
                  Browse
                </button>
              </div>
              <div v-if="bodyBlock.bgImage" style="display: flex; gap: 8px; margin-top: 6px; align-items: center;">
                <span style="font-size: 11px; color: #10b981; display: flex; align-items: center; gap: 4px;">
                  ✓ Image Active
                </span>
                <button 
                  type="button" 
                  @click="bodyBlock.bgImage = ''; saveHistory()" 
                  style="font-size: 11px; color: #ef4444; background: none; border: none; cursor: pointer; padding: 0;"
                >
                  Remove
                </button>
              </div>
            </div>

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

    <!-- Media Library Overlay Modal -->
    <MediaLibraryModal
      :open="libraryOpen"
      type="image"
      collection="library"
      @close="libraryOpen = false"
      @select="onLibrarySelect"
    />
  </div>
</template>

<script setup>
import { ref, computed, inject, nextTick, onMounted } from 'vue';
import draggable from 'vuedraggable';
import CwColorPicker from '@/Components/CwColorPicker.vue';
import MediaLibraryModal from '@/Components/MediaLibrary/MediaLibraryModal.vue';
import {
  PALETTE_ITEMS,
  SECTION_TEMPLATES,
  makeBlock,
  makeBlockFromDef
} from './editorUtils';

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

const libraryOpen = ref(false);
const libraryTarget = ref(null);

const bodyBlock = computed(() => {
  return blocks.value.find(b => b.type === 'body');
});

const PATTERNS = [
  { id: '', label: 'None' },
  { id: 'dots', label: 'Dots' },
  { id: 'grid', label: 'Grid' },
  { id: 'stripes', label: 'Stripes' },
  { id: 'abstract', label: 'Abstract' },
];

function setPattern(patternId) {
  if (bodyBlock.value) {
    bodyBlock.value.bgPattern = patternId;
    bodyBlock.value.bgImage = ''; // Clear image when pattern is chosen
    saveHistory();
  }
}

function openLibrary(block, field) {
  libraryTarget.value = { block, field };
  libraryOpen.value = true;
}

function onLibrarySelect(item) {
  if (libraryTarget.value) {
    libraryTarget.value.block[libraryTarget.value.field] = item.url;
    saveHistory();
  }
  libraryOpen.value = false;
}

const activeTab = ref('blocks');
const sectionCategory = ref('All');
const SECTION_CATEGORIES = ['All', 'General', 'E-commerce', 'SaaS', 'Events', 'Services', 'Media'];

const hasFooterBlock = computed(() => {
  return blocks.value.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;
  });
});

const filteredSections = computed(() =>
  sectionCategory.value === 'All'
    ? SECTION_TEMPLATES
    : SECTION_TEMPLATES.filter(s => s.category === sectionCategory.value)
);

function insertSection(template) {
  const newBlocks = template.blocks.map(makeBlockFromDef);
  blocks.value.push(...newBlocks);
  selectedBlockId.value = newBlocks[0]?.id ?? null;
  nextTick(() => {
    const canvas = document.querySelector('.cw-canvas-wrap');
    if (canvas) canvas.scrollTop = canvas.scrollHeight;
  });
}

const templates = ref([]);

onMounted(async () => {
  try {
    const res = await window.axios.get(route('templates.api'));
    templates.value = res.data;
  } catch (e) {
    console.error(e);
  }
});

function importTemplate(template) {
  if (confirm(`Are you sure you want to replace the current layout with the template "${template.title}"?`)) {
    const newBlocks = JSON.parse(JSON.stringify(template.email_body || []));
    blocks.value = newBlocks;
    selectedBlockId.value = null;
    saveHistory();
  }
}

function getMiniBlockStyle(block) {
  const style = {};
  if (block.type === 'spacer') return style;
  
  const pt = Math.min((block.styles?.paddingTop ?? 16) / 6, 6);
  const pb = Math.min((block.styles?.paddingBottom ?? 16) / 6, 6);
  const pl = Math.min((block.styles?.paddingLeft ?? 24) / 8, 8);
  const pr = Math.min((block.styles?.paddingRight ?? 24) / 8, 8);
  style.padding = `${pt}px ${pr}px ${pb}px ${pl}px`;
  
  if (block.styles?.bgColor) {
    style.backgroundColor = block.styles.bgColor;
  } else if (block.type !== 'column' && block.type !== 'social' && block.type !== 'divider') {
    style.backgroundColor = '#ffffff';
  }
  
  return style;
}
</script>

<style scoped>
.cw-lp-tabs {
    display: flex;
    border-bottom: 2px solid #e5e7eb;
    flex-shrink: 0;
}
.cw-lp-tab {
    flex: 1;
    padding: 12px 4px;
    font-size: 13px;
    font-weight: 500;
    color: #6b7280;
    background: none;
    border: none;
    border-bottom: 2px solid transparent;
    margin-bottom: -2px;
    cursor: pointer;
    transition: color 0.15s, border-color 0.15s;
}
.cw-lp-tab.is-active {
    color: var(--active-text);
    border-bottom-color: var(--active-text);
    font-weight: 600;
}

.cw-block-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}
.cw-block-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    padding: 10px 6px 10px;
    background: var(--bg-surface);
    border: 1.5px solid var(--border-color);
    border-radius: 10px;
    cursor: grab;
    user-select: none;
    transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;
    position: relative;
    width: calc(33.333% - 6px);
    box-sizing: border-box;
}
.cw-block-card:hover {
    border-color: #10b981;
    background: #f0fdf4;
    box-shadow: 0 2px 8px rgba(16,185,129,0.10);
}
.cw-block-card:active {
    cursor: grabbing;
}
.cw-block-card-dots {
    position: absolute;
    top: 4px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 11px;
    color: #d1d5db;
    letter-spacing: 1px;
    line-height: 1;
}
.cw-block-card-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #10b981;
    margin-top: 8px;
}
.cw-block-card-label {
    font-size: 11px;
    font-weight: 500;
    color: var(--text-primary);
    text-align: center;
    line-height: 1.2;
}

.cw-template-item {
    display: flex;
    flex-direction: column;
    padding: 12px;
    border: 1.5px solid #e5e7eb;
    border-radius: 8px;
    cursor: pointer;
    background: #fff;
    transition: border-color 0.15s, background 0.15s;
}
.cw-template-item:hover {
    border-color: #6366f1;
    background: #f5f7ff;
}

.cw-template-preview {
    background: #f4f4f5;
    border-radius: 6px;
    padding: 8px;
    display: flex;
    flex-direction: column;
    gap: 3px;
    max-height: 140px;
    overflow-y: auto;
    border: 1.5px solid #e5e7eb;
    pointer-events: none;
    box-sizing: border-box;
    width: 100%;
    margin-bottom: 8px;
}
.cw-mini-block {
    box-sizing: border-box;
    width: 100%;
}
</style>
