import { publicWebUrl } from '../config/env';
import type { EmailBrand } from './email-brand';

/**
 * The emails HostelCare sends, each as plain text and HTML.
 *
 * One house frame for everything: the hostel's name and colour at the top,
 * a clear title, one highlighted figure where there is one (an amount, a
 * code, a date), a details card, a single button, and the office's contact
 * details in the footer. Built with tables and inline styles only, because
 * that is what Gmail, Outlook and the phone mail apps actually render.
 *
 * Amounts arrive as whole rupees; dates as already-formatted strings. These
 * functions build strings only — nothing here touches the database or the
 * network, so `npm run email:preview` can render every one of them.
 */

export interface EmailMessage {
  subject: string;
  text: string;
  html: string;
}

export function escapeHtml(s: string): string {
  return s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
}

const rupees = (n: number) => `₹${n.toLocaleString('en-IN')}`;
const DEFAULT_ACCENT = '#1a3a5c';
const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";
const INK = '#0f172a';
const MUTED = '#64748b';
const LINE = '#e2e8f0';

type Tone = 'info' | 'good' | 'warning' | 'danger' | 'neutral';
const TONES: Record<Tone, { bg: string; fg: string }> = {
  info: { bg: '#e8f0fe', fg: '#1d4ed8' },
  good: { bg: '#dcfce7', fg: '#15803d' },
  warning: { bg: '#fef3c7', fg: '#b45309' },
  danger: { bg: '#fee2e2', fg: '#b91c1c' },
  neutral: { bg: '#f1f5f9', fg: '#475569' },
};

/** A hex colour the owner typed, or the house navy when it is missing or odd. */
function accentOf(brand: EmailBrand): string {
  const a = brand.accent?.trim() ?? '';
  return /^#[0-9a-f]{6}$/i.test(a) ? a : DEFAULT_ACCENT;
}

function detailsTable(rows: [string, string][]): string {
  return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:separate;border-spacing:0;margin:20px 0 0;border:1px solid ${LINE};border-radius:12px;overflow:hidden">
${rows
  .map(
    ([k, v], i) =>
      `<tr><td style="padding:11px 16px;font-family:${FONT};font-size:13px;color:${MUTED};background:${i % 2 ? '#ffffff' : '#f8fafc'};width:44%;vertical-align:top">${escapeHtml(k)}</td><td style="padding:11px 16px;font-family:${FONT};font-size:14px;color:${INK};font-weight:600;background:${i % 2 ? '#ffffff' : '#f8fafc'};text-align:right;vertical-align:top">${escapeHtml(v)}</td></tr>`,
  )
  .join('\n')}
</table>`;
}

function detailsText(rows: [string, string][]): string {
  const w = Math.max(...rows.map(([k]) => k.length));
  return rows.map(([k, v]) => `  ${k.padEnd(w)}  ${v}`).join('\n');
}

/** The one figure the reader is looking for: an amount, a code, a date. */
function highlight(label: string, value: string, accent: string, opts: { mono?: boolean; spaced?: boolean; tone?: Tone } = {}): string {
  const tone = opts.tone ? TONES[opts.tone] : null;
  return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:20px 0 0"><tr><td align="center" style="padding:18px 20px;border-radius:12px;background:${tone ? tone.bg : '#f8fafc'};border:1px solid ${tone ? tone.bg : LINE}">
<div style="font-family:${FONT};font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:${tone ? tone.fg : MUTED}">${escapeHtml(label)}</div>
<div style="margin-top:6px;font-family:${opts.mono ? "'SFMono-Regular',Menlo,Consolas,monospace" : FONT};font-size:${opts.spaced ? '32px' : '28px'};font-weight:700;letter-spacing:${opts.spaced ? '8px' : '-0.01em'};color:${tone ? tone.fg : accent}">${escapeHtml(value)}</div>
</td></tr></table>`;
}

/** A bulletproof button: a table cell, so Outlook draws it too. */
function button(url: string, label: string, accent: string): string {
  return `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:24px auto 0"><tr><td align="center" style="border-radius:12px;background:${accent}"><a href="${escapeHtml(url)}" style="display:inline-block;padding:14px 28px;font-family:${FONT};font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:12px">${escapeHtml(label)}</a></td></tr></table>
<p style="margin:10px 0 0;font-family:${FONT};font-size:12px;color:#94a3b8;text-align:center;word-break:break-all">If the button does not open, copy this link: ${escapeHtml(url)}</p>`;
}

function badge(text: string, tone: Tone): string {
  const t = TONES[tone];
  return `<span style="display:inline-block;padding:5px 11px;border-radius:999px;background:${t.bg};color:${t.fg};font-family:${FONT};font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase">${escapeHtml(text)}</span>`;
}

/** A quoted passage: the body of a notice, a visitor's message. */
function quote(text: string, accent: string): string {
  return `<div style="margin:20px 0 0;padding:16px 18px;background:#f8fafc;border-left:4px solid ${accent};border-radius:0 10px 10px 0;font-family:${FONT};font-size:15px;line-height:1.65;color:${INK};white-space:pre-wrap">${escapeHtml(text)}</div>`;
}

interface Frame {
  brand: EmailBrand;
  /** The pill above the title. */
  badge?: { text: string; tone: Tone };
  title: string;
  /** May contain <strong>; everything else must be escaped by the caller. */
  intro: string;
  /** Rendered between the intro and the footer note. */
  bodyHtml?: string;
  /** Small print under the body. */
  note?: string;
  /** Hidden preview line the inbox shows next to the subject. */
  preheader?: string;
  /** What the reader should know about why they got this. */
  reason?: string;
  /** L6: a lead's one-click way to stop all HostelCare messages. */
  unsubscribeUrl?: string;
}

