const nodemailer = require("nodemailer");

/**
 * Email Service for NordSafe EHS
 * Handles sending emails using Nodemailer
 */

/**
 * Create email transporter
 * For local testing, uses Ethereal.email
 * For production, configure with real SMTP credentials
 */
const createTransporter = async () => {
  // Check if we're in production with real SMTP credentials
  if (process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASS) {
    return nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: process.env.SMTP_PORT || 587,
      secure: process.env.SMTP_SECURE === "true", // true for 465, false for other ports
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
    });
  }

  // For local testing, create Ethereal test account
  const testAccount = await nodemailer.createTestAccount();
  
  return nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false,
    auth: {
      user: testAccount.user,
      pass: testAccount.pass,
    },
  });
};

/**
 * Send registration confirmation email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.name - User's full name
 * @param {string} options.companyName - Company name
 * @param {string} options.companyEmail - Company email
 * @param {string} options.companyAddress - Company address
 * @param {string} options.companyId - Company ID (formatted, e.g., EHS-001)
 * @param {Date} options.expiryDate - Subscription expiry date
 */
const sendRegistrationEmail = async ({
  to,
  name,
  companyName,
  companyEmail,
  companyAddress,
  companyId,
  expiryDate,
}) => {
  try {
    const transporter = await createTransporter();

    // Format expiry date
    const formattedExpiryDate = new Date(expiryDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Email content
    const subject = "Your Registration Is Confirmed";
    const text = `
Dear ${name},

Thank you for registering with NordSafe EHS.

Details of company:
- Company ID: ${companyId}
- Company Name: ${companyName}
- Company Email: ${companyEmail}
- Address: ${companyAddress}

Your account has been successfully created. You can now access the platform and start using our services.

Your registration until date: ${formattedExpiryDate}

For further information, please reach out to our support team: support@nordsafe-ehs.com

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background-color: #101E33;
      color: white;
      padding: 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .company-info {
      background-color: #F0F9F6;
      padding: 15px;
      border-left: 4px solid #1BB489;
      margin: 20px 0;
    }
    .company-info p {
      margin: 5px 0;
    }
    .company-id {
      background-color: #1BB489;
      color: white;
      padding: 8px 16px;
      border-radius: 20px;
      font-weight: bold;
      display: inline-block;
      font-size: 16px;
      margin: 10px 0;
    }
    .highlight {
      color: #1BB489;
      font-weight: bold;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>Welcome to NordSafe EHS</h1>
  </div>
  <div class="content">
    <p>Dear <strong>${name}</strong>,</p>
    
    <p>Thank you for registering with NordSafe EHS.</p>
    
    <div class="company-info">
      <h3>Details of company:</h3>
      <p><strong>Company ID:</strong> <span class="company-id">${companyId}</span></p>
      <p><strong>Company Name:</strong> ${companyName}</p>
      <p><strong>Company Email:</strong> ${companyEmail}</p>
      <p><strong>Address:</strong> ${companyAddress}</p>
    </div>
    
    <p>Your account has been successfully created. You can now access the platform and start using our services.</p>
    
    <p>Your registration until date: <span class="highlight">${formattedExpiryDate}</span></p>
    
    <p>For further information, please reach out to our support team: 
      <a href="mailto:support@nordsafe-ehs.com">support@nordsafe-ehs.com</a>
    </p>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Registration email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending registration email:", error);
    throw error;
  }
};

/**
 * Send generic email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.subject - Email subject
 * @param {string} options.text - Plain text content
 * @param {string} options.html - HTML content
 */
const sendEmail = async ({ to, subject, text, html }) => {
  try {
    const transporter = await createTransporter();

    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Email sent successfully!");
    console.log("Message ID:", info.messageId);

    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending email:", error);
    throw error;
  }
};

/**
 * Send plan upgrade confirmation email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.name - User's full name
 * @param {string} options.companyName - Company name
 * @param {string} options.companyEmail - Company email
 * @param {string} options.companyAddress - Company address
 * @param {string} options.companyPhone - Company phone
 * @param {string} options.currentPlan - Current plan name
 * @param {string} options.newPlan - New plan name
 * @param {Date} options.activateDate - Activation date
 */
const sendPlanUpgradeEmail = async ({
  to,
  name,
  companyName,
  companyEmail,
  companyAddress,
  companyPhone,
  currentPlan,
  newPlan,
  activateDate,
}) => {
  try {
    const transporter = await createTransporter();

    // Format activation date and time
    const formattedDate = new Date(activateDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
    
    const formattedTime = new Date(activateDate).toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: true,
    });

    // Email content
    const subject = "Your Subscription Plan Has Been Upgraded";
    const text = `
Dear ${name},

This email confirms that your subscription plan has been successfully upgraded.

Upgrade details:

Details of company:
- Company Name: ${companyName}
- Company Email: ${companyEmail}
- Company Phone: ${companyPhone}
- Address: ${companyAddress}

• Current Plan: ${currentPlan}
• New plan: ${newPlan}
• Activate Date: ${formattedDate}
• Time: ${formattedTime}

The new plan features are now active and available in your account.

For further information, please reach out to our support team: support@nordsafe-ehs.com

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #101E33 0%, #3B6594 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .company-info {
      background-color: #F0F9F6;
      padding: 15px;
      border-left: 4px solid #1BB489;
      margin: 20px 0;
    }
    .company-info p {
      margin: 5px 0;
    }
    .upgrade-box {
      background-color: white;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .upgrade-box h3 {
      color: #101E33;
      margin-top: 0;
      border-bottom: 2px solid #1BB489;
      padding-bottom: 10px;
    }
    .upgrade-item {
      display: flex;
      align-items: center;
      margin: 10px 0;
      padding: 10px;
      background-color: #F9FBFA;
      border-radius: 5px;
    }
    .upgrade-item strong {
      min-width: 140px;
      color: #101E33;
    }
    .plan-badge {
      display: inline-block;
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      margin-left: 10px;
    }
    .old-plan {
      background-color: #f0f0f0;
      color: #666;
      text-decoration: line-through;
    }
    .new-plan {
      background-color: #1BB489;
      color: white;
    }
    .highlight {
      color: #1BB489;
      font-weight: bold;
    }
    .success-icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>🎉 Plan Upgrade Confirmed!</h1>
  </div>
  <div class="content">
    <p>Dear <strong>${name}</strong>,</p>
    
    <div class="success-icon">✅</div>
    
    <p>This email confirms that your subscription plan has been successfully upgraded.</p>
    
    <div class="upgrade-box">
      <h3>Upgrade Details</h3>
      <div class="upgrade-item">
        <strong>Current Plan:</strong>
        <span class="plan-badge old-plan">${currentPlan}</span>
      </div>
      <div class="upgrade-item">
        <strong>New Plan:</strong>
        <span class="plan-badge new-plan">${newPlan}</span>
      </div>
      <div class="upgrade-item">
        <strong>Activate Date:</strong>
        <span>${formattedDate}</span>
      </div>
      <div class="upgrade-item">
        <strong>Time:</strong>
        <span>${formattedTime}</span>
      </div>
    </div>
    
    <div class="company-info">
      <h3>Details of Company</h3>
      <p><strong>Company Name:</strong> ${companyName}</p>
      <p><strong>Company Email:</strong> ${companyEmail}</p>
      <p><strong>Company Phone:</strong> ${companyPhone}</p>
      <p><strong>Address:</strong> ${companyAddress}</p>
    </div>
    
    <p style="background-color: #F0F9F6; padding: 15px; border-radius: 5px; border-left: 4px solid #1BB489;">
      <strong>🚀 The new plan features are now active and available in your account.</strong>
    </p>
    
    <p>For further information, please reach out to our support team: 
      <a href="mailto:support@nordsafe-ehs.com" style="color: #1BB489; text-decoration: none;">support@nordsafe-ehs.com</a>
    </p>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Plan upgrade email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending plan upgrade email:", error);
    throw error;
  }
};

/**
 * Send plan downgrade confirmation email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.name - User's full name
 * @param {string} options.companyName - Company name
 * @param {string} options.companyEmail - Company email
 * @param {string} options.companyAddress - Company address
 * @param {string} options.companyPhone - Company phone
 * @param {string} options.currentPlan - Current plan name
 * @param {string} options.newPlan - New plan name
 * @param {Date} options.activateDate - Activation date
 */
const sendPlanDowngradeEmail = async ({
  to,
  name,
  companyName,
  companyEmail,
  companyAddress,
  companyPhone,
  currentPlan,
  newPlan,
  activateDate,
}) => {
  try {
    const transporter = await createTransporter();

    // Format activation date and time
    const formattedDate = new Date(activateDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
    
    const formattedTime = new Date(activateDate).toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: true,
    });

    // Email content
    const subject = "Your Subscription Plan Has Been Downgraded";
    const text = `
Dear ${name},

This email confirms that your subscription plan has been downgraded.

Downgrade details:

Details of company:
- Company Name: ${companyName}
- Company Email: ${companyEmail}
- Company Phone: ${companyPhone}
- Address: ${companyAddress}

• Current Plan: ${currentPlan}
• New plan: ${newPlan}
• Activate Date: ${formattedDate}
• Time: ${formattedTime}

Your account will continue to function based on the limits of the new plan.

For further information, please reach out to our support team: support@nordsafe-ehs.com

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #101E33 0%, #3B6594 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .company-info {
      background-color: #F0F9F6;
      padding: 15px;
      border-left: 4px solid #3B6594;
      margin: 20px 0;
    }
    .company-info p {
      margin: 5px 0;
    }
    .downgrade-box {
      background-color: white;
      border: 2px solid #3B6594;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .downgrade-box h3 {
      color: #101E33;
      margin-top: 0;
      border-bottom: 2px solid #3B6594;
      padding-bottom: 10px;
    }
    .downgrade-item {
      display: flex;
      align-items: center;
      margin: 10px 0;
      padding: 10px;
      background-color: #F9FBFA;
      border-radius: 5px;
    }
    .downgrade-item strong {
      min-width: 140px;
      color: #101E33;
    }
    .plan-badge {
      display: inline-block;
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      margin-left: 10px;
    }
    .old-plan {
      background-color: #1BB489;
      color: white;
    }
    .new-plan {
      background-color: #3B6594;
      color: white;
    }
    .info-icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
      color: #3B6594;
    }
    .notice-box {
      background-color: #FFF9E6;
      border-left: 4px solid #FFA500;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .notice-box strong {
      color: #FF8C00;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>Plan Downgrade Notification</h1>
  </div>
  <div class="content">
    <p>Dear <strong>${name}</strong>,</p>
    
    <div class="info-icon">ℹ️</div>
    
    <p>This email confirms that your subscription plan has been downgraded.</p>
    
    <div class="downgrade-box">
      <h3>Downgrade Details</h3>
      <div class="downgrade-item">
        <strong>Current Plan:</strong>
        <span class="plan-badge old-plan">${currentPlan}</span>
      </div>
      <div class="downgrade-item">
        <strong>New Plan:</strong>
        <span class="plan-badge new-plan">${newPlan}</span>
      </div>
      <div class="downgrade-item">
        <strong>Activate Date:</strong>
        <span>${formattedDate}</span>
      </div>
      <div class="downgrade-item">
        <strong>Time:</strong>
        <span>${formattedTime}</span>
      </div>
    </div>
    
    <div class="company-info">
      <h3>Details of Company</h3>
      <p><strong>Company Name:</strong> ${companyName}</p>
      <p><strong>Company Email:</strong> ${companyEmail}</p>
      <p><strong>Company Phone:</strong> ${companyPhone}</p>
      <p><strong>Address:</strong> ${companyAddress}</p>
    </div>
    
    <div class="notice-box">
      <strong>⚠️ Important Notice:</strong><br>
      Your account will continue to function based on the limits of the new plan.
    </div>
    
    <p>For further information, please reach out to our support team: 
      <a href="mailto:support@nordsafe-ehs.com" style="color: #3B6594; text-decoration: none;">support@nordsafe-ehs.com</a>
    </p>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Plan downgrade email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending plan downgrade email:", error);
    throw error;
  }
};

/**
 * Send participant assignment confirmation email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.participantName - Participant's full name
 * @param {string} options.projectName - Project name
 * @param {string} options.assignedBy - Name of person who assigned
 * @param {Date} options.preparedDate - Date when assignment was prepared
 * @param {Date} options.deadlineDate - Deadline date (default: 3 weeks from prepared date)
 * @param {string} options.reportType - Type of report (optional)
 * @param {string} options.reportId - Report ID (optional)
 * @param {string} options.priority - Priority level (low, medium, high, urgent)
 */
const sendParticipantAssignmentEmail = async ({
  to,
  participantName,
  projectName,
  assignedBy,
  preparedDate,
  deadlineDate,
  reportType,
  reportId,
  priority = "medium",
}) => {
  try {
    const transporter = await createTransporter();

    // Format dates
    const formattedPreparedDate = new Date(preparedDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
    
    // If no deadline provided, default to 3 weeks from prepared date
    const deadline = deadlineDate || new Date(new Date(preparedDate).getTime() + 21 * 24 * 60 * 60 * 1000);
    const formattedDeadline = new Date(deadline).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Format priority for display
    const priorityDisplay = priority.charAt(0).toUpperCase() + priority.slice(1);
    const priorityColors = {
      low: { bg: "#E8F5E9", text: "#2E7D32", border: "#4CAF50" },
      medium: { bg: "#FFF9E6", text: "#F57C00", border: "#FFA500" },
      high: { bg: "#FFE5E5", text: "#C62828", border: "#F44336" },
      urgent: { bg: "#FFEBEE", text: "#B71C1C", border: "#D32F2F" },
    };
    const priorityColor = priorityColors[priority.toLowerCase()] || priorityColors.medium;

    // Email content
    const subject = "Participant Assignment Confirmation";
    const text = `
Hello ${participantName},

You have been assigned as a participant on the NordSafe EHS platform.

Assignment Details:

• Project: ${projectName}
• Assigned By: ${assignedBy}
• Prepared Date: ${formattedPreparedDate}
• Deadline: ${formattedDeadline} (3 weeks)
${reportType ? `• Report Type: ${reportType}` : ''}
${reportId ? `• Report ID: ${reportId}` : ''}
• Priority: ${priorityDisplay}

Please log in to your account to view your assigned sessions, activities, or responsibilities.

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #101E33 0%, #1BB489 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .greeting {
      font-size: 18px;
      color: #101E33;
      margin-bottom: 20px;
    }
    .assignment-box {
      background-color: white;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .assignment-box h3 {
      color: #101E33;
      margin-top: 0;
      border-bottom: 2px solid #1BB489;
      padding-bottom: 10px;
    }
    .assignment-item {
      display: flex;
      margin: 12px 0;
      padding: 12px;
      background-color: #F9FBFA;
      border-radius: 5px;
      border-left: 3px solid #1BB489;
    }
    .assignment-item strong {
      min-width: 140px;
      color: #101E33;
    }
    .assignment-item span {
      color: #3B6594;
      font-weight: 500;
    }
    .deadline-highlight {
      background-color: #FFF9E6;
      border-left: 4px solid #FFA500;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .deadline-highlight strong {
      color: #FF8C00;
    }
    .action-box {
      background-color: #F0F9F6;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .action-box p {
      margin: 10px 0;
      font-size: 16px;
    }
    .login-button {
      display: inline-block;
      background-color: #1BB489;
      color: white;
      padding: 12px 30px;
      text-decoration: none;
      border-radius: 5px;
      font-weight: bold;
      margin-top: 10px;
    }
    .login-button:hover {
      background-color: #159f75;
    }
    .icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>📋 New Assignment</h1>
  </div>
  <div class="content">
    <div class="icon">👤</div>
    
    <p class="greeting">Hello <strong>${participantName}</strong>,</p>
    
    <p>You have been assigned as a participant on the NordSafe EHS platform.</p>
    
    <div class="assignment-box">
      <h3>Assignment Details</h3>
      <div class="assignment-item">
        <strong>📁 Project:</strong>
        <span>${projectName}</span>
      </div>
      <div class="assignment-item">
        <strong>👨‍💼 Assigned By:</strong>
        <span>${assignedBy}</span>
      </div>
      <div class="assignment-item">
        <strong>📅 Prepared Date:</strong>
        <span>${formattedPreparedDate}</span>
      </div>
      ${reportType ? `
      <div class="assignment-item">
        <strong>📝 Report Type:</strong>
        <span>${reportType}</span>
      </div>
      ` : ''}
      ${reportId ? `
      <div class="assignment-item">
        <strong>🔢 Report ID:</strong>
        <span>${reportId}</span>
      </div>
      ` : ''}
      <div class="assignment-item">
        <strong>⚡ Priority:</strong>
        <span class="priority-badge" style="background-color: ${priorityColor.bg}; color: ${priorityColor.text}; border: 2px solid ${priorityColor.border};">
          ${priorityDisplay}
        </span>
      </div>
    </div>
    
    <div class="deadline-highlight">
      <strong>⏰ Deadline:</strong> ${formattedDeadline} (3 weeks)
    </div>
    
    <div class="action-box">
      <p><strong>Please log in to your account to view your assigned sessions, activities, or responsibilities.</strong></p>
      <a href="${process.env.FRONTEND_URL || 'http://localhost:5174'}" class="login-button">
        Login to NordSafe EHS
      </a>
    </div>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Participant assignment email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending participant assignment email:", error);
    throw error;
  }
};

