/**
 * Tiny mustache-style template renderer.
 * Substitutes {{key}} occurrences with values from `vars`.
 * Missing keys are left as empty strings.
 */
export function renderTemplate(text: string, vars: Record<string, string | number | null | undefined>): string {
  return text.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_match, key) => {
    const v = vars[key];
    return v === undefined || v === null ? '' : String(v);
  });
}

/** Variables exposed to the VISITOR_INVITE template. */
export interface VisitorInviteVars {
  visitor_name: string;
  visitor_email: string;
  visitor_mobile: string;
  visitor_id: string;
  visit_date: string;
  visit_time: string;
  visit_notes: string;
  reason_for_visit: string;
  host_name: string;
  host_email: string;
  // Block placeholders — when present in the body, the corresponding
  // HTML card renders inline at that exact spot. Their values flow
  // through the renderer as sentinel strings that escapeHtml leaves
  // untouched, then get swapped for real HTML after escaping.
  visit_details: string;
  qr_code: string;
  // One-shot decision URLs used by the Approval Request email's
  // Approve / Reject buttons. Only APPROVER_REQUEST resolves these to
  // real URLs; other templates get harmless placeholder values so the
  // preview still renders if a user pastes the button HTML in there.
  approve_url: string;
  reject_url: string;
}

// Sentinel strings the renderer swaps for the visit-details + QR HTML
// after escapeHtml has run on the body. Picked so escapeHtml can't mangle
// them (no <, >, &, ", or '). Exported because both the email pipeline and
// the preview pipeline need to substitute them.
export const VISIT_DETAILS_SENTINEL = '__GP_VISIT_DETAILS_BLOCK__';
export const QR_CODE_SENTINEL = '__GP_QR_CODE_BLOCK__';

/** Sample values used for the preview button. */
export const VISITOR_INVITE_SAMPLE: VisitorInviteVars = {
  visitor_name: 'Priya Sharma',
  visitor_email: 'priya@example.com',
  visitor_mobile: '+91 98765 43210',
  visitor_id: 'X4JTI6MGJE',
  visit_date: 'Mon, May 19, 2026',
  visit_time: '10:00 AM',
  visit_notes: 'Quarterly audit prep — escort to floor 4',
  reason_for_visit: 'Audit',
  host_name: 'Hardip K',
  host_email: 'hardip.k@upsquare.in',
  visit_details: VISIT_DETAILS_SENTINEL,
  qr_code: QR_CODE_SENTINEL,
  // Preview URLs — point at a no-op so a stray click in the editor's
  // iframe doesn't fire a real request.
  approve_url: '#preview-approve',
  reject_url: '#preview-reject',
};

// Reusable info-box markup the default templates drop their visit-meta
// rows into. Pulled out so the three defaults read consistently and
// future tweaks live in one place.
const INFO_BOX_OPEN = '<div style="background-color:#f9fafb;border:1px solid #e5e7eb;border-radius:12px;padding:16px 18px;margin:16px 0;">';
const INFO_BOX_CLOSE = '</div>';
const row = (label: string, value: string) =>
  `<p style="margin:6px 0;font-size:14px;color:#111827;"><strong>${label}:</strong> ${value}</p>`;

/** Default body the system seeds when no template exists. Constructed from
 * individual variables — admins customise it freely via the rich-text
 * editor, and the Insert Variable dropdown exposes each field so they can
 * rearrange the info-box rows. */
export const DEFAULT_VISITOR_INVITE = {
  subject: "You're invited to visit {{host_name}} on {{visit_date}}",
  body: `<p>Hi <strong>{{visitor_name}}</strong>,</p>
<p>You're confirmed for your visit. Here are the details:</p>
${INFO_BOX_OPEN}
${row('Date', '{{visit_date}}')}
${row('Time', '{{visit_time}}')}
${row('Reason', '{{reason_for_visit}}')}
${row('Host', '{{host_name}}')}
${row('Pass ID', '{{visitor_id}}')}
${INFO_BOX_CLOSE}
<p>Please show the QR at reception when you arrive — or share the Pass ID if the QR doesn't scan.</p>
<p style="text-align:center;">{{qr_code}}</p>
<p>See you soon,<br><strong>{{host_name}}</strong></p>`,
};

