/**
 * Email Preview Frame Component
 * Renders a live preview of the email template with applied styles.
 *
 * When a `body` prop is supplied (e.g. Email Verification) the preview
 * renders that text instead of the default subscription sample content.
 * Placeholders like {{user_name}} are swapped for sample values and
 * {{verification_link}} becomes a CTA button.
 */

import { useMemo } from 'react';
import type { EmailCustomizerSettings, DevicePreview } from '../types';
import type { ProductCardConfig, CouponDisplayConfig } from '../sections';
import { getGoogleFontLinkTag } from '../types';

interface EmailPreviewFrameProps {
  settings: EmailCustomizerSettings;
  device: DevicePreview;
  darkMode?: boolean;
  emailType?: string;
  heading?: string;
  /** Optional user-editable body text (with placeholders). */
  body?: string;
  preheaderText?: string;
  additionalContent?: string;
  /** Optional product card config for product-oriented emails. */
  productCard?: ProductCardConfig;
  /** Optional coupon display config for recovery emails. */
  couponDisplay?: CouponDisplayConfig;
}

// ---------------------------------------------------------------------------
// Sample content per email type (subscription defaults)
// ---------------------------------------------------------------------------

function getEmailTypeContent(emailType: string) {
  const emailContents: Record<string, { intro: string; body: string; alert?: { type: string; message: string }; buttonText: string }> = {
    new_subscription: {
      intro: 'Thank you for subscribing!',
      body: 'Your subscription for <strong>Premium Membership</strong> has been created successfully. Your first billing date is <strong>January 15, 2025</strong>.',
      buttonText: 'View Subscription',
    },
    subscription_activated: {
      intro: 'Great news!',
      body: 'Your subscription for <strong>Premium Membership</strong> is now active. Your next billing date is <strong>February 15, 2025</strong>.',
      buttonText: 'View Subscription',
    },
    subscription_cancelled: {
      intro: 'We\'re sorry to see you go.',
      body: 'Your subscription for <strong>Premium Membership</strong> has been cancelled as requested. You will continue to have access until <strong>January 15, 2025</strong>.',
      alert: { type: 'warning', message: 'Access expires: January 15, 2025' },
      buttonText: 'Resubscribe',
    },
    subscription_expired: {
      intro: 'Your subscription period has ended.',
      body: 'Your subscription for <strong>Premium Membership</strong> has expired. To continue enjoying our services, please renew your subscription.',
      alert: { type: 'error', message: 'Subscription expired' },
      buttonText: 'Renew Subscription',
    },
    subscription_on_hold: {
      intro: 'Your subscription has been paused.',
      body: 'Your subscription for <strong>Premium Membership</strong> is currently on hold. This may be due to a payment issue or at your request.',
      alert: { type: 'warning', message: 'Your access is temporarily suspended' },
      buttonText: 'Manage Subscription',
    },
    renewal_reminder: {
      intro: 'This is a friendly reminder.',
      body: 'Your subscription for <strong>Premium Membership</strong> will automatically renew on <strong>January 15, 2025</strong> for <strong>$29.99</strong>.',
      alert: { type: 'info', message: 'Renewal Date: January 15, 2025 • Amount: $29.99' },
      buttonText: 'Manage Subscription',
    },
    trial_ending: {
      intro: 'Your trial period is almost over.',
      body: 'Your free trial for <strong>Premium Membership</strong> ends on <strong>January 15, 2025</strong>. After that, your subscription will begin billing at <strong>$29.99</strong> automatically.',
      alert: { type: 'info', message: 'Trial ends: January 15, 2025' },
      buttonText: 'Manage Subscription',
    },
    payment_failed: {
      intro: 'We were unable to process your payment.',
      body: 'The renewal payment for your <strong>Premium Membership</strong> subscription has failed. Please update your payment method to avoid service interruption.',
      alert: { type: 'error', message: '⚠ Payment failed - action required' },
      buttonText: 'Update Payment Method',
    },
    payment_retry: {
      intro: 'We are retrying your payment.',
      body: 'We will attempt to process your payment for <strong>Premium Membership</strong> again shortly. No action is required at this time.',
      alert: { type: 'info', message: 'Next retry: Tomorrow at 9:00 AM' },
      buttonText: 'View Payment Details',
    },
  };

  return emailContents[emailType] || emailContents.subscription_activated;
}