/** The house frame. */
function wrap(f: Frame): string {
  const accent = accentOf(f.brand);
  const firm = escapeHtml(f.brand.firm);
  const monogram = escapeHtml((f.brand.firm.trim().charAt(0) || 'H').toUpperCase());
  const contact = [f.brand.address, f.brand.phone, f.brand.email].filter((x): x is string => !!x && x.trim().length > 0);
  const preheader = f.preheader ?? f.intro.replace(/<[^>]+>/g, '');
  return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="light">
<meta name="supported-color-schemes" content="light">
<title>${escapeHtml(f.title)}</title>
</head>
<body style="margin:0;padding:0;background:#eef2f7;-webkit-text-size-adjust:100%">
<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;font-size:1px;line-height:1px">${escapeHtml(preheader)}&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#eef2f7"><tr><td align="center" style="padding:32px 12px 40px">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px">

<tr><td style="padding:0 6px 14px">
<table role="presentation" cellpadding="0" cellspacing="0"><tr>
<td style="width:40px;height:40px;border-radius:12px;background:${accent};text-align:center;vertical-align:middle;font-family:${FONT};font-size:18px;font-weight:700;color:#ffffff">${monogram}</td>
<td style="padding-left:12px;font-family:${FONT};font-size:16px;font-weight:700;color:${INK};vertical-align:middle">${firm}${f.brand.firm.trim().toLowerCase() === 'hostelcare' ? '' : `<div style="font-size:11px;font-weight:500;color:${MUTED};margin-top:1px">via HostelCare</div>`}</td>
</tr></table>
</td></tr>

<tr><td style="background:#ffffff;border-radius:18px;border:1px solid ${LINE};border-top:5px solid ${accent};padding:32px 32px 28px">
${f.badge ? `<div style="margin-bottom:14px">${badge(f.badge.text, f.badge.tone)}</div>` : ''}
<h1 style="margin:0 0 10px;font-family:${FONT};font-size:24px;line-height:1.25;font-weight:700;color:${INK};letter-spacing:-0.01em">${escapeHtml(f.title)}</h1>
<p style="margin:0;font-family:${FONT};font-size:15px;line-height:1.65;color:#334155">${f.intro}</p>
${f.bodyHtml ?? ''}
${f.note ? `<p style="margin:22px 0 0;font-family:${FONT};font-size:13px;line-height:1.6;color:${MUTED}">${f.note}</p>` : ''}
</td></tr>

<tr><td style="padding:22px 24px 0;text-align:center;font-family:${FONT};font-size:12px;line-height:1.7;color:#94a3b8">
<div style="font-weight:600;color:${MUTED}">${firm}</div>
${contact.length ? `<div>${contact.map((c) => escapeHtml(c)).join(' &nbsp;·&nbsp; ')}</div>` : ''}
<div style="margin-top:8px">${escapeHtml(f.reason ?? 'You are receiving this because you have an account with this hostel on HostelCare.')}</div>${f.unsubscribeUrl ? `<div style="margin-top:8px"><a href="${escapeHtml(f.unsubscribeUrl)}" style="color:#94a3b8;text-decoration:underline">Unsubscribe from HostelCare messages</a></div>` : ''}
<div>This is an automated message${f.brand.email ? `; write to <a href="mailto:${escapeHtml(f.brand.email)}" style="color:${MUTED}">${escapeHtml(f.brand.email)}</a> to reach the office` : ''}.</div>
<div style="margin-top:8px"><a href="${escapeHtml(publicWebUrl)}" style="color:${accent};font-weight:600;text-decoration:none">Open HostelCare</a></div>
</td></tr>

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

const app = (hash: string) => `${publicWebUrl}/#${hash}`;
const brandOf = (p: { firm: string; brand?: Partial<EmailBrand> | null }): EmailBrand => ({ firm: p.brand?.firm || p.firm, accent: p.brand?.accent, address: p.brand?.address, phone: p.brand?.phone, email: p.brand?.email });

export interface InvoiceFacts {
  number: string;
  /** 'Rent', 'Mess' or 'Bill' (lib/invoice-words.ts). */
  kind: string;
  periodLabel: string; // "October 2026" or "Oct 2026 – Dec 2026"
  amount: number;
  paid: number;
  balance: number;
  dueDate: string | null;
}

type Branded = { firm: string; brand?: Partial<EmailBrand> | null };

// ── Sign-in and two-step codes ───────────────────────────────────────────────

export function otpEmail(p: { name: string; code: string; minutes: number; purpose: 'LOGIN' | 'ENABLE_2FA' | 'DISABLE_2FA' | 'STEP_UP' | 'TRIAL' }): EmailMessage {
  const copy = {
    LOGIN: { subject: 'Your HostelCare sign-in code', title: 'Your sign-in code', lead: 'Use this code to finish signing in to HostelCare.' },
    ENABLE_2FA: { subject: 'Confirm two-step verification', title: 'Turn on two-step verification', lead: 'Use this code to turn on two-step verification for your HostelCare account.' },
    DISABLE_2FA: { subject: 'Confirm turning off two-step verification', title: 'Turn off two-step verification', lead: 'Use this code to turn off two-step verification for your HostelCare account.' },
    STEP_UP: { subject: 'Confirm a CRM action', title: 'Confirm it is you', lead: 'Use this code to confirm a sensitive action in the HostelCare CRM, such as deleting or exporting records.' },
    TRIAL: { subject: 'Your HostelCare free trial code', title: 'Confirm your email', lead: 'Use this code to confirm your email and start your free 7-day HostelCare trial.' },
  }[p.purpose];
  const brand: EmailBrand = { firm: 'HostelCare' };
  return {
    subject: copy.subject,
    text: `Hi ${p.name},\n\n${copy.lead}\n\n    ${p.code}\n\nThe code expires in ${p.minutes} minutes and can be used once.\nIf you didn't ask for this, you can ignore this email — your password is still needed to sign in.\n\n— HostelCare`,
    html: wrap({
      brand,
      badge: { text: 'Security', tone: 'info' },
      title: copy.title,
      intro: `Hi ${escapeHtml(p.name)}, ${escapeHtml(copy.lead.charAt(0).toLowerCase() + copy.lead.slice(1))}`,
      bodyHtml: highlight('Your code', p.code, DEFAULT_ACCENT, { mono: true, spaced: true }),
      note: `The code expires in ${p.minutes} minutes and can be used once. If you didn't ask for this, you can ignore this email — your password is still needed to sign in.`,
      preheader: `${p.code} is your HostelCare code. It expires in ${p.minutes} minutes.`,
      reason: 'You are receiving this because someone used your email address to sign in to HostelCare.',
    }),
  };
}

// ── Payment confirmation ─────────────────────────────────────────────────────

export function paymentReceivedEmail(p: Branded & {
  studentName: string;
  amount: number;
  paidOn: string;
  method: string;
  reference: string | null;
  paymentId: string;
  invoice: InvoiceFacts;
  receiptAttached: boolean;
}): EmailMessage {
  const brand = brandOf(p);
  const settled = p.invoice.balance <= 0;
  const rows: [string, string][] = [
    ['Received on', p.paidOn],
    ['Paid by', p.method],
    ...(p.reference ? ([['Transaction ref', p.reference]] as [string, string][]) : []),
    ['Payment ID', p.paymentId],
    ['Towards', `${p.invoice.kind} · ${p.invoice.periodLabel}`],
    ['Invoice', p.invoice.number],
    ['Invoice amount', rupees(p.invoice.amount)],
    [settled ? 'Status' : 'Still due', settled ? 'Paid in full' : `${rupees(p.invoice.balance)}${p.invoice.dueDate ? ` by ${p.invoice.dueDate}` : ''}`],
  ];
  const intro = `Hi ${escapeHtml(p.studentName)}, thank you — we have recorded your payment towards ${escapeHtml(p.invoice.kind.toLowerCase())} for ${escapeHtml(p.invoice.periodLabel)}.`;
  const note = p.receiptAttached ? 'Your receipt is attached as a PDF. You can also download it any time from Dues &amp; Invoices in HostelCare.' : 'You can download your receipt any time from Dues &amp; Invoices in HostelCare.';
  return {
    subject: `Payment received: ${rupees(p.amount)} towards ${p.invoice.kind.toLowerCase()} · ${p.invoice.periodLabel}`,
    text: `Hi ${p.studentName},\n\nThank you — we have recorded your payment of ${rupees(p.amount)}.\n\n${detailsText([['Amount received', rupees(p.amount)], ...rows])}\n\n${p.receiptAttached ? 'Your receipt is attached as a PDF.' : 'You can download your receipt from Dues & Invoices in HostelCare.'}\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: settled ? 'Paid in full' : 'Payment recorded', tone: 'good' },
      title: 'Payment received',
      intro,
      bodyHtml: highlight('Amount received', rupees(p.amount), accentOf(brand), { tone: 'good' }) + detailsTable(rows) + button(app('dues'), 'View receipt', accentOf(brand)),
      note,
      preheader: `${rupees(p.amount)} received towards ${p.invoice.kind.toLowerCase()} for ${p.invoice.periodLabel}.`,
    }),
  };
}

// ── Payment failure ──────────────────────────────────────────────────────────

export function paymentFailedEmail(p: Branded & {
  studentName: string;
  amount: number;
  paidOn: string;
  method: string;
  reference: string | null;
  paymentId: string;
  reason: string | null;
  invoice: InvoiceFacts;
  contact: string | null;
}): EmailMessage {
  const brand = brandOf(p);
  const rows: [string, string][] = [
    ['Payment', `${rupees(p.amount)} by ${p.method} on ${p.paidOn}`],
    ...(p.reference ? ([['Transaction ref', p.reference]] as [string, string][]) : []),
    ['Payment ID', p.paymentId],
    ...(p.reason ? ([['Reason', p.reason]] as [string, string][]) : []),
    ['Towards', `${p.invoice.kind} · ${p.invoice.periodLabel} (${p.invoice.number})`],
  ];
  const intro = `Hi ${escapeHtml(p.studentName)}, a payment we had recorded against your account <strong>did not go through</strong>, so it has been reversed.`;
  const note = `Please arrange the payment again${p.contact ? `, or contact the office at ${escapeHtml(p.contact)} if you believe this is a mistake` : ''}.`;
  return {
    subject: `Payment failed: ${rupees(p.amount)} towards ${p.invoice.kind.toLowerCase()} · ${p.invoice.periodLabel}`,
    text: `Hi ${p.studentName},\n\nA payment we had recorded against your account did not go through, so it has been reversed.\n\n${detailsText([...rows, ['Now due', `${rupees(p.invoice.balance)}${p.invoice.dueDate ? ` by ${p.invoice.dueDate}` : ''}`]])}\n\nPlease arrange the payment again${p.contact ? `, or contact the office at ${p.contact} if you believe this is a mistake` : ''}.\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: 'Action needed', tone: 'danger' },
      title: 'Payment failed',
      intro,
      bodyHtml: highlight(p.invoice.dueDate ? `Now due by ${p.invoice.dueDate}` : 'Now due', rupees(p.invoice.balance), accentOf(brand), { tone: 'danger' }) + detailsTable(rows) + button(app('dues'), 'Pay again', accentOf(brand)),
      note,
      preheader: `A payment of ${rupees(p.amount)} was reversed; ${rupees(p.invoice.balance)} is due.`,
    }),
  };
}

// ── Fee due: a new invoice, or a reminder ────────────────────────────────────

export function invoiceRaisedEmail(p: Branded & { studentName: string; invoice: InvoiceFacts; cycleMonths: number }): EmailMessage {
  const brand = brandOf(p);
  const rows: [string, string][] = [
    ['Invoice', p.invoice.number],
    ['For', `${p.invoice.kind} · ${p.invoice.periodLabel}${p.cycleMonths > 1 ? ` (${p.cycleMonths}-month cycle)` : ''}`],
    ['Due by', p.invoice.dueDate ?? '—'],
  ];
  const intro = `Hi ${escapeHtml(p.studentName)}, your ${escapeHtml(p.invoice.kind.toLowerCase())} for <strong>${escapeHtml(p.invoice.periodLabel)}</strong> has been raised.`;
  return {
    subject: `${p.invoice.kind} due: ${rupees(p.invoice.amount)} for ${p.invoice.periodLabel}${p.invoice.dueDate ? ` by ${p.invoice.dueDate}` : ''}`,
    text: `Hi ${p.studentName},\n\nYour ${p.invoice.kind.toLowerCase()} for ${p.invoice.periodLabel} has been raised.\n\n${detailsText([['Amount', rupees(p.invoice.amount)], ...rows])}\n\nPay in HostelCare or at the office, and quote the invoice number.\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: 'New invoice', tone: 'info' },
      title: `${p.invoice.kind} for ${p.invoice.periodLabel}`,
      intro,
      bodyHtml: highlight(p.invoice.dueDate ? `Due by ${p.invoice.dueDate}` : 'Amount due', rupees(p.invoice.amount), accentOf(brand)) + detailsTable(rows) + button(app('dues'), 'View and pay', accentOf(brand)),
      note: 'Pay in HostelCare, or at the office quoting the invoice number. You will get a receipt by email once the payment is recorded.',
      preheader: `${rupees(p.invoice.amount)} for ${p.invoice.periodLabel}${p.invoice.dueDate ? `, due by ${p.invoice.dueDate}` : ''}.`,
    }),
  };
}

// ── Online payment link ──────────────────────────────────────────────────────

export function paymentLinkEmail(p: Branded & {
  studentName: string;
  invoiceNumber: string;
  kind: string;
  periodLabel: string;
  baseAmount: number;
  grossAmount: number;
  feeBearer: 'STUDENT' | 'HOSTEL';
  dueDate: string | null;
  linkUrl: string;
  expiresAt: Date;
}): EmailMessage {
  const brand = brandOf(p);
  const until = p.expiresAt.toLocaleString('en-IN', { day: '2-digit', month: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });
  const feeRow: [string, string][] = p.grossAmount !== p.baseAmount ? [['Including gateway charges', rupees(p.grossAmount - p.baseAmount)]] : [];
  const rows: [string, string][] = [
    ['Invoice', p.invoiceNumber],
    ['For', `${p.kind} · ${p.periodLabel}`],
    ['Amount due', rupees(p.baseAmount)],
    ...feeRow,
    ...(p.dueDate ? ([['Due date', p.dueDate]] as [string, string][]) : []),
    ['Link valid until', `${until} IST`],
  ];
  const intro = `Hi ${escapeHtml(p.studentName)}, you can pay your ${escapeHtml(p.kind.toLowerCase())} for ${escapeHtml(p.periodLabel)} by UPI, card or net banking.`;
  return {
    subject: `Pay ${rupees(p.grossAmount)} online · ${p.kind} ${p.periodLabel} (${p.invoiceNumber})`,
    text: `Hi ${p.studentName},\n\nYou can pay ${rupees(p.grossAmount)} for your ${p.kind.toLowerCase()} (${p.periodLabel}) online by UPI, card or net banking:\n\n${p.linkUrl}\n\n${detailsText(rows)}\n\nThe link is valid until ${until} IST. If it has expired, open HostelCare and press Pay to get a fresh one.\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: 'Payment link', tone: 'info' },
      title: 'Pay online',
      intro,
      bodyHtml: highlight('Pay online', rupees(p.grossAmount), accentOf(brand)) + detailsTable(rows) + button(p.linkUrl, `Pay ${rupees(p.grossAmount)}`, accentOf(brand)),
      note: 'Secure payment by Razorpay. If the link has expired, open HostelCare and press Pay to get a fresh one.',
      preheader: `Pay ${rupees(p.grossAmount)} for ${p.kind.toLowerCase()} ${p.periodLabel}. Link valid until ${until} IST.`,
    }),
  };
}

