<template>
  <Teleport to="body">
    <div v-if="open" class="modal-overlay is-open" @click.self="$emit('close')">
      <div class="aft-modal">

        <!-- Modal Header -->
        <div class="aft-modal__header">
          <div>
            <h3 class="aft-modal__title">Pre-Built Email Templates</h3>
            <p class="aft-modal__sub">Select a pre-designed email layout or choose from your custom templates.</p>
          </div>
          <button type="button" class="modal-close" @click="$emit('close')">✕</button>
        </div>

        <!-- Modal Body -->
        <div class="aft-modal__body">

          <!-- Left Sidebar -->
          <div class="aft-sidebar">
            <!-- Category Filter Tabs -->
            <div class="aft-categories" :class="{ 'is-mobile-open': catMobileOpen }">
              <!-- Mobile Category Toggle Button -->
              <button type="button" class="aft-cat-mobile-toggle" @click="catMobileOpen = !catMobileOpen">
                <div class="aft-cat-mobile-toggle-left">
                  <span class="aft-cat-icon" v-html="currentCatObj.icon"></span>
                  <span class="aft-cat-mobile-label">{{ currentCatObj.label }}</span>
                  <span class="aft-cat-count">{{ getCategoryCount(currentCatObj.id) }}</span>
                </div>
                <div class="aft-cat-mobile-toggle-right">
                  <span class="aft-cat-mobile-hint">{{ catMobileOpen ? 'Close' : 'Categories' }}</span>
                  <svg class="aft-cat-chevron" :class="{ 'is-open': catMobileOpen }" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                  </svg>
                </div>
              </button>

              <!-- Category list -->
              <div class="aft-cat-list" :class="{ 'is-open': catMobileOpen }">
                <button
                  v-for="cat in categories"
                  :key="cat.id"
                  class="aft-cat-btn"
                  :class="{ 'is-active': activeCategory === cat.id }"
                  @click="activeCategory = cat.id; selectedTemplate = null; catMobileOpen = false"
                >
                  <span class="aft-cat-icon" v-html="cat.icon"></span>
                  <span class="aft-cat-label-text">{{ cat.label }}</span>
                  <span class="aft-cat-count">{{ getCategoryCount(cat.id) }}</span>
                </button>
              </div>
            </div>

            <!-- Template List Grid -->
            <div class="aft-list">
              <!-- Build from Scratch Card -->
              <div
                class="aft-card aft-card--scratch"
                :class="{ 'is-active': selectedTemplate === 'scratch' }"
                @click="selectedTemplate = 'scratch'"
              >
                <div class="aft-card__icon aft-card__icon--scratch">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/>
                  </svg>
                </div>
                <div class="aft-card__body">
                  <div class="aft-card__name">Build from Scratch</div>
                  <div class="aft-card__desc">Start with a blank canvas and design custom blocks</div>
                </div>
              </div>

              <!-- Template Cards -->
              <div
                v-for="tpl in filteredTemplates"
                :key="(tpl.is_custom ? 'custom-' : 'builtin-') + tpl.id"
                class="aft-card"
                :class="{ 'is-active': selectedTemplate?.id === tpl.id && selectedTemplate?.is_custom === tpl.is_custom }"
                @click="selectedTemplate = tpl"
              >
                <div class="aft-card__icon" :style="{ background: getIconMeta(tpl).bg, color: getIconMeta(tpl).color }">
                  <span v-html="getIconMeta(tpl).icon"></span>
                </div>
                <div class="aft-card__body">
                  <div class="aft-card__name">{{ tpl.title }}</div>
                  <div class="aft-card__desc">{{ tpl.email_subject || (tpl.is_custom ? 'Custom Template' : 'Business Scenario Template') }}</div>
                </div>
                <span v-if="tpl.is_custom" class="aft-card__badge aft-card__badge--custom">Custom</span>
                <span v-else-if="tpl.id <= 3" class="aft-card__badge">Popular</span>
              </div>
            </div>
          </div>

          <!-- Right Preview Panel -->
          <div class="aft-preview">
            <div class="aft-preview__scroll">

              <!-- Scratch Preview -->
              <template v-if="selectedTemplate === 'scratch'">
                <div class="aft-preview__empty">
                  <div class="aft-preview__scratch-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" width="40" height="40">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                    </svg>
                  </div>
                  <h4>Build your own email template</h4>
                  <p>Design a custom template using drag-and-drop elements and full block customization.</p>
                </div>
              </template>

              <!-- Template Preview -->
              <template v-else-if="selectedTemplate">
                <div class="aft-preview__header">
                  <div class="aft-preview__tpl-icon" :style="{ background: getIconMeta(selectedTemplate).bg, color: getIconMeta(selectedTemplate).color }">
                    <span v-html="getIconMeta(selectedTemplate).icon"></span>
                  </div>
                  <div>
                    <h4 class="aft-preview__tpl-name">{{ selectedTemplate.title }}</h4>
                    <span class="aft-preview__tpl-cat">{{ getIconMeta(selectedTemplate).categoryLabel }}</span>
                  </div>
                </div>

                <div class="aft-preview__meta">
                  <div class="aft-preview__meta-item" v-if="selectedTemplate.email_subject">
                    <strong style="color:var(--text-primary)">Subject:</strong> {{ selectedTemplate.email_subject }}
                  </div>
                  <div class="aft-preview__meta-item" v-if="selectedTemplate.email_pre_header">
                    <strong style="color:var(--text-primary)">Pre-header:</strong> {{ selectedTemplate.email_pre_header }}
                  </div>
                </div>

                <!-- Rendered Blocks Preview -->
                <div class="gallery-preview-frame">
                  <div v-html="renderBlocksHtml(selectedTemplate.email_body)" class="gallery-rendered-body"></div>
                </div>
              </template>

              <!-- Default Empty State -->
              <template v-else>
                <div class="aft-preview__empty">
                  <div class="aft-preview__empty-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" width="40" height="40">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zm-7.518-.267A8.25 8.25 0 1120.25 10.5M8.288 14.212A5.25 5.25 0 1117.25 10.5"/>
                    </svg>
                  </div>
                  <h4>Select a template</h4>
                  <p>Click any pre-built or custom template on the left to preview its content and layout before using.</p>
                </div>
              </template>

            </div>

            <!-- Footer Action Button -->
            <div class="aft-preview__footer" v-if="selectedTemplate">
              <div class="aft-preview__footer-meta" v-if="selectedTemplate !== 'scratch'">
                <span>{{ (selectedTemplate.email_body || []).length }} content blocks</span>
                <span>·</span>
                <span>{{ selectedTemplate.is_custom ? 'Custom User Template' : 'Business Scenario Ready' }}</span>
              </div>
              <button class="btn btn-primary aft-import-btn" @click="confirmSelect">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="15" height="15">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                </svg>
                {{ selectedTemplate === 'scratch' ? 'Start building' : 'Use this template' }}
              </button>
            </div>
          </div>

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

