// utils/mailer.js
import nodemailer from "nodemailer";

// ════════════════════════════════════════════════════════════
//  ✅ BRAND CONFIG — sirf yahan badlo, poori app mein apply
// ════════════════════════════════════════════════════════════
const BRAND = {
    companyName:  "Rigveda Herbs Pvt. Ltd.",
    tagline:      "Ancient Wisdom. Modern Wellness.",
  supportEmail: "support@kanakherbal.com",  
  website:      "https://rigvedaherbs.com",    // apni website daalo
  logoUrl:      "http://localhost:5000/images/rv_logo.png", // backend se serve hoga
  phone:        "+91-XXXXXXXXXX",
  frontendUrl:  "http://localhost:5173",

  // 🎨 Golden + Green — ayurvedic brand palette
  colors: {
    headerBg:    "#1B4332",   // dark green  — header background
    headerBorder:"#B7882C",   // golden      — header bottom border
    primary:     "#2D6A4F",   // deep green  — title bar, accents
    accent:      "#B7882C",   // golden      — borders, highlights
    accentLight: "#F0C040",   // light gold  — OTP digits, badge
    bodyBg:      "#F7F3EA",   // warm cream  — email background
    cardBg:      "#FFFFFF",   // white       — content card
    footerBg:    "#1B4332",   // dark green  — footer
    textPrimary: "#1C1C1C",   // body text
    textMuted:   "#6B6B6B",   // muted text
    textOnDark:  "#FFFFFF",   // text on green
    textGold:    "#F0C040",   // gold text on dark
    success:     "#2D6A4F",   // green for approved
    danger:      "#C0392B",   // red for rejected
    tableBg:     "#F0EBD8",   // warm tint — table header
    borderLight: "#E8DFCA",   // light border — table rows
  },
};

// ════════════════════════════════════════════════════════════
//  SMTP TRANSPORTER
// ════════════════════════════════════════════════════════════
const transporter = nodemailer.createTransport({
  host:   "mail.kanakherbal.com",
  port:   465,
  secure: true,
  auth: {
    user: BRAND.supportEmail,
    pass: "Kanak@123",
  },
});

// ════════════════════════════════════════════════════════════
//  INTERNAL HELPERS
// ════════════════════════════════════════════════════════════
const C = BRAND.colors;

const sendMail = async ({ to, subject, html }) =>
  transporter.sendMail({
    from:    `"${BRAND.companyName}" <${BRAND.supportEmail}>`,
    to,
    subject,
    html,
  });

// ── Reusable info row for tables ─────────────────────────────
const infoRow = (label, value) => `
  <tr>
    <td style="padding:9px 12px;font-weight:600;color:${C.textPrimary};background:${C.tableBg};width:40%;border-bottom:1px solid ${C.borderLight};">
      ${label}
    </td>
    <td style="padding:9px 12px;color:${C.textPrimary};background:${C.cardBg};border-bottom:1px solid ${C.borderLight};">
      ${value}
    </td>
  </tr>`;

// ── Status badge ─────────────────────────────────────────────
const badge = (text, color) => `
  <span style="display:inline-block;padding:4px 14px;background:${color}18;color:${color};
    border:1px solid ${color};border-radius:20px;font-size:13px;font-weight:600;">
    ${text}
  </span>`;