export function feeReminderEmail(p: Branded & { studentName: string; invoice: InvoiceFacts; when: string; overdue: boolean; payUrl?: string | null; payAmount?: number | null }): EmailMessage {
  const brand = brandOf(p);
  const rows: [string, string][] = [
    ['Invoice', p.invoice.number],
    ['For', `${p.invoice.kind} · ${p.invoice.periodLabel}`],
    ['Due date', p.invoice.dueDate ?? '—'],
  ];
  const title = p.overdue ? `${p.invoice.kind} overdue` : `${p.invoice.kind} due ${p.when}`;
  const intro = p.overdue
    ? `Hi ${escapeHtml(p.studentName)}, your ${escapeHtml(p.invoice.kind.toLowerCase())} for ${escapeHtml(p.invoice.periodLabel)} is <strong>overdue</strong>; it was due ${escapeHtml(p.when)}.`
    : `Hi ${escapeHtml(p.studentName)}, a reminder that your ${escapeHtml(p.invoice.kind.toLowerCase())} for ${escapeHtml(p.invoice.periodLabel)} is due ${escapeHtml(p.when)}.`;
  return {
    subject: `Reminder: ${p.invoice.kind.toLowerCase()} of ${rupees(p.invoice.balance)} due ${p.when} · ${p.invoice.periodLabel}`,
    text: `Hi ${p.studentName},\n\nA reminder that ${rupees(p.invoice.balance)} of your ${p.invoice.kind.toLowerCase()} for ${p.invoice.periodLabel} is due ${p.when}.\n\n${detailsText([['Amount due', rupees(p.invoice.balance)], ...rows])}\n\n${p.payUrl ? `Pay online (UPI, card or net banking): ${p.payUrl}\n\n` : ''}Please pay to avoid a late fee. If you have already paid, you can ignore this.\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: p.overdue ? 'Overdue' : 'Reminder', tone: p.overdue ? 'danger' : 'warning' },
      title,
      intro,
      bodyHtml: highlight(p.overdue ? 'Overdue amount' : `Due ${p.when}`, rupees(p.invoice.balance), accentOf(brand), { tone: p.overdue ? 'danger' : 'warning' }) + detailsTable(rows) + button(p.payUrl ?? app('dues'), p.payUrl ? `Pay ${rupees(p.payAmount ?? p.invoice.balance)} online` : 'View and pay', accentOf(brand)),
      note: 'Please pay to avoid a late fee. If you have already paid, you can ignore this email.',
      preheader: `${rupees(p.invoice.balance)} of ${p.invoice.kind.toLowerCase()} is due ${p.when}.`,
    }),
  };
}

// ── Settlement shared ────────────────────────────────────────────────────────

export function settlementSharedEmail(p: Branded & {
  studentName: string;
  lastDay: string;
  depositHeld: number;
  dues: number;
  deductions: { label: string; amount: number }[];
  refundDue: number;
  shortfall: number;
  promisedDate: string;
  attached: boolean;
}): EmailMessage {
  const brand = brandOf(p);
  const rows: [string, string][] = [
    ['Last day', p.lastDay],
    ['Deposit held', rupees(p.depositHeld)],
    ...(p.dues > 0 ? ([['Unpaid dues', `− ${rupees(p.dues)}`]] as [string, string][]) : []),
    ...p.deductions.map((d) => [`Deduction · ${d.label}`, `− ${rupees(d.amount)}`] as [string, string]),
    p.shortfall > 0 ? ['Payable by', p.lastDay] : ['Refund promised by', p.promisedDate],
  ];
  const intro = p.shortfall > 0
    ? `Hi ${escapeHtml(p.studentName)}, your move-out settlement is ready. The deposit did not cover everything, so the balance has been raised as a final invoice.`
    : `Hi ${escapeHtml(p.studentName)}, your move-out settlement is ready. Your refund will reach you by <strong>${escapeHtml(p.promisedDate)}</strong>.`;
  const note = `${p.attached ? 'The statement is attached as a PDF. ' : ''}If you disagree with a deduction, open HostelCare and press “Dispute settlement” within 7 days.`;
  return {
    subject: p.shortfall > 0 ? `Move-out settlement: ${rupees(p.shortfall)} due · ${brand.firm}` : `Move-out settlement: ${rupees(p.refundDue)} refund by ${p.promisedDate} · ${brand.firm}`,
    text: `Hi ${p.studentName},\n\nYour move-out settlement is ready.\n\n${detailsText([...rows, p.shortfall > 0 ? ['Amount due from you', rupees(p.shortfall)] : ['Refund due to you', rupees(p.refundDue)]])}\n\n${p.attached ? 'The statement is attached as a PDF.' : 'The statement is in HostelCare under Dues & Invoices.'} If you disagree with a deduction, open HostelCare and press “Dispute settlement” within 7 days.\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: 'Settlement', tone: p.shortfall > 0 ? 'warning' : 'good' },
      title: 'Move-out settlement',
      intro,
      bodyHtml: highlight(p.shortfall > 0 ? 'Amount due from you' : 'Refund due to you', rupees(p.shortfall > 0 ? p.shortfall : p.refundDue), accentOf(brand), { tone: p.shortfall > 0 ? 'warning' : 'good' }) + detailsTable(rows) + button(app('dues'), 'Open the settlement', accentOf(brand)),
      note,
      preheader: p.shortfall > 0 ? `${rupees(p.shortfall)} is due on your move-out settlement.` : `${rupees(p.refundDue)} will be refunded by ${p.promisedDate}.`,
    }),
  };
}

// ── Gate: late return ────────────────────────────────────────────────────────

export function lateReturnEmail(p: Branded & { recipientName: string; studentName: string; dueBack: string; destination: string | null; forGuardian: boolean }): EmailMessage {
  const brand = brandOf(p);
  const rows: [string, string][] = [
    ['Student', p.studentName],
    ...(p.destination ? ([['Went to', p.destination]] as [string, string][]) : []),
  ];
  const intro = p.forGuardian
    ? `Hi ${escapeHtml(p.recipientName)}, <strong>${escapeHtml(p.studentName)}</strong> went out on a gate pass and has not returned by the time it ended. The hostel has been told as well; please check with them.`
    : `Hi ${escapeHtml(p.recipientName)}, <strong>${escapeHtml(p.studentName)}</strong> has not returned from a gate pass. The pass is flagged overdue at the gate and on the overview.`;
  return {
    subject: `Late return: ${p.studentName} · due back ${p.dueBack}`,
    text: `Hi ${p.recipientName},\n\n${p.studentName} has not returned from a gate pass that ended at ${p.dueBack} IST.\n\n${detailsText([...rows, ['Was due back', `${p.dueBack} IST`]])}\n\n${p.forGuardian ? 'The hostel has been told as well; please check with them.' : 'The pass is flagged overdue at the gate and on the overview.'}\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: 'Overdue', tone: 'danger' },
      title: 'Late return',
      intro,
      bodyHtml: highlight('Was due back', `${p.dueBack} IST`, accentOf(brand), { tone: 'danger' }) + detailsTable(rows) + (p.forGuardian ? '' : button(app('gate'), 'Open the gate board', accentOf(brand))),
      reason: p.forGuardian ? 'You are receiving this because you are listed as a guardian for this student on HostelCare.' : 'You are receiving this because you are staff at this hostel on HostelCare.',
      preheader: `${p.studentName} was due back ${p.dueBack} IST and has not scanned in.`,
    }),
  };
}

// ── Enquiry from the public vacancy page ─────────────────────────────────────

export function enquiryEmail(p: Branded & { name: string; phone: string; email: string | null; roomType: string | null; moveIn: string | null; message: string | null }): EmailMessage {
  const brand = brandOf(p);
  const rows: [string, string][] = [
    ['Name', p.name],
    ['Phone', p.phone],
    ...(p.email ? ([['Email', p.email]] as [string, string][]) : []),
    ...(p.roomType ? ([['Looking for', p.roomType]] as [string, string][]) : []),
    ...(p.moveIn ? ([['Move-in', p.moveIn]] as [string, string][]) : []),
  ];
  return {
    subject: `New enquiry: ${p.name} · ${p.phone}`,
    text: `Someone asked about a bed from your vacancy page.\n\n${detailsText(rows)}${p.message ? `\n\n${p.message}` : ''}\n\nOpen Enquiries in HostelCare to call them back or hold a bed.\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: 'Enquiry', tone: 'info' },
      title: `${p.name} asked about a bed`,
      intro: `Someone sent an enquiry from the vacancy page for <strong>${escapeHtml(p.firm)}</strong>. Call them back while it is fresh.`,
      bodyHtml: detailsTable(rows) + (p.message ? quote(p.message, accentOf(brand)) : '') + button(app('properties'), 'Open enquiries', accentOf(brand)),
      reason: 'You are receiving this because you are an admin of this hostel on HostelCare.',
      preheader: `${p.name} (${p.phone})${p.roomType ? ` wants a ${p.roomType}` : ''}${p.moveIn ? ` from ${p.moveIn}` : ''}.`,
    }),
  };
}

