All files / src/components/organizer/Admin EmailTemplatePreviewModal.tsx

100% Statements 25/25
100% Branches 16/16
100% Functions 6/6
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167                                                    1x             8x             8x   7x                 1x 13x 13x 13x 13x   13x   8x 8x 8x   1x         7x   6x 6x       1x         5x     1x     8x     8x     13x   13x                                                                                     11x                                                          
/**
 * EmailTemplatePreviewModal (Story 10.2)
 *
 * Renders a preview of the email template in an iframe.
 * For content templates with layoutKey: fetches layout and merges client-side.
 * For standalone / layout templates: renders htmlBody directly.
 */
 
import React, { useEffect, useState } from 'react';
import {
  Box,
  Chip,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogTitle,
  Divider,
  IconButton,
  Typography,
} from '@mui/material';
import { Close as CloseIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import { emailTemplateService } from '@/services/emailTemplateService';
import type { EmailTemplateResponse } from '@/hooks/useEmailTemplates';
 
const CONTENT_PLACEHOLDER = `
<div style="background:#f0f0f0;border:2px dashed #999;padding:24px;margin:16px;text-align:center;color:#666;font-family:sans-serif;border-radius:4px;">
  [CONTENT AREA]
</div>`;
 
/** Replace system/layout variables with sensible preview values. */
function substitutePreviewVariables(html: string): string {
  const previewValues: Record<string, string> = {
    logoUrl: '/BATbern_white_logo.png',
    currentYear: String(new Date().getFullYear()),
    dashboardLink: '#',
    eventUrl: '#',
    supportUrl: '#',
  };
  return html.replace(
    /\{\{(\w+)\}\}/g,
    (_match, key: string) => previewValues[key] ?? `{{${key}}}`
  );
}
 
interface Props {
  template: EmailTemplateResponse;
  onClose: () => void;
}
 
export const EmailTemplatePreviewModal: React.FC<Props> = ({ template, onClose }) => {
  const { t } = useTranslation();
  const { isMobile } = useBreakpoints();
  const [mergedHtml, setMergedHtml] = useState<string>('');
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    async function buildPreview() {
      setLoading(true);
      try {
        if (template.isLayout) {
          // Replace {{content}} with a visible placeholder, then substitute system vars
          setMergedHtml(
            substitutePreviewVariables(
              template.htmlBody.replace('{{content}}', CONTENT_PLACEHOLDER)
            )
          );
        } else if (template.layoutKey) {
          // Fetch layout and merge
          try {
            const layout = await emailTemplateService.getTemplate(
              template.layoutKey,
              template.locale
            );
            setMergedHtml(
              substitutePreviewVariables(layout.htmlBody.replace('{{content}}', template.htmlBody))
            );
          } catch {
            // Layout not found — show content directly
            setMergedHtml(substitutePreviewVariables(template.htmlBody));
          }
        } else {
          setMergedHtml(substitutePreviewVariables(template.htmlBody));
        }
      } finally {
        setLoading(false);
      }
    }
    buildPreview();
  }, [template]);
 
  const variables = template.variables ? Object.keys(template.variables) : [];
 
  return (
    <Dialog open onClose={onClose} maxWidth="lg" fullWidth fullScreen={isMobile}>
      <DialogTitle
        sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}
      >
        <Box>
          <Typography variant="h6">{t('emailTemplates.preview', 'Preview')}</Typography>
          <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', mt: 0.5 }}>
            <Chip label={template.templateKey} size="small" variant="outlined" />
            <Chip label={template.locale.toUpperCase()} size="small" color="primary" />
            {template.layoutKey && (
              <Chip
                label={`${t('emailTemplates.layoutKey', 'Layout')}: ${template.layoutKey}`}
                size="small"
                color="secondary"
              />
            )}
          </Box>
        </Box>
        <IconButton onClick={onClose} size="small">
          <CloseIcon />
        </IconButton>
      </DialogTitle>
 
      <DialogContent dividers>
        {template.subject && (
          <Box sx={{ mb: 2 }}>
            <Typography variant="caption" color="text.secondary">
              {t('emailTemplates.subject', 'Subject')}:
            </Typography>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>
              {template.subject}
            </Typography>
          </Box>
        )}
 
        {variables.length > 0 && (
          <Box sx={{ mb: 2 }}>
            <Typography variant="caption" color="text.secondary">
              {t('emailTemplates.variables', 'Available Variables')}:
            </Typography>
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mt: 0.5 }}>
              {variables.map((v) => (
                <Chip key={v} label={`{{${v}}}`} size="small" variant="outlined" />
              ))}
            </Box>
          </Box>
        )}
 
        <Divider sx={{ mb: 2 }} />
 
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
            <CircularProgress />
          </Box>
        ) : (
          <iframe
            srcDoc={mergedHtml}
            sandbox="allow-same-origin"
            title={t('emailTemplates.previewTitle', 'Email Preview')}
            style={{
              width: '100%',
              height: '600px',
              border: '1px solid #e0e0e0',
              borderRadius: 4,
            }}
          />
        )}
      </DialogContent>
    </Dialog>
  );
};