<script setup>
import { ref, computed, watch } from 'vue';
import { getSocialPlatform, socialIconStyle, socialIconSvg } from '@/Components/EmailEditor/editorUtils';

const props = defineProps({
  open: { type: Boolean, default: false },
  builtinTemplates: { type: Array, default: () => [] },
  customTemplates: { type: Array, default: () => [] },
});

const emit = defineEmits(['close', 'select']);

const activeCategory = ref('all');
const selectedTemplate = ref('scratch');
const catMobileOpen = ref(false);

watch(() => props.open, (isOpen) => {
  if (isOpen && !selectedTemplate.value) {
    selectedTemplate.value = 'scratch';
  }
}, { immediate: true });

const currentCatObj = computed(() => {
  return categories.find(c => c.id === activeCategory.value) || categories[0];
});

const categories = [
  { id: 'all', label: 'All Templates', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z"/></svg>` },
  { id: 'custom', label: 'Custom Templates', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z"/></svg>` },
  { id: 'onboarding', label: 'Onboarding & Welcome', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/></svg>` },
  { id: 'sales', label: 'Sales & Promotions', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 10-7.5 0v4.5m11.356-1.993l1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 01-1.12-1.243l1.264-12A1.125 1.125 0 015.513 7.5h12.974c.576 0 1.059.435 1.119 1.007z"/></svg>` },
  { id: 'newsletter', label: 'Newsletters & Updates', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.75m-3.75 3h3.75m-3.75 3h3.75m-3.75 3h3.75M3 21h18M3 3h18v18H3V3z"/></svg>` },
  { id: 'feedback', label: 'Feedback & Security', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"/></svg>` },
  { id: 'events', label: 'Events & Resources', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="15" height="15"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/></svg>` },
];

const normalizedCustomTemplates = computed(() => {
  return (props.customTemplates || []).map(t => ({
    ...t,
    is_custom: true
  }));
});

const normalizedBuiltinTemplates = computed(() => {
  return (props.builtinTemplates || []).map(t => ({
    ...t,
    is_custom: false
  }));
});

const allTemplatesList = computed(() => {
  return [...normalizedCustomTemplates.value, ...normalizedBuiltinTemplates.value];
});

const filteredTemplates = computed(() => {
  if (activeCategory.value === 'all') return allTemplatesList.value;
  if (activeCategory.value === 'custom') return normalizedCustomTemplates.value;
  return normalizedBuiltinTemplates.value.filter(t => {
    const cat = getIconMeta(t).category;
    return cat === activeCategory.value;
  });
});

function getCategoryCount(catId) {
  if (catId === 'all') return allTemplatesList.value.length;
  if (catId === 'custom') return normalizedCustomTemplates.value.length;
  return normalizedBuiltinTemplates.value.filter(t => getIconMeta(t).category === catId).length;
}

function getIconMeta(tpl) {
  if (tpl.is_custom) {
    return {
      category: 'custom',
      categoryLabel: 'Custom Template',
      bg: '#eff6ff',
      color: '#2563eb',
      icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z"/></svg>`
    };
  }
  const title = (tpl.title || '').toLowerCase();
  if (title.includes('welcome') || title.includes('onboarding') || title.includes('trial') || title.includes('getting started')) {
    return {
      category: 'onboarding',
      categoryLabel: 'Onboarding & Welcome',
      bg: '#e8f0fe',
      color: '#1a73e8',
      icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/></svg>`
    };
  }
  if (title.includes('sale') || title.includes('offer') || title.includes('cart') || title.includes('friday') || title.includes('receipt') || title.includes('order') || title.includes('subscription') || title.includes('renewal') || title.includes('vip') || title.includes('loyalty')) {
    return {
      category: 'sales',
      categoryLabel: 'Sales & Promotions',
      bg: '#fce8e6',
      color: '#ea4335',
      icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 10-7.5 0v4.5m11.356-1.993l1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 01-1.12-1.243l1.264-12A1.125 1.125 0 015.513 7.5h12.974c.576 0 1.059.435 1.119 1.007z"/></svg>`
    };
  }
  if (title.includes('digest') || title.includes('newsletter') || title.includes('updates') || title.includes('feature') || title.includes('launch') || title.includes('story') || title.includes('case study')) {
    return {
      category: 'newsletter',
      categoryLabel: 'Newsletters & Updates',
      bg: '#e6f4ea',
      color: '#34a853',
      icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.75m-3.75 3h3.75m-3.75 3h3.75m-3.75 3h3.75M3 21h18M3 3h18v18H3V3z"/></svg>`
    };
  }
  if (title.includes('feedback') || title.includes('miss you') || title.includes('survey') || title.includes('nps') || title.includes('security') || title.includes('password')) {
    return {
      category: 'feedback',
      categoryLabel: 'Feedback & Security',
      bg: '#fef7e0',
      color: '#f9ab00',
      icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"/></svg>`
    };
  }
  return {
    category: 'events',
    categoryLabel: 'Events & Resources',
    bg: '#f3e8ff',
    color: '#9333ea',
    icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="22" height="22"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/></svg>`
  };
}

function confirmSelect() {
  emit('select', selectedTemplate.value);
  emit('close');
}

function renderSingleBlock(block) {
  if (!block || !block.type || block.type === 'body') return '';
  const s = block.styles || {};
  const pt = s.paddingTop ?? 16;
  const pb = s.paddingBottom ?? 16;
  const pl = s.paddingLeft ?? 24;
  const pr = s.paddingRight ?? 24;
  const bgColor = s.bgColor ? `background-color:${s.bgColor};` : '';
  const borderRadius = s.borderRadius ? `border-radius:${s.borderRadius}px;` : '';
  const border = s.borderWidth ? `border:${s.borderWidth}px solid ${s.borderColor || '#e5e7eb'};` : '';
  const baseWrap = `padding:${pt}px ${pr}px ${pb}px ${pl}px;${bgColor}${borderRadius}${border}`;

  if (block.type === 'heading' || block.type === 'header') {
    const align = s.textAlign || block.align || 'left';
    const color = s.color || block.textColor || '#111827';
    const size = s.fontSize || 24;
    const weight = s.fontWeight || 700;
    const content = block.content || block.title || '';
    return `<div style="${baseWrap}"><h2 style="margin:0;text-align:${align};color:${color};font-size:${size}px;font-weight:${weight};">${content}</h2></div>`;
  }

  if (block.type === 'text') {
    const align = s.textAlign || block.align || 'left';
    const color = s.color || block.textColor || '#374151';
    const size = s.fontSize || 14;
    const lh = s.lineHeight || 1.6;
    const content = (block.content || block.html || '').replace(/\n/g, '<br>');
    return `<div style="${baseWrap}"><p style="margin:0;text-align:${align};color:${color};font-size:${size}px;line-height:${lh};">${content}</p></div>`;
  }

  if (block.type === 'button') {
    const text = block.text || 'Click here';
    const href = block.href || block.url || '#';
    const bg = s.backgroundColor || block.btnColor || '#4285f4';
    const color = s.textColor || block.textColor || '#ffffff';
    const radius = s.borderRadius ?? 6;
    const size = s.fontSize ?? 14;
    const align = s.blockAlign || s.textAlign || block.align || 'center';
    return `<div style="${baseWrap}text-align:${align}"><a href="${href}" target="_blank" style="display:inline-block;background:${bg};color:${color};border-radius:${radius}px;font-size:${size}px;font-weight:600;padding:10px 24px;text-decoration:none;">${text}</a></div>`;
  }

  if (block.type === 'image') {
    const src = block.src || block.url || '';
    const alt = block.alt || '';
    const align = s.blockAlign || s.textAlign || block.align || 'center';
    const width = s.width ?? 100;
    const widthVal = width === 'auto' ? 'auto' : `${width}%`;
    if (!src) return '';
    return `<div style="${baseWrap}text-align:${align}"><img src="${src}" alt="${alt}" style="max-width:100%;width:${widthVal};display:inline-block;vertical-align:top;" /></div>`;
  }

  if (block.type === 'logo') {
    const align = s.blockAlign || s.textAlign || 'center';
    const brandText = block.brandText || 'BrandName';
    const src = block.src || '';
    const logoType = block.logoType || (src ? 'image' : 'text');
    let innerHtml = '';
    if (logoType === 'text') {
      const ff = s.fontFamily || 'sans-serif';
      const fw = s.fontWeight || 'bold';
      const fs = s.fontSize || 24;
      const color = s.color || '#333333';
      innerHtml = `<span style="font-family:${ff};font-weight:${fw};font-size:${fs}px;color:${color};line-height:1;">${brandText}</span>`;
    } else if (logoType === 'image') {
      const width = s.width ?? 50;
      innerHtml = src ? `<img src="${src}" alt="Logo" style="max-width:100%;width:${width}%;display:inline-block;vertical-align:middle;" />` : '';
    } else {
      const width = s.width ?? 50;
      const ff = s.fontFamily || 'sans-serif';
      const fw = s.fontWeight || 'bold';
      const fs = s.fontSize || 24;
      const color = s.color || '#333333';
      const imgHtml = src ? `<img src="${src}" alt="Logo" style="max-width:100%;width:${width}%;display:inline-block;vertical-align:middle;margin-right:12px;" />` : '';
      const textHtml = `<span style="font-family:${ff};font-weight:${fw};font-size:${fs}px;color:${color};line-height:1;display:inline-block;vertical-align:middle;">${brandText}</span>`;
      innerHtml = logoType === 'image-text-stacked' ? `${imgHtml}<br/>${textHtml}` : `${imgHtml}${textHtml}`;
    }
    return `<div style="${baseWrap}text-align:${align}">${innerHtml}</div>`;
  }

  if (block.type === 'social') {
    const align = s.textAlign || 'center';
    const spaceBetween = block.spaceBetween || 8;
    const links = block.links || [];
    const iconsHtml = links.map(link => {
      const p = getSocialPlatform(link.platform);
      if (!p) return '';
      const styleObj = socialIconStyle(block, link);
      const svgStr = socialIconSvg(block, link);
      const inlineCss = Object.entries(styleObj).map(([k, v]) => `${k.replace(/[A-Z]/g, m => '-' + m.toLowerCase())}:${v}`).join(';');
      return `<a href="${link.url || '#'}" target="_blank" style="${inlineCss};margin:0 ${Math.round(spaceBetween / 2)}px 6px ${Math.round(spaceBetween / 2)}px;text-decoration:none;">${svgStr}</a>`;
    }).join('');

    return `<div style="${baseWrap}text-align:${align}"><div style="display:inline-flex;align-items:center;justify-content:${align === 'center' ? 'center' : (align === 'right' ? 'flex-end' : 'flex-start')};flex-wrap:wrap;">${iconsHtml}</div></div>`;
  }

  if (block.type === 'footer') {
    const align = s.textAlign || 'center';
    const color = s.color || '#9ca3af';
    const size = s.fontSize || 11;
    const lh = s.lineHeight || 1.8;
    const content = block.content || "You're receiving this email because you subscribed to our newsletter.";
    const copyright = block.copyright || `© ${new Date().getFullYear()} Your Company · All rights reserved`;
    const borderTop = s.borderTopWidth ? `border-top:${s.borderTopWidth}px solid ${s.borderColor || '#e5e7eb'};` : 'border-top:1px solid #e5e7eb;';
    return `<div style="${baseWrap}${borderTop}text-align:${align};line-height:${lh};font-size:${size}px;color:${color};">
      <p style="margin:0 0 4px 0;">${content}</p>
      <p style="margin:0 0 4px 0;"><a href="#" style="color:#4285f4;text-decoration:none;">Unsubscribe</a> · <a href="#" style="color:#4285f4;text-decoration:none;">Privacy Policy</a></p>
      <p style="margin:0;">${copyright}</p>
    </div>`;
  }

  if (block.type === 'column') {
    const cols = block.columns || [];
    const colWidths = block.colWidths || [];
    const tds = cols.map((col, idx) => {
      const pct = colWidths[idx] || (100 / Math.max(1, cols.length));
      const inner = (col.blocks || []).map(renderSingleBlock).join('');
      return `<td style="width:${pct}%;vertical-align:top;padding:0 6px;">${inner}</td>`;
    }).join('');
    return `<div style="${baseWrap}"><table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;table-layout:fixed;"><tr>${tds}</tr></table></div>`;
  }

  if (block.type === 'divider') {
    const color = s.borderColor || block.lineColor || '#e5e7eb';
    const thickness = s.dividerThickness ?? s.borderWidth ?? 1;
    const align = s.blockAlign || s.textAlign || 'center';
    const width = s.width ?? 100;
    const margin = align === 'center' ? '0 auto' : (align === 'right' ? '0 0 0 auto' : '0 auto 0 0');
    return `<div style="${baseWrap}"><hr style="border:none;border-top:${thickness}px solid ${color};width:${width}%;margin:${margin};" /></div>`;
  }

  if (block.type === 'spacer') {
    const height = s.height ?? 24;
    return `<div style="height:${height}px;"></div>`;
  }

  return `<div style="${baseWrap}">${block.html || ''}</div>`;
}

function renderBlocksHtml(blocks) {
  if (!blocks || !Array.isArray(blocks) || !blocks.length) {
    return '<div style="padding:40px;text-align:center;color:#9ca3af;">Empty template blocks</div>';
  }

  const bodyBlock = blocks.find(b => b?.type === 'body') || {};
  const outerBgColor = bodyBlock.bgColor || '#f3f4f6';
  const outerBgImage = bodyBlock.bgImage || '';
  const outerBgPattern = bodyBlock.bgPattern || '';
  const innerBgColor = bodyBlock.contentBgColor || '#ffffff';
  const contentWidth = bodyBlock.contentWidth || 600;

  let innerBgStyle = `background-color:${innerBgColor};`;
  if (outerBgImage) {
    innerBgStyle += `background-image:url(${outerBgImage});background-repeat:repeat;background-size:auto;`;
  } else if (outerBgPattern) {
    if (outerBgPattern === 'dots') {
      innerBgStyle += 'background-image:radial-gradient(rgba(0,0,0,0.1) 1px, transparent 1px);background-size:16px 16px;';
    } else if (outerBgPattern === 'grid') {
      innerBgStyle += 'background-image:linear-gradient(rgba(0,0,0,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(0,0,0,0.04) 1px, transparent 1px);background-size:20px 20px;';
    } else if (outerBgPattern === 'stripes') {
      innerBgStyle += 'background-image:repeating-linear-gradient(45deg, rgba(0,0,0,0.02) 0px, rgba(0,0,0,0.02) 1px, transparent 1px, transparent 10px);';
    } else if (outerBgPattern === 'abstract') {
      innerBgStyle += 'background-image:linear-gradient(45deg, rgba(0,0,0,0.015) 25%, transparent 25%), linear-gradient(-45deg, rgba(0,0,0,0.015) 25%, transparent 25%);background-size:30px 30px;';
    }
  }

  const renderedInner = blocks.map(renderSingleBlock).join('');

  return `
    <div style="background-color:${outerBgColor};padding:24px 12px;">
      <div style="max-width:${contentWidth}px;margin:0 auto;${innerBgStyle}border-radius:8px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.08);">
        ${renderedInner}
      </div>
    </div>
  `;
}
</script>

<style scoped>
.aft-modal {
  width: 90vw;
  max-width: 1040px;
  height: 82vh;
  max-height: 720px;
  background: var(--bg-surface);
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
  border: 1px solid var(--border-color);
}
.aft-modal__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px 16px;
  border-bottom: 1px solid var(--border-color);
}
.aft-modal__title {
  font-size: 18px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 2px;
}
.aft-modal__sub {
  font-size: 12.5px;
  color: var(--text-secondary);
  margin: 0;
}
.aft-modal__body {
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

/* Left sidebar */
.aft-sidebar {
  width: 320px;
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  background: var(--bg-page);
  flex-shrink: 0;
}
.aft-categories {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: 10px;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-surface);
}
.aft-cat-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 7px 10px;
  border: none;
  background: none;
  border-radius: 7px;
  font-size: 12.5px;
  font-weight: 500;
  color: var(--text-secondary);
  cursor: pointer;
  text-align: left;
  transition: background 0.12s, color 0.12s;
  width: 100%;
}
.aft-cat-btn:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}
.aft-cat-btn.is-active {
  background: var(--active-bg);
  color: var(--active-text);
  font-weight: 600;
}
.aft-cat-icon {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  opacity: 0.75;
}
.aft-cat-count {
  margin-left: auto;
  font-size: 11px;
  background: var(--bg-hover-strong);
  color: var(--text-muted);
  border-radius: 10px;
  padding: 1px 7px;
  font-weight: 500;
}
.aft-cat-btn.is-active .aft-cat-count {
  background: var(--active-bg);
  color: var(--active-text);
}