// ── Guardian invite ──────────────────────────────────────────────────────────

export function guardianInviteEmail(p: Branded & { guardianName: string; studentName: string; email: string; temporaryPassword: string | null }): EmailMessage {
  const brand = brandOf(p);
  const rows: [string, string][] = [
    ['Student', p.studentName],
    ['Sign in with', p.email],
  ];
  const intro = `Hi ${escapeHtml(p.guardianName)}, ${escapeHtml(brand.firm)} has given you a guardian login for <strong>${escapeHtml(p.studentName)}</strong>: their dues and receipts, attendance, gate passes and notices, in one place.`;
  return {
    subject: `Your guardian login for ${p.studentName} · ${brand.firm}`,
    text: `Hi ${p.guardianName},\n\n${brand.firm} has given you a guardian login for ${p.studentName}.\n\n${detailsText([...rows, ...(p.temporaryPassword ? ([['One-time password', p.temporaryPassword]] as [string, string][]) : [])])}\n\n${p.temporaryPassword ? 'Sign in to HostelCare with the password above and change it under Profile.' : 'Sign in to HostelCare with your existing password.'}\n\n— ${brand.firm}`,
    html: wrap({
      brand,
      badge: { text: 'Guardian access', tone: 'info' },
      title: 'You are a guardian on HostelCare',
      intro,
      bodyHtml: detailsTable(rows) + (p.temporaryPassword ? highlight('One-time password', p.temporaryPassword, accentOf(brand), { mono: true }) : '') + button(`${publicWebUrl}/login`, 'Sign in', accentOf(brand)),
      note: p.temporaryPassword ? 'Sign in with the one-time password and change it under Profile. It works once.' : 'Sign in with your existing password.',
      reason: 'You are receiving this because a hostel added you as a guardian on HostelCare.',
      preheader: `Your guardian login for ${p.studentName} at ${brand.firm}.`,
    }),
  };
}

// ── Important notices ────────────────────────────────────────────────────────

export function noticeEmail(p: Branded & { recipientName: string; title: string; body: string; postedBy: string; category: string }): EmailMessage {
  const brand = brandOf(p);
  return {
    subject: `Important notice: ${p.title}`,
    text: `Hi ${p.recipientName},\n\nAn important notice from ${brand.firm}:\n\n${p.title}\n\n${p.body}\n\n— Posted by ${p.postedBy}`,
    html: wrap({
      brand,
      badge: { text: p.category === 'MESS' ? 'Mess notice' : 'Important notice', tone: 'danger' },
      title: p.title,
      intro: `Hi ${escapeHtml(p.recipientName)}, an important notice from your hostel.`,
      bodyHtml: quote(p.body, accentOf(brand)) + `<p style="margin:12px 0 0;font-family:${FONT};font-size:12px;color:${MUTED}">Posted by ${escapeHtml(p.postedBy)}</p>` + button(app('notices'), 'See all notices', accentOf(brand)),
      preheader: p.body.slice(0, 140),
    }),
  };
}

/** Sprint 2 (TEPL): a complaint or repair closed — with the last word from the hostel, and a way to rate it. */
export function requestClosedEmail(p: Branded & { recipientName: string; subject: string; outcome: 'RESOLVED' | 'REJECTED'; lastReply: string | null }): EmailMessage {
  const brand = brandOf(p);
  const done = p.outcome === 'RESOLVED';
  const headline = done ? `Resolved: ${p.subject}` : `Closed: ${p.subject}`;
  return {
    subject: headline,
    text: `Hi ${p.recipientName},

Your request "${p.subject}" was ${done ? 'resolved' : 'closed without action'} by ${brand.firm}.${p.lastReply ? `

Their last note: ${p.lastReply}` : ''}

Open Requests in the app to see the thread and rate how it was handled.`,
    html: wrap({
      brand,
      badge: { text: done ? 'Resolved' : 'Closed', tone: done ? 'good' : 'neutral' },
      title: headline,
      intro: `Hi ${escapeHtml(p.recipientName)}, your request was ${done ? 'resolved' : 'closed without action'}.`,
      bodyHtml: (p.lastReply ? quote(p.lastReply, accentOf(brand)) : '') + button(app('requests'), 'See it and rate it', accentOf(brand)),
      preheader: done ? 'Your request was resolved.' : 'Your request was closed.',
    }),
  };
}

// ── Platform subscription invoice (super admin → hostel) ─────────────────────

export function subscriptionInvoiceEmail(p: {
  seller: { name: string; email?: string | null; phone?: string | null; address?: string | null };
  hostelName: string;
  number: string;
  amount: number;
  balance: number;
  dueDate: string | null;
  description: string;
  period: string | null;
}): EmailMessage {
  const brand: EmailBrand = { firm: p.seller.name, address: p.seller.address, phone: p.seller.phone, email: p.seller.email };
  const rows: [string, string][] = [
    ['Invoice', p.number],
    ['For', p.description],
    ...(p.period ? ([['Period', p.period]] as [string, string][]) : []),
    ['Total', rupees(p.amount)],
    ['Due by', p.dueDate ?? '—'],
  ];
  const owing = p.balance > 0;
  const intro = `Hello, please find attached invoice <strong>${escapeHtml(p.number)}</strong> for <strong>${escapeHtml(p.hostelName)}</strong>.`;
  return {
    subject: `Invoice ${p.number} from ${p.seller.name}`,
    text: `Hello,\n\nPlease find attached invoice ${p.number} for ${p.hostelName}.\n\n${detailsText(rows)}\n\n${owing ? `Please pay ${rupees(p.balance)}${p.dueDate ? ` by ${p.dueDate}` : ''} and quote ${p.number} as the reference.` : 'This invoice is fully paid. Thank you.'}\n\nThanks,\n${p.seller.name} Team`,
    html: wrap({
      brand,
      badge: { text: owing ? 'Invoice' : 'Paid', tone: owing ? 'info' : 'good' },
      title: `Invoice ${p.number}`,
      intro,
      bodyHtml: highlight(owing ? (p.dueDate ? `Due by ${p.dueDate}` : 'Amount due') : 'Paid in full', rupees(owing ? p.balance : p.amount), accentOf(brand)) + detailsTable(rows),
      note: owing ? `The invoice is attached as a PDF. Please quote ${escapeHtml(p.number)} when you pay.` : 'The invoice is attached as a PDF for your records.',
      preheader: `${rupees(p.amount)} — invoice ${p.number}${p.dueDate ? `, due by ${p.dueDate}` : ''}.`,
      reason: `You are receiving this because ${p.hostelName} uses HostelCare.`,
    }),
  };
}


// ── Plan expiry (9 Oct 2026) ─────────────────────────────────────────────────

/**
 * To a hostel: its paid-for HostelCare period ends soon. From the platform's
 * billing identity; names the renewal invoice when one is waiting.
 */