// ════════════════════════════════════════════════════════════
//  BASE HTML TEMPLATE
// ════════════════════════════════════════════════════════════
const baseTemplate = (title, bodyHtml) => `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>${title} — ${BRAND.companyName}</title>
</head>
<body style="margin:0;padding:0;background:${C.bodyBg};font-family:'Segoe UI',Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:${C.bodyBg};padding:36px 16px;">
<tr><td align="center">
<table width="560" cellpadding="0" cellspacing="0"
  style="max-width:560px;width:100%;border-radius:14px;overflow:hidden;
         box-shadow:0 4px 24px rgba(0,0,0,0.10);">

  <!-- ══ HEADER ══ -->
  <tr>
    <td style="background:${C.headerBg};padding:28px 32px 20px;text-align:center;
               border-bottom:4px solid ${C.accent};">
      <img src="${BRAND.logoUrl}" alt="${BRAND.companyName}"
        width="76" height="76"
        style="border-radius:50%;border:3px solid ${C.accent};
               object-fit:cover;display:block;margin:0 auto 14px;"
        onerror="this.style.display='none'"/>
      <p style="margin:0;font-size:19px;font-weight:700;color:${C.textGold};
                letter-spacing:0.4px;">
        ${BRAND.companyName}
      </p>
      <p style="margin:5px 0 0;font-size:11px;color:${C.accent};letter-spacing:2px;
                text-transform:uppercase;">
        ${BRAND.tagline}
      </p>
    </td>
  </tr>

  <!-- ══ TITLE BAR ══ -->
  <tr>
    <td style="background:${C.primary};padding:13px 32px;text-align:center;">
      <p style="margin:0;font-size:16px;font-weight:700;color:${C.textOnDark};
                letter-spacing:0.3px;">
        ${title}
      </p>
    </td>
  </tr>

  <!-- ══ BODY ══ -->
  <tr>
    <td style="background:${C.cardBg};padding:28px 32px;color:${C.textPrimary};
               font-size:14px;line-height:1.8;">
      ${bodyHtml}
    </td>
  </tr>

  <!-- ══ FOOTER ══ -->
  <tr>
    <td style="background:${C.footerBg};padding:20px 32px;text-align:center;
               border-top:3px solid ${C.accent};">
      <p style="margin:0 0 6px;font-size:13px;color:${C.textGold};font-weight:600;">
        ${BRAND.companyName}
      </p>
      <p style="margin:0;font-size:11px;color:${C.accent};">
        📞 ${BRAND.phone} &nbsp;|&nbsp;
        🌐 <a href="${BRAND.website}" style="color:${C.accent};text-decoration:none;">${BRAND.website}</a>
      </p>
      <p style="margin:10px 0 0;font-size:11px;color:#7a9e8a;">
        &copy; ${new Date().getFullYear()} ${BRAND.companyName}. All rights reserved.<br/>
        This is an automated email — please do not reply.
      </p>
    </td>
  </tr>

</table>
</td></tr>
</table>
</body>
</html>`;

// ════════════════════════════════════════════════════════════
//  EMAIL FUNCTIONS
// ════════════════════════════════════════════════════════════

// ── OTP ──────────────────────────────────────────────────────
export const sendOtpEmail = async (to, otp, name = "") => {
  await sendMail({
    to,
    subject: "Your OTP for Password Reset",
    html: baseTemplate("Password Reset OTP", `
      <p>Dear ${name ? `<strong>${name}</strong>` : "User"},</p>
      <p>We received a request to reset your password. Use the OTP below:</p>

      <div style="text-align:center;margin:28px 0;">
        <div style="display:inline-block;background:${C.tableBg};
                    border:2px dashed ${C.accent};border-radius:12px;
                    padding:18px 36px;">
          <p style="margin:0 0 4px;font-size:11px;color:${C.textMuted};
                    letter-spacing:2px;text-transform:uppercase;">Your OTP</p>
          <p style="margin:0;font-size:44px;font-weight:800;
                    letter-spacing:12px;color:${C.accent};font-family:monospace;">
            ${otp}
          </p>
        </div>
      </div>

      <p style="text-align:center;color:${C.textMuted};font-size:13px;">
        ⏱ Valid for <strong>10 minutes</strong> only.
      </p>
      <p style="color:${C.textMuted};font-size:13px;
                border-left:3px solid ${C.accent};padding-left:12px;margin-top:20px;">
        If you did not request this, please ignore this email. 
        Do not share this OTP with anyone.
      </p>
    `),
  });
};