// ---------------------------------------------------------------------------
// Process a user-editable body template for preview
// ---------------------------------------------------------------------------

/** Sample values used to replace common placeholders in the preview. */
const samplePlaceholders: Record<string, string> = {
  '{{user_name}}': 'John',
  '{{user_email}}': 'john@example.com',
  '{{site_name}}': 'Your Store',
  '{{site_url}}': 'https://yourstore.com',
  '{{expiry_time}}': '24 hours',
  '{customer_name}': 'John Doe',
  '{customer_full_name}': 'John Doe',
  '{order_number}': '1024',
  '{order_id}': '1024',
  '{tracking_number}': '1234567890123456',
  '{carrier}': 'FedEx',
  '{date_shipped}': 'June 18, 2026',
  '{estimated_delivery_date}': 'June 21, 2026',
  '{tracking_url}': '#',
  '{site_name}': 'Your Store',
  '{site_url}': 'https://yourstore.com',
  '{product_count}': '2',
  '{wishlist_url}': '#',
  '{product_name}': 'Blue Running Shoes',
  '{product_price}': '$49.99',
  '{product_url}': '#',
  '{customer_email}': 'john@example.com',
};

/**
 * Convert plain-text body with placeholders into HTML for the preview pane.
 * - Known placeholders are replaced with sample values.
 * - `{{verification_link}}` becomes a styled CTA button.
 * - Double newlines become paragraph breaks; single newlines become `<br>`.
 */
function processBodyForPreview(
  body: string,
  buttonBg: string,
  buttonText: string,
  borderRadius: number,
  fontSize: number,
  textColor: string,
): string {
  let text = body;

  // Replace known placeholders (except verification_link).
  for (const [tag, val] of Object.entries(samplePlaceholders)) {
    text = text.split(tag).join(val);
  }

  const pStyle = `font-size: ${fontSize}px; color: ${textColor}; margin: 0 0 16px 0;`;

  // Split into paragraphs on double-newline.
  const paragraphs = text.split(/\n\n+/);

  return paragraphs
    .map((p) => {
      const trimmed = p.trim();
      if (!trimmed) return '';

      // Render {{verification_link}} as a CTA button.
      if (trimmed === '{{verification_link}}') {
        return `
          <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 8px 0 24px 0;">
            <tr>
              <td align="center">
                <a href="#" style="display: inline-block; background-color: ${buttonBg}; color: ${buttonText}; padding: 12px 24px; font-size: ${fontSize}px; font-weight: 600; text-decoration: none; border-radius: ${borderRadius}px;">
                  Verify Email Address
                </a>
              </td>
            </tr>
          </table>`;
      }

      // Normal paragraph — single newlines become <br>.
      const withBr = trimmed.replace(/\n/g, '<br>');
      return `<p style="${pStyle}">${withBr}</p>`;
    })
    .filter(Boolean)
    .join('\n');
}