/**
 * Send deviation assignment email (Action Required)
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.participantName - Participant's full name
 * @param {string} options.projectName - Project name
 * @param {string} options.deviationId - Deviation ID (formatted)
 * @param {string} options.assignedBy - Name of person who assigned
 * @param {Date} options.preparedDate - Date when assignment was prepared
 * @param {Date} options.deadlineDate - Deadline date (default: 3 weeks from prepared date)
 * @param {string} options.priority - Priority level (low, medium, high, urgent)
 */
const sendDeviationAssignmentEmail = async ({
  to,
  participantName,
  projectName,
  deviationId,
  assignedBy,
  preparedDate,
  deadlineDate,
  priority = "medium",
}) => {
  try {
    const transporter = await createTransporter();

    // Format dates
    const formattedPreparedDate = new Date(preparedDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
    
    // If no deadline provided, default to 3 weeks from prepared date
    const deadline = deadlineDate || new Date(new Date(preparedDate).getTime() + 21 * 24 * 60 * 60 * 1000);
    const formattedDeadline = new Date(deadline).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Format priority for display
    const priorityDisplay = priority.charAt(0).toUpperCase() + priority.slice(1);
    const priorityColors = {
      low: { bg: "#E8F5E9", text: "#2E7D32", border: "#4CAF50" },
      medium: { bg: "#FFF9E6", text: "#F57C00", border: "#FFA500" },
      high: { bg: "#FFE5E5", text: "#C62828", border: "#F44336" },
      urgent: { bg: "#FFEBEE", text: "#B71C1C", border: "#D32F2F" },
    };
    const priorityColor = priorityColors[priority.toLowerCase()] || priorityColors.medium;

    // Email content
    const subject = "Deviation Case Assignment - Action Required";
    const text = `
Hello ${participantName},

You have been assigned to a Deviation to close a case on the NordSafe EHS platform.

Assignment Details:

• Project: ${projectName}
• Deviation ID: ${deviationId}
• Assigned By: ${assignedBy}
• Prepared Date: ${formattedPreparedDate}
• Deadline: ${formattedDeadline} (3 weeks)
• Priority: ${priorityDisplay}

Please log in to your account to review the deviation details and complete the required actions.

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #9E0D0D 0%, #101E33 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .header .subtitle {
      margin: 5px 0 0 0;
      font-size: 16px;
      color: #FFD700;
      font-weight: bold;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .greeting {
      font-size: 18px;
      color: #101E33;
      margin-bottom: 20px;
    }
    .alert-box {
      background-color: #FFF3CD;
      border: 2px solid #FFA500;
      border-radius: 8px;
      padding: 15px;
      margin: 20px 0;
      text-align: center;
    }
    .alert-box strong {
      color: #9E0D0D;
      font-size: 16px;
    }
    .assignment-box {
      background-color: white;
      border: 2px solid #9E0D0D;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .assignment-box h3 {
      color: #9E0D0D;
      margin-top: 0;
      border-bottom: 2px solid #9E0D0D;
      padding-bottom: 10px;
    }
    .assignment-item {
      display: flex;
      margin: 12px 0;
      padding: 12px;
      background-color: #F9FBFA;
      border-radius: 5px;
      border-left: 3px solid #9E0D0D;
    }
    .assignment-item strong {
      min-width: 140px;
      color: #101E33;
    }
    .assignment-item span {
      color: #3B6594;
      font-weight: 500;
    }
    .deviation-id {
      background-color: #9E0D0D;
      color: white;
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      display: inline-block;
    }
    .deadline-highlight {
      background-color: #FFE5E5;
      border-left: 4px solid #9E0D0D;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .deadline-highlight strong {
      color: #9E0D0D;
    }
    .priority-badge {
      display: inline-block;
      padding: 6px 16px;
      border-radius: 20px;
      font-weight: bold;
      font-size: 14px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    .action-box {
      background-color: #F0F9F6;
      border: 2px solid #9E0D0D;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .action-box p {
      margin: 10px 0;
      font-size: 16px;
      color: #101E33;
    }
    .login-button {
      display: inline-block;
      background-color: #9E0D0D;
      color: white;
      padding: 12px 30px;
      text-decoration: none;
      border-radius: 5px;
      font-weight: bold;
      margin-top: 10px;
    }
    .login-button:hover {
      background-color: #7A0A0A;
    }
    .icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>⚠️ Deviation Case Assignment</h1>
    <p class="subtitle">ACTION REQUIRED</p>
  </div>
  <div class="content">
    <div class="icon">🚨</div>
    
    <p class="greeting">Hello <strong>${participantName}</strong>,</p>
    
    <div class="alert-box">
      <strong>You have been assigned to a Deviation to close a case on the NordSafe EHS platform.</strong>
    </div>
    
    <div class="assignment-box">
      <h3>Assignment Details</h3>
      <div class="assignment-item">
        <strong>📁 Project:</strong>
        <span>${projectName}</span>
      </div>
      <div class="assignment-item">
        <strong>🔢 Deviation ID:</strong>
        <span class="deviation-id" style="background-color: #9E0D0D; color: #FFFFFF; padding: 5px 15px; border-radius: 20px; font-weight: bold; display: inline-block;">${deviationId}</span>
      </div>
      <div class="assignment-item">
        <strong>👨‍💼 Assigned By:</strong>
        <span>${assignedBy}</span>
      </div>
      <div class="assignment-item">
        <strong>📅 Prepared Date:</strong>
        <span>${formattedPreparedDate}</span>
      </div>
      <div class="assignment-item">
        <strong>⚡ Priority:</strong>
        <span class="priority-badge" style="background-color: ${priorityColor.bg}; color: ${priorityColor.text}; border: 2px solid ${priorityColor.border};">
          ${priorityDisplay}
        </span>
      </div>
    </div>
    
    <div class="deadline-highlight">
      <strong>⏰ Deadline:</strong> ${formattedDeadline} (3 weeks)
    </div>
    
    <div class="action-box">
      <p><strong>Please log in to your account to review the deviation details and complete the required actions.</strong></p>
      <a href="${process.env.FRONTEND_URL || 'http://localhost:5174'}" class="login-button">
        Review Deviation Now
      </a>
    </div>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Deviation assignment email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending deviation assignment email:", error);
    throw error;
  }
};

/**
 * Send case investigation assignment email (Action Required)
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.participantName - Participant's full name
 * @param {string} options.projectName - Project name
 * @param {string} options.caseId - Case ID (formatted)
 * @param {string} options.assignedBy - Name of person who assigned
 * @param {Date} options.preparedDate - Date when assignment was prepared
 * @param {Date} options.deadlineDate - Deadline date (default: 3 weeks from prepared date)
 * @param {string} options.priority - Priority level (low, medium, high, urgent)
 */
const sendCaseInvestigationAssignmentEmail = async ({
  to,
  participantName,
  projectName,
  caseId,
  assignedBy,
  preparedDate,
  deadlineDate,
  priority = "medium",
}) => {
  try {
    const transporter = await createTransporter();

    // Format dates
    const formattedPreparedDate = new Date(preparedDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
    
    // If no deadline provided, default to 3 weeks from prepared date
    const deadline = deadlineDate || new Date(new Date(preparedDate).getTime() + 21 * 24 * 60 * 60 * 1000);
    const formattedDeadline = new Date(deadline).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Format priority for display
    const priorityDisplay = priority.charAt(0).toUpperCase() + priority.slice(1);
    const priorityColors = {
      low: { bg: "#E8F5E9", text: "#2E7D32", border: "#4CAF50" },
      medium: { bg: "#FFF9E6", text: "#F57C00", border: "#FFA500" },
      high: { bg: "#FFE5E5", text: "#C62828", border: "#F44336" },
      urgent: { bg: "#FFEBEE", text: "#B71C1C", border: "#D32F2F" },
    };
    const priorityColor = priorityColors[priority.toLowerCase()] || priorityColors.medium;

    // Email content
    const subject = "Case Investigation Assignment - Action Required";
    const text = `
Hello ${participantName},

You have been assigned to a Case Investigation to close a case on the NordSafe EHS platform.

Assignment Details:

• Project: ${projectName}
• Case ID: ${caseId}
• Assigned By: ${assignedBy}
• Prepared Date: ${formattedPreparedDate}
• Deadline: ${formattedDeadline} (3 weeks)
• Priority: ${priorityDisplay}

Please log in to your account to review the case details and complete the investigation.

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #3B6594 0%, #101E33 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .header .subtitle {
      margin: 5px 0 0 0;
      font-size: 16px;
      color: #FFD700;
      font-weight: bold;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .greeting {
      font-size: 18px;
      color: #101E33;
      margin-bottom: 20px;
    }
    .alert-box {
      background-color: #E3F2FD;
      border: 2px solid #3B6594;
      border-radius: 8px;
      padding: 15px;
      margin: 20px 0;
      text-align: center;
    }
    .alert-box strong {
      color: #3B6594;
      font-size: 16px;
    }
    .assignment-box {
      background-color: white;
      border: 2px solid #3B6594;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .assignment-box h3 {
      color: #3B6594;
      margin-top: 0;
      border-bottom: 2px solid #3B6594;
      padding-bottom: 10px;
    }
    .assignment-item {
      display: flex;
      margin: 12px 0;
      padding: 12px;
      background-color: #F9FBFA;
      border-radius: 5px;
      border-left: 3px solid #3B6594;
    }
    .assignment-item strong {
      min-width: 140px;
      color: #101E33;
    }
    .assignment-item span {
      color: #3B6594;
      font-weight: 500;
    }
    .case-id {
      background-color: #3B6594;
      color: white;
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      display: inline-block;
    }
    .deadline-highlight {
      background-color: #FFF9E6;
      border-left: 4px solid #FFA500;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .deadline-highlight strong {
      color: #FF8C00;
    }
    .action-box {
      background-color: #E3F2FD;
      border: 2px solid #3B6594;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .action-box p {
      margin: 10px 0;
      font-size: 16px;
      color: #101E33;
    }
    .login-button {
      display: inline-block;
      background-color: #3B6594;
      color: white;
      padding: 12px 30px;
      text-decoration: none;
      border-radius: 5px;
      font-weight: bold;
      margin-top: 10px;
    }
    .login-button:hover {
      background-color: #2A4A6F;
    }
    .icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>🔍 Case Investigation Assignment</h1>
    <p class="subtitle">ACTION REQUIRED</p>
  </div>
  <div class="content">
    <div class="icon">📋</div>
    
    <p class="greeting">Hello <strong>${participantName}</strong>,</p>
    
    <div class="alert-box">
      <strong>You have been assigned to a Case Investigation to close a case on the NordSafe EHS platform.</strong>
    </div>
    
    <div class="assignment-box">
      <h3>Assignment Details</h3>
      <div class="assignment-item">
        <strong>📁 Project:</strong>
        <span>${projectName}</span>
      </div>
      <div class="assignment-item">
        <strong>🔢 Case ID:</strong>
        <span class="case-id" style="background-color: #3B6594; color: #FFFFFF; padding: 5px 15px; border-radius: 20px; font-weight: bold; display: inline-block;">${caseId}</span>
      </div>
      <div class="assignment-item">
        <strong>👨‍💼 Assigned By:</strong>
        <span>${assignedBy}</span>
      </div>
      <div class="assignment-item">
        <strong>📅 Prepared Date:</strong>
        <span>${formattedPreparedDate}</span>
      </div>
      <div class="assignment-item">
        <strong>⚡ Priority:</strong>
        <span class="priority-badge" style="background-color: ${priorityColor.bg}; color: ${priorityColor.text}; border: 2px solid ${priorityColor.border};">
          ${priorityDisplay}
        </span>
      </div>
    </div>
    
    <div class="deadline-highlight">
      <strong>⏰ Deadline:</strong> ${formattedDeadline} (3 weeks)
    </div>
    
    <div class="action-box">
      <p><strong>Please log in to your account to review the case details and complete the investigation.</strong></p>
      <a href="${process.env.FRONTEND_URL || 'http://localhost:5174'}" class="login-button">
        Review Case Investigation
      </a>
    </div>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Case investigation assignment email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending case investigation assignment email:", error);
    throw error;
  }
};

/**
 * Send password reset request email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.customerName - Customer's full name
 * @param {string} options.resetLink - Password reset link with token
 */
const sendPasswordResetEmail = async ({
  to,
  customerName,
  resetLink,
}) => {
  try {
    const transporter = await createTransporter();

    // Email content
    const subject = "Password Reset Request";
    const text = `
Dear ${customerName},

A request has been received to reset the password associated with your NordSafe EHS account.

To proceed, please use the secure link below to set a new password:

${resetLink}

For security reasons, this link will expire after a limited time and may only be used once.

If you did not initiate this request, no action is required and your account will remain secure.

For further information, please reach out to our support team: support@nordsafe-ehs.com

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #101E33 0%, #3B6594 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .greeting {
      font-size: 18px;
      color: #101E33;
      margin-bottom: 20px;
    }
    .message-box {
      background-color: white;
      border: 2px solid #3B6594;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .message-box p {
      margin: 10px 0;
      color: #101E33;
    }
    .reset-button {
      display: inline-block;
      background-color: #1BB489;
      color: white;
      padding: 15px 40px;
      text-decoration: none;
      border-radius: 5px;
      font-weight: bold;
      margin: 20px 0;
      font-size: 16px;
    }
    .reset-button:hover {
      background-color: #159f75;
    }
    .security-notice {
      background-color: #FFF9E6;
      border-left: 4px solid #FFA500;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .security-notice strong {
      color: #FF8C00;
    }
    .info-box {
      background-color: #E3F2FD;
      border-left: 4px solid #3B6594;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .info-box p {
      margin: 5px 0;
      color: #101E33;
    }
    .icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
    .link-text {
      word-break: break-all;
      color: #3B6594;
      font-size: 12px;
      margin-top: 10px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>🔐 Password Reset Request</h1>
  </div>
  <div class="content">
    <div class="icon">🔑</div>
    
    <p class="greeting">Dear <strong>${customerName}</strong>,</p>
    
    <p>A request has been received to reset the password associated with your NordSafe EHS account.</p>
    
    <div class="message-box">
      <p><strong>To proceed, please use the secure link below to set a new password:</strong></p>
      <a href="${resetLink}" class="reset-button">
        Reset Password
      </a>
      <p class="link-text">Or copy this link: ${resetLink}</p>
    </div>
    
    <div class="security-notice">
      <strong>⚠️ Security Notice:</strong><br>
      For security reasons, this link will expire after a limited time and may only be used once.
    </div>
    
    <div class="info-box">
      <p><strong>ℹ️ Didn't request this?</strong></p>
      <p>If you did not initiate this request, no action is required and your account will remain secure.</p>
    </div>
    
    <p>For further information, please reach out to our support team: 
      <a href="mailto:support@nordsafe-ehs.com" style="color: #1BB489; text-decoration: none;">support@nordsafe-ehs.com</a>
    </p>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Password reset email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending password reset email:", error);
    throw error;
  }
};

/**
 * Send subscription cancellation confirmation email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.customerName - Customer's full name
 * @param {string} options.companyName - Company name
 * @param {string} options.companyEmail - Company email
 * @param {string} options.companyAddress - Company address
 * @param {string} options.companyPhone - Company phone
 * @param {Date} options.cancellationDate - Date of cancellation
 * @param {boolean} options.isTrialPeriod - Whether cancelled during trial
 */
const sendSubscriptionCancellationEmail = async ({
  to,
  customerName,
  companyName,
  companyEmail,
  companyAddress,
  companyPhone,
  cancellationDate,
  isTrialPeriod = false,
}) => {
  try {
    const transporter = await createTransporter();

    // Format cancellation date
    const formattedCancellationDate = new Date(cancellationDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Calculate data deletion date (3 months from cancellation)
    const deletionDate = new Date(cancellationDate);
    deletionDate.setMonth(deletionDate.getMonth() + 3);
    const formattedDeletionDate = deletionDate.toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Email content
    const subject = "Subscription Cancellation Confirmation";
    const text = `
Dear ${customerName},

This email confirms that your NordSafe EHS subscription has been successfully canceled.

Details of company:
- Company Name: ${companyName}
- Company Email: ${companyEmail}
- Company Phone: ${companyPhone}
- Address: ${companyAddress}
- Cancellation Date: ${formattedCancellationDate}

Please note that your account data will be retained for up to three (3) months after the cancellation date. After this period (${formattedDeletionDate}), all data will be permanently deleted unless retention is required by law.

${isTrialPeriod ? 'Since you canceled during a trial period, no charges will apply.' : ''}

For further information or assistance, please reach out to our support team: support@nordsafe-ehs.com

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #666 0%, #101E33 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .greeting {
      font-size: 18px;
      color: #101E33;
      margin-bottom: 20px;
    }
    .confirmation-box {
      background-color: #FFF9E6;
      border: 2px solid #FFA500;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .confirmation-box strong {
      color: #FF8C00;
      font-size: 16px;
    }
    .company-info {
      background-color: white;
      border: 2px solid #666;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .company-info h3 {
      color: #101E33;
      margin-top: 0;
      border-bottom: 2px solid #666;
      padding-bottom: 10px;
    }
    .info-item {
      display: flex;
      margin: 10px 0;
      padding: 10px;
      background-color: #F9FBFA;
      border-radius: 5px;
    }
    .info-item strong {
      min-width: 160px;
      color: #101E33;
    }
    .info-item span {
      color: #666;
    }
    .data-retention-box {
      background-color: #FFE5E5;
      border-left: 4px solid #9E0D0D;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .data-retention-box strong {
      color: #9E0D0D;
    }
    .trial-notice {
      background-color: #E8F5E9;
      border-left: 4px solid #4CAF50;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .trial-notice strong {
      color: #2E7D32;
    }
    .support-box {
      background-color: #E3F2FD;
      border: 2px solid #3B6594;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .support-box p {
      margin: 10px 0;
      color: #101E33;
    }
    .icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>Subscription Cancellation</h1>
  </div>
  <div class="content">
    <div class="icon">📋</div>
    
    <p class="greeting">Dear <strong>${customerName}</strong>,</p>
    
    <div class="confirmation-box">
      <strong>This email confirms that your NordSafe EHS subscription has been successfully canceled.</strong>
    </div>
    
    <div class="company-info">
      <h3>Details of Company</h3>
      <div class="info-item">
        <strong>Company Name:</strong>
        <span>${companyName}</span>
      </div>
      <div class="info-item">
        <strong>Company Email:</strong>
        <span>${companyEmail}</span>
      </div>
      <div class="info-item">
        <strong>Company Phone:</strong>
        <span>${companyPhone}</span>
      </div>
      <div class="info-item">
        <strong>Address:</strong>
        <span>${companyAddress}</span>
      </div>
      <div class="info-item">
        <strong>Cancellation Date:</strong>
        <span>${formattedCancellationDate}</span>
      </div>
    </div>
    
    <div class="data-retention-box">
      <strong>⚠️ Data Retention Notice:</strong><br>
      Please note that your account data will be retained for up to three (3) months after the cancellation date. 
      After this period (<strong>${formattedDeletionDate}</strong>), all data will be permanently deleted unless retention is required by law.
    </div>
    
    ${isTrialPeriod ? `
    <div class="trial-notice">
      <strong>✓ Trial Period Cancellation:</strong><br>
      Since you canceled during a trial period, no charges will apply.
    </div>
    ` : ''}
    
    <div class="support-box">
      <p><strong>Need Help?</strong></p>
      <p>For further information or assistance, please reach out to our support team:</p>
      <p><a href="mailto:support@nordsafe-ehs.com" style="color: #1BB489; text-decoration: none; font-weight: bold;">support@nordsafe-ehs.com</a></p>
    </div>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
      <p style="font-size: 12px; color: #999; margin-top: 10px;">
        We're sorry to see you go. If you change your mind, you can always reactivate your subscription.
      </p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ Subscription cancellation email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending subscription cancellation email:", error);
    throw error;
  }
};