// ── Member Registration ───────────────────────────────────────
export const sendMemberRegistrationEmail = async (to, { name, memberId, sponsorId }) => {
  await sendMail({
    to,
    subject: "Welcome! Your Member Registration is Received",
    html: baseTemplate("Registration Received", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Thank you for registering with <strong>${BRAND.companyName}</strong>. 
         Your application has been submitted and is currently under admin review.</p>

      <table width="100%" cellpadding="0" cellspacing="0"
        style="border-radius:8px;overflow:hidden;border:1px solid ${C.borderLight};margin:20px 0;">
        ${infoRow("Member ID", `<strong>${memberId}</strong>`)}
        ${infoRow("Sponsor ID", sponsorId || "—")}
        ${infoRow("Status", badge("Under Review", C.accent))}
      </table>

      <p>You will receive an email notification once your account is approved.</p>
      <p style="color:${C.textMuted};font-size:13px;">
        For any queries, contact us at 
        <a href="mailto:${BRAND.supportEmail}" style="color:${C.primary};">${BRAND.supportEmail}</a>
      </p>
    `),
  });
};

// ── Member Approval ───────────────────────────────────────────
export const sendMemberApprovalEmail = async (to, { name, memberId }) => {
  await sendMail({
    to,
    subject: "✅ Your Member Account is Approved!",
    html: baseTemplate("Account Approved", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Congratulations! 🎉 Your member account has been 
        ${badge("Approved", C.success)}
      </p>

      <table width="100%" cellpadding="0" cellspacing="0"
        style="border-radius:8px;overflow:hidden;border:1px solid ${C.borderLight};margin:20px 0;">
        ${infoRow("Member ID", `<strong>${memberId}</strong>`)}
        ${infoRow("Status", badge("Active", C.success))}
      </table>

      <p>You can now log in to your member portal and start exploring your dashboard.</p>
      <div style="text-align:center;margin:24px 0;">
        <a href="${BRAND.frontendUrl}"
          style="display:inline-block;background:${C.primary};color:#fff;
                 padding:12px 32px;border-radius:8px;text-decoration:none;
                 font-weight:600;font-size:14px;border:2px solid ${C.accent};">
          Login to Portal →
        </a>
      </div>
    `),
  });
};

// ── Member Rejection ──────────────────────────────────────────
export const sendMemberRejectionEmail = async (to, { name, remark }) => {
  await sendMail({
    to,
    subject: "❌ Member Registration Update",
    html: baseTemplate("Registration Not Approved", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>We regret to inform you that your member registration has been 
        ${badge("Rejected", C.danger)}
      </p>
      ${remark ? `
      <div style="background:${C.tableBg};border-left:4px solid ${C.danger};
                  border-radius:0 8px 8px 0;padding:14px 16px;margin:20px 0;">
        <p style="margin:0;font-size:13px;color:${C.textMuted};">Reason</p>
        <p style="margin:4px 0 0;font-weight:600;color:${C.textPrimary};">${remark}</p>
      </div>` : ""}
      <p>If you believe this is an error or need assistance, please contact our support team at 
        <a href="mailto:${BRAND.supportEmail}" style="color:${C.primary};">${BRAND.supportEmail}</a>.
      </p>
    `),
  });
};

// ── Customer Registration ─────────────────────────────────────
export const sendCustomerRegistrationEmail = async (to, { name, customerId }) => {
  await sendMail({
    to,
    subject: "Welcome! Your Customer Registration is Received",
    html: baseTemplate("Customer Registration Received", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Thank you for registering with <strong>${BRAND.companyName}</strong>. 
         Your application is under review.</p>

      <table width="100%" cellpadding="0" cellspacing="0"
        style="border-radius:8px;overflow:hidden;border:1px solid ${C.borderLight};margin:20px 0;">
        ${infoRow("Customer ID", `<strong>${customerId}</strong>`)}
        ${infoRow("Status", badge("Under Review", C.accent))}
      </table>

      <p>We will notify you once your account is approved.</p>
    `),
  });
};

