# 🎯 DanakMail Template Builder MVP - Implementation Plan

## 📋 Executive Summary

This MVP combines the best features of Waypoint's template builder with your current Persian email template system to create a powerful, RTL-compatible email template builder.

## 🎨 Key Features to Implement

### Phase 1: Core Block System (Week 1-2)
- ✅ **Text Block**: Rich text editing with Persian support
- ✅ **Button Block**: Customizable CTAs with styling
- ✅ **Image Block**: Upload/URL with responsive options
- ✅ **Container Block**: Layout wrapper with styling
- ✅ **Spacer Block**: Vertical spacing control

### Phase 2: Drag & Drop Interface (Week 3-4)
- 🔄 **Block Library**: Sidebar with draggable blocks
- 🔄 **Canvas Area**: Drop zone for template building
- 🔄 **Block Management**: Add, remove, reorder blocks
- 🔄 **Properties Panel**: Context-sensitive editing

### Phase 3: Template Variables (Week 5-6)
- 📝 **Variable System**: Dynamic content placeholders
- 📝 **Test Data**: Preview with sample data
- 📝 **Conditional Logic**: Show/hide based on data
- 📝 **Loop Support**: Repeat blocks with arrays

### Phase 4: Export & Preview (Week 7-8)
- 📤 **HTML Export**: Email-compatible HTML
- 📤 **Live Preview**: Real-time template preview
- 📤 **Mobile Preview**: Responsive design testing
- 📤 **Email Client Testing**: Gmail, Outlook compatibility

## 🏗️ Architecture Overview

```
src/
├── pages/
│   └── email-builder/
│       ├── EmailBuilder.tsx          # Main builder interface
│       ├── components/
│       │   ├── blocks/               # Block components
│       │   │   ├── TextBlock.tsx
│       │   │   ├── ButtonBlock.tsx
│       │   │   ├── ImageBlock.tsx
│       │   │   ├── ContainerBlock.tsx
│       │   │   └── SpacerBlock.tsx
│       │   ├── panels/               # Side panels
│       │   │   ├── BlockLibrary.tsx
│       │   │   ├── PropertiesPanel.tsx
│       │   │   └── VariablesPanel.tsx
│       │   ├── canvas/               # Canvas area
│       │   │   ├── Canvas.tsx
│       │   │   ├── DropZone.tsx
│       │   │   └── BlockRenderer.tsx
│       │   └── preview/              # Preview system
│       │       ├── LivePreview.tsx
│       │       ├── MobilePreview.tsx
│       │       └── EmailPreview.tsx
│       ├── hooks/
│       │   ├── useEmailBuilder.ts
│       │   ├── useDragDrop.ts
│       │   └── useTemplateExport.ts
│       ├── store/
│       │   ├── builderStore.ts
│       │   └── templatesStore.ts
│       ├── types/
│       │   ├── blocks.ts
│       │   ├── template.ts
│       │   └── export.ts
│       └── utils/
│           ├── blockRenderers.ts
│           ├── htmlExporter.ts
│           └── templateValidator.ts
```

## 🔧 Technical Implementation

### 1. Block Interface Definition

```typescript
// src/pages/email-builder/types/blocks.ts
interface BaseBlock {
  id: string
  type: BlockType
  data: BlockData
  style: BlockStyle
  responsive?: ResponsiveSettings
}

interface TextBlock extends BaseBlock {
  type: 'text'
  data: {
    content: string
    variables?: string[]
  }
  style: {
    fontSize: number
    fontWeight: string
    color: string
    textAlign: 'left' | 'center' | 'right'
    lineHeight: number
  }
}

interface ButtonBlock extends BaseBlock {
  type: 'button'
  data: {
    text: string
    url: string
    variables?: string[]
  }
  style: {
    backgroundColor: string
    textColor: string
    borderRadius: number
    padding: Spacing
    fontSize: number
  }
}
```

### 2. Drag & Drop Implementation

```typescript
// src/pages/email-builder/hooks/useDragDrop.ts
import { useDragDropManager } from '@dnd-kit/core'

export const useDragDrop = () => {
  const { addBlock, moveBlock, removeBlock } = useEmailBuilderStore()
  
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    
    if (active.data.current?.type === 'library-block') {
      // Add new block from library
      addBlock(active.data.current.blockType, over?.id)
    } else if (active.data.current?.type === 'canvas-block') {
      // Reorder existing blocks
      moveBlock(active.id, over?.id)
    }
  }
  
  return { handleDragEnd }
}
```

