import React, { useState, useEffect } from 'react'; import { ArrowLeft, Save, Plus, Trash2, Settings2, Eye, Layout, Type, Image as ImageIcon, MousePointer2, Minus } from 'lucide-react'; const EmailDesigner = ({ template, onBack }) => { const [name, setName] = useState(template?.name || 'Untitled Template'); const [subject, setSubject] = useState(template?.subject || ''); const [blocks, setBlocks] = useState(() => { if (template?.body_json) { try { return JSON.parse(template.body_json); } catch (e) { console.error('Failed to parse body_json:', e); } } return [ { id: '1', type: 'text', content: '

Welcome to our Newsletter!

Start designing your beautiful email here.

' } ]; }); const [selectedBlockId, setSelectedBlockId] = useState(null); const [saving, setSaving] = useState(false); const [uploadingImage, setUploadingImage] = useState(false); const [uploadError, setUploadError] = useState(null); const [showPreview, setShowPreview] = useState(false); const blockTypes = [ { type: 'text', icon: Type, label: 'Text Block' }, { type: 'button', icon: MousePointer2, label: 'Button' }, { type: 'image', icon: ImageIcon, label: 'Image' }, { type: 'divider', icon: Minus, label: 'Divider' }, { type: 'spacer', icon: Layout, label: 'Spacer' }, ]; const addBlock = (type) => { let content = ''; let styles = {}; switch (type) { case 'text': content = '

Enter your text here...

'; break; case 'button': content = 'Click Me'; styles = { backgroundColor: '#3b82f6', color: '#ffffff', padding: '12px 24px', borderRadius: '6px', url: '#' }; break; case 'image': content = 'https://via.placeholder.com/600x300?text=Your+Image'; break; case 'divider': content = ''; styles = { borderTop: '1px solid #e5e7eb', margin: '20px 0' }; break; case 'spacer': styles = { height: '30px' }; break; } const newBlock = { id: Math.random().toString(36).substr(2, 9), type, content, styles }; setBlocks([...blocks, newBlock]); setSelectedBlockId(newBlock.id); }; const removeBlock = (id) => { setBlocks(blocks.filter(b => b.id !== id)); if (selectedBlockId === id) setSelectedBlockId(null); }; const updateBlock = (id, updates) => { setBlocks(blocks.map(b => b.id === id ? { ...b, ...updates } : b)); }; const getMediaApiUrl = () => { if (!window.wpbotAutomator?.apiUrl) { return '/wp-json/wp/v2/media'; } try { const apiUrl = new URL(window.wpbotAutomator.apiUrl); const mediaPath = apiUrl.pathname.replace(/\/wpbot-automator\/v1\/?$/, '/wp/v2/'); return `${apiUrl.origin}${mediaPath}media`; } catch (error) { return '/wp-json/wp/v2/media'; } }; const uploadImageFile = async (file) => { if (!file) { return null; } setUploadingImage(true); setUploadError(null); try { const formData = new FormData(); formData.append('file', file); const response = await fetch(getMediaApiUrl(), { method: 'POST', headers: { 'X-WP-Nonce': window.wpbotAutomator.nonce, }, body: formData, }); const result = await response.json(); if (!response.ok || !result?.source_url) { throw new Error(result?.message || 'Failed to upload image'); } if (selectedBlockId) { updateBlock(selectedBlockId, { content: result.source_url }); } return result.source_url; } catch (error) { console.error('Image upload failed:', error); setUploadError(error.message || 'Failed to upload image.'); return null; } finally { setUploadingImage(false); } }; const handleImageFileChange = async (event) => { const file = event.target.files?.[0]; if (!file) { return; } await uploadImageFile(file); event.target.value = ''; }; const handleSave = async () => { setSaving(true); const html = generateHTML(); const data = { name, subject, body_html: html, body_json: JSON.stringify(blocks) }; try { const baseUrl = window.wpbotAutomator.apiUrl.replace(/\/$/, ''); const url = template?.id ? `${baseUrl}/email-templates/${template.id}` : `${baseUrl}/email-templates`; const response = await fetch(url, { method: template?.id ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': window.wpbotAutomator.nonce, }, body: JSON.stringify(data), }); const result = await response.json(); if (result.success) { alert('Template saved successfully!'); if (!template?.id) onBack(); // Go back if it was new } else { alert(result.message || 'Failed to save template.'); } } catch (error) { console.error('Error saving template:', error); } finally { setSaving(false); } }; const generateHTML = () => { let html = `
`; blocks.forEach(block => { switch (block.type) { case 'text': html += `
${block.content}
`; break; case 'button': const s = block.styles; html += `
${block.content}
`; break; case 'image': html += `
Image
`; break; case 'divider': html += `
`; break; case 'spacer': html += `
`; break; } }); html += `
Sent by ${window.wpbotAutomator.blogname || 'Our Website'}
`; return html; }; const selectedBlock = blocks.find(b => b.id === selectedBlockId); return (
{/* Header */}
setName(e.target.value)} className="text-xl font-bold bg-transparent border-none focus:ring-0 p-0 hover:bg-muted/50 rounded px-2 cursor-text transition-colors" />
Subject: setSubject(e.target.value)} placeholder="Enter email subject..." className="text-xs text-primary bg-transparent border-none focus:ring-0 p-0 w-64 placeholder:text-muted-foreground/50" />
{showPreview ? (