// ── Customer Approval ─────────────────────────────────────────
export const sendCustomerApprovalEmail = async (to, { name, customerId }) => {
  await sendMail({
    to,
    subject: "✅ Your Customer Account is Approved!",
    html: baseTemplate("Account Approved", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Your customer account has been ${badge("Approved", C.success)}</p>

      <table width="100%" cellpadding="0" cellspacing="0"
        style="border-radius:8px;overflow:hidden;border:1px solid ${C.borderLight};margin:20px 0;">
        ${infoRow("Customer ID", `<strong>${customerId}</strong>`)}
        ${infoRow("Status", badge("Active", C.success))}
      </table>

      <div style="text-align:center;margin:24px 0;">
        <a href="${BRAND.frontendUrl}"
          style="display:inline-block;background:${C.primary};color:#fff;
                 padding:12px 32px;border-radius:8px;text-decoration:none;
                 font-weight:600;font-size:14px;border:2px solid ${C.accent};">
          Login to Portal →
        </a>
      </div>
    `),
  });
};

// ── Customer Rejection ────────────────────────────────────────
export const sendCustomerRejectionEmail = async (to, { name, remark }) => {
  await sendMail({
    to,
    subject: "❌ Customer Registration Update",
    html: baseTemplate("Registration Not Approved", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Your customer registration has been ${badge("Rejected", C.danger)}</p>
      ${remark ? `
      <div style="background:${C.tableBg};border-left:4px solid ${C.danger};
                  border-radius:0 8px 8px 0;padding:14px 16px;margin:20px 0;">
        <p style="margin:0;font-size:13px;color:${C.textMuted};">Reason</p>
        <p style="margin:4px 0 0;font-weight:600;color:${C.textPrimary};">${remark}</p>
      </div>` : ""}
      <p>Contact us at 
        <a href="mailto:${BRAND.supportEmail}" style="color:${C.primary};">${BRAND.supportEmail}</a> 
        for assistance.
      </p>
    `),
  });
};



