import "server-only";
import { db } from "./db";

/**
 * Email template registry.
 * Every trigger renders a template: subject + HTML body with {{variable}}
 * placeholders. Admins can override subject/body per template (EmailTemplate
 * table, managed at /admin/templates); code falls back to these defaults.
 * The branded outer shell (header bar, footer) is fixed in code — only the
 * message content is editable.
 */

export type TemplateDef = {
  key: string;
  label: string;
  description: string;
  /** Variables available to this template, with sample values for previews/tests. */
  variables: Record<string, string>;
  subject: string;
  body: string; // HTML fragment
};

const btn = (urlVar: string, label: string) =>
  `<p><a href="{{${urlVar}}}" style="display:inline-block;background:{{accent}};color:#ffffff;text-decoration:none;font-weight:700;padding:11px 22px;border-radius:10px;margin:8px 0;">${label}</a></p>`;

export const EMAIL_TEMPLATES: TemplateDef[] = [
  {
    key: "welcome",
    label: "Account welcome",
    description: "Sent when a new account is created via the normal signup form.",
    variables: { name: "Kavya Singhal", ctaUrl: "https://confexe.indicops.com/dashboard", ctaLabel: "Open my dashboard" },
    subject: "Welcome to Confexe 👋",
    body: `<p>Hi {{name}},</p>
<p>Your Confexe account is ready. From one place you can discover conferences, register in a couple of clicks, and keep your tickets and certificates together — or run your own conference with a website, registration engine, agenda builder and check-in tools built in.</p>
${btn("ctaUrl", "{{ctaLabel}}")}
<p style="color:#61708a;font-size:13px;">Need help getting started? Just reply to this email.</p>`,
  },
  {
    key: "onboarding_code",
    label: "Email verification code",
    description: "The 6-digit OTP sent during the start-your-conference signup funnel.",
    variables: { name: "Kavya Singhal", code: "482916", conferenceName: "Rajasthan Startup Summit 2027", expiresMinutes: "15" },
    subject: "{{code}} is your Confexe verification code",
    body: `<p>Hi {{name}},</p>
<p>You're one step away from launching <strong>{{conferenceName}}</strong>. Enter this code to verify your email address:</p>
<p style="font-size:32px;font-weight:800;letter-spacing:8px;background:#eef2ff;border-radius:12px;padding:16px;text-align:center;color:#1f2a44;">{{code}}</p>
<p style="color:#61708a;font-size:13px;">The code expires in {{expiresMinutes}} minutes. If you didn't request it, you can safely ignore this email.</p>`,
  },
  {
    key: "onboarding_welcome",
    label: "Organizer onboarding welcome",
    description: "Sent after email verification in the start funnel — includes the one-time password for new accounts.",
    variables: { name: "Kavya Singhal", email: "kavya@example.org", conferenceName: "Rajasthan Startup Summit 2027", tempPassword: "cfx-4f9a2b1c", dashboardUrl: "https://confexe.indicops.com/dashboard" },
    subject: "Welcome to Confexe — your organizer account is ready 🎉",
    body: `<p>Hi {{name}},</p>
<p><strong>{{conferenceName}}</strong> is set up as a private draft in your organizer dashboard. You're already signed in on the device you used to verify.</p>
<p>For future logins:</p>
<p style="background:#f6f7fd;border-radius:10px;padding:12px 16px;">Email: <strong>{{email}}</strong><br/>Temporary password: <strong style="font-family:monospace;">{{tempPassword}}</strong></p>
${btn("dashboardUrl", "Open my dashboard")}
<p style="color:#61708a;font-size:13px;">Please change the password from Dashboard → Settings → Security.</p>`,
  },
  {
    key: "registration_pending",
    label: "Registration received (payment pending)",
    description: "Sent when a visitor registers but payment is not completed yet.",
    variables: { name: "Rohan Verma", conferenceName: "TechBharat Summit 2026", regCode: "CFX-8K2M4P", passName: "Regular Pass", amount: "₹1,999", payUrl: "https://confexe.indicops.com/c/techbharat/register" },
    subject: "Almost there — complete your registration for {{conferenceName}}",
    body: `<p>Hi {{name}},</p>
<p>We've received your registration for <strong>{{conferenceName}}</strong> — it's reserved under ID <strong style="font-family:monospace;">{{regCode}}</strong> and waiting for payment.</p>
<table style="font-size:14px;color:#33415c;line-height:1.9;"><tr><td style="color:#8fa0b8;padding-right:16px;">Pass</td><td>{{passName}}</td></tr><tr><td style="color:#8fa0b8;">Amount due</td><td><strong>{{amount}}</strong></td></tr></table>
${btn("payUrl", "Complete payment")}
<p style="color:#61708a;font-size:13px;">Your seat is held until payment is completed. If you've already paid, you can ignore this email — the confirmation follows separately.</p>`,
  },
  {
    key: "registration_confirmed",
    label: "Registration confirmed (ticket)",
    description: "The ticket email with QR link, sent when a registration is confirmed.",
    variables: { name: "Rohan Verma", conferenceName: "TechBharat Summit 2026", regCode: "CFX-8K2M4P", passName: "Regular Pass", amount: "₹1,999", dates: "3–5 Oct 2026", venue: "Bharat Mandapam, New Delhi", ticketUrl: "https://confexe.indicops.com/ticket/CFX-8K2M4P", scheduleUrl: "https://confexe.indicops.com/c/techbharat/schedule" },
    subject: "🎟️ You're in! Ticket for {{conferenceName}}",
    body: `<p>Hi {{name}},</p>
<p>Your registration is <strong>confirmed</strong>. Here are your details:</p>
<table style="font-size:14px;color:#33415c;line-height:1.9;">
<tr><td style="color:#8fa0b8;padding-right:16px;">Registration ID</td><td><strong style="font-family:monospace;">{{regCode}}</strong></td></tr>
<tr><td style="color:#8fa0b8;">Pass</td><td>{{passName}} · {{amount}}</td></tr>
<tr><td style="color:#8fa0b8;">Dates</td><td>{{dates}}</td></tr>
<tr><td style="color:#8fa0b8;">Venue</td><td>{{venue}}</td></tr>
</table>
${btn("ticketUrl", "View my QR ticket")}
<p style="color:#61708a;font-size:13px;">Show the QR code at the check-in desk. The full agenda is at <a href="{{scheduleUrl}}">the conference schedule</a>.</p>`,
  },
  {
    key: "refund_processed",
    label: "Refund processed",
    description: "Sent when finance refunds a payment and cancels the registration.",
    variables: { name: "Rohan Verma", conferenceName: "TechBharat Summit 2026", amount: "₹1,999", regCode: "CFX-8K2M4P" },
    subject: "Refund processed — {{conferenceName}}",
    body: `<p>Hi {{name}},</p>
<p>Your payment of <strong>{{amount}}</strong> for registration <span style="font-family:monospace;">{{regCode}}</span> has been <strong>refunded</strong> and the registration cancelled.</p>
<p style="color:#61708a;font-size:13px;">Refunds typically reach your account in 5–7 business days. Reply to this email if you have questions.</p>`,
  },
  {
    key: "certificate_issued",
    label: "Certificate issued",
    description: "Sent when a participation/speaker certificate is generated.",
    variables: { name: "Rohan Verma", conferenceName: "TechBharat Summit 2026", certType: "participation", certId: "CFX-CERT-9D3A21BC", verifyUrl: "https://confexe.indicops.com/verify/CFX-CERT-9D3A21BC", issuedOn: "5 Oct 2026" },
    subject: "🏅 Your certificate from {{conferenceName}}",
    body: `<p>Hi {{name}},</p>
<p>Your <strong>{{certType}}</strong> certificate is ready. It carries a unique ID (<span style="font-family:monospace;">{{certId}}</span>) and can be verified by anyone at the link below.</p>
${btn("verifyUrl", "View & download certificate")}
<p style="color:#61708a;font-size:13px;">Issued {{issuedOn}} · printable A4 with QR verification.</p>`,
  },
  {
    key: "submission_received",
    label: "Submission received",
    description: "Acknowledgement sent when an author submits a paper/abstract to the CFP.",
    variables: { name: "Dr. Kavita Rao", conferenceName: "TechBharat Summit 2026", title: "Multilingual evaluation of Indic LLMs", category: "PAPER", submissionsUrl: "https://confexe.indicops.com/me/submissions" },
    subject: "We received your submission — {{conferenceName}}",
    body: `<p>Hi {{name}},</p>
<p>Thank you — your submission to <strong>{{conferenceName}}</strong> has been received and is now with the programme committee.</p>
<p style="border-left:3px solid {{accent}};padding-left:12px;color:#33415c;"><strong>{{title}}</strong><br/><span style="color:#8fa0b8;font-size:13px;">{{category}}</span></p>
${btn("submissionsUrl", "Track my submission")}
<p style="color:#61708a;font-size:13px;">You'll get another email as soon as a decision is made.</p>`,
  },
  {
    key: "submission_decision",
    label: "Submission decision",
    description: "Sent when the committee accepts, rejects or requests revision.",
    variables: { name: "Dr. Kavita Rao", conferenceName: "TechBharat Summit 2026", title: "Multilingual evaluation of Indic LLMs", category: "PAPER", decisionLine: "Congratulations — your submission has been <strong>accepted</strong>!", submissionsUrl: "https://confexe.indicops.com/me/submissions" },
    subject: "Decision on your submission — {{conferenceName}}",
    body: `<p>Hi {{name}},</p>
<p>{{decisionLine}}</p>
<p style="border-left:3px solid {{accent}};padding-left:12px;color:#33415c;"><strong>{{title}}</strong><br/><span style="color:#8fa0b8;font-size:13px;">{{category}}</span></p>
${btn("submissionsUrl", "View my submissions")}`,
  },
  {
    key: "reviewer_assigned",
    label: "Reviewer assignment",
    description: "Sent to a reviewer when a paper is assigned to them.",
    variables: { conferenceName: "TechBharat Summit 2026", reviewsUrl: "https://confexe.indicops.com/me/reviews" },
    subject: "📄 New review assignment — {{conferenceName}}",
    body: `<p>A paper has been assigned to you for review at <strong>{{conferenceName}}</strong>.</p>
${btn("reviewsUrl", "Open my review inbox")}
<p style="color:#61708a;font-size:13px;">Reviews are single-blind — authors will not see your name.</p>`,
  },
  {
    key: "volunteer_welcome",
    label: "Volunteer welcome",
    description: "Sent when an organizer adds a volunteer (includes one-time password for new accounts).",
    variables: { name: "Sameer Khan", conferenceName: "TechBharat Summit 2026", duties: "Check-in desk, Registrations", credentialsBlock: "Email: <strong>sameer@example.org</strong><br/>Temporary password: <strong style=\"font-family:monospace;\">cfx-7a2b9c1d</strong>", loginUrl: "https://confexe.indicops.com/login" },
    subject: "🙋 You're a volunteer at {{conferenceName}}",
    body: `<p>Hi {{name}},</p>
<p>You've been added to the volunteer team for <strong>{{conferenceName}}</strong>.</p>
<p><strong>Your duties:</strong> {{duties}}</p>
<p style="background:#f6f7fd;border-radius:10px;padding:12px 16px;">{{credentialsBlock}}</p>
${btn("loginUrl", "Open my volunteer dashboard")}
<p style="color:#61708a;font-size:13px;">Please keep your login details safe.</p>`,
  },
  {
    key: "team_invite",
    label: "Team member invite",
    description: "Sent when an organization admin adds someone to the team.",
    variables: { name: "Meera Krishnan", orgName: "Bharat Tech Foundation", role: "Finance Manager", credentialsBlock: "Email: <strong>meera@example.org</strong><br/>Temporary password: <strong style=\"font-family:monospace;\">cfx-2e8d4f6a</strong>", dashboardUrl: "https://confexe.indicops.com/dashboard" },
    subject: "You've been added to {{orgName}} on Confexe",
    body: `<p>Hi {{name}},</p>
<p><strong>{{orgName}}</strong> has added you to their team on Confexe as <strong>{{role}}</strong>. Your console shows exactly the modules your role covers.</p>
<p style="background:#f6f7fd;border-radius:10px;padding:12px 16px;">{{credentialsBlock}}</p>
${btn("dashboardUrl", "Open the Organizer Console")}
<p style="color:#61708a;font-size:13px;">If you already had a Confexe account, sign in with your usual password.</p>`,
  },
  {
    key: "announcement",
    label: "Conference announcement",
    description: "The blast sent to confirmed registrants when organizers post an email-enabled announcement.",
    variables: { name: "Rohan Verma", conferenceName: "TechBharat Summit 2026", announcementTitle: "Hall change for the opening keynote", announcementBody: "The 9 AM keynote moves to the Main Auditorium. Doors open 8:30.", siteUrl: "https://confexe.indicops.com/c/techbharat" },
    subject: "📢 {{conferenceName}}: {{announcementTitle}}",
    body: `<p>Hi {{name}},</p>
<p><strong>{{announcementTitle}}</strong></p>
<p>{{announcementBody}}</p>
${btn("siteUrl", "Open conference site")}`,
  },
];