export function planExpiryReminderEmail(p: {
  seller: { name: string; email?: string | null; phone?: string | null; address?: string | null };
  hostelName: string;
  planName: string;
  endsOn: string;
  daysLeft: number;
  renewal: { number: string; balance: number; dueDate: string | null } | null;
  /** A free trial rather than a paid plan. */
  trial?: boolean;
}): EmailMessage {
  const brand: EmailBrand = { firm: p.seller.name, address: p.seller.address, phone: p.seller.phone, email: p.seller.email };
  const when = p.daysLeft === 1 ? 'tomorrow' : p.daysLeft === 0 ? 'today' : `in ${p.daysLeft} days`;
  if (p.trial) {
    const contact = [p.seller.email, p.seller.phone].filter(Boolean).join(' or ');
    const ask = `To keep using HostelCare after that, choose a plan${contact ? ` — reply to this email or contact us at ${contact}` : ' — reply to this email'}. Without one, sign-in pauses for everyone on the account until a plan is taken.`;
    const rows: [string, string][] = [
      ['Hostel', p.hostelName],
      ['Trial ends', p.endsOn],
    ];
    return {
      subject: `Your HostelCare free trial ends ${when} (${p.endsOn})`,
      text: `Hello,\n\nThe HostelCare free trial for ${p.hostelName} ends on ${p.endsOn} — that is ${when}.\n\n${detailsText(rows)}\n\n${ask}\n\nThanks,\n${p.seller.name} Team`,
      html: wrap({
        brand,
        badge: { text: p.daysLeft <= 1 ? 'Ends soon' : 'Free trial', tone: p.daysLeft <= 1 ? 'warning' : 'info' },
        title: `Your free trial ends ${when}`,
        intro: `The HostelCare free trial for <strong>${escapeHtml(p.hostelName)}</strong> ends on <strong>${escapeHtml(p.endsOn)}</strong>.`,
        bodyHtml: highlight('Trial ends', p.endsOn, accentOf(brand), { tone: p.daysLeft <= 1 ? 'warning' : undefined }) + detailsTable(rows),
        note: escapeHtml(ask),
        preheader: `Your HostelCare free trial ends on ${p.endsOn}.`,
        reason: `You are receiving this because ${p.hostelName} uses HostelCare and this address is on its account.`,
      }),
    };
  }
  const rows: [string, string][] = [
    ['Hostel', p.hostelName],
    ['Plan', p.planName],
    ['Paid until', p.endsOn],
    ...(p.renewal ? ([['Renewal invoice', p.renewal.number], ['Amount due', rupees(p.renewal.balance)], ['Due by', p.renewal.dueDate ?? '—']] as [string, string][]) : []),
  ];
  const contact = [p.seller.email, p.seller.phone].filter(Boolean).join(' or ');
  const ask = p.renewal
    ? `To continue without a break, please pay invoice ${p.renewal.number} (${rupees(p.renewal.balance)})${p.renewal.dueDate ? ` by ${p.renewal.dueDate}` : ''}.`
    : `To continue without a break, please renew before then${contact ? ` — reply to this email or contact us at ${contact}` : ' — reply to this email'}.`;
  const after = ' If it is not renewed, sign-in pauses for everyone on the account the next day; nothing is deleted.';
  return {
    subject: `Your HostelCare plan ends ${when} (${p.endsOn})`,
    text: `Hello,\n\nThe HostelCare ${p.planName} plan for ${p.hostelName} is paid until ${p.endsOn} — that is ${when}.\n\n${detailsText(rows)}\n\n${ask}${after}\n\nThanks,\n${p.seller.name} Team`,
    html: wrap({
      brand,
      badge: { text: p.daysLeft <= 1 ? 'Ends soon' : 'Reminder', tone: p.daysLeft <= 1 ? 'warning' : 'info' },
      title: `Your plan ends ${when}`,
      intro: `The HostelCare <strong>${escapeHtml(p.planName)}</strong> plan for <strong>${escapeHtml(p.hostelName)}</strong> is paid until <strong>${escapeHtml(p.endsOn)}</strong>.`,
      bodyHtml: highlight('Paid until', p.endsOn, accentOf(brand), { tone: p.daysLeft <= 1 ? 'warning' : undefined }) + detailsTable(rows),
      note: escapeHtml(ask + after),
      preheader: `Your HostelCare plan is paid until ${p.endsOn}.`,
      reason: `You are receiving this because ${p.hostelName} uses HostelCare and this address is on its account.`,
    }),
  };
}

/** To a hostel: its trial or plan ran out and access is paused until renewal. */
export function accessPausedEmail(p: {
  seller: { name: string; email?: string | null; phone?: string | null; address?: string | null };
  hostelName: string;
  trial: boolean;
  endedOn: string;
}): EmailMessage {
  const brand: EmailBrand = { firm: p.seller.name, address: p.seller.address, phone: p.seller.phone, email: p.seller.email };
  const what = p.trial ? 'free trial' : 'plan';
  const contact = [p.seller.email, p.seller.phone].filter(Boolean).join(' or ');
  const ask = `Nothing is deleted. Everything resumes the moment it is renewed${contact ? ` — contact us at ${contact}` : ' — reply to this email'}.`;
  const rows: [string, string][] = [
    ['Hostel', p.hostelName],
    [p.trial ? 'Trial ended' : 'Plan ended', p.endedOn],
  ];
  return {
    subject: `HostelCare is paused for ${p.hostelName}`,
    text: `Hello,\n\nThe HostelCare ${what} for ${p.hostelName} ended on ${p.endedOn}, so access is paused: admins, staff, students and guardians cannot sign in until it is renewed.\n\n${detailsText(rows)}\n\n${ask}\n\nThanks,\n${p.seller.name} Team`,
    html: wrap({
      brand,
      badge: { text: 'Access paused', tone: 'warning' },
      title: `Your ${what} has ended`,
      intro: `The HostelCare ${what} for <strong>${escapeHtml(p.hostelName)}</strong> ended on <strong>${escapeHtml(p.endedOn)}</strong>, so access is paused: admins, staff, students and guardians cannot sign in until it is renewed.`,
      bodyHtml: detailsTable(rows),
      note: escapeHtml(ask),
      preheader: `HostelCare is paused for ${p.hostelName} until the ${what} is renewed.`,
      reason: `You are receiving this because ${p.hostelName} uses HostelCare and this address is on its account.`,
    }),
  };
}

// ── CRM: account emails and super admin notices ──────────────────────────────

const CRM_BRAND: EmailBrand = { firm: 'HostelCare' };

/** The link a new CRM user opens to set their first password, or a reset link. */
export function crmInviteEmail(p: { name: string; inviterName: string; url: string; hours: number; kind: 'INVITE' | 'RESET' }): EmailMessage {
  const invite = p.kind === 'INVITE';
  const title = invite ? 'You are invited to HostelCare CRM' : 'Set a new password';
  const lead = invite
    ? `${p.inviterName} has added you to the HostelCare CRM. Set your password to get started.`
    : `${p.inviterName} sent you a link to set a new password for your HostelCare CRM account.`;
  const label = invite ? 'Set my password' : 'Set a new password';
  const expiry = `The link works once and expires in ${p.hours} ${p.hours === 1 ? 'hour' : 'hours'}.`;
  const signIn = 'After that you sign in with your email, your password and a code we email you each time.';
  return {
    subject: invite ? 'Your HostelCare CRM invitation' : 'Set a new HostelCare CRM password',
    text: `Hi ${p.name},\n\n${lead}\n\n${label}: ${p.url}\n\n${expiry} ${signIn}\nIf you were not expecting this, you can ignore this email.\n\n— HostelCare`,
    html: wrap({
      brand: CRM_BRAND,
      badge: { text: 'CRM', tone: 'info' },
      title,
      intro: `Hi ${escapeHtml(p.name)}, ${escapeHtml(lead.charAt(0).toLowerCase() + lead.slice(1))}`,
      bodyHtml: button(p.url, label, DEFAULT_ACCENT),
      note: `${escapeHtml(expiry)} ${escapeHtml(signIn)} If you were not expecting this, you can ignore this email.`,
      preheader: invite ? 'Set your password to start using the HostelCare CRM.' : 'Use this link to set a new password.',
      reason: 'You are receiving this because the HostelCare super admin added your email to the CRM.',
    }),
  };
}

/** A short notice to the super admin's copy address: what happened in the CRM. */
export function crmNoticeEmail(p: { title: string; intro: string; rows: [string, string][]; badge?: string }): EmailMessage {
  return {
    subject: `CRM · ${p.title}`,
    text: `${p.intro}\n\n${detailsText(p.rows)}\n\nYou get this copy because CRM emails are copied to the super admin. Change it in CRM settings.\n\n— HostelCare CRM`,
    html: wrap({
      brand: CRM_BRAND,
      badge: { text: p.badge ?? 'CRM', tone: 'info' },
      title: p.title,
      intro: escapeHtml(p.intro),
      bodyHtml: detailsTable(p.rows),
      preheader: p.intro,
      reason: 'You get this copy because CRM emails are copied to the super admin. Change it in CRM settings.',
    }),
  };
}

/**
 * A person's own email sent from the CRM (the assistant, after the super
 * admin confirmed it): plain paragraphs, no banner, so it reads like a
 * normal email from them. Replies go to them via Reply-To.
 */
export function crmPersonalEmail(p: { subject: string; body: string }): EmailMessage {
  const body = p.body.trim();
  const paras = body
    .split(/\n{2,}/)
    .map((par) => `<p style="margin:0 0 14px;font-family:${FONT};font-size:15px;line-height:1.6;color:${INK}">${escapeHtml(par).replace(/\n/g, '<br>')}</p>`)
    .join('');
  return { subject: p.subject, text: body, html: `<!doctype html><html><body style="margin:0;padding:24px;background:#ffffff">${paras}</body></html>` };
}

/** One line in a CRM email: what happened or what is due, and where to open it. */
export interface CrmEmailItem {
  text: string;
  sub?: string | null;
  url?: string | null;
  /** Shown on the right, e.g. a value or a time. */
  aside?: string | null;
  tone?: 'warning' | 'good' | null;
}

export interface CrmEmailSection {
  heading: string;
  items: CrmEmailItem[];
  /** Said when the section has nothing in it; the section is dropped if absent. */
  empty?: string;
}

/**
 * The one shape every CRM notification takes: a title, a line of context,
 * optional headline figures, then sections of linked items. Alerts,
 * reminders, the daily and weekly summaries and the new-device warning all
 * use it, so they read as one family.
 */