export function EmailPreviewFrame({
  settings,
  device,
  darkMode = false,
  emailType = 'subscription_activated',
  heading = 'Your Subscription is Active',
  body,
  preheaderText = '',
  additionalContent = '',
  productCard,
  couponDisplay,
}: EmailPreviewFrameProps) {
  const { logo, colors, typography, layout, footer, table } = settings;

  // Should we render the user-editable body instead of subscription sample?
  const useCustomBody = body !== undefined;

  // Calculate container width based on device
  const containerWidth = device === 'mobile' ? 320 : layout.containerWidth;

  // Dark mode color overrides - simulates how email clients render in dark mode
  const darkModeColors = darkMode ? {
    bodyBackground: '#1a1a1a',
    headerBackground: '#2d2d2d',
    contentBackground: '#262626',
    primaryText: '#e5e5e5',
    secondaryText: '#a3a3a3',
    borderColor: '#404040',
  } : null;

  // Get plugin URL for local assets
  const pluginUrl = window.swiftCommerceData?.pluginUrl || '';
  const iconBaseUrl = `${pluginUrl}assets/img/icons/`;

  // Get content based on email type
  const emailContent = getEmailTypeContent(emailType);

  // Process custom body for preview if provided.
  const processedBody = useCustomBody
    ? processBodyForPreview(
        body,
        colors.buttonBackground,
        colors.buttonText,
        layout.borderRadius,
        typography.bodySize,
        darkModeColors?.primaryText ?? colors.primaryText,
      )
    : null;

  // Build product card HTML for preview if provided.
  const productCardHTML = useMemo(() => {
    if (!productCard || !useCustomBody) return '';
    const { showImage, showTitle, showPrice, buttonText, sample } = productCard;
    if (!showImage && !showTitle && !showPrice) {
      // Still show the CTA button even without product details.
      return `
        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 24px 0;">
          <tr>
            <td align="center">
              <a href="${sample.productUrl || '#'}" style="display: inline-block; background-color: ${colors.buttonBackground}; color: ${colors.buttonText}; padding: 14px 32px; font-size: ${typography.bodySize}px; font-weight: 600; text-decoration: none; border-radius: ${layout.borderRadius}px;">
                ${buttonText}
              </a>
            </td>
          </tr>
        </table>`;
    }

    const placeholderImg = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 200 200'%3E%3Crect fill='%23f3f4f6' width='200' height='200'/%3E%3Cpath d='M70 130l30-50 30 50' fill='none' stroke='%23d1d5db' stroke-width='4' stroke-linejoin='round'/%3E%3Cpath d='M95 130l12-20 12 20' fill='none' stroke='%23d1d5db' stroke-width='4' stroke-linejoin='round'/%3E%3Ccircle cx='78' cy='82' r='8' fill='%23d1d5db'/%3E%3C/svg%3E";
    const imageUrl = sample.imageUrl || placeholderImg;
    const cardBg = darkModeColors ? '#303030' : '#f9fafb';
    const titleColor = darkModeColors?.primaryText ?? '#1f2937';
    const priceColor = colors.buttonBackground;

    let cardInner = '';

    // Image cell.
    if (showImage) {
      cardInner += `
        <td style="padding: 20px; width: 120px; vertical-align: top;">
          <a href="${sample.productUrl || '#'}">
            <img src="${imageUrl}" alt="${sample.name}" style="width: 100px; height: 100px; object-fit: cover; border-radius: 8px; display: block;" />
          </a>
        </td>`;
    }

    // Details cell.
    let detailsContent = '';
    if (showTitle) {
      detailsContent += `<h2 style="margin: 0 0 8px; font-family: ${typography.fontFamily}; font-size: 18px; font-weight: 600; color: ${titleColor};"><a href="${sample.productUrl || '#'}" style="color: ${titleColor}; text-decoration: none;">${sample.name}</a></h2>`;
    }
    if (showPrice) {
      detailsContent += `<p style="margin: 0; font-family: ${typography.fontFamily}; font-size: 16px; color: ${priceColor}; font-weight: 600;">${sample.price}</p>`;
    }
    if (detailsContent) {
      cardInner += `<td style="padding: 20px; vertical-align: middle;">${detailsContent}</td>`;
    }

    let html = `
      <table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="background-color: ${cardBg}; border-radius: 8px; margin: 24px 0;">
        <tr>${cardInner}</tr>
      </table>`;

    // CTA button.
    html += `
      <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 24px 0;">
        <tr>
          <td align="center">
            <a href="${sample.productUrl || '#'}" style="display: inline-block; background-color: ${colors.buttonBackground}; color: ${colors.buttonText}; padding: 14px 32px; font-size: ${typography.bodySize}px; font-weight: 600; text-decoration: none; border-radius: ${layout.borderRadius}px;">
              ${buttonText}
            </a>
          </td>
        </tr>
      </table>`;

    return html;
  }, [productCard, useCustomBody, colors, typography, layout, darkModeColors]);

  // Build coupon display HTML for preview if provided.
  const couponDisplayHTML = useMemo(() => {
    if (!couponDisplay || !useCustomBody) return '';
    const msg = couponDisplay.messageText || 'Use code {coupon_code} at checkout for a special discount!';
    const parts = msg.split('{coupon_code}');
    const codeHtml = `<code style="background: ${couponDisplay.codeBgColor}; padding: 2px 8px; border-radius: 4px;">${(settings as any)._couponPrefix || 'RECOVER'}-A1B2C3D4</code>`;
    const messageHtml = parts.join(codeHtml);

    return `
      <div style="background: ${couponDisplay.boxBgColor}; border: 1px solid ${couponDisplay.boxBorderColor}; border-radius: 8px; padding: 16px; text-align: center; margin: 16px 0;">
        <p style="margin: 0; font-weight: 600; color: ${couponDisplay.boxTextColor}; font-size: ${typography.bodySize}px;">
          ${messageHtml}
        </p>
    </div>`;
  }, [couponDisplay, useCustomBody, typography, settings]);

  // Build shipment tracking sample block for tracking notification emails.
  const shipmentTrackingHTML = useMemo(() => {
    if (!useCustomBody || emailType !== 'shipment_tracking') return '';

    const trackingBlockColors = darkMode ? {
      headerBackground: '#2d2d2d',
      borderColor: '#404040',
    } : {
      headerBackground: table.headerBackground,
      borderColor: table.borderColor,
    };

    return `
      <div style="margin: 24px 0; padding: 20px; background: ${trackingBlockColors.headerBackground}; border: 1px solid ${trackingBlockColors.borderColor}; border-radius: ${layout.borderRadius}px;">
        <h3 style="font-size: ${typography.bodySize + 2}px; color: ${darkModeColors?.primaryText ?? colors.primaryText}; margin: 0 0 14px 0;">Tracking Information</h3>
        <p style="font-size: ${typography.bodySize}px; color: ${darkModeColors?.primaryText ?? colors.primaryText}; margin: 0 0 8px 0;"><strong>Carrier:</strong> FedEx</p>
        <p style="font-size: ${typography.bodySize}px; color: ${darkModeColors?.primaryText ?? colors.primaryText}; margin: 0 0 8px 0;"><strong>Tracking Number:</strong> 1234567890123456</p>
        <p style="font-size: ${typography.bodySize}px; color: ${darkModeColors?.primaryText ?? colors.primaryText}; margin: 0 0 8px 0;"><strong>Ship Date:</strong> June 18, 2026</p>
        <p style="font-size: ${typography.bodySize}px; color: ${darkModeColors?.primaryText ?? colors.primaryText}; margin: 0;"><strong>Estimated Delivery:</strong> June 21, 2026</p>
        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 18px 0 0 0;">
          <tr>
            <td>
              <a href="#" style="display: inline-block; background-color: ${colors.buttonBackground}; color: ${colors.buttonText}; padding: 12px 24px; font-size: ${typography.bodySize}px; font-weight: 600; text-decoration: none; border-radius: ${layout.borderRadius}px;">Track Your Package</a>
            </td>
          </tr>
        </table>
      </div>`;
  }, [useCustomBody, emailType, darkMode, table, layout, typography, darkModeColors, colors]);

  const wishlistProductsHTML = useMemo(() => {
    if (!useCustomBody || !['wishlist_on_sale', 'wishlist_back_in_stock'].includes(emailType)) {
      return '';
    }

    const effectiveTable = darkMode ? {
      headerBackground: '#2d2d2d',
      headerTextColor: '#e5e5e5',
      rowBackground: '#262626',
      alternateRowBackground: '#303030',
      borderColor: '#404040',
    } : {
      headerBackground: table.headerBackground,
      headerTextColor: table.headerTextColor,
      rowBackground: table.rowBackground,
      alternateRowBackground: table.alternateRowBackground,
      borderColor: table.borderColor,
    };

    const sampleProducts = emailType === 'wishlist_on_sale'
      ? [
          { name: 'Ceramic Dinner Plate', price: '$29.99', url: '#' },
          { name: 'Handmade Coffee Mug', price: '$18.00', url: '#' },
        ]
      : [
          { name: 'Stoneware Serving Bowl', price: '$42.00', url: '#' },
          { name: 'Matte Glaze Vase', price: '$36.00', url: '#' },
        ];

    const rows = sampleProducts.map((product, index) => `
      <tr style="background-color: ${index % 2 === 0 ? effectiveTable.rowBackground : effectiveTable.alternateRowBackground};">
        <td style="padding: ${table.cellPadding}px; font-size: ${typography.bodySize}px; color: ${darkModeColors?.primaryText ?? colors.primaryText}; border-bottom: 1px solid ${effectiveTable.borderColor};">
          <a href="${product.url}" style="color: ${colors.linkColor}; text-decoration: none;">${product.name}</a>
        </td>
        <td style="padding: ${table.cellPadding}px; text-align: right; font-size: ${typography.bodySize}px; color: ${darkModeColors?.primaryText ?? colors.primaryText}; border-bottom: 1px solid ${effectiveTable.borderColor};">
          ${product.price}
        </td>
      </tr>
    `).join('');

    return `
      <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 24px 0; border: 1px solid ${effectiveTable.borderColor}; border-radius: ${layout.borderRadius}px; overflow: hidden;">
        <tr style="background-color: ${effectiveTable.headerBackground};">
          <th style="padding: ${table.cellPadding}px; text-align: left; font-size: ${typography.bodySize}px; color: ${effectiveTable.headerTextColor}; border-bottom: 1px solid ${effectiveTable.borderColor}; font-weight: ${table.headerFontWeight};">Product</th>
          <th style="padding: ${table.cellPadding}px; text-align: right; font-size: ${typography.bodySize}px; color: ${effectiveTable.headerTextColor}; border-bottom: 1px solid ${effectiveTable.borderColor}; font-weight: ${table.headerFontWeight};">Price</th>
        </tr>
        ${rows}
      </table>
      <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 24px 0;">
        <tr>
          <td align="center">
            <a href="#" style="display: inline-block; background-color: ${colors.buttonBackground}; color: ${colors.buttonText}; padding: 12px 24px; font-size: ${typography.bodySize}px; font-weight: 600; text-decoration: none; border-radius: ${layout.borderRadius}px;">View Wishlist</a>
          </td>
        </tr>
      </table>
    `;
  }, [useCustomBody, emailType, darkMode, table, typography, darkModeColors, colors, layout]);

  // Generate the email HTML for preview
  const emailHTML = useMemo(() => {
    const socialLinksHTML = footer.showSocialLinks
      ? `
        <div class="email-social-links" style="text-align: center; margin-top: 16px;">
          ${footer.socialLinks.facebook ? `<a href="${footer.socialLinks.facebook}" style="display: inline-block; margin: 0 8px;"><img src="${iconBaseUrl}facebook.png" alt="Facebook" width="24" height="24" /></a>` : ''}
          ${footer.socialLinks.twitter ? `<a href="${footer.socialLinks.twitter}" style="display: inline-block; margin: 0 8px;"><img src="${iconBaseUrl}twitter.png" alt="Twitter" width="24" height="24" /></a>` : ''}
          ${footer.socialLinks.instagram ? `<a href="${footer.socialLinks.instagram}" style="display: inline-block; margin: 0 8px;"><img src="${iconBaseUrl}instagram.png" alt="Instagram" width="24" height="24" /></a>` : ''}
          ${footer.socialLinks.linkedin ? `<a href="${footer.socialLinks.linkedin}" style="display: inline-block; margin: 0 8px;"><img src="${iconBaseUrl}linkedin.png" alt="LinkedIn" width="24" height="24" /></a>` : ''}
          ${footer.socialLinks.youtube ? `<a href="${footer.socialLinks.youtube}" style="display: inline-block; margin: 0 8px;"><img src="${iconBaseUrl}youtube.png" alt="YouTube" width="24" height="24" /></a>` : ''}
        </div>
      `
      : '';

    const copyrightText = footer.copyrightText
      .replace('{year}', new Date().getFullYear().toString())
      .replace('{site_name}', 'Your Store')
      .replace('{site_url}', 'https://yourstore.com');

    // Apply dark mode overrides
    const effectiveColors = {
      ...colors,
      ...(darkModeColors || {}),
    };

    // Generate alert HTML if exists
    const alertColors: Record<string, { bg: string; border: string; text: string }> = darkMode 
      ? {
          info: { bg: '#1e3a5f', border: '#2196f3', text: '#90caf9' },
          warning: { bg: '#4a3000', border: '#ff9800', text: '#ffcc80' },
          error: { bg: '#4a1515', border: '#f44336', text: '#ef9a9a' },
        }
      : {
          info: { bg: '#e3f2fd', border: '#2196f3', text: '#1565c0' },
          warning: { bg: '#fff3e0', border: '#ff9800', text: '#e65100' },
          error: { bg: '#ffebee', border: '#f44336', text: '#c62828' },
        };
    
    const alertHTML = emailContent.alert
      ? `<div style="background-color: ${alertColors[emailContent.alert.type]?.bg || alertColors.info.bg}; border: 1px solid ${alertColors[emailContent.alert.type]?.border || alertColors.info.border}; border-radius: ${layout.borderRadius}px; padding: 12px 16px; margin-bottom: 24px; color: ${alertColors[emailContent.alert.type]?.text || alertColors.info.text}; font-size: ${typography.bodySize}px;">
          ${emailContent.alert.message}
        </div>`
      : '';

    // Table colors for dark mode
    const effectiveTableColors = darkMode ? {
      headerBackground: '#2d2d2d',
      headerTextColor: '#e5e5e5',
      rowBackground: '#262626',
      alternateRowBackground: '#303030',
      borderColor: '#404040',
    } : table;

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        ${preheaderText ? `<meta name="x-apple-disable-message-reformatting">` : ''}
        ${getGoogleFontLinkTag(typography.fontFamily)}
        <style>
          * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
          }
          body {
            font-family: ${typography.fontFamily};
            font-size: ${typography.bodySize}px;
            line-height: ${typography.lineHeight};
            color: ${effectiveColors.primaryText};
            background-color: ${effectiveColors.bodyBackground};
            -webkit-font-smoothing: antialiased;
          }
          a {
            color: ${colors.linkColor};
            text-decoration: none;
          }
          a:hover {
            text-decoration: underline;
          }
        </style>
      </head>
      <body>
        ${preheaderText ? `<div style="display:none;font-size:1px;color:#ffffff;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;">${preheaderText}</div>` : ''}
        
        <div class="email-wrapper" style="background-color: ${effectiveColors.bodyBackground}; padding: 20px 0;">
          <table width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr>
              <td align="center">
                <table class="email-container" width="${containerWidth}" cellpadding="0" cellspacing="0" border="0" style="max-width: ${containerWidth}px;">
                  
                  <!-- Header -->
                  <tr>
                    <td class="email-header" style="background-color: ${effectiveColors.headerBackground}; padding: ${layout.contentPadding / 2}px; text-align: ${logo.alignment}; border-radius: ${layout.borderRadius}px ${layout.borderRadius}px 0 0;">
                      ${logo.url ? `<img class="email-logo" src="${logo.url}" alt="Logo" width="${logo.width}" style="max-width: 100%; height: auto;" />` : `<h2 style="font-size: ${typography.headingSize}px; color: ${effectiveColors.primaryText}; margin: 0;">Your Store</h2>`}
                    </td>
                  </tr>
                  
                  <!-- Content -->
                  <tr>
                    <td class="email-content" style="background-color: ${effectiveColors.contentBackground}; padding: ${layout.contentPadding}px; border-left: 1px solid ${effectiveColors.borderColor}; border-right: 1px solid ${effectiveColors.borderColor};">
                      
                      <h1 class="email-heading" style="font-size: ${typography.headingSize}px; color: ${effectiveColors.primaryText}; margin: 0 0 16px 0; line-height: 1.3;">
                        ${heading}
                      </h1>
                      
                      ${useCustomBody && processedBody
                        ? `
                          ${processedBody}
                          ${shipmentTrackingHTML}
                          ${wishlistProductsHTML}
                          ${productCardHTML}
                          ${couponDisplayHTML}
                        `
                        : `
                          <p class="email-body" style="font-size: ${typography.bodySize}px; color: ${effectiveColors.primaryText}; margin: 0 0 16px 0;">
                            Hi Customer,
                          </p>
                          
                          <p class="email-body" style="font-size: ${typography.bodySize}px; color: ${effectiveColors.primaryText}; margin: 0 0 24px 0;">
                            ${emailContent.body}
                          </p>
                          
                          ${alertHTML}
                          
                          <!-- Subscription Details Table -->
                          <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 24px; border: 1px solid ${effectiveTableColors.borderColor}; border-radius: ${layout.borderRadius}px; overflow: hidden;">
                            <tr style="background-color: ${effectiveTableColors.headerBackground};">
                              <th style="padding: ${table.cellPadding}px; text-align: left; font-size: ${typography.bodySize}px; color: ${effectiveTableColors.headerTextColor}; border-bottom: 1px solid ${effectiveTableColors.borderColor}; font-weight: ${table.headerFontWeight};">Product</th>
                              <th style="padding: ${table.cellPadding}px; text-align: right; font-size: ${typography.bodySize}px; color: ${effectiveTableColors.headerTextColor}; border-bottom: 1px solid ${effectiveTableColors.borderColor}; font-weight: ${table.headerFontWeight};">Price</th>
                            </tr>
                            <tr style="background-color: ${effectiveTableColors.rowBackground};">
                              <td style="padding: ${table.cellPadding}px; font-size: ${typography.bodySize}px; color: ${effectiveColors.primaryText};">Premium Membership</td>
                              <td style="padding: ${table.cellPadding}px; text-align: right; font-size: ${typography.bodySize}px; color: ${effectiveColors.primaryText};">$29.99 / month</td>
                            </tr>
                          </table>
                          
                          <!-- Action Button -->
                          <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 24px;">
                            <tr>
                              <td align="center">
                                <a href="#" class="email-button" style="display: inline-block; background-color: ${colors.buttonBackground}; color: ${colors.buttonText}; padding: 12px 24px; font-size: ${typography.bodySize}px; font-weight: 600; text-decoration: none; border-radius: ${layout.borderRadius}px;">
                                  ${emailContent.buttonText}
                                </a>
                              </td>
                            </tr>
                          </table>
                        `
                      }
                      
                      ${additionalContent ? `<p class="email-body" style="font-size: ${typography.bodySize}px; color: ${effectiveColors.secondaryText}; margin: 0 0 16px 0;">${additionalContent}</p>` : ''}
                      
                      ${!useCustomBody ? `
                      <p class="email-body" style="font-size: ${typography.bodySize}px; color: ${effectiveColors.secondaryText}; margin: 0;">
                        If you have any questions, please don't hesitate to <a href="#" style="color: ${colors.linkColor};">contact us</a>.
                      </p>
                      ` : ''}
                      
                    </td>
                  </tr>
                  
                  <!-- Footer -->
                  <tr>
                    <td class="email-footer" style="background-color: ${effectiveColors.headerBackground}; padding: ${layout.contentPadding / 2}px; text-align: center; border-radius: 0 0 ${layout.borderRadius}px ${layout.borderRadius}px; border: 1px solid ${effectiveColors.borderColor}; border-top: none;">
                      
                      ${footer.text ? `<p style="font-size: ${typography.bodySize - 2}px; color: ${effectiveColors.secondaryText}; margin: 0 0 8px 0;">${footer.text}</p>` : ''}
                      
                      ${socialLinksHTML}
                      
                      ${footer.showUnsubscribeLink ? `
                      <p style="font-size: ${typography.bodySize - 3}px; color: ${effectiveColors.secondaryText}; margin: 12px 0 0 0;">
                        <a href="#" style="color: ${effectiveColors.secondaryText}; text-decoration: underline;">
                          ${footer.unsubscribeText || 'Unsubscribe from these emails'}
                        </a>
                      </p>
                      ` : ''}
                      
                      <p style="font-size: ${typography.bodySize - 2}px; color: ${effectiveColors.secondaryText}; margin: ${footer.showSocialLinks || footer.showUnsubscribeLink ? '16px' : '0'} 0 0 0;">
                        ${copyrightText}
                      </p>
                      
                    </td>
                  </tr>
                  
                </table>
              </td>
            </tr>
          </table>
        </div>
      </body>
      </html>
    `;
  }, [settings, containerWidth, heading, preheaderText, additionalContent, emailType, emailContent, logo, colors, typography, layout, footer, table, iconBaseUrl, darkMode, darkModeColors, useCustomBody, processedBody, shipmentTrackingHTML, wishlistProductsHTML, productCardHTML, couponDisplayHTML]);

  return (
    <div
      className="relative bg-muted/30 rounded-lg overflow-hidden transition-all duration-300 h-full"
      style={{
        width: device === 'mobile' ? '375px' : '100%',
        margin: device === 'mobile' ? '0 auto' : '0',
      }}
    >
      {/* Device Frame */}
      {device === 'mobile' && (
        <div className="absolute top-0 left-0 right-0 h-6 bg-gray-800 rounded-t-lg flex items-center justify-center">
          <div className="w-20 h-1 bg-gray-600 rounded-full" />
        </div>
      )}

      {/* Email Preview iframe */}
      <iframe
        srcDoc={emailHTML}
        title="Email Preview"
        className="w-full border-0"
        style={{
          height: device === 'mobile' ? '600px' : '100%',
          marginTop: device === 'mobile' ? '24px' : '0',
          borderRadius: device === 'mobile' ? '0' : '8px',
        }}
      />

      {/* Mobile Home Indicator */}
      {device === 'mobile' && (
        <div className="absolute bottom-0 left-0 right-0 h-6 bg-gray-800 rounded-b-lg flex items-center justify-center">
          <div className="w-32 h-1 bg-gray-600 rounded-full" />
        </div>
      )}
    </div>
  );
}

export default EmailPreviewFrame;