/**
 * Send new user added to project email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.userName - User's full name
 * @param {string} options.projectName - Project name
 * @param {string} options.companyName - Company name
 * @param {string} options.userRole - User role (User/Admin/Visitor)
 * @param {string} options.addedBy - Name of person who added the user
 * @param {Date} options.addedDate - Date when user was added
 */
const sendNewUserAddedEmail = async ({
  to,
  userName,
  projectName,
  companyName,
  userRole,
  addedBy,
  addedDate,
}) => {
  try {
    const transporter = await createTransporter();

    // Format date
    const formattedDate = new Date(addedDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Capitalize role
    const formattedRole = userRole.charAt(0).toUpperCase() + userRole.slice(1);

    // Email content
    const subject = "You Have Been Added to a Project on NordSafe EHS";
    const text = `
Dear ${userName},

You have been successfully added as a user on the NordSafe EHS platform and assigned to a specific project.

Project Details:

• Project Name: ${projectName}
• Company: ${companyName}
• Role: ${formattedRole}
• Added By: ${addedBy}
• Date: ${formattedDate}

You can now access the project through your dashboard and begin using the assigned features and tools.

Please log in to your account to view the project details and your assigned responsibilities.

For further information or assistance, please reach out to our support team: support@nordsafe-ehs.com

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #1BB489 0%, #101E33 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .greeting {
      font-size: 18px;
      color: #101E33;
      margin-bottom: 20px;
    }
    .welcome-box {
      background-color: #F0F9F6;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .welcome-box strong {
      color: #1BB489;
      font-size: 16px;
    }
    .project-details {
      background-color: white;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .project-details h3 {
      color: #101E33;
      margin-top: 0;
      border-bottom: 2px solid #1BB489;
      padding-bottom: 10px;
    }
    .detail-item {
      display: flex;
      margin: 12px 0;
      padding: 12px;
      background-color: #F9FBFA;
      border-radius: 5px;
      border-left: 3px solid #1BB489;
    }
    .detail-item strong {
      min-width: 140px;
      color: #101E33;
    }
    .detail-item span {
      color: #3B6594;
      font-weight: 500;
    }
    .role-badge {
      background-color: #1BB489;
      color: white;
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      display: inline-block;
    }
    .info-box {
      background-color: #E3F2FD;
      border-left: 4px solid #3B6594;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .info-box p {
      margin: 5px 0;
      color: #101E33;
    }
    .action-box {
      background-color: #F0F9F6;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .action-box p {
      margin: 10px 0;
      font-size: 16px;
      color: #101E33;
    }
    .login-button {
      display: inline-block;
      background-color: #1BB489;
      color: white;
      padding: 12px 30px;
      text-decoration: none;
      border-radius: 5px;
      font-weight: bold;
      margin-top: 10px;
    }
    .login-button:hover {
      background-color: #159f75;
    }
    .icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>🎉 Welcome to NordSafe EHS!</h1>
  </div>
  <div class="content">
    <div class="icon">👋</div>
    
    <p class="greeting">Dear <strong>${userName}</strong>,</p>
    
    <div class="welcome-box">
      <strong>You have been successfully added as a user on the NordSafe EHS platform and assigned to a specific project.</strong>
    </div>
    
    <div class="project-details">
      <h3>Project Details</h3>
      <div class="detail-item">
        <strong>📁 Project Name:</strong>
        <span>${projectName}</span>
      </div>
      <div class="detail-item">
        <strong>🏢 Company:</strong>
        <span>${companyName}</span>
      </div>
      <div class="detail-item">
        <strong>👤 Role:</strong>
        <span class="role-badge">${formattedRole}</span>
      </div>
      <div class="detail-item">
        <strong>👨‍💼 Added By:</strong>
        <span>${addedBy}</span>
      </div>
      <div class="detail-item">
        <strong>📅 Date:</strong>
        <span>${formattedDate}</span>
      </div>
    </div>
    
    <div class="info-box">
      <p><strong>✓ What's Next?</strong></p>
      <p>You can now access the project through your dashboard and begin using the assigned features and tools.</p>
    </div>
    
    <div class="action-box">
      <p><strong>Please log in to your account to view the project details and your assigned responsibilities.</strong></p>
      <a href="${process.env.FRONTEND_URL || 'http://localhost:5174'}" class="login-button">
        Login to Dashboard
      </a>
    </div>
    
    <p>For further information or assistance, please reach out to our support team: 
      <a href="mailto:support@nordsafe-ehs.com" style="color: #1BB489; text-decoration: none;">support@nordsafe-ehs.com</a>
    </p>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
      <p style="font-size: 12px; color: #999; margin-top: 10px;">
        Welcome aboard! We're excited to have you on the team.
      </p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ New user added email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending new user added email:", error);
    throw error;
  }
};

/**
 * Send Minutes of Meeting participant assignment email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email address
 * @param {string} options.participantName - Name of the participant
 * @param {string} options.projectName - Name of the project
 * @param {string} options.momId - Minutes of Meeting ID (formatted)
 * @param {string} options.meetingTitle - Title of the meeting
 * @param {string} options.meetingDate - Date of the meeting
 * @param {string} options.assignedBy - Name of the person who assigned
 * @param {string} options.role - Role of the user (participant, responsible person, or both)
 */
const sendMinutesOfMeetingEmail = async ({
  to,
  participantName,
  projectName,
  momId,
  meetingTitle,
  meetingDate,
  assignedBy,
  role = "participant",
}) => {
  try {
    // Format meeting date
    const formattedMeetingDate = new Date(meetingDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    const subject = "Minutes of Meeting - Assignment Notification";
    const text = `
Hello ${participantName},

You have been assigned as a ${role} for a Minutes of Meeting.

Meeting Details:
• Project: ${projectName}
• Meeting ID: ${momId}
• Meeting Title: ${meetingTitle}
• Meeting Date: ${formattedMeetingDate}
• Your Role: ${role.charAt(0).toUpperCase() + role.slice(1)}
• Assigned By: ${assignedBy}

Please log in to the NordSafe EHS platform to review the meeting details and participate.

Best regards,
NordSafe EHS Team
    `;

    const html = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      line-height: 1.6;
      color: #333;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
    }
    .container {
      max-width: 600px;
      margin: 20px auto;
      background-color: #ffffff;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .header {
      background-color: #101E33;
      color: white;
      padding: 20px;
      text-align: center;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
    }
    .content h2 {
      color: #101E33;
      margin-top: 0;
    }
    .company-info {
      background-color: #F0F9F6;
      padding: 15px;
      border-left: 4px solid #1BB489;
      margin: 20px 0;
      border-radius: 5px;
    }
    .assignment-box {
      background-color: white;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .assignment-box h3 {
      color: #101E33;
      margin-top: 0;
      font-size: 18px;
    }
    .assignment-item {
      margin: 12px 0;
      padding: 12px;
      background-color: #F9FBFA;
      border-radius: 5px;
      border-left: 3px solid #1BB489;
    }
    .assignment-item strong {
      color: #101E33;
      display: inline-block;
      min-width: 140px;
    }
    .assignment-item span {
      color: #3B6594;
      font-weight: 500;
    }
    .mom-id {
      background-color: #1BB489;
      color: #FFFFFF;
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      display: inline-block;
    }
    .role-badge {
      background-color: #3B6594;
      color: #FFFFFF;
      padding: 5px 15px;
      border-radius: 20px;
      font-weight: bold;
      display: inline-block;
      text-transform: capitalize;
    }
    .meeting-highlight {
      background-color: #E3F2FD;
      border-left: 4px solid #1BB489;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .meeting-highlight strong {
      color: #1BB489;
    }
    .action-box {
      background-color: #F0F9F6;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .action-box p {
      margin: 10px 0;
      font-size: 16px;
      color: #101E33;
    }
    .login-button {
      display: inline-block;
      background-color: #1BB489;
      color: white;
      padding: 12px 30px;
      text-decoration: none;
      border-radius: 5px;
      font-weight: bold;
      margin-top: 10px;
    }
    .login-button:hover {
      background-color: #159f75;
    }
    .icon {
      font-size: 20px;
      margin-right: 5px;
    }
    .footer {
      background-color: #101E33;
      color: white;
      text-align: center;
      padding: 20px;
      font-size: 14px;
    }
    .footer a {
      color: #1BB489;
      text-decoration: none;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>📋 Minutes of Meeting Assignment</h1>
    </div>
    
    <div class="content">
      <h2>Hello ${participantName},</h2>
      
      <p>You have been assigned as a <strong>${role}</strong> for a Minutes of Meeting session.</p>
      
      <div class="company-info">
        <p style="margin: 0;">
          <strong>📢 Important:</strong> Your ${role === "participant" ? "participation" : "involvement"} is required for this meeting. Please review the details below and ensure your ${role === "participant" ? "attendance" : "action"}.
        </p>
      </div>

      <div class="assignment-box">
        <h3>Meeting Details</h3>
        <div class="assignment-item">
          <strong>📁 Project:</strong>
          <span>${projectName}</span>
        </div>
        <div class="assignment-item">
          <strong>🔢 Meeting ID:</strong>
          <span class="mom-id" style="background-color: #1BB489; color: #FFFFFF; padding: 5px 15px; border-radius: 20px; font-weight: bold; display: inline-block;">${momId}</span>
        </div>
        <div class="assignment-item">
          <strong>📝 Meeting Title:</strong>
          <span>${meetingTitle}</span>
        </div>
        <div class="assignment-item">
          <strong>📅 Meeting Date:</strong>
          <span>${formattedMeetingDate}</span>
        </div>
        <div class="assignment-item">
          <strong>👤 Your Role:</strong>
          <span class="role-badge" style="background-color: #3B6594; color: #FFFFFF; padding: 5px 15px; border-radius: 20px; font-weight: bold; display: inline-block; text-transform: capitalize;">${role}</span>
        </div>
        <div class="assignment-item">
          <strong>👨‍💼 Assigned By:</strong>
          <span>${assignedBy}</span>
        </div>
      </div>
      
      <div class="meeting-highlight">
        <p style="margin: 0;">
          <strong>📌 Note:</strong> Please log in to the platform to view the full meeting agenda, discussion items, ${role.includes("responsible") ? "your assigned tasks," : ""} and action logs.
        </p>
      </div>

      <div class="action-box">
        <p><strong>Ready to ${role === "participant" ? "participate" : "take action"}?</strong></p>
        <p>Click the button below to access the meeting details:</p>
        <a href="${process.env.FRONTEND_URL || "https://nordsafe-ehs.com"}" class="login-button">
          View Meeting Details
        </a>
      </div>

      <p style="color: #666; font-size: 14px; margin-top: 30px;">
        If you have any questions or concerns, please contact your project administrator.
      </p>
    </div>
    
    <div class="footer">
      <p>This is an automated message from <strong>NordSafe EHS</strong></p>
      <p>© ${new Date().getFullYear()} NordSafe EHS. All rights reserved.</p>
    </div>
  </div>
</body>
</html>
    `;

    await sendEmail(to, subject, text, html);
    console.log(`✅ Minutes of Meeting email sent to ${to} (${role})`);
  } catch (error) {
    console.error("❌ Error sending Minutes of Meeting email:", error);
    throw error;
  }
};

/**
 * Send HAZOP/HAZID action assignment email
 * @param {Object} options - Email options
 * @param {string} options.to - Recipient email
 * @param {string} options.ownerName - Action owner's full name
 * @param {string} options.studyTitle - Study title
 * @param {string} options.studyType - Study type (HAZOP or HAZID)
 * @param {string} options.studyId - Study ID (formatted, e.g., HZP-001)
 * @param {string} options.findingRef - Finding reference (e.g., N-01-F-02 or HZD-03)
 * @param {string} options.description - Action description
 * @param {string} options.riskLevel - Risk level (Low, Medium, High, Critical)
 * @param {Date} options.dueDate - Action due date
 * @param {string} options.baseUrl - Base URL for the application
 */
const sendHazopActionAssignmentEmail = async ({
  to,
  ownerName,
  studyTitle,
  studyType,
  studyId,
  findingRef,
  description,
  riskLevel,
  dueDate,
  baseUrl,
}) => {
  try {
    const transporter = await createTransporter();

    // Format due date
    const formattedDueDate = new Date(dueDate).toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    // Risk level colors
    const riskColors = {
      Low: { bg: "#E8F5E9", text: "#2E7D32", border: "#4CAF50" },
      Medium: { bg: "#FFF9E6", text: "#F57C00", border: "#FFA500" },
      High: { bg: "#FFE5E5", text: "#C62828", border: "#F44336" },
      Critical: { bg: "#FFEBEE", text: "#B71C1C", border: "#D32F2F" },
    };
    const riskColor = riskColors[riskLevel] || riskColors.Medium;

    // Study type display
    const studyTypeDisplay = studyType.toUpperCase();

    // Email content
    const subject = `New Safety Action Assigned: ${findingRef}`;
    const text = `
Hello ${ownerName},

You have been assigned a new safety action from ${studyTypeDisplay} study "${studyTitle}".

Action Details:

• Study ID: ${studyId}
• Finding Reference: ${findingRef}
• Risk Level: ${riskLevel}
• Description: ${description}
• Due Date: ${formattedDueDate}

Please review and take appropriate action.

View in NordSafe: ${baseUrl}/hazop/studies/${studyId}

Best regards,
NordSafe EHS
    `.trim();

    const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 600px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #101E33 0%, #C62828 100%);
      color: white;
      padding: 30px 20px;
      text-align: center;
      border-radius: 5px 5px 0 0;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      background-color: #f9f9f9;
      padding: 30px;
      border: 1px solid #ddd;
      border-top: none;
    }
    .greeting {
      font-size: 18px;
      color: #101E33;
      margin-bottom: 20px;
    }
    .action-box {
      background-color: white;
      border: 2px solid #C62828;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .action-box h3 {
      color: #101E33;
      margin-top: 0;
      border-bottom: 2px solid #C62828;
      padding-bottom: 10px;
    }
    .action-item {
      display: flex;
      margin: 12px 0;
      padding: 12px;
      background-color: #F9FBFA;
      border-radius: 5px;
      border-left: 3px solid #C62828;
    }
    .action-item strong {
      min-width: 160px;
      color: #101E33;
    }
    .action-item span {
      color: #3B6594;
      font-weight: 500;
    }
    .risk-badge {
      display: inline-block;
      padding: 6px 16px;
      border-radius: 20px;
      font-weight: bold;
      background-color: ${riskColor.bg};
      color: ${riskColor.text};
      border: 2px solid ${riskColor.border};
    }
    .description-box {
      background-color: #F0F9F6;
      border-left: 4px solid #1BB489;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
    }
    .description-box strong {
      color: #101E33;
      display: block;
      margin-bottom: 8px;
    }
    .due-date-highlight {
      background-color: #FFF9E6;
      border-left: 4px solid #FFA500;
      padding: 15px;
      margin: 20px 0;
      border-radius: 5px;
      text-align: center;
    }
    .due-date-highlight strong {
      color: #FF8C00;
      font-size: 18px;
    }
    .view-button-box {
      background-color: #F0F9F6;
      border: 2px solid #1BB489;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
      text-align: center;
    }
    .view-button-box p {
      margin: 10px 0;
      font-size: 16px;
    }
    .view-button {
      display: inline-block;
      background-color: #1BB489;
      color: white;
      padding: 12px 30px;
      text-decoration: none;
      border-radius: 5px;
      font-weight: bold;
      margin-top: 10px;
    }
    .view-button:hover {
      background-color: #159f75;
    }
    .icon {
      font-size: 48px;
      text-align: center;
      margin: 20px 0;
    }
    .footer {
      text-align: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ddd;
      color: #666;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>⚠️ New Safety Action Assigned</h1>
  </div>
  <div class="content">
    <div class="icon">🎯</div>
    
    <p class="greeting">Hello <strong>${ownerName}</strong>,</p>
    
    <p>You have been assigned a new safety action from <strong>${studyTypeDisplay}</strong> study "<strong>${studyTitle}</strong>".</p>
    
    <div class="action-box">
      <h3>Action Details</h3>
      <div class="action-item">
        <strong>📋 Study ID:</strong>
        <span>${studyId}</span>
      </div>
      <div class="action-item">
        <strong>🔍 Finding Reference:</strong>
        <span>${findingRef}</span>
      </div>
      <div class="action-item">
        <strong>⚡ Risk Level:</strong>
        <span class="risk-badge">${riskLevel}</span>
      </div>
    </div>
    
    <div class="description-box">
      <strong>📝 Action Description:</strong>
      <p style="margin: 5px 0; color: #3B6594;">${description}</p>
    </div>
    
    <div class="due-date-highlight">
      <strong>⏰ Due Date: ${formattedDueDate}</strong>
    </div>
    
    <div class="view-button-box">
      <p><strong>Please review and take appropriate action.</strong></p>
      <a href="${baseUrl}/hazop/studies/${studyId}" class="view-button">
        View Study in NordSafe
      </a>
    </div>
    
    <div class="footer">
      <p><strong>Best regards,</strong><br>NordSafe EHS Team</p>
    </div>
  </div>
</body>
</html>
    `.trim();

    // Send email
    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      replyTo: process.env.EMAIL_REPLY_TO || 'support@nordsafe-ehs.com',
      to,
      subject,
      text,
      html,
    });

    console.log("✅ HAZOP action assignment email sent successfully!");
    console.log("Message ID:", info.messageId);

    // For Ethereal testing, log preview URL
    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 Preview URL:", nodemailer.getTestMessageUrl(info));
      console.log("👆 Open this URL in your browser to view the email");
    }

    return {
      success: true,
      messageId: info.messageId,
      previewUrl: nodemailer.getTestMessageUrl(info),
    };
  } catch (error) {
    console.error("❌ Error sending HAZOP action assignment email:", error);
    throw error;
  }
};

/**
 * Notify company admin when super admin sets subscription prices (with Stripe payment link).
 */
const sendPriceSetEmail = async ({
  to,
  adminName,
  companyName,
  subscription,
  paymentUrl,
}) => {
  try {
    const transporter = await createTransporter();

    const usersLine = `${subscription.usersCount} users × $${subscription.userPrice} = $${subscription.usersCount * subscription.userPrice}`;
    const projectsLine = `${subscription.projectsCount} projects × $${subscription.projectPrice} = $${subscription.projectsCount * subscription.projectPrice}`;
    const sdsSaveLine = `${subscription.monthlySDSSaveCount} SDS saves × $${subscription.SDSSavePrice} = $${subscription.monthlySDSSaveCount * subscription.SDSSavePrice}`;
    const sdsSearchLine = `SDS search per save × $${subscription.SDSSearchPerSavePrice} × ${subscription.monthlySDSSaveCount} saves = $${subscription.monthlySDSSaveCount * subscription.SDSSearchPerSavePrice}`;

    const total =
      subscription.usersCount * subscription.userPrice +
      subscription.projectsCount * subscription.projectPrice +
      subscription.monthlySDSSaveCount * subscription.SDSSavePrice +
      subscription.monthlySDSSaveCount * subscription.SDSSearchPerSavePrice;

    const subject = "NordSafe EHS — Your subscription pricing is ready";
    const text = `
Dear ${adminName},

Your NordSafe EHS subscription request for ${companyName} has been priced.

Plan details:
- ${usersLine}
- ${projectsLine}
- ${sdsSaveLine}
- ${sdsSearchLine}

Estimated monthly total: $${total.toFixed(2)}

Pay securely here:
${paymentUrl}

Thank you,
NordSafe EHS
`;

    const html = `
<!DOCTYPE html>
<html><body style="font-family: Arial, sans-serif; color: #172E4E;">
  <p>Dear ${adminName},</p>
  <p>Your NordSafe EHS subscription request for <strong>${companyName}</strong> has been priced.</p>
  <table style="border-collapse: collapse; margin: 16px 0;">
    <tr><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">Users</td><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">${usersLine}</td></tr>
    <tr><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">Projects</td><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">${projectsLine}</td></tr>
    <tr><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">SDS saves</td><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">${sdsSaveLine}</td></tr>
    <tr><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">SDS search (per save)</td><td style="padding: 6px 12px; border: 1px solid #e5e7eb;">${sdsSearchLine}</td></tr>
  </table>
  <p><strong>Estimated monthly total: $${total.toFixed(2)}</strong></p>
  <p><a href="${paymentUrl}" style="display:inline-block; padding:12px 24px; background:#36D399; color:#172E4E; text-decoration:none; border-radius:6px; font-weight:bold;">Pay now</a></p>
  <p style="color:#64748b; font-size:12px;">If the button does not work, copy this link: ${paymentUrl}</p>
  <p>Thank you,<br/>NordSafe EHS</p>
</body></html>`;

    const info = await transporter.sendMail({
      from: process.env.EMAIL_FROM || '"NordSafe EHS" <no-reply@nordsafe-ehs.com>',
      to,
      subject,
      text,
      html,
    });

    if (nodemailer.getTestMessageUrl(info)) {
      console.log("📧 sendPriceSetEmail preview:", nodemailer.getTestMessageUrl(info));
    }

    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error("sendPriceSetEmail error:", error);
    throw error;
  }
};

module.exports = {
  sendRegistrationEmail,
  sendPlanUpgradeEmail,
  sendPlanDowngradeEmail,
  sendParticipantAssignmentEmail,
  sendDeviationAssignmentEmail,
  sendCaseInvestigationAssignmentEmail,
  sendPasswordResetEmail,
  sendSubscriptionCancellationEmail,
  sendNewUserAddedEmail,
  sendMinutesOfMeetingEmail,
  sendHazopActionAssignmentEmail,
  sendPriceSetEmail,
  sendEmail,
};