export function crmEmail(p: {
  title: string;
  intro: string;
  badge: string;
  tone?: Tone;
  figures?: [string, string][];
  sections: CrmEmailSection[];
  cta?: { label: string; url: string };
  reason: string;
  preheader?: string;
  copyFor?: string | null;
  /** Last line of the text version; the CRM's own by default. */
  signoff?: string;
}): EmailMessage {
  const sections = p.sections.filter((s) => s.items.length || s.empty);
  const accent = DEFAULT_ACCENT;
  const figuresHtml = p.figures?.length
    ? `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:20px 0 0"><tr>${p.figures
        .map(
          ([label, value]) =>
            `<td style="padding:12px 14px;background:#f8fafc;border-radius:12px;font-family:${FONT}" valign="top"><div style="font-size:11px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;color:${MUTED}">${escapeHtml(label)}</div><div style="margin-top:4px;font-size:18px;font-weight:700;color:${INK}">${escapeHtml(value)}</div></td>`,
        )
        .join('<td style="width:8px"></td>')}</tr></table>`
    : '';
  const item = (i: CrmEmailItem) => {
    const color = i.tone === 'warning' ? '#b91c1c' : i.tone === 'good' ? '#15803d' : INK;
    const text = i.url ? `<a href="${escapeHtml(i.url)}" style="color:${color};font-weight:600;text-decoration:none">${escapeHtml(i.text)}</a>` : `<span style="color:${color};font-weight:600">${escapeHtml(i.text)}</span>`;
    return `<tr><td style="padding:10px 0;border-top:1px solid ${LINE};font-family:${FONT};font-size:14px;line-height:1.5" valign="top">${text}${i.sub ? `<div style="font-size:12px;color:${MUTED};margin-top:2px">${escapeHtml(i.sub)}</div>` : ''}</td>${i.aside ? `<td style="padding:10px 0 10px 12px;border-top:1px solid ${LINE};font-family:${FONT};font-size:13px;color:${MUTED};white-space:nowrap;text-align:right" valign="top">${escapeHtml(i.aside)}</td>` : '<td style="border-top:1px solid ' + LINE + '"></td>'}</tr>`;
  };
  const sectionsHtml = sections
    .map(
      (s) =>
        `<div style="margin:24px 0 0"><div style="font-family:${FONT};font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:${MUTED};margin-bottom:4px">${escapeHtml(s.heading)}</div>${
          s.items.length
            ? `<table role="presentation" width="100%" cellpadding="0" cellspacing="0">${s.items.map(item).join('')}</table>`
            : `<p style="margin:6px 0 0;font-family:${FONT};font-size:13px;color:${MUTED}">${escapeHtml(s.empty ?? '')}</p>`
        }</div>`,
    )
    .join('');
  const copyNote = p.copyFor ? `<p style="margin:0 0 16px;padding:8px 12px;background:#f1f5f9;border-radius:10px;font-family:${FONT};font-size:12px;color:${MUTED}">Copy for the super admin of an email sent to ${escapeHtml(p.copyFor)}.</p>` : '';
  const text = [
    ...(p.copyFor ? [`(Copy of an email sent to ${p.copyFor}.)`, ''] : []),
    p.intro,
    ...(p.figures?.length ? ['', ...p.figures.map(([l, v]) => `${l}: ${v}`)] : []),
    ...sections.flatMap((s) => ['', s.heading.toUpperCase(), ...(s.items.length ? s.items.map((i) => `- ${i.text}${i.aside ? ` (${i.aside})` : ''}${i.sub ? `\n  ${i.sub}` : ''}${i.url ? `\n  ${i.url}` : ''}`) : [s.empty ?? ''])]),
    ...(p.cta ? ['', `${p.cta.label}: ${p.cta.url}`] : []),
    '',
    p.reason,
    '',
    p.signoff ?? '— HostelCare CRM',
  ].join('\n');
  return {
    subject: p.title,
    text,
    html: wrap({
      brand: CRM_BRAND,
      badge: { text: p.badge, tone: p.tone ?? 'info' },
      title: p.title,
      intro: copyNote + escapeHtml(p.intro),
      bodyHtml: figuresHtml + sectionsHtml + (p.cta ? button(p.cta.url, p.cta.label, accent) : ''),
      preheader: p.preheader ?? p.intro,
      reason: p.reason,
    }),
  };
}

// ── Self-serve trial (Sprint L2) ────────────────────────────────────────────

/** Sent once the trial hostel exists: where to sign in, until when, and what to do first. */
export function trialWelcomeEmail(p: { name: string; hostelName: string; email: string; endsOn: string; signInUrl: string; rooms: number; beds: number }): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  const steps = [
    'Add your students (or customers) and put them in their beds.',
    'Raise this month\'s rent invoices in one click.',
    'Send a UPI payment link and watch the payment arrive.',
  ];
  return {
    subject: `Your HostelCare trial is ready: ${p.hostelName}`,
    text: `Hi ${p.name},\n\n${p.hostelName} is set up on HostelCare with ${p.rooms} rooms and ${p.beds} beds. Your free trial runs until ${p.endsOn}.\n\nSign in: ${p.signInUrl}\nEmail: ${p.email}\n\nThree things to try first:\n${steps.map((x, i) => `${i + 1}. ${x}`).join('\n')}\n\nReply to this email if you need a hand — we'll help you set up.\n\n— HostelCare`,
    html: wrap({
      brand,
      badge: { text: 'Free trial', tone: 'good' },
      title: 'Your HostelCare trial is ready',
      intro: `Hi ${escapeHtml(p.name)}, <strong>${escapeHtml(p.hostelName)}</strong> is set up with ${p.rooms} rooms and ${p.beds} beds. Your free trial runs until <strong>${escapeHtml(p.endsOn)}</strong>.`,
      bodyHtml:
        button(p.signInUrl, 'Sign in to HostelCare', DEFAULT_ACCENT) +
        `<p style="margin:24px 0 8px;font-family:${FONT};font-size:14px;font-weight:700;color:${INK}">Three things to try first</p><ol style="margin:0;padding-left:20px;font-family:${FONT};font-size:14px;line-height:1.7;color:${INK}">${steps.map((x) => `<li>${escapeHtml(x)}</li>`).join('')}</ol>`,
      note: `You sign in with ${escapeHtml(p.email)} and the password you chose. Reply to this email if you need a hand — we'll help you set up.`,
      preheader: `${p.hostelName} is ready. Your trial runs until ${p.endsOn}.`,
      reason: 'You are receiving this because you started a free HostelCare trial.',
    }),
  };
}

// ── Demo booking (Sprint L3) ────────────────────────────────────────────────

export type DemoOwnerEmailKind = 'CONFIRMED' | 'MOVED' | 'EVENING' | 'HOUR' | 'CANCELLED' | 'RECAP' | 'NO_SHOW';

/**
 * What the owner gets about their demo: the confirmation (and again when it
 * moves), the evening-before and one-hour reminders, the cancellation, the
 * recap with the trial link, and "sorry we missed you" with the booking link.
 */
export function demoOwnerEmail(
  kind: DemoOwnerEmailKind,
  p: { unsubscribeUrl?: string; name: string; when: string; minutes: number; hostName: string | null; meetUrl: string | null; manageUrl: string; bookUrl: string; trialUrl: string; hindi: boolean },
): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  const who = p.hostName ? ` with ${p.hostName}` : '';
  const lang = p.hindi ? ' The demo will be in Hindi.' : '';
  const meetLine = p.meetUrl ? `Join on Google Meet: ${p.meetUrl}` : 'We will send the Google Meet link before the demo.';
  const c = {
    CONFIRMED: { subject: `Your HostelCare demo: ${p.when}`, badge: 'Demo booked', tone: 'good' as Tone, title: 'Your demo is booked', intro: `Hi ${p.name}, your ${p.minutes}-minute HostelCare demo${who} is on <strong>${escapeHtml(p.when)}</strong> (India time).${lang}`, cta: p.meetUrl ? { url: p.meetUrl, label: 'Join on Google Meet' } : null, note: 'The calendar invite is attached. Need another time? Use the link below to move or cancel it.' },
    MOVED: { subject: `Your HostelCare demo has moved: ${p.when}`, badge: 'Demo moved', tone: 'info' as Tone, title: 'Your demo has a new time', intro: `Hi ${p.name}, your HostelCare demo${who} is now on <strong>${escapeHtml(p.when)}</strong> (India time).${lang}`, cta: p.meetUrl ? { url: p.meetUrl, label: 'Join on Google Meet' } : null, note: 'An updated calendar invite is attached.' },
    EVENING: { subject: `Tomorrow: your HostelCare demo at ${p.when}`, badge: 'Reminder', tone: 'info' as Tone, title: 'Your demo is tomorrow', intro: `Hi ${p.name}, a reminder that your HostelCare demo${who} is on <strong>${escapeHtml(p.when)}</strong>. Keep a laptop or phone handy; it takes ${p.minutes} minutes.`, cta: p.meetUrl ? { url: p.meetUrl, label: 'Join on Google Meet' } : null, note: "Can't make it? Move it to another time with the link below." },
    HOUR: { subject: `In one hour: your HostelCare demo`, badge: 'Starting soon', tone: 'warning' as Tone, title: 'Your demo starts in an hour', intro: `Hi ${p.name}, your HostelCare demo${who} starts at <strong>${escapeHtml(p.when)}</strong>.`, cta: p.meetUrl ? { url: p.meetUrl, label: 'Join on Google Meet' } : null, note: "Running late or can't join? Move it with the link below." },
    CANCELLED: { subject: 'Your HostelCare demo is cancelled', badge: 'Cancelled', tone: 'neutral' as Tone, title: 'Your demo is cancelled', intro: `Hi ${p.name}, your HostelCare demo on ${escapeHtml(p.when)} is cancelled. Book another time whenever it suits you.`, cta: { url: p.bookUrl, label: 'Book another time' }, note: '' },
    RECAP: { subject: 'Thanks for your time — start your free HostelCare trial', badge: 'Thank you', tone: 'good' as Tone, title: 'Thanks for seeing HostelCare', intro: `Hi ${p.name}, thank you for the demo${who}. The quickest way to see it work for your hostel is to try it: set up your rooms in two minutes and use it free for 7 days.`, cta: { url: p.trialUrl, label: 'Start my free 7-day trial' }, note: 'Reply to this email with any question; we will help you set up.' },
    NO_SHOW: { subject: 'Sorry we missed you — book another time', badge: 'We missed you', tone: 'neutral' as Tone, title: 'Sorry we missed you', intro: `Hi ${p.name}, we were ready for your HostelCare demo on ${escapeHtml(p.when)} but couldn't connect. No problem — pick another time that suits you.`, cta: { url: p.bookUrl, label: 'Book another time' }, note: '' },
  }[kind];
  const manage = kind === 'CONFIRMED' || kind === 'MOVED' || kind === 'EVENING' || kind === 'HOUR';
  const textLines = [
    `Hi ${p.name},`,
    '',
    c.intro.replace(/<[^>]+>/g, '').replace(/^Hi [^,]+, /, ''),
    ...(manage ? ['', meetLine, `Move or cancel: ${p.manageUrl}`] : c.cta ? ['', `${c.cta.label}: ${c.cta.url}`] : []),
    '',
    '— HostelCare',
  ];
  return {
    subject: c.subject,
    text: textLines.join('\n') + (p.unsubscribeUrl ? `\n\nUnsubscribe: ${p.unsubscribeUrl}` : ''),
    html: wrap({
      unsubscribeUrl: p.unsubscribeUrl,
      brand,
      badge: { text: c.badge, tone: c.tone },
      title: c.title,
      intro: c.intro.replace(`Hi ${p.name},`, `Hi ${escapeHtml(p.name)},`),
      bodyHtml:
        (manage ? highlight('When', p.when, DEFAULT_ACCENT) : '') +
        (c.cta ? button(c.cta.url, c.cta.label, DEFAULT_ACCENT) : '') +
        (manage ? `<p style="margin:18px 0 0;font-family:${FONT};font-size:13px;color:${MUTED};text-align:center"><a href="${escapeHtml(p.manageUrl)}" style="color:${DEFAULT_ACCENT};font-weight:600">Move or cancel this demo</a></p>` : ''),
      note: c.note || undefined,
      preheader: kind === 'RECAP' || kind === 'NO_SHOW' || kind === 'CANCELLED' ? c.title : `${c.title}: ${p.when}`,
      reason: 'You are receiving this because you booked a HostelCare demo.',
    }),
  };
}