/* Template list */
.aft-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.aft-list::-webkit-scrollbar { width: 4px; }
.aft-list::-webkit-scrollbar-track { background: transparent; }
.aft-list::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 2px; }

.aft-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 12px;
  border-radius: 9px;
  border: 1.5px solid transparent;
  cursor: pointer;
  transition: background 0.12s, border-color 0.12s, box-shadow 0.12s;
  position: relative;
  background: none;
  text-align: left;
}
.aft-card:hover {
  background: var(--bg-hover);
  border-color: var(--border-color);
}
.aft-card.is-active {
  background: var(--active-bg);
  border-color: var(--active-text, #C5D9FD);
}
.aft-card--scratch {
  border-style: dashed;
  border-color: var(--border-color);
  background: none;
}
.aft-card--scratch:hover {
  background: var(--bg-hover);
  border-color: var(--active-text);
}
.aft-card--scratch.is-active {
  border-color: var(--active-text);
  background: var(--active-bg);
}
.aft-card__icon {
  width: 38px;
  height: 38px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background: var(--bg-hover);
  color: var(--text-secondary);
}
.aft-card__icon--scratch {
  background: linear-gradient(135deg, #4285F4 0%, #b3c7e6 100%);
  color: #fff;
}
.aft-card__body {
  flex: 1;
  min-width: 0;
  padding-right: 54px;
}
.aft-card__name {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 1px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.aft-card__desc {
  font-size: 11.5px;
  color: var(--text-muted);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.aft-card__badge {
  position: absolute;
  right: 10px;
  top: 8px;
  font-size: 10px;
  font-weight: 600;
  color: #2563eb;
  background: #eff6ff;
  border: 1px solid #dbeafe;
  border-radius: 6px;
  padding: 1px 6px;
  letter-spacing: 0.02em;
  z-index: 1;
}
.aft-card__badge--custom {
  color: #2563eb;
  background: #eff6ff;
  border-color: #dbeafe;
}

/* Right preview */
.aft-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  background: var(--bg-surface);
}
.aft-preview__scroll {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24px;
  display: flex;
  flex-direction: column;
  -webkit-overflow-scrolling: touch;
}
.aft-preview__scroll::-webkit-scrollbar {
  width: 6px;
}
.aft-preview__scroll::-webkit-scrollbar-track {
  background: transparent;
}
.aft-preview__scroll::-webkit-scrollbar-thumb {
  background: var(--border-color, #e5e7eb);
  border-radius: 4px;
}
.aft-preview__scroll::-webkit-scrollbar-thumb:hover {
  background: var(--text-muted, #9ca3af);
}
.aft-preview__empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  text-align: center;
  gap: 10px;
  padding: 40px 20px;
  color: var(--text-muted);
}
.aft-preview__empty-icon, .aft-preview__scratch-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  background: var(--bg-hover-strong);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
  margin-bottom: 4px;
}
.aft-preview__header {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 14px;
}
.aft-preview__tpl-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.aft-preview__tpl-name {
  font-size: 16px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 4px;
}
.aft-preview__tpl-cat {
  font-size: 11px;
  font-weight: 600;
  color: var(--active-text);
  background: var(--active-bg);
  padding: 2px 8px;
  border-radius: 6px;
}
.aft-preview__meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 16px;
  padding: 10px 14px;
  background: var(--bg-hover);
  border-radius: 8px;
  font-size: 12px;
  color: var(--text-secondary);
}
.gallery-preview-frame {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.gallery-rendered-body {
  background: #ffffff;
  color: #111827;
  min-height: 240px;
}
.aft-preview__footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
  padding: 14px 24px;
  border-top: 1px solid var(--border-color);
  background: var(--bg-surface);
  flex-shrink: 0;
}
.aft-preview__footer-meta {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--text-muted);
  margin-right: auto;
}
.aft-import-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13.5px;
  padding: 9px 20px;
}