// ── Order Approved ────────────────────────────────────────────
// ── Order Approved — items ke saath ──────────────────────────
export const sendOrderApprovedEmail = async (to, { name, orderId, items, total }) => {
  const itemRows = items?.map(i => `
    <tr>
      <td style="padding:9px 12px;border-bottom:1px solid ${C.borderLight};color:${C.textPrimary};">
        ${i.name}
      </td>
      <td style="padding:9px 12px;border-bottom:1px solid ${C.borderLight};text-align:center;">
        ${i.qty}
      </td>
      <td style="padding:9px 12px;border-bottom:1px solid ${C.borderLight};text-align:right;">
        ₹${i.price}
      </td>
    </tr>`).join("") || "";

  await sendMail({
    to,
    subject: `✅ Order #${orderId} Approved — Rigveda Herbs`,
    html: baseTemplate("Order Approved", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Great news! 🎉 Your order <strong>#${orderId}</strong> has been 
        ${badge("Approved", C.success)} and is now being processed.
      </p>

      ${itemRows ? `
      <table width="100%" cellpadding="0" cellspacing="0"
        style="border-radius:8px;overflow:hidden;border:1px solid ${C.borderLight};margin:20px 0;font-size:13px;">
        <thead>
          <tr style="background:${C.tableBg};">
            <th style="padding:10px 12px;text-align:left;font-weight:600;border-bottom:2px solid ${C.accent};">Item</th>
            <th style="padding:10px 12px;text-align:center;font-weight:600;border-bottom:2px solid ${C.accent};">Qty</th>
            <th style="padding:10px 12px;text-align:right;font-weight:600;border-bottom:2px solid ${C.accent};">Price</th>
          </tr>
        </thead>
        <tbody>${itemRows}</tbody>
        <tfoot>
          <tr style="background:${C.tableBg};">
            <td colspan="2" style="padding:10px 12px;font-weight:700;text-align:right;border-top:2px solid ${C.accent};">
              Total Amount
            </td>
            <td style="padding:10px 12px;font-weight:700;color:${C.accent};font-size:15px;text-align:right;border-top:2px solid ${C.accent};">
              ₹${total}
            </td>
          </tr>
        </tfoot>
      </table>` : ""}

      <p style="color:${C.textMuted};font-size:13px;">
        You will receive further updates as your order progresses. Thank you for shopping with us!
      </p>

      <div style="text-align:center;margin:24px 0;">
        <a href="${BRAND.frontendUrl}"
          style="display:inline-block;background:${C.primary};color:#fff;
                 padding:12px 32px;border-radius:8px;text-decoration:none;
                 font-weight:600;font-size:14px;border:2px solid ${C.accent};">
          View My Orders →
        </a>
      </div>
    `),
  });
};

// ── Order Rejected ────────────────────────────────────────────
export const sendOrderRejectedEmail = async (to, { name, orderId, reason }) => {
  await sendMail({
    to,
    subject: `❌ Order #${orderId} Update`,
    html: baseTemplate("Order Not Approved", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Your order <strong>#${orderId}</strong> has been 
        ${badge("Rejected", C.danger)}
      </p>
      ${reason ? `
      <div style="background:${C.tableBg};border-left:4px solid ${C.danger};
                  border-radius:0 8px 8px 0;padding:14px 16px;margin:20px 0;">
        <p style="margin:0;font-size:13px;color:${C.textMuted};">Reason</p>
        <p style="margin:4px 0 0;font-weight:600;color:${C.textPrimary};">${reason}</p>
      </div>` : ""}
      <p>Please contact support if you need assistance placing a new order.</p>
    `),
  });
};

// ── Member Welcome (registration ke baad — password ke saath) ─
export const sendMemberWelcomeEmail = async (to, { name, memberId, sponsorId, email, password, mobile }) => {
  await sendMail({
    to,
    subject: "🎉 Welcome to Rigveda Herbs — Your Login Details",
    html: baseTemplate("Welcome! Registration Successful", `
      <p>Dear <strong>${name}</strong>,</p>
      <p>Thank you for joining <strong>${BRAND.companyName}</strong>! 
         Your registration has been received successfully. 
         Below are your account details:</p>

      <table width="100%" cellpadding="0" cellspacing="0"
        style="border-radius:8px;overflow:hidden;border:1px solid ${C.borderLight};margin:20px 0;">
        ${infoRow("Member ID",  `<strong style="color:${C.accent};font-size:15px;">${memberId}</strong>`)}
        ${infoRow("Full Name",  name)}
        ${infoRow("Email",      email)}
        ${infoRow("Mobile",     mobile || "—")}
        ${infoRow("Sponsor ID", sponsorId || "—")}
        ${infoRow("Status",     badge("Pending Approval", C.accent))}
      </table>

      <div style="background:${C.tableBg};border:2px dashed ${C.accent};
                  border-radius:10px;padding:18px 20px;margin:24px 0;text-align:center;">
        <p style="margin:0 0 6px;font-size:12px;color:${C.textMuted};
                  letter-spacing:2px;text-transform:uppercase;">Your Login Password</p>
        <p style="margin:0;font-size:28px;font-weight:800;
                  letter-spacing:6px;color:${C.accent};font-family:monospace;">
          ${password}
        </p>
      </div>

      <div style="background:#FFF8E7;border-left:4px solid ${C.accent};
                  border-radius:0 8px 8px 0;padding:14px 16px;margin:20px 0;">
        <p style="margin:0;font-size:13px;color:#7A5800;font-weight:600;">
          ⚠️ Important: Please save these credentials safely and change your password after first login.
        </p>
      </div>

      <p style="color:${C.textMuted};font-size:13px;">
        Your account is currently under admin review. You will receive another email once approved.
      </p>

      <div style="text-align:center;margin:24px 0;">
        <a href="${BRAND.frontendUrl}"
          style="display:inline-block;background:${C.primary};color:#fff;
                 padding:12px 32px;border-radius:8px;text-decoration:none;
                 font-weight:600;font-size:14px;border:2px solid ${C.accent};">
          Login to Portal →
        </a>
      </div>

      <p style="color:${C.textMuted};font-size:13px;">
        For any queries, contact us at 
        <a href="mailto:${BRAND.supportEmail}" style="color:${C.primary};">${BRAND.supportEmail}</a>
      </p>
    `),
  });
};