export const TEMPLATE_KEYS = EMAIL_TEMPLATES.map((t) => t.key);

export function templateDef(key: string): TemplateDef | undefined {
  return EMAIL_TEMPLATES.find((t) => t.key === key);
}

function substitute(text: string, vars: Record<string, string>): string {
  return text.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k: string) => vars[k] ?? "");
}

/** Branded HTML shell shared by every trigger (fixed — not admin-editable). */
export function emailLayout(opts: { title: string; bodyHtml: string; accent?: string; footer?: string }): string {
  const accent = opts.accent ?? "#6366f1";
  return `<!doctype html><html><body style="margin:0;background:#eef1fb;font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;padding:24px 12px;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td align="center">
  <table role="presentation" width="560" cellpadding="0" cellspacing="0" style="max-width:560px;width:100%;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 8px 32px rgba(80,90,180,.12);">
    <tr><td style="background:${accent};padding:20px 28px;">
      <div style="color:#ffffff;font-size:18px;font-weight:800;">${opts.title}</div>
    </td></tr>
    <tr><td style="padding:28px;color:#1f2a44;font-size:15px;line-height:1.6;">${opts.bodyHtml}</td></tr>
    <tr><td style="padding:16px 28px;border-top:1px solid #eef1fb;color:#8fa0b8;font-size:12px;">
      ${opts.footer ?? "Sent by Confexe — the conference operating system."}
    </td></tr>
  </table></td></tr></table></body></html>`;
}

/**
 * Render a template: admin override (DB) if present, else the default.
 * Returns the final subject and full HTML (body wrapped in the branded shell).
 */
export async function renderTemplate(
  key: string,
  vars: Record<string, string>,
  opts?: { title?: string; accent?: string }
): Promise<{ subject: string; html: string } | null> {
  const def = templateDef(key);
  if (!def) return null;
  let subject = def.subject;
  let body = def.body;
  try {
    const override = await db.emailTemplate.findUnique({ where: { key } });
    if (override) {
      subject = override.subject || subject;
      body = override.body || body;
    }
  } catch { /* fall back to defaults if the table is unreachable */ }
  const accent = opts?.accent ?? "#6366f1";
  const allVars = { accent, ...vars };
  return {
    subject: substitute(subject, allVars),
    html: emailLayout({
      title: opts?.title ?? "Confexe",
      accent,
      bodyHtml: substitute(body, allVars),
    }),
  };
}