/** A calendar invite (.ics) for one demo. `sequence` rises each time it moves. */
export function demoIcs(p: { uid: string; start: Date; end: Date; title: string; description: string; url: string | null; sequence: number; cancelled?: boolean }): string {
  const stamp = (d: Date) => d.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
  const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/;/g, '\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');
  return [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//HostelCare//Demo booking//EN',
    'CALSCALE:GREGORIAN',
    `METHOD:${p.cancelled ? 'CANCEL' : 'PUBLISH'}`,
    'BEGIN:VEVENT',
    `UID:${p.uid}@hostelcare`,
    `SEQUENCE:${p.sequence}`,
    `DTSTAMP:${stamp(new Date())}`,
    `DTSTART:${stamp(p.start)}`,
    `DTEND:${stamp(p.end)}`,
    `SUMMARY:${esc(p.title)}`,
    `DESCRIPTION:${esc(p.description)}`,
    ...(p.url ? [`LOCATION:${esc(p.url)}`, `URL:${p.url}`] : []),
    `STATUS:${p.cancelled ? 'CANCELLED' : 'CONFIRMED'}`,
    'BEGIN:VALARM',
    'TRIGGER:-PT15M',
    'ACTION:DISPLAY',
    'DESCRIPTION:HostelCare demo in 15 minutes',
    'END:VALARM',
    'END:VEVENT',
    'END:VCALENDAR',
    '',
  ].join('\r\n');
}

// ── First touch (Sprint L4) ─────────────────────────────────────────────────

/**
 * What a new lead gets at once, when WhatsApp cannot reach them (no phone,
 * no consent, or the template is not approved yet): the two next steps.
 * `kind` NO_ANSWER is the note after a second unanswered call.
 */
export function leadTouchEmail(kind: 'FIRST' | 'NO_ANSWER', p: { unsubscribeUrl?: string; name: string; trialUrl: string; bookUrl: string }): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  const first = kind === 'FIRST';
  const subject = first ? 'Thanks for your interest in HostelCare' : 'We tried to call you — HostelCare';
  const intro = first
    ? `Hi ${p.name}, thanks for getting in touch. Someone from our team will call you within working hours (Monday to Saturday, 10 am – 7 pm). Meanwhile, two ways to see HostelCare:`
    : `Hi ${p.name}, we tried to call you about HostelCare but couldn't get through. Pick a time that suits you for a 15-minute demo, or try it yourself:`;
  return {
    subject,
    text: `${intro}\n\nBook a 15-minute demo: ${p.bookUrl}\nStart a free 7-day trial: ${p.trialUrl}\n\n— HostelCare` + (p.unsubscribeUrl ? `\n\nUnsubscribe: ${p.unsubscribeUrl}` : ''),
    html: wrap({
      unsubscribeUrl: p.unsubscribeUrl,
      brand,
      badge: { text: first ? 'Welcome' : 'We missed you', tone: first ? 'good' : 'neutral' },
      title: first ? 'Thanks for getting in touch' : 'We tried to call you',
      intro: escapeHtml(intro),
      bodyHtml:
        button(p.bookUrl, 'Book a 15-minute demo', DEFAULT_ACCENT) +
        `<p style="margin:18px 0 0;font-family:${FONT};font-size:14px;color:${MUTED};text-align:center">or <a href="${escapeHtml(p.trialUrl)}" style="color:${DEFAULT_ACCENT};font-weight:600">start a free 7-day trial</a> — set up your rooms in two minutes.</p>`,
      preheader: first ? 'Book a demo or try HostelCare free for 7 days.' : 'Pick a time for a 15-minute demo.',
      reason: 'You are receiving this because you asked HostelCare to get in touch.',
    }),
  };
}

// ── Trial journey (Sprint L5) ───────────────────────────────────────────────

export type TrialStep = 'students' | 'invoice' | 'payment' | 'convert';

/** What each trial nudge asks the owner to do next, in one line (also the WhatsApp text). */
export function trialStepLine(step: TrialStep, dorm: boolean): string {
  const people = dorm ? 'customers' : 'students';
  return {
    students: `Add your ${people} to their beds — or import them from your Excel sheet in one go.`,
    invoice: dorm ? 'Check in a guest: HostelCare raises their bill for the nights by itself.' : "Raise this month's rent invoices — one click for everyone.",
    payment: 'Record a payment, or send a UPI payment link and watch it come in.',
    convert: "You're running your hostel on HostelCare. Keep everything going after the trial — it's ₹20 a bed a month.",
  }[step];
}

/** A trial nudge on day 0, 1, 3, 5 or 6: the next thing to do; day 6 also says the trial ends tomorrow. */
export function trialNudgeEmail(p: { unsubscribeUrl?: string; name: string; hostelName: string; day: number; endsIn?: number | null; step: TrialStep; dorm: boolean; endsOn: string; monthly: number; appUrl: string }): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  // The trial's last day is its end date: ends tomorrow the day before, ends today on it.
  const last = p.endsIn === 0 || p.endsIn === 1;
  const when = p.endsIn === 0 ? 'today' : 'tomorrow';
  const line = trialStepLine(p.step, p.dorm);
  const title = last ? `Your free trial ends ${when}` : p.step === 'convert' ? "You're all set" : p.day === 0 ? 'Your first step' : 'Your next step';
  const subject = last ? `${p.hostelName}: your HostelCare trial ends ${when}` : `${p.hostelName}: ${p.step === 'convert' ? "you're all set on HostelCare" : 'your next step on HostelCare'}`;
  const price = `₹${p.monthly.toLocaleString('en-IN')} a month`;
  const intro = last
    ? `Hi ${p.name}, your free trial for ${p.hostelName} ends on ${p.endsOn}. To keep going without a break, reply to this email or call us — it's ${price} for your beds.`
    : `Hi ${p.name}, here's the one thing that gets the most out of your HostelCare trial today.`;
  return {
    subject,
    text: `${intro}\n\n${line}\n\nOpen HostelCare: ${p.appUrl}\n\n— HostelCare` + (p.unsubscribeUrl ? `\n\nUnsubscribe: ${p.unsubscribeUrl}` : ''),
    html: wrap({
      unsubscribeUrl: p.unsubscribeUrl,
      brand,
      badge: { text: last ? (p.endsIn === 0 ? 'Last day' : 'Last day tomorrow') : `Trial day ${p.day}`, tone: last ? 'warning' : 'info' },
      title,
      intro: escapeHtml(intro),
      bodyHtml: quote(line, DEFAULT_ACCENT) + button(p.appUrl, last ? 'Open HostelCare' : 'Do it now', DEFAULT_ACCENT),
      note: last ? `After ${p.endsOn} the account pauses; nothing is deleted, and it comes back the moment you continue.` : 'Reply to this email if you get stuck — we will help you set up.',
      preheader: line,
      reason: 'You are receiving this because you are trying HostelCare for free.',
    }),
  };
}

/** After the first paid platform invoice: welcome as a customer. */
export function customerWelcomeEmail(p: { unsubscribeUrl?: string; name: string; hostelName: string; appUrl: string }): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  const intro = `Hi ${p.name}, thank you for choosing HostelCare for ${p.hostelName}. Your account carries on exactly as it is — everything you set up in the trial stays.`;
  const tips = ['Share the student app link so residents see their rent and pay by UPI.', 'Turn on WhatsApp rent reminders in Settings.', 'Write to us any time — a real person answers.'];
  return {
    subject: `Welcome to HostelCare, ${p.hostelName}`,
    text: `${intro}\n\n${tips.map((t) => `• ${t}`).join('\n')}\n\nOpen HostelCare: ${p.appUrl}\n\n— HostelCare` + (p.unsubscribeUrl ? `\n\nUnsubscribe: ${p.unsubscribeUrl}` : ''),
    html: wrap({
      unsubscribeUrl: p.unsubscribeUrl,
      brand,
      badge: { text: 'Welcome', tone: 'good' },
      title: 'Welcome to HostelCare',
      intro: escapeHtml(intro),
      bodyHtml: `<ul style="margin:18px 0 0;padding-left:20px;font-family:${FONT};font-size:14px;line-height:1.7;color:${INK}">${tips.map((t) => `<li>${escapeHtml(t)}</li>`).join('')}</ul>` + button(p.appUrl, 'Open HostelCare', DEFAULT_ACCENT),
      preheader: 'Everything from your trial stays. Here are three things to do next.',
      reason: 'You are receiving this because your hostel uses HostelCare.',
    }),
  };
}

