// Simple Email Template Editor - NO GRAPESJS
const SimpleEmailEditor = {
  canvas: null,
  components: [],
  selectedComponent: null,
  draggedElement: null,
  propertiesPanel: null,

  init(canvasId) {
    this.canvas = document.getElementById(canvasId);
    if (!this.canvas) return;
    
    this.canvas.innerHTML = '';
    this.canvas.className = 'simple-email-canvas';
    this.canvas.addEventListener('click', (e) => {
      if (e.target === this.canvas) {
        this.deselectAll();
      }
    });
    
    // Setup drop zone on canvas
    this.canvas.addEventListener('dragover', (e) => {
      e.preventDefault();
      e.stopPropagation();
      e.dataTransfer.dropEffect = 'copy';
      this.canvas.classList.add('drag-over');
    });
    
    this.canvas.addEventListener('dragleave', (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (e.target === this.canvas) {
        this.canvas.classList.remove('drag-over');
      }
    });
    
    this.canvas.addEventListener('drop', (e) => {
      e.preventDefault();
      e.stopPropagation();
      this.canvas.classList.remove('drag-over');
      
      console.log('Drop event triggered!', this.draggedElement);
      
      if (this.draggedElement) {
        const type = this.draggedElement.dataset.type;
        console.log('Adding component:', type);
        this.addComponent(type);
        this.draggedElement = null;
      } else {
        // Fallback: try to get type from dataTransfer
        const type = e.dataTransfer.getData('text/plain');
        if (type) {
          console.log('Adding component from dataTransfer:', type);
          this.addComponent(type);
        }
      }
    });
    
    // Also setup drop zone on canvas parent
    const canvasParent = this.canvas.parentElement;
    if (canvasParent) {
      canvasParent.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
      });
      
      canvasParent.addEventListener('drop', (e) => {
        e.preventDefault();
        e.stopPropagation();
        
        if (this.draggedElement) {
          const type = this.draggedElement.dataset.type;
          this.addComponent(type);
          this.draggedElement = null;
        } else {
          const type = e.dataTransfer.getData('text/plain');
          if (type) {
            this.addComponent(type);
          }
        }
      });
    }
    
    this.renderPlaceholder();
  },

  renderPlaceholder() {
    if (this.components.length === 0) {
      this.canvas.innerHTML = `<div class="canvas-placeholder">${this.t('email.editor.drop_here', 'Drop here to add at end')}</div>`;
      
      // Ensure drop works on placeholder too
      const placeholder = this.canvas.querySelector('.canvas-placeholder');
      if (placeholder) {
        placeholder.addEventListener('dragover', (e) => {
          e.preventDefault();
          e.stopPropagation();
          e.dataTransfer.dropEffect = 'copy';
          this.canvas.classList.add('drag-over');
        });
        
        placeholder.addEventListener('drop', (e) => {
          e.preventDefault();
          e.stopPropagation();
          this.canvas.classList.remove('drag-over');
          
          const type = e.dataTransfer.getData('text/plain') || this.draggedElement?.dataset.type;
          if (type) {
            this.addComponent(type);
            this.draggedElement = null;
          }
        });
      }
    }
    this.renderPropertiesPanel();
  },

  addComponent(type, content, meta) {
    const id = 'comp-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
    const baseMeta = this.getDefaultMeta(type);
    const finalMeta = { ...baseMeta, ...(meta || {}) };
    const component = {
      id,
      type,
      content,
      meta: finalMeta,
      html: this.getComponentHTML(type, content, finalMeta)
    };
    
    this.components.push(component);
    this.render();
    return component;
  },

  getDefaultMeta(type) {
    if (type === 'heading') {
      return { align: 'left', color: '#1a202c', fontSize: 32 };
    }
    if (type === 'paragraph') {
      return { align: 'left', color: '#4a5568', fontSize: 16 };
    }
    if (type === 'text') {
      return { align: 'left', color: '#2d3748', fontSize: 15 };
    }
    if (type === 'button') {
      return {
        href: 'https://example.com',
        bgColor: '#3182ce',
        textColor: '#ffffff',
        align: 'center',
        radius: 8,
        paddingX: 28,
        paddingY: 14
      };
    }
    if (type === 'link') {
      return { href: 'https://example.com', color: '#3182ce', align: 'left' };
    }
    if (type === 'image') {
      return { src: '', href: '', align: 'center', width: '100%', radius: 8 };
    }
    if (type === '2cols') {
      return {
        leftHtml: '',
        rightHtml: '',
        gap: 16
      };
    }
    if (type === '3cols') {
      return {
        leftHtml: '',
        centerHtml: '',
        rightHtml: '',
        gap: 16
      };
    }
    return {};
  },

  normalizeUnit(value, fallback) {
    if (value === undefined || value === null || value === '') return fallback;
    const text = String(value).trim();
    if (/^\d+$/.test(text)) return `${text}px`;
    return text;
  },

  t(key, fallback) {
    if (typeof window !== 'undefined') {
      if (typeof window.emailT === 'function') {
        return window.emailT(key, fallback);
      }
      if (window.i18n && typeof window.i18n.t === 'function') {
        const translated = window.i18n.t(key);
        if (!translated || translated === key) {
          return fallback;
        }
        return translated;
      }
    }
    return fallback;
  },

  getComponentHTML(type, content, meta) {
    const attrs = { ...this.getDefaultMeta(type), ...(meta || {}) };
    switch(type) {
      case 'heading':
        return `<h1 style="font-size: ${attrs.fontSize}px; font-weight: bold; margin: 0 0 16px 0; color: ${attrs.color}; line-height: 1.2; text-align: ${attrs.align};">${content || this.t('email.editor.default_heading', 'Your Heading Here')}</h1>`;
      
      case 'paragraph':
        return `<p style="font-size: ${attrs.fontSize}px; line-height: 1.6; color: ${attrs.color}; margin: 0 0 16px 0; text-align: ${attrs.align};">${content || this.t('email.editor.default_paragraph', 'Add your paragraph text here. Use {{first_name}} for personalization.')}</p>`;
      
      case 'text':
        return `<div style="font-size: ${attrs.fontSize}px; line-height: 1.5; color: ${attrs.color}; margin: 0 0 12px 0; text-align: ${attrs.align};">${content || this.t('email.editor.default_text', 'Simple text block')}</div>`;
      
      case 'button':
        return `<div style="text-align: ${attrs.align}; margin: 16px 0;">
          <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="display: inline-table;">
            <tr>
              <td style="background: ${attrs.bgColor}; padding: ${attrs.paddingY}px ${attrs.paddingX}px; border-radius: ${attrs.radius}px; text-align: center;">
                <a href="${attrs.href || 'https://example.com'}" style="color: ${attrs.textColor}; text-decoration: none; font-weight: 600; font-size: 16px; display: inline-block;">${content || this.t('email.editor.default_button', 'Call to Action')}</a>
              </td>
            </tr>
          </table>
        </div>`;
      
      case 'link':
        return `<div style="text-align: ${attrs.align};"><a href="${attrs.href || 'https://example.com'}" style="color: ${attrs.color}; text-decoration: underline; font-size: 15px;">${content || this.t('email.editor.default_link', 'Click here')}</a></div>`;
      
      case 'image': {
        const imageWidth = this.normalizeUnit(attrs.width, '100%');
        const imageRadius = Number.isFinite(attrs.radius) ? attrs.radius : 8;
        if (attrs.src) {
          const imageTag = `<img src="${attrs.src}" alt="" style="width: ${imageWidth}; max-width: 100%; height: auto; border-radius: ${imageRadius}px; display: block; margin: 0 auto;">`;
          if (attrs.href) {
            return `<div style="text-align: ${attrs.align}; margin: 16px 0;"><a href="${attrs.href}" style="display: inline-block;">${imageTag}</a></div>`;
          }
          return `<div style="text-align: ${attrs.align}; margin: 16px 0;">${imageTag}</div>`;
        }
        return `<div style="text-align: ${attrs.align}; margin: 16px 0;">
          <div style="width: 100%; max-width: 600px; height: 200px; border: 2px dashed #cbd5e0; border-radius: 8px; background: #f7fafc; display: inline-flex; align-items: center; justify-content: center; color: #a0aec0; font-size: 14px;">
            <div><i class="fas fa-image" style="font-size: 48px; margin-bottom: 8px;"></i><br>${this.t('email.editor.default_image', 'Add image URL')}</div>
          </div>
        </div>`;
      }
      
      case 'divider':
        return `<hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 24px 0;">`;
      
      case 'spacer':
        return `<div style="height: 32px; line-height: 32px; font-size: 0;">&nbsp;</div>`;
      
      case '2cols': {
        const gap = Number.isFinite(Number(attrs.gap)) ? Number(attrs.gap) : 16;
        const halfGap = Math.max(0, Math.round(gap / 2));
        return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="width: 100%; margin: 16px 0; border-collapse: separate; border-spacing: 0;">
          <tr>
            <td style="width: 50%; vertical-align: top; padding-right: ${halfGap}px;">
              <div class="column-content" data-col="left" style="padding: 12px; min-height: 60px;">${attrs.leftHtml || this.t('email.editor.default_left_column', 'Left column')}</div>
            </td>
            <td style="width: 50%; vertical-align: top; padding-left: ${halfGap}px;">
              <div class="column-content" data-col="right" style="padding: 12px; min-height: 60px;">${attrs.rightHtml || this.t('email.editor.default_right_column', 'Right column')}</div>
            </td>
          </tr>
        </table>`;
      }
      
      case '3cols': {
        const gap = Number.isFinite(Number(attrs.gap)) ? Number(attrs.gap) : 16;
        const thirdGap = Math.max(0, Math.round(gap / 3));
        return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="width: 100%; margin: 16px 0; border-collapse: separate; border-spacing: 0;">
          <tr>
            <td style="width: 33.33%; vertical-align: top; padding-right: ${thirdGap}px;">
              <div class="column-content" data-col="left" style="padding: 12px; min-height: 60px;">${attrs.leftHtml || this.t('email.editor.default_left_column', 'Left column')}</div>
            </td>
            <td style="width: 33.33%; vertical-align: top; padding-left: ${thirdGap}px; padding-right: ${thirdGap}px;">
              <div class="column-content" data-col="center" style="padding: 12px; min-height: 60px;">${attrs.centerHtml || this.t('email.editor.default_center_column', 'Center column')}</div>
            </td>
            <td style="width: 33.33%; vertical-align: top; padding-left: ${thirdGap}px;">
              <div class="column-content" data-col="right" style="padding: 12px; min-height: 60px;">${attrs.rightHtml || this.t('email.editor.default_right_column', 'Right column')}</div>
            </td>
          </tr>
        </table>`;
      }
      
      default:
        return `<div>${content || this.t('email.editor.default_component', 'Component')}</div>`;
    }
  },

  render() {
    if (this.components.length === 0) {
      this.renderPlaceholder();
      return;
    }

    this.canvas.innerHTML = '';
    
    this.components.forEach((comp, index) => {
      const wrapper = document.createElement('div');
      wrapper.className = 'component-wrapper';
      wrapper.dataset.id = comp.id;
      wrapper.dataset.index = index;
      
      comp.meta = { ...this.getDefaultMeta(comp.type), ...(comp.meta || {}) };
      comp.html = this.getComponentHTML(comp.type, comp.content, comp.meta);
      const content = document.createElement('div');
      content.className = 'component-content';
      content.innerHTML = comp.html;
      if (comp.type === '2cols' || comp.type === '3cols') {
        content.contentEditable = false;
        content.querySelectorAll('.column-content').forEach(col => {
          col.contentEditable = false;
          
          // Make inner elements editable
          this.makeColumnContentEditable(col, comp);
          
          col.addEventListener('dragover', (event) => {
            event.preventDefault();
            event.stopPropagation();
            if (event.dataTransfer) {
              event.dataTransfer.dropEffect = 'copy';
            }
            col.classList.add('drag-over');
          });
          col.addEventListener('dragleave', () => {
            col.classList.remove('drag-over');
          });
          col.addEventListener('drop', (event) => {
            event.preventDefault();
            event.stopPropagation();
            col.classList.remove('drag-over');
            const type = this.getDropType(event);
            if (type) {
              const column = col.dataset.col;
              this.appendBlockToColumn(comp, column, type);
            }
          });
          col.addEventListener('click', (event) => {
            // If clicking on empty space, select the column component
            if (event.target === col) {
              event.stopPropagation();
              this.selectComponent(comp.id);
            }
          });
        });
      } else {
        content.contentEditable = comp.type !== 'image';
        content.addEventListener('blur', (e) => {
          if (comp.type === 'button' || comp.type === 'link') {
            const text = e.target.textContent || '';
            comp.content = text.trim() || comp.content;
          } else if (comp.type !== 'image') {
            comp.content = e.target.innerHTML;
          }
          comp.html = this.getComponentHTML(comp.type, comp.content, comp.meta);
          this.renderPropertiesPanel();
        });
      }
      
      const toolbar = document.createElement('div');
      toolbar.className = 'component-toolbar';
      toolbar.innerHTML = `
        <button class="toolbar-btn" data-action="edit" title="Edit"><i class="fas fa-pen"></i></button>
        <button class="toolbar-btn" data-action="up" title="Move Up"><i class="fas fa-arrow-up"></i></button>
        <button class="toolbar-btn" data-action="down" title="Move Down"><i class="fas fa-arrow-down"></i></button>
        <button class="toolbar-btn" data-action="duplicate" title="Duplicate"><i class="fas fa-clone"></i></button>
        <button class="toolbar-btn" data-action="delete" title="Delete"><i class="fas fa-trash"></i></button>
      `;
      
      toolbar.addEventListener('click', (e) => {
        const btn = e.target.closest('.toolbar-btn');
        if (!btn) return;
        
        const action = btn.dataset.action;
        this.handleToolbarAction(action, index);
      });
      
      wrapper.appendChild(toolbar);
      wrapper.appendChild(content);
      
      wrapper.addEventListener('click', (e) => {
        if (!e.target.closest('.component-toolbar')) {
          this.selectComponent(comp.id);
        }
      });
      if (comp.id === this.selectedComponent) {
        wrapper.classList.add('selected');
      }
      this.canvas.appendChild(wrapper);
    });
    this.renderPropertiesPanel();
  },

  handleToolbarAction(action, index) {
    switch(action) {
      case 'edit':
        this.editComponent(index);
        break;
      case 'up':
        if (index > 0) {
          [this.components[index], this.components[index - 1]] = [this.components[index - 1], this.components[index]];
          this.render();
        }
        break;
      
      case 'down':
        if (index < this.components.length - 1) {
          [this.components[index], this.components[index + 1]] = [this.components[index + 1], this.components[index]];
          this.render();
        }
        break;
      
      case 'duplicate':
        const comp = this.components[index];
        this.addComponent(comp.type, comp.content, JSON.parse(JSON.stringify(comp.meta || {})));
        break;
      
      case 'delete':
        this.components.splice(index, 1);
        this.render();
        break;
    }
  },

  editComponent(index) {
    const comp = this.components[index];
    if (!comp) return;
    this.selectedComponent = comp.id;
    this.render();
    this.focusPropertiesPanel();
  },

  getDropType(event) {
    const transferType = event?.dataTransfer?.getData('text/plain');
    if (transferType) return transferType;
    if (this.draggedElement?.dataset?.type) return this.draggedElement.dataset.type;
    return null;
  },

  makeColumnContentEditable(col, comp) {
    // Make blocks inside columns clickable to edit
    col.querySelectorAll('.column-block').forEach(blockEl => {
      const blockId = blockEl.dataset.blockId;
      if (!blockId || !comp.meta.blocks || !comp.meta.blocks[blockId]) return;
      
      blockEl.style.cursor = 'pointer';
      blockEl.style.transition = 'all 0.2s ease';
      blockEl.style.padding = '8px';
      blockEl.style.borderRadius = '4px';
      blockEl.style.border = '2px solid transparent';
      
      blockEl.addEventListener('mouseenter', () => {
        blockEl.style.borderColor = '#cbd5e0';
        blockEl.style.backgroundColor = '#f8fafc';
      });
      
      blockEl.addEventListener('mouseleave', () => {
        if (!blockEl.classList.contains('selected-block')) {
          blockEl.style.borderColor = 'transparent';
          blockEl.style.backgroundColor = 'transparent';
        }
      });
      
      blockEl.addEventListener('click', (e) => {
        e.stopPropagation();
        
        // Deselect all blocks
        col.querySelectorAll('.column-block').forEach(b => {
          b.classList.remove('selected-block');
          b.style.borderColor = 'transparent';
          b.style.backgroundColor = 'transparent';
        });
        
        // Select this block
        blockEl.classList.add('selected-block');
        blockEl.style.borderColor = '#3182ce';
        blockEl.style.backgroundColor = '#ebf8ff';
        
        // Show properties panel for this block
        this.showBlockProperties(comp, blockId);
      });
    });
  },

  showBlockProperties(comp, blockId) {
    if (!this.propertiesPanel) return;
    
    const block = comp.meta.blocks[blockId];
    if (!block) return;
    
    this.propertiesPanel.innerHTML = '';
    
    const header = document.createElement('div');
    header.className = 'template-properties-header';
    header.textContent = this.t('email.editor.block_properties_title', 'Block Properties');
    
    const body = document.createElement('div');
    body.className = 'template-properties-body';
    
    this.propertiesPanel.appendChild(header);
    this.propertiesPanel.appendChild(body);
    
    const addSection = (title) => {
      const section = document.createElement('div');
      section.className = 'template-properties-section';
      if (title) {
        const sectionTitle = document.createElement('div');
        sectionTitle.className = 'template-properties-section-title';
        sectionTitle.textContent = title;
        section.appendChild(sectionTitle);
      }
      body.appendChild(section);
      return section;
    };
    
    const addField = (section, labelText, input) => {
      const field = document.createElement('div');
      field.className = 'template-properties-field';
      const label = document.createElement('label');
      label.textContent = labelText;
      field.appendChild(label);
      field.appendChild(input);
      section.appendChild(field);
      return input;
    };
    
    const addRow = (section) => {
      const row = document.createElement('div');
      row.className = 'template-properties-row';
      section.appendChild(row);
      return row;
    };
    
    const applyChanges = () => {
      // Regenerate HTML for this block
      const blockHtml = this.getComponentHTML(block.type, block.content, block.meta);
      
      // Update the HTML in the column
      const column = this.findBlockColumn(comp, blockId);
      if (column) {
        const columnHtml = comp.meta[column + 'Html'] || '';
        const parser = new DOMParser();
        const doc = parser.parseFromString(columnHtml, 'text/html');
        const blockEl = doc.querySelector(`[data-block-id="${blockId}"]`);
        if (blockEl) {
          blockEl.innerHTML = blockHtml;
          comp.meta[column + 'Html'] = doc.body.innerHTML;
        }
      }
      
      comp.html = this.getComponentHTML(comp.type, comp.content, comp.meta);
      this.render();
      this.selectComponent(comp.id);
      
      // Re-select the block
      setTimeout(() => {
        const blockEl = document.querySelector(`[data-block-id="${blockId}"]`);
        if (blockEl) {
          blockEl.click();
        }
      }, 50);
    };
    
    const basics = addSection(this.t('email.editor.section_content', 'Content'));
    
    // Content editing based on block type
    if (block.type === 'heading' || block.type === 'paragraph' || block.type === 'text') {
      const textarea = document.createElement('textarea');
      textarea.className = 'template-properties-textarea';
      textarea.value = block.content || '';
      addField(basics, this.t('email.editor.label_text', 'Text'), textarea);
      textarea.addEventListener('blur', () => {
        block.content = textarea.value;
        applyChanges();
      });
      
      const style = addSection(this.t('email.editor.section_style', 'Style'));
      const row = addRow(style);
      
      const fontSizeInput = document.createElement('input');
      fontSizeInput.type = 'number';
      fontSizeInput.min = '8';
      fontSizeInput.className = 'template-properties-input';
      fontSizeInput.value = block.meta.fontSize;
      const fontField = document.createElement('div');
      fontField.className = 'template-properties-field';
      const fontLabel = document.createElement('label');
      fontLabel.textContent = this.t('email.editor.label_size', 'Size');
      fontField.appendChild(fontLabel);
      fontField.appendChild(fontSizeInput);
      row.appendChild(fontField);
      fontSizeInput.addEventListener('change', () => {
        block.meta.fontSize = Number(fontSizeInput.value) || block.meta.fontSize;
        applyChanges();
      });
      
      const colorInput = document.createElement('input');
      colorInput.type = 'color';
      colorInput.className = 'template-properties-input';
      colorInput.value = block.meta.color;
      const colorField = document.createElement('div');
      colorField.className = 'template-properties-field';
      const colorLabel = document.createElement('label');
      colorLabel.textContent = this.t('email.editor.label_color', 'Color');
      colorField.appendChild(colorLabel);
      colorField.appendChild(colorInput);
      row.appendChild(colorField);
      colorInput.addEventListener('change', () => {
        block.meta.color = colorInput.value;
        applyChanges();
      });
      
      const alignSelect = document.createElement('select');
      alignSelect.className = 'template-properties-select';
      ['left', 'center', 'right'].forEach(value => {
        const option = document.createElement('option');
        option.value = value;
        option.textContent = this.t(`email.editor.align_${value}`, value.charAt(0).toUpperCase() + value.slice(1));
        if (block.meta.align === value) option.selected = true;
        alignSelect.appendChild(option);
      });
      addField(style, this.t('email.editor.label_alignment', 'Alignment'), alignSelect);
      alignSelect.addEventListener('change', () => {
        block.meta.align = alignSelect.value;
        applyChanges();
      });
    }
    
    if (block.type === 'button') {
      const labelInput = document.createElement('input');
      labelInput.className = 'template-properties-input';
      labelInput.value = block.content || 'Call to Action';
      addField(basics, this.t('email.editor.button_text', 'Button text'), labelInput);
      labelInput.addEventListener('blur', () => {
        block.content = labelInput.value.trim() || block.content;
        applyChanges();
      });
      
      const hrefInput = document.createElement('input');
      hrefInput.className = 'template-properties-input';
      hrefInput.value = block.meta.href || '';
      addField(basics, this.t('email.editor.button_link', 'Button link'), hrefInput);
      hrefInput.addEventListener('blur', () => {
        block.meta.href = hrefInput.value.trim();
        applyChanges();
      });
      
      const style = addSection(this.t('email.editor.section_style', 'Style'));
      const row1 = addRow(style);
      
      const bgInput = document.createElement('input');
      bgInput.type = 'color';
      bgInput.className = 'template-properties-input';
      bgInput.value = block.meta.bgColor;
      const bgField = document.createElement('div');
      bgField.className = 'template-properties-field';
      const bgLabel = document.createElement('label');
      bgLabel.textContent = this.t('email.editor.button_color', 'Button color');
      bgField.appendChild(bgLabel);
      bgField.appendChild(bgInput);
      row1.appendChild(bgField);
      bgInput.addEventListener('change', () => {
        block.meta.bgColor = bgInput.value;
        applyChanges();
      });
      
      const textColorInput = document.createElement('input');
      textColorInput.type = 'color';
      textColorInput.className = 'template-properties-input';
      textColorInput.value = block.meta.textColor;
      const textColorField = document.createElement('div');
      textColorField.className = 'template-properties-field';
      const textColorLabel = document.createElement('label');
      textColorLabel.textContent = this.t('email.editor.text_color', 'Text color');
      textColorField.appendChild(textColorLabel);
      textColorField.appendChild(textColorInput);
      row1.appendChild(textColorField);
      textColorInput.addEventListener('change', () => {
        block.meta.textColor = textColorInput.value;
        applyChanges();
      });
    }
    
    if (block.type === 'image') {
      const srcInput = document.createElement('input');
      srcInput.className = 'template-properties-input';
      srcInput.value = block.meta.src || '';
      srcInput.placeholder = 'https://';
      addField(basics, this.t('email.editor.image_url', 'Image URL'), srcInput);
      srcInput.addEventListener('blur', () => {
        block.meta.src = srcInput.value.trim();
        applyChanges();
      });
      
      // Upload section
      const uploadSection = addSection(this.t('email.editor.upload_from_device', 'Upload from device'));
      const uploadRow = document.createElement('div');
      uploadRow.className = 'template-properties-action';
      const uploadButton = document.createElement('button');
      uploadButton.type = 'button';
      uploadButton.className = 'template-properties-button';
      uploadButton.textContent = this.t('email.editor.upload_image', 'Upload image');
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = 'image/*';
      fileInput.style.display = 'none';
      uploadRow.appendChild(uploadButton);
      uploadRow.appendChild(fileInput);
      uploadSection.appendChild(uploadRow);
      uploadButton.addEventListener('click', () => {
        fileInput.click();
      });
      fileInput.addEventListener('change', () => {
        const file = fileInput.files && fileInput.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = () => {
          block.meta.src = reader.result;
          srcInput.value = reader.result;
          applyChanges();
        };
        reader.readAsDataURL(file);
      });
      
      const hrefInput = document.createElement('input');
      hrefInput.className = 'template-properties-input';
      hrefInput.value = block.meta.href || '';
      hrefInput.placeholder = 'https://';
      addField(basics, this.t('email.editor.image_link_optional', 'Image link (optional)'), hrefInput);
      hrefInput.addEventListener('blur', () => {
        block.meta.href = hrefInput.value.trim();
        applyChanges();
      });
    }
    
    // Delete button
    const deleteSection = addSection('');
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'btn btn-danger btn-sm';
    deleteBtn.textContent = this.t('email.editor.delete_block', 'Delete Block');
    deleteBtn.style.width = '100%';
    deleteBtn.addEventListener('click', () => {
      this.deleteBlockFromColumn(comp, blockId);
    });
    deleteSection.appendChild(deleteBtn);
  },

  findBlockColumn(comp, blockId) {
    if ((comp.meta.leftHtml || '').includes(`data-block-id="${blockId}"`)) return 'left';
    if ((comp.meta.centerHtml || '').includes(`data-block-id="${blockId}"`)) return 'center';
    if ((comp.meta.rightHtml || '').includes(`data-block-id="${blockId}"`)) return 'right';
    return null;
  },

  deleteBlockFromColumn(comp, blockId) {
    const column = this.findBlockColumn(comp, blockId);
    if (!column) return;
    
    const columnHtml = comp.meta[column + 'Html'] || '';
    const parser = new DOMParser();
    const doc = parser.parseFromString(columnHtml, 'text/html');
    const blockEl = doc.querySelector(`[data-block-id="${blockId}"]`);
    if (blockEl) {
      blockEl.remove();
      comp.meta[column + 'Html'] = doc.body.innerHTML;
    }
    
    // Remove from blocks storage
    if (comp.meta.blocks) {
      delete comp.meta.blocks[blockId];
    }
    
    comp.html = this.getComponentHTML(comp.type, comp.content, comp.meta);
    this.render();
    this.selectComponent(comp.id);
  },

  appendBlockToColumn(comp, column, type) {
    // Create a unique ID for the block
    const blockId = 'block-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
    const blockMeta = this.getDefaultMeta(type);
    const blockContent = this.getDefaultContent(type);
    
    // Store block data in component meta
    if (!comp.meta.blocks) {
      comp.meta.blocks = {};
    }
    comp.meta.blocks[blockId] = {
      id: blockId,
      type: type,
      content: blockContent,
      meta: blockMeta
    };
    
    // Generate HTML with data attribute
    const snippet = `<div class="column-block" data-block-id="${blockId}">${this.getComponentHTML(type, blockContent, blockMeta)}</div>`;
    
    let current = '';
    if (column === 'left') {
      current = comp.meta.leftHtml || '';
    } else if (column === 'center') {
      current = comp.meta.centerHtml || '';
    } else {
      current = comp.meta.rightHtml || '';
    }
    const spacer = current.trim() ? '<div style="height: 12px;"></div>' : '';
    const nextHtml = `${current}${spacer}${snippet}`;
    if (column === 'left') {
      comp.meta.leftHtml = nextHtml;
    } else if (column === 'center') {
      comp.meta.centerHtml = nextHtml;
    } else {
      comp.meta.rightHtml = nextHtml;
    }
    comp.html = this.getComponentHTML(comp.type, comp.content, comp.meta);
    this.render();
    this.selectComponent(comp.id);
  },

  getDefaultContent(type) {
    switch(type) {
      case 'heading': return 'Heading';
      case 'paragraph': return 'Add your paragraph text here';
      case 'text': return 'Simple text';
      case 'button': return 'Call to Action';
      case 'link': return 'Click here';
      default: return '';
    }
  },

  setPropertiesPanel(panel) {
    this.propertiesPanel = panel;
    this.renderPropertiesPanel();
  },

  getSelectedComponent() {
    if (!this.selectedComponent) return null;
    return this.components.find(comp => comp.id === this.selectedComponent) || null;
  },

  focusPropertiesPanel() {
    if (!this.propertiesPanel) return;
    const input = this.propertiesPanel.querySelector('input, textarea, select, button');
    if (input && typeof input.focus === 'function') {
      input.focus();
    }
  },

  renderPropertiesPanel() {
    if (!this.propertiesPanel) return;
    this.propertiesPanel.innerHTML = '';
    const header = document.createElement('div');
    header.className = 'template-properties-header';
    header.textContent = this.t('email.editor.properties_title', 'Properties');
    const body = document.createElement('div');
    body.className = 'template-properties-body';
    this.propertiesPanel.appendChild(header);
    this.propertiesPanel.appendChild(body);

    const comp = this.getSelectedComponent();
    if (!comp) {
      const empty = document.createElement('div');
      empty.className = 'template-properties-empty';
      empty.textContent = this.t('email.editor.select_block', 'Select a block to edit');
      body.appendChild(empty);
      return;
    }

    comp.meta = { ...this.getDefaultMeta(comp.type), ...(comp.meta || {}) };

    const addSection = (title) => {
      const section = document.createElement('div');
      section.className = 'template-properties-section';
      if (title) {
        const sectionTitle = document.createElement('div');
        sectionTitle.className = 'template-properties-section-title';
        sectionTitle.textContent = title;
        section.appendChild(sectionTitle);
      }
      body.appendChild(section);
      return section;
    };

    const addField = (section, labelText, input) => {
      const field = document.createElement('div');
      field.className = 'template-properties-field';
      const label = document.createElement('label');
      label.textContent = labelText;
      field.appendChild(label);
      field.appendChild(input);
      section.appendChild(field);
      return input;
    };

    const addRow = (section) => {
      const row = document.createElement('div');
      row.className = 'template-properties-row';
      section.appendChild(row);
      return row;
    };

    const applyChanges = () => {
      comp.html = this.getComponentHTML(comp.type, comp.content, comp.meta);
      this.render();
      this.selectComponent(comp.id);
    };

    const basics = addSection(this.t('email.editor.section_content', 'Content'));

    if (comp.type === 'heading' || comp.type === 'paragraph' || comp.type === 'text') {
      const textarea = document.createElement('textarea');
      textarea.className = 'template-properties-textarea';
      textarea.value = comp.content || '';
      addField(basics, this.t('email.editor.label_text', 'Text'), textarea);
      textarea.addEventListener('change', () => {
        comp.content = textarea.value;
        applyChanges();
      });

      const style = addSection(this.t('email.editor.section_style', 'Style'));
      const row = addRow(style);

      const fontSizeInput = document.createElement('input');
      fontSizeInput.type = 'number';
      fontSizeInput.min = '8';
      fontSizeInput.className = 'template-properties-input';
      fontSizeInput.value = comp.meta.fontSize;
      const fontField = document.createElement('div');
      fontField.className = 'template-properties-field';
      const fontLabel = document.createElement('label');
      fontLabel.textContent = this.t('email.editor.label_size', 'Size');
      fontField.appendChild(fontLabel);
      fontField.appendChild(fontSizeInput);
      row.appendChild(fontField);
      fontSizeInput.addEventListener('change', () => {
        comp.meta.fontSize = Number(fontSizeInput.value) || comp.meta.fontSize;
        applyChanges();
      });

      const colorInput = document.createElement('input');
      colorInput.type = 'color';
      colorInput.className = 'template-properties-input';
      colorInput.value = comp.meta.color;
      const colorField = document.createElement('div');
      colorField.className = 'template-properties-field';
      const colorLabel = document.createElement('label');
      colorLabel.textContent = this.t('email.editor.label_color', 'Color');
      colorField.appendChild(colorLabel);
      colorField.appendChild(colorInput);
      row.appendChild(colorField);
      colorInput.addEventListener('change', () => {
        comp.meta.color = colorInput.value;
        applyChanges();
      });

      const alignSelect = document.createElement('select');
      alignSelect.className = 'template-properties-select';
      ['left', 'center', 'right'].forEach(value => {
        const option = document.createElement('option');
        option.value = value;
        option.textContent = value === 'left'
          ? this.t('email.editor.align_left', 'Left')
          : value === 'center'
            ? this.t('email.editor.align_center', 'Center')
            : this.t('email.editor.align_right', 'Right');
        if (comp.meta.align === value) option.selected = true;
        alignSelect.appendChild(option);
      });
      addField(style, this.t('email.editor.label_alignment', 'Alignment'), alignSelect);
      alignSelect.addEventListener('change', () => {
        comp.meta.align = alignSelect.value;
        applyChanges();
      });
      return;
    }

    if (comp.type === 'button') {
      const labelInput = document.createElement('input');
      labelInput.className = 'template-properties-input';
      labelInput.value = comp.content || this.t('email.editor.default_button', 'Call to Action');
      addField(basics, this.t('email.editor.button_text', 'Button text'), labelInput);
      labelInput.addEventListener('change', () => {
        comp.content = labelInput.value.trim() || comp.content;
        applyChanges();
      });

      const hrefInput = document.createElement('input');
      hrefInput.className = 'template-properties-input';
      hrefInput.value = comp.meta.href || '';
      addField(basics, this.t('email.editor.button_link', 'Button link'), hrefInput);
      hrefInput.addEventListener('change', () => {
        comp.meta.href = hrefInput.value.trim();
        applyChanges();
      });

      const style = addSection(this.t('email.editor.section_style', 'Style'));
      const row1 = addRow(style);

      const bgInput = document.createElement('input');
      bgInput.type = 'color';
      bgInput.className = 'template-properties-input';
      bgInput.value = comp.meta.bgColor;
      const bgField = document.createElement('div');
      bgField.className = 'template-properties-field';
      const bgLabel = document.createElement('label');
      bgLabel.textContent = this.t('email.editor.button_color', 'Button color');
      bgField.appendChild(bgLabel);
      bgField.appendChild(bgInput);
      row1.appendChild(bgField);
      bgInput.addEventListener('change', () => {
        comp.meta.bgColor = bgInput.value;
        applyChanges();
      });

      const textColorInput = document.createElement('input');
      textColorInput.type = 'color';
      textColorInput.className = 'template-properties-input';
      textColorInput.value = comp.meta.textColor;
      const textColorField = document.createElement('div');
      textColorField.className = 'template-properties-field';
      const textColorLabel = document.createElement('label');
      textColorLabel.textContent = this.t('email.editor.text_color', 'Text color');
      textColorField.appendChild(textColorLabel);
      textColorField.appendChild(textColorInput);
      row1.appendChild(textColorField);
      textColorInput.addEventListener('change', () => {
        comp.meta.textColor = textColorInput.value;
        applyChanges();
      });

      const row2 = addRow(style);
      const radiusInput = document.createElement('input');
      radiusInput.type = 'number';
      radiusInput.min = '0';
      radiusInput.className = 'template-properties-input';
      radiusInput.value = comp.meta.radius;
      const radiusField = document.createElement('div');
      radiusField.className = 'template-properties-field';
      const radiusLabel = document.createElement('label');
      radiusLabel.textContent = this.t('email.editor.radius', 'Radius');
      radiusField.appendChild(radiusLabel);
      radiusField.appendChild(radiusInput);
      row2.appendChild(radiusField);
      radiusInput.addEventListener('change', () => {
        comp.meta.radius = Number(radiusInput.value) || comp.meta.radius;
        applyChanges();
      });

      const row3 = addRow(style);
      const paddingYInput = document.createElement('input');
      paddingYInput.type = 'number';
      paddingYInput.min = '0';
      paddingYInput.className = 'template-properties-input';
      paddingYInput.value = comp.meta.paddingY;
      const paddingYField = document.createElement('div');
      paddingYField.className = 'template-properties-field';
      const paddingYLabel = document.createElement('label');
      paddingYLabel.textContent = this.t('email.editor.padding_vertical', 'Vertical padding');
      paddingYField.appendChild(paddingYLabel);
      paddingYField.appendChild(paddingYInput);
      row3.appendChild(paddingYField);
      paddingYInput.addEventListener('change', () => {
        comp.meta.paddingY = Number(paddingYInput.value) || comp.meta.paddingY;
        applyChanges();
      });

      const paddingXInput = document.createElement('input');
      paddingXInput.type = 'number';
      paddingXInput.min = '0';
      paddingXInput.className = 'template-properties-input';
      paddingXInput.value = comp.meta.paddingX;
      const paddingXField = document.createElement('div');
      paddingXField.className = 'template-properties-field';
      const paddingXLabel = document.createElement('label');
      paddingXLabel.textContent = this.t('email.editor.padding_horizontal', 'Horizontal padding');
      paddingXField.appendChild(paddingXLabel);
      paddingXField.appendChild(paddingXInput);
      row3.appendChild(paddingXField);
      paddingXInput.addEventListener('change', () => {
        comp.meta.paddingX = Number(paddingXInput.value) || comp.meta.paddingX;
        applyChanges();
      });

      const alignSelect = document.createElement('select');
      alignSelect.className = 'template-properties-select';
      ['left', 'center', 'right'].forEach(value => {
        const option = document.createElement('option');
        option.value = value;
        option.textContent = value === 'left'
          ? this.t('email.editor.align_left', 'Left')
          : value === 'center'
            ? this.t('email.editor.align_center', 'Center')
            : this.t('email.editor.align_right', 'Right');
        if (comp.meta.align === value) option.selected = true;
        alignSelect.appendChild(option);
      });
      addField(style, this.t('email.editor.label_alignment', 'Alignment'), alignSelect);
      alignSelect.addEventListener('change', () => {
        comp.meta.align = alignSelect.value;
        applyChanges();
      });
      return;
    }

    if (comp.type === 'link') {
      const labelInput = document.createElement('input');
      labelInput.className = 'template-properties-input';
      labelInput.value = comp.content || this.t('email.editor.default_link', 'Click here');
      addField(basics, this.t('email.editor.link_text', 'Link text'), labelInput);
      labelInput.addEventListener('change', () => {
        comp.content = labelInput.value.trim() || comp.content;
        applyChanges();
      });

      const hrefInput = document.createElement('input');
      hrefInput.className = 'template-properties-input';
      hrefInput.value = comp.meta.href || '';
      addField(basics, this.t('email.editor.link_url', 'Link URL'), hrefInput);
      hrefInput.addEventListener('change', () => {
        comp.meta.href = hrefInput.value.trim();
        applyChanges();
      });

      const style = addSection(this.t('email.editor.section_style', 'Style'));
      const colorInput = document.createElement('input');
      colorInput.type = 'color';
      colorInput.className = 'template-properties-input';
      colorInput.value = comp.meta.color;
      addField(style, this.t('email.editor.label_color', 'Color'), colorInput);
      colorInput.addEventListener('change', () => {
        comp.meta.color = colorInput.value;
        applyChanges();
      });

      const alignSelect = document.createElement('select');
      alignSelect.className = 'template-properties-select';
      ['left', 'center', 'right'].forEach(value => {
        const option = document.createElement('option');
        option.value = value;
        option.textContent = value === 'left'
          ? this.t('email.editor.align_left', 'Left')
          : value === 'center'
            ? this.t('email.editor.align_center', 'Center')
            : this.t('email.editor.align_right', 'Right');
        if (comp.meta.align === value) option.selected = true;
        alignSelect.appendChild(option);
      });
      addField(style, this.t('email.editor.label_alignment', 'Alignment'), alignSelect);
      alignSelect.addEventListener('change', () => {
        comp.meta.align = alignSelect.value;
        applyChanges();
      });
      return;
    }

    if (comp.type === 'image') {
      const srcInput = document.createElement('input');
      srcInput.className = 'template-properties-input';
      srcInput.value = comp.meta.src || '';
      srcInput.placeholder = 'https://';
      addField(basics, this.t('email.editor.image_url', 'Image URL'), srcInput);
      srcInput.addEventListener('change', () => {
        comp.meta.src = srcInput.value.trim();
        applyChanges();
      });

      const hrefInput = document.createElement('input');
      hrefInput.className = 'template-properties-input';
      hrefInput.value = comp.meta.href || '';
      hrefInput.placeholder = 'https://';
      addField(basics, this.t('email.editor.image_link', 'Image link'), hrefInput);
      hrefInput.addEventListener('change', () => {
        comp.meta.href = hrefInput.value.trim();
        applyChanges();
      });

      const uploadSection = addSection(this.t('email.editor.upload', 'Upload'));
      const uploadRow = document.createElement('div');
      uploadRow.className = 'template-properties-action';
      const uploadButton = document.createElement('button');
      uploadButton.type = 'button';
      uploadButton.className = 'template-properties-button';
      uploadButton.textContent = this.t('email.editor.upload_image', 'Upload image');
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = 'image/*';
      fileInput.style.display = 'none';
      uploadRow.appendChild(uploadButton);
      uploadRow.appendChild(fileInput);
      uploadSection.appendChild(uploadRow);
      uploadButton.addEventListener('click', () => {
        fileInput.click();
      });
      fileInput.addEventListener('change', () => {
        const file = fileInput.files && fileInput.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = () => {
          comp.meta.src = reader.result;
          applyChanges();
        };
        reader.readAsDataURL(file);
      });

      const style = addSection(this.t('email.editor.section_style', 'Style'));
      const row = addRow(style);
      const widthInput = document.createElement('input');
      widthInput.className = 'template-properties-input';
      widthInput.value = comp.meta.width || '100%';
      const widthField = document.createElement('div');
      widthField.className = 'template-properties-field';
      const widthLabel = document.createElement('label');
      widthLabel.textContent = this.t('email.editor.width', 'Width');
      widthField.appendChild(widthLabel);
      widthField.appendChild(widthInput);
      row.appendChild(widthField);
      widthInput.addEventListener('change', () => {
        comp.meta.width = widthInput.value.trim() || comp.meta.width;
        applyChanges();
      });

      const radiusInput = document.createElement('input');
      radiusInput.type = 'number';
      radiusInput.min = '0';
      radiusInput.className = 'template-properties-input';
      radiusInput.value = comp.meta.radius;
      const radiusField = document.createElement('div');
      radiusField.className = 'template-properties-field';
      const radiusLabel = document.createElement('label');
      radiusLabel.textContent = this.t('email.editor.radius', 'Radius');
      radiusField.appendChild(radiusLabel);
      radiusField.appendChild(radiusInput);
      row.appendChild(radiusField);
      radiusInput.addEventListener('change', () => {
        comp.meta.radius = Number(radiusInput.value) || comp.meta.radius;
        applyChanges();
      });

      const alignSelect = document.createElement('select');
      alignSelect.className = 'template-properties-select';
      ['left', 'center', 'right'].forEach(value => {
        const option = document.createElement('option');
        option.value = value;
        option.textContent = value === 'left'
          ? this.t('email.editor.align_left', 'Left')
          : value === 'center'
            ? this.t('email.editor.align_center', 'Center')
            : this.t('email.editor.align_right', 'Right');
        if (comp.meta.align === value) option.selected = true;
        alignSelect.appendChild(option);
      });
      addField(style, this.t('email.editor.label_alignment', 'Alignment'), alignSelect);
      alignSelect.addEventListener('change', () => {
        comp.meta.align = alignSelect.value;
        applyChanges();
      });
      return;
    }

    if (comp.type === '2cols' || comp.type === '3cols') {
      const info = document.createElement('div');
      info.className = 'template-properties-info';
      info.innerHTML = `<i class="fas fa-info-circle"></i> ${this.t('email.editor.drop_columns_hint', 'Drag blocks into the columns')}`;
      basics.appendChild(info);

      const style = addSection(this.t('email.editor.section_layout', 'Layout'));
      const gapInput = document.createElement('input');
      gapInput.type = 'number';
      gapInput.min = '0';
      gapInput.className = 'template-properties-input';
      gapInput.value = comp.meta.gap;
      addField(style, this.t('email.editor.gap_between_columns', 'Gap between columns'), gapInput);
      gapInput.addEventListener('change', () => {
        comp.meta.gap = Number(gapInput.value) || comp.meta.gap;
        applyChanges();
      });
      return;
    }
  },

  selectComponent(id) {
    this.deselectAll();
    this.selectedComponent = id;
    const wrapper = this.canvas.querySelector(`[data-id="${id}"]`);
    if (wrapper) {
      wrapper.classList.add('selected');
    }
    this.renderPropertiesPanel();
  },

  deselectAll() {
    this.selectedComponent = null;
    this.canvas.querySelectorAll('.component-wrapper').forEach(w => {
      w.classList.remove('selected');
    });
    this.renderPropertiesPanel();
  },

  getHTML() {
    let html = '';
    this.components.forEach(comp => {
      html += comp.html;
    });
    return html;
  },

  setHTML(html) {
    // Simple parser - just set as one component for now
    if (html) {
      this.components = [{
        id: 'comp-loaded',
        type: 'custom',
        content: html,
        html: html
      }];
      this.render();
    }
  },

  clear() {
    this.components = [];
    this.render();
  }
};

if (typeof window !== 'undefined') {
  window.SimpleEmailEditor = SimpleEmailEditor;
}