/** Default body for the check-in confirmation email. */
export const DEFAULT_CHECK_IN_CONFIRMATION = {
  subject: "Welcome — you're checked in at {{host_name}}",
  body: `<p>Hi <strong>{{visitor_name}}</strong>,</p>
<p>You're checked in. Reception has logged your arrival; your host <strong>{{host_name}}</strong> has been notified and will receive you shortly.</p>
${INFO_BOX_OPEN}
${row('Reason', '{{reason_for_visit}}')}
${row('Host', '{{host_name}}')}
${row('Pass ID', '{{visitor_id}}')}
${INFO_BOX_CLOSE}
<p>If you need anything during your visit, please ask reception for assistance.</p>
<p>Have a great visit,<br><strong>{{host_name}}</strong></p>`,
};

/** Default body for the email that pings the host/approver when a
 * visitor lands in AWAITING_APPROVAL. Recipient is the approver, so the
 * tone addresses them directly and the body emphasises who's at reception
 * + how to decide. {{host_name}} resolves to the approver themselves. */
// Email-client-safe action buttons. Outlook chokes on flexbox / CSS
// gap, so the two CTAs sit in a table row with explicit padding and
// inline-block anchors styled to look like buttons.
const APPROVAL_BUTTONS = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:20px auto;">
  <tr>
    <td style="padding-right:8px;">
      <a href="{{approve_url}}" style="display:inline-block;padding:12px 28px;background-color:#10b981;color:#ffffff;font-weight:600;font-size:14px;text-decoration:none;border-radius:8px;">Approve</a>
    </td>
    <td style="padding-left:8px;">
      <a href="{{reject_url}}" style="display:inline-block;padding:12px 28px;background-color:#ef4444;color:#ffffff;font-weight:600;font-size:14px;text-decoration:none;border-radius:8px;">Reject</a>
    </td>
  </tr>
</table>`;

export const DEFAULT_APPROVER_REQUEST = {
  subject: "Approval needed: {{visitor_name}} is here to see you",
  body: `<p>Hi <strong>{{host_name}}</strong>,</p>
<p><strong>{{visitor_name}}</strong> just arrived at reception and is waiting for your approval.</p>
${INFO_BOX_OPEN}
${row('Visitor', '{{visitor_name}}')}
${row('Mobile', '{{visitor_mobile}}')}
${row('Email', '{{visitor_email}}')}
${row('Reason', '{{reason_for_visit}}')}
${row('Notes', '{{visit_notes}}')}
${row('Pass ID', '{{visitor_id}}')}
${INFO_BOX_CLOSE}
${APPROVAL_BUTTONS}
<p style="font-size:13px;color:#6b7280;text-align:center;">One-click decision — no login required. The links expire once used.</p>`,
};

/** Default body for the 24h visit reminder. */
export const DEFAULT_VISITOR_REMINDER = {
  subject: "Reminder: your visit with {{host_name}} is tomorrow",
  body: `<p>Hi <strong>{{visitor_name}}</strong>,</p>
<p>A quick reminder that your visit is tomorrow. Please bring a photo ID and show the QR (or share the Pass ID) at reception when you arrive.</p>
${INFO_BOX_OPEN}
${row('Date', '{{visit_date}}')}
${row('Time', '{{visit_time}}')}
${row('Reason', '{{reason_for_visit}}')}
${row('Host', '{{host_name}}')}
${row('Pass ID', '{{visitor_id}}')}
${INFO_BOX_CLOSE}
<p style="text-align:center;">{{qr_code}}</p>
<p>Looking forward to seeing you,<br><strong>{{host_name}}</strong></p>`,
};

// Variables surfaced in the Insert Variable dropdown. Individual rows
// (visit_date / visit_time / reason_for_visit / etc.) are what the default
// templates use — admins build the info-box themselves. The
// {{visit_details}} sentinel is also still exposed and resolves at render
// time for any hand-edited template that contains it.
export const KNOWN_VISITOR_INVITE_KEYS: Array<keyof VisitorInviteVars> = [
  'visitor_name', 'visitor_email', 'visitor_mobile', 'visitor_id',
  'visit_date', 'visit_time', 'visit_notes', 'reason_for_visit',
  'host_name', 'host_email',
  // Block placeholders — render inline at the spot they're dropped.
  'visit_details', 'qr_code',
];

// Approver-only variables — the decision URLs only resolve to real
// values for APPROVER_REQUEST sends. emailTemplates.controller's
// variablesFor() concatenates this onto the base list for that kind.
export const APPROVER_REQUEST_EXTRA_KEYS: Array<keyof VisitorInviteVars> = [
  'approve_url', 'reject_url',
];