/** Day 30 as a customer: how is it going, and a review if they are happy. */
export function reviewRequestEmail(p: { unsubscribeUrl?: string; name: string; hostelName: string; reviewUrl: string | null }): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  const intro = `Hi ${p.name}, ${p.hostelName} has been on HostelCare for a month. How is it going? ${p.reviewUrl ? 'If it is helping, a short review helps other hostel owners find us.' : 'Reply and tell us — what works, and what we should fix.'}`;
  return {
    subject: 'A month on HostelCare — how is it going?',
    text: `${intro}${p.reviewUrl ? `\n\nLeave a review: ${p.reviewUrl}` : ''}\n\n— HostelCare` + (p.unsubscribeUrl ? `\n\nUnsubscribe: ${p.unsubscribeUrl}` : ''),
    html: wrap({
      unsubscribeUrl: p.unsubscribeUrl,
      brand,
      badge: { text: 'One month', tone: 'good' },
      title: 'How is it going?',
      intro: escapeHtml(intro),
      bodyHtml: p.reviewUrl ? button(p.reviewUrl, 'Leave a review', DEFAULT_ACCENT) : '',
      note: 'Something not right? Just reply — it comes straight to our team.',
      preheader: 'A quick question after your first month.',
      reason: 'You are receiving this because your hostel uses HostelCare.',
    }),
  };
}

/** Sales gave the one 7-day extension. */
export function trialExtendedEmail(p: { unsubscribeUrl?: string; name: string; hostelName: string; endsOn: string; appUrl: string }): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  const intro = `Hi ${p.name}, we've extended the free trial for ${p.hostelName} by 7 days. It now runs until ${p.endsOn}.`;
  return {
    subject: `Your HostelCare trial is extended to ${p.endsOn}`,
    text: `${intro}\n\nOpen HostelCare: ${p.appUrl}\n\n— HostelCare` + (p.unsubscribeUrl ? `\n\nUnsubscribe: ${p.unsubscribeUrl}` : ''),
    html: wrap({
      unsubscribeUrl: p.unsubscribeUrl, brand, badge: { text: 'Trial extended', tone: 'good' }, title: 'Your trial is extended', intro: escapeHtml(intro), bodyHtml: button(p.appUrl, 'Open HostelCare', DEFAULT_ACCENT), preheader: `Now until ${p.endsOn}.`, reason: 'You are receiving this because you are trying HostelCare for free.' }),
  };
}

// ── Nurture (Sprint L6) ─────────────────────────────────────────────────────

/** The month's nurture email: a short note, one link (the month's best blog or tip), and the unsubscribe. */
export function nurtureEmail(p: { name: string; subject: string; body: string; linkUrl?: string | null; linkLabel?: string | null; unsubscribeUrl: string }): EmailMessage {
  const brand: EmailBrand = { firm: 'HostelCare' };
  const greeting = `Hi ${p.name},`;
  return {
    subject: p.subject,
    text: `${greeting}\n\n${p.body}${p.linkUrl ? `\n\n${p.linkLabel || 'Read more'}: ${p.linkUrl}` : ''}\n\n— HostelCare\n\nUnsubscribe: ${p.unsubscribeUrl}`,
    html: wrap({
      brand,
      title: p.subject,
      intro: escapeHtml(greeting),
      bodyHtml: `<div style="margin:12px 0 0;font-family:${FONT};font-size:15px;line-height:1.7;color:${INK};white-space:pre-wrap">${escapeHtml(p.body)}</div>` + (p.linkUrl ? button(p.linkUrl, p.linkLabel || 'Read more', DEFAULT_ACCENT) : ''),
      preheader: p.body.slice(0, 120),
      reason: 'You are receiving this because you asked HostelCare about hostel software.',
      unsubscribeUrl: p.unsubscribeUrl,
    }),
  };
}

/** An invite or password link for a website blog editor (docs/blog-cms-plan.md). */
export function blogInviteEmail(p: { name: string; inviterName: string; url: string; hours: number; kind: 'INVITE' | 'RESET' }): EmailMessage {
  const invite = p.kind === 'INVITE';
  const title = invite ? 'You are invited to write for the HostelCare blog' : 'Set a new password';
  const lead = invite
    ? `${p.inviterName} has added you as a writer for the HostelCare website blog. Set your password to get started.`
    : `${p.inviterName} sent you a link to set a new password for your HostelCare blog account.`;
  const label = invite ? 'Set my password' : 'Set a new password';
  const expiry = `The link works once and expires in ${p.hours} ${p.hours === 1 ? 'hour' : 'hours'}.`;
  const signIn = 'After that you sign in with your email, your password and a code we email you each time.';
  return {
    subject: invite ? 'Your HostelCare blog invitation' : 'Set a new HostelCare blog password',
    text: `Hi ${p.name},\n\n${lead}\n\n${label}: ${p.url}\n\n${expiry} ${signIn}\nIf you were not expecting this, you can ignore this email.\n\n— HostelCare`,
    html: wrap({
      brand: CRM_BRAND,
      badge: { text: 'Blog', tone: 'info' },
      title,
      intro: `Hi ${escapeHtml(p.name)}, ${escapeHtml(lead.charAt(0).toLowerCase() + lead.slice(1))}`,
      bodyHtml: button(p.url, label, DEFAULT_ACCENT),
      note: `${escapeHtml(expiry)} ${escapeHtml(signIn)} If you were not expecting this, you can ignore this email.`,
      preheader: invite ? 'Set your password to start writing for the HostelCare blog.' : 'Use this link to set a new password.',
      reason: 'You are receiving this because the HostelCare super admin added your email as a blog writer.',
    }),
  };
}

/** An invite or password link for a bug tracker tester or developer (docs/bug-tracker-plan.md). */
export function bugTrackerInviteEmail(p: { name: string; inviterName: string; url: string; hours: number; kind: 'INVITE' | 'RESET'; as: 'tester' | 'developer' }): EmailMessage {
  const invite = p.kind === 'INVITE';
  const title = invite ? 'You are invited to the HostelCare bug tracker' : 'Set a new password';
  const lead = invite
    ? `${p.inviterName} has added you to the HostelCare bug tracker as a ${p.as}. Set your password to get started.`
    : `${p.inviterName} sent you a link to set a new password for your HostelCare bug tracker account.`;
  const label = invite ? 'Set my password' : 'Set a new password';
  const expiry = `The link works once and expires in ${p.hours} ${p.hours === 1 ? 'hour' : 'hours'}.`;
  const signIn = 'After that you sign in with your email, your password and a code we email you each time.';
  return {
    subject: invite ? 'Your HostelCare bug tracker invitation' : 'Set a new HostelCare bug tracker password',
    text: `Hi ${p.name},\n\n${lead}\n\n${label}: ${p.url}\n\n${expiry} ${signIn}\nIf you were not expecting this, you can ignore this email.\n\n— HostelCare`,
    html: wrap({
      brand: CRM_BRAND,
      badge: { text: 'Bug tracker', tone: 'info' },
      title,
      intro: `Hi ${escapeHtml(p.name)}, ${escapeHtml(lead.charAt(0).toLowerCase() + lead.slice(1))}`,
      bodyHtml: button(p.url, label, DEFAULT_ACCENT),
      note: `${escapeHtml(expiry)} ${escapeHtml(signIn)} If you were not expecting this, you can ignore this email.`,
      preheader: invite ? 'Set your password to start using the HostelCare bug tracker.' : 'Use this link to set a new password.',
      reason: 'You are receiving this because the HostelCare super admin added your email to the bug tracker.',
    }),
  };
}

/**
 * One thing that happened on a bug, told to one person (docs/bug-tracker-plan.md,
 * BT4): assigned to you, a question, a fix to verify, reopened, a comment, a mention.
 */
export function bugNotificationEmail(p: {
  name: string;
  /** "Reopened", "Assigned to you": the pill, and the start of the subject. */
  label: string;
  tone: 'info' | 'good' | 'warning' | 'danger' | 'neutral';
  /** "Asha reopened BUG-12". */
  headline: string;
  bugKey: string;
  bugTitle: string;
  /** The note, question or comment that came with it. */
  snippet?: string | null;
  rows: [string, string][];
  url: string;
  settingsUrl: string;
}): EmailMessage {
  const reason = 'You get this because you are on this bug in the HostelCare bug tracker (you reported it, it is assigned to you, you follow it or you were mentioned).';
  const off = `To stop these emails, open Notifications in the bug tracker: ${p.settingsUrl}`;
  return {
    subject: `[${p.bugKey}] ${p.label} · ${p.bugTitle}`.slice(0, 200),
    text: [`Hi ${p.name},`, '', `${p.headline}: ${p.bugTitle}`, ...(p.snippet ? ['', p.snippet] : []), '', detailsText(p.rows), '', `Open ${p.bugKey}: ${p.url}`, '', reason, off, '', '— HostelCare bug tracker'].join('\n'),
    html: wrap({
      brand: CRM_BRAND,
      badge: { text: p.label, tone: p.tone },
      title: `${p.bugKey}: ${p.bugTitle}`,
      intro: `Hi ${escapeHtml(p.name)}, ${escapeHtml(p.headline)}.`,
      bodyHtml: (p.snippet ? quote(p.snippet, DEFAULT_ACCENT) : '') + detailsTable(p.rows) + button(p.url, `Open ${p.bugKey}`, DEFAULT_ACCENT),
      note: `To stop these emails, open <a href="${escapeHtml(p.settingsUrl)}" style="color:${MUTED}">Notifications</a> in the bug tracker and switch them off.`,
      preheader: `${p.headline}: ${p.bugTitle}`,
      reason,
    }),
  };
}