.aft-categories {
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 2px;
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
}
.aft-cat-mobile-toggle {
  display: none;
}
.aft-cat-list {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

/* Responsive breakpoint */
@media (max-width: 768px) {
  .aft-modal {
    width: 95vw;
    height: 90vh;
    max-height: 90vh;
    border-radius: 12px;
    margin: auto;
  }
  .aft-modal__body {
    flex-direction: column;
    overflow-y: auto;
    height: auto;
  }
  .aft-sidebar {
    width: 100%;
    max-height: none;
    flex-shrink: 0;
    border-right: none;
    border-bottom: 1px solid var(--border-color);
  }
  .aft-categories {
    padding: 8px 10px;
    width: 100%;
    box-sizing: border-box;
  }
  .aft-cat-mobile-toggle {
    display: flex !important;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 8px 12px;
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-primary);
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    box-sizing: border-box;
  }
  .aft-cat-mobile-toggle-left {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 0;
  }
  .aft-cat-mobile-label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 13px;
  }
  .aft-cat-mobile-toggle-right {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-shrink: 0;
  }
  .aft-cat-mobile-hint {
    font-size: 11px;
    color: var(--text-muted);
    font-weight: 600;
  }
  .aft-cat-chevron {
    width: 14px;
    height: 14px;
    transition: transform 0.2s ease;
    flex-shrink: 0;
  }
  .aft-cat-chevron.is-open {
    transform: rotate(180deg);
  }
  .aft-cat-list {
    display: none;
    flex-direction: column;
    gap: 4px;
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid var(--border-color);
    max-height: 220px;
    overflow-y: auto;
  }
  .aft-cat-list.is-open {
    display: flex !important;
  }
  .aft-cat-btn {
    width: 100% !important;
    white-space: normal;
    padding: 8px 10px;
  }
  .aft-cat-count {
    margin-left: auto;
  }
  .aft-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: 250px;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 10px 12px;
    box-sizing: border-box;
    -webkit-overflow-scrolling: touch;
  }
  .aft-card {
    width: 100% !important;
    flex-shrink: 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 12px;
    padding: 10px 12px;
    border-radius: 10px;
    box-sizing: border-box;
  }
  .aft-card__icon {
    flex-shrink: 0;
    width: 38px;
    height: 38px;
    border-radius: 9px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .aft-card__body {
    flex: 1;
    min-width: 0;
  }
  .aft-card__name {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .aft-card__desc {
    font-size: 11.5px;
    color: var(--text-secondary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-top: 1px;
  }
  .aft-card__badge {
    flex-shrink: 0;
    font-size: 10px;
    padding: 2px 6px;
  }
  .aft-modal {
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .aft-modal__body {
    flex: 1;
    overflow-y: auto;
    padding-bottom: 75px;
  }
  .aft-preview__footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 50;
    background: var(--bg-surface);
    border-top: 1px solid var(--border-color);
    padding: 10px 14px;
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.35);
    display: flex !important;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    width: 100%;
    box-sizing: border-box;
  }
  .aft-preview__footer-meta {
    display: none !important;
  }
  .aft-import-btn {
    width: 100% !important;
    justify-content: center;
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.35);
  }
}
</style>