### 3. Template Variable System

```typescript
// src/pages/email-builder/utils/templateProcessor.ts
export const processTemplate = (template: Template, variables: Record<string, any>) => {
  return template.blocks.map(block => {
    switch (block.type) {
      case 'text':
        return {
          ...block,
          data: {
            ...block.data,
            content: replaceVariables(block.data.content, variables)
          }
        }
      case 'button':
        return {
          ...block,
          data: {
            ...block.data,
            text: replaceVariables(block.data.text, variables),
            url: replaceVariables(block.data.url, variables)
          }
        }
      default:
        return block
    }
  })
}

const replaceVariables = (content: string, variables: Record<string, any>) => {
  return content.replace(/\{\{(\w+)\}\}/g, (match, key) => {
    return variables[key] || match
  })
}
```

### 4. HTML Export System

```typescript
// src/pages/email-builder/utils/htmlExporter.ts
export const exportToHTML = (template: Template, options: ExportOptions) => {
  const styles = generateEmailStyles(template, options)
  const bodyHTML = renderBlocks(template.blocks, options)
  
  return `
    <!DOCTYPE html>
    <html dir="${options.rtlSupport ? 'rtl' : 'ltr'}">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>${template.name}</title>
      ${styles}
    </head>
    <body>
      <table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td align="center">
            <table width="600" cellpadding="0" cellspacing="0" border="0">
              ${bodyHTML}
            </table>
          </td>
        </tr>
      </table>
    </body>
    </html>
  `
}
```

## 📊 Comparison Matrix

| Feature | Current System | Waypoint | MVP Target |
|---------|---------------|----------|------------|
| RTL Support | ✅ Full | ❌ None | ✅ Full |
| Drag & Drop | ❌ None | ✅ Full | ✅ Full |
| Block System | ⚠️ Limited | ✅ Rich | ✅ Rich |
| Variables | ❌ None | ✅ LiquidJS | ✅ Simple |
| Email Client Support | ⚠️ Basic | ✅ Full | ✅ Full |
| Persian UI | ✅ Full | ❌ None | ✅ Full |
| Template Library | ✅ Basic | ✅ Rich | ✅ Rich |
| Live Preview | ⚠️ Basic | ✅ Advanced | ✅ Advanced |

## 🚀 Development Timeline

### Week 1-2: Foundation
- [ ] Setup new email builder structure
- [ ] Implement basic block types
- [ ] Create block components
- [ ] Setup Zustand store

### Week 3-4: Drag & Drop
- [ ] Install @dnd-kit/core
- [ ] Implement block library sidebar
- [ ] Create canvas drop zone
- [ ] Add block management

### Week 5-6: Advanced Features
- [ ] Template variables system
- [ ] Properties panel
- [ ] Test data scenarios
- [ ] Conditional rendering

### Week 7-8: Export & Polish
- [ ] HTML export optimization
- [ ] Email client testing
- [ ] Mobile responsive preview
- [ ] Performance optimization

## 💻 Getting Started

1. **Install Dependencies**:
```bash
npm install @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities
npm install react-beautiful-dnd @types/react-beautiful-dnd
```

2. **Update Store Structure**:
```typescript
// Extend existing personality store
interface EmailBuilderStore extends PersonalityStore {
  blocks: Block[]
  template: Template
  variables: TemplateVariable[]
  addBlock: (type: BlockType, position?: number) => void
  updateBlock: (id: string, updates: Partial<Block>) => void
  removeBlock: (id: string) => void
}
```

3. **Migration Path**:
- Keep existing personality system
- Add new email builder alongside
- Gradually migrate users to new system
- Maintain backward compatibility

## 🎯 Success Metrics

- **User Adoption**: 80% of users try new builder within first month
- **Template Creation Time**: 50% reduction compared to current system
- **Email Compatibility**: 99% rendering across major clients
- **Mobile Responsiveness**: Perfect rendering on all devices
- **Persian RTL Support**: Flawless right-to-left layout

## 🔮 Future Enhancements (Post-MVP)

1. **AI-Powered Templates**: Generate templates from text descriptions
2. **Collaboration**: Real-time editing with team members
3. **Analytics**: Template performance tracking
4. **A/B Testing**: Compare template variants
5. **Animation Support**: CSS animations for email elements
6. **Component Library**: Reusable design system components

---

*This MVP plan provides a clear roadmap to build a world-class email template builder that combines Waypoint's advanced features with your system's Persian/RTL strengths.* 