/**
 * System email templates (order-intake workflow doc §11-16, 2026-09-07).
 * The two core templates ship as CODE DEFAULTS so the admin dashboard works
 * before the DB migration; saved edits in email_templates override them.
 * Actual SENDING is the email backend (later) — including where the Synchron
 * intake/order address is configured (backend/env decision, TODO).
 */

import { SITE_URL, SUPPORT_EMAIL } from '@/lib/app-url'

/**
 * Dashboard links — one fixed variable per user type (Nash, 2026-09-19: "we
 * should not use the variable dashboard link… set in stone so we send the
 * right user type to the right dashboard"). Every sender includes all five;
 * a template for freight brokers uses the freight broker one, and so on.
 */
export const DASHBOARD_LINKS = {
  freight_broker_dashboard_link: `${SITE_URL}/fb-dashboard`,
  carrier_dispatch_dashboard_link: `${SITE_URL}/cd-dashboard`,
  pilot_dispatch_dashboard_link: `${SITE_URL}/pd-dashboard`,
  carrier_driver_dashboard_link: `${SITE_URL}/ct-dashboard`,
  pilot_driver_dashboard_link: `${SITE_URL}/pc-dashboard`,
} as const
export type DashboardLinkVariable = keyof typeof DASHBOARD_LINKS

export interface TemplateDefault {
  key: string
  name: string
  subject: string
  body: string
  recipients_note: string
  cc_rules: string
  trigger_note: string
}

/** Dynamic variables available in subjects and bodies (doc §14). */
export const TEMPLATE_VARIABLES = [
  // Freight Broker Leads campaigns (2026-09-23)
  'old_email',
  'first_name',
  'last_name',
  'full_name',
  'brokerage_name',
  'join_link',
  'broker_name',
  'broker_company',
  'carrier_company',
  'dispatcher_name',
  'dispatcher_email',
  'dispatcher_phone',
  'driver_name',
  'trip_id',
  'order_id',
  'pickup_location',
  'delivery_location',
  'load_number',
  'rate_confirmation_link',
  'workspace_link',
  'permit_handling_option',
  'payment_responsible_party',
  'route_inclusion_statement',
  'support_email',
  'synchron_order_email',
  'created_datetime',
  // Permit re-order (Task 75): who asked, who pays, which permit expired.
  'requester_name',
  'requester_role',
  'requester_role_label',
  'requester_company',
  'requester_company_suffix',
  'requester_line',
  'requester_email',
  'page_name',
  'page_description',
  'page_link',
  'granted_by',
  'access_note',
  'sign_in_link',
  'permit_state',
  'permit_state_code',
  'permit_number',
  'permit_source',
  'mismatch_rows',
  'permit_expiration_date',
  'payer',
  'order_number',
  'source_order_number',
  'unit_number',
  'commodity',
  'pickup_date',
  'delivery_date',
  'load_dimensions',
  'overall_dimensions',
  'axle_summary',
  'truck_info',
  'trailer_info',
  'previous_permit_summary',
  'previous_permit_attachment',
  'rate_confirmation_summary',
  'attachments_list',
  'request_notes',
  // Company access approval (Task 90, article §17).
  'user_name',
  'user_email',
  'user_phone',
  'company_name',
  'requested_role',
  'requested_access_level',
  'company_match_info',
  'approve_link',
  'deny_link',
  // Carrier Company Info — dispatcher ↔ carrier relationship (2026-09-19).
  'company_mc',
  'company_dot',
  'decided_by',
  'rejection_reason',
  'request_date',
  // Fixed per-user-type dashboard links (never a generic one).
  'freight_broker_dashboard_link',
  'carrier_dispatch_dashboard_link',
  'pilot_dispatch_dashboard_link',
  'carrier_driver_dashboard_link',
  'pilot_driver_dashboard_link',
  // Broker relationship verification (2026-09-19, §31).
  'requester_first_name',
  'requester_last_name',
  'requester_full_name',
  'requester_phone',
  'company_display_name',
  'mc_number',
  'usdot_number',
  'verification_expiration_date',
  'approve_button',
  'reject_button',
  'reject_link',
  'company_footer',
  // Company Admin invitations (2026-09-19).
  'invited_by',
  'invited_by_email',
  'invited_by_phone',
  // Email architecture (2026-09-22).
  'verification_link',
  'unsubscribe_link',
  'preferences_link',
  // Public intake (2026-09-22).
  'verification_code',
  'code_minutes',
  'intake_link',
  'report_link',
  // Pilot invoice (Pro Tools article §33, 2026-09-12). Sending is the email
  // backend (later); the admin manages the wording here now.
  'invoice_number',
  'invoice_link',
  'pilot_name',
  'assignment_id',
  'assignment_states',
  'assignment_permits',
  'amount_due',
  'due_date',
  'payment_instructions',
  'preferred_payment_method',
  'pilot_contact',
  // Pilot-to-trip invitations (Nash, 2026-09-13): a pilot driver adds a
  // pilot dispatch or an additional pilot to an assignment.
  'pilot_driver_name',
  'pilot_driver_phone',
  'invitee_name',
  'shared_access',
  'signup_link',
  // Pilot paperwork request (Nash, 2026-09-17): the inviter asks a pilot for
  // the documents the trip needs on file.
  'pilot_kind',
  'paperwork_list',
  // Auto-Participants (Nash, 2026-09-30): who includes whom, and the link to act.
  'owner_name',
  'company_name',
  'scope_label',
  'requested_by',
  'accept_link',
  'trip_route',
  'rule_type',
  'triggering_user',
  'reason',
] as const

/** Sample values for preview/test mode (doc §16 example data). */
export const TEMPLATE_SAMPLE_DATA: Record<string, string> = {
  old_email: 'you@old-company.com',
  first_name: 'Sam',
  last_name: 'Rivera',
  full_name: 'Sam Rivera',
  brokerage_name: 'ABC FREIGHT BROKERAGE LLC',
  join_link: `${SITE_URL}/join/sample-token`,
  requester_first_name: 'John',
  requester_last_name: 'Smith',
  requester_full_name: 'John Smith',
  requester_phone: '(555) 123-4567',
  company_display_name: 'ABC Freight Brokerage',
  mc_number: '123456',
  usdot_number: '1234567',
  verification_expiration_date: 'October 3, 2026',
  approve_button: `Approve request → ${SITE_URL}/company-approval/sample-token?decision=approve`,
  reject_button: `Reject request → ${SITE_URL}/company-approval/sample-token?decision=deny`,
  reject_link: `${SITE_URL}/company-approval/sample-token?decision=deny`,
  company_footer: 'HeavyHaul Agent · Oversize load permits, routes and escorts in one workspace.',
  invited_by: 'Alex Broker',
  invited_by_email: 'alex@abcfreight.com',
  invited_by_phone: '(615) 555-0140',
  verification_link: `${SITE_URL}/email/verify/sample-token`,
  verification_code: '482913',
  code_minutes: '10',
  intake_link: `${SITE_URL}/intake/abc-freight?invite=sample-token`,
  unsubscribe_link: `${SITE_URL}/email/unsubscribe/sample-token`,
  preferences_link: `${SITE_URL}/email/preferences/sample-token`,
  company_mc: '123456',
  company_dot: '1234567',
  decided_by: 'Jane Admin',
  rejection_reason: 'We do not recognize this person',
  request_date: 'September 19, 2026',
  ...DASHBOARD_LINKS,
  broker_name: 'ABC Broker',
  broker_company: 'ABC Broker LLC',
  carrier_company: 'XYZ Trucking',
  dispatcher_name: 'John Smith',
  dispatcher_email: 'john@xyztrucking.com',
  dispatcher_phone: '(555) 123-4567 x204',
  driver_name: 'Sam Driver',
  trip_id: 'HH-00000000',
  order_id: 'ORD-0000',
  pickup_location: 'Houston, TX',
  delivery_location: 'Atlanta, GA',
  load_number: 'L-4821',
  rate_confirmation_link: `${SITE_URL}/docs/sample-rate-con`,
  workspace_link: `${SITE_URL}/trips/sample`,
  permit_handling_option: 'Request Permits From Synchron Permits',
  payment_responsible_party: 'Carrier',
  route_inclusion_statement:
    'Routes are included for each permit processed by Synchron Permits — no separate Google Maps route purchase is required for those permits.',
  support_email: SUPPORT_EMAIL,
  synchron_order_email: 'synchronpermits@gmail.com',
  created_datetime: 'Sep 07, 2026, 9:00 AM',
  requester_name: 'Sam Driver',
  requester_role: 'driver',
  requester_email: 'sam@xyztrucking.com',
  permit_state: 'Georgia',
  permit_state_code: 'GA',
  permit_number: '48843549-GA',
  permit_expiration_date: 'Sep 03, 2026',
  payer: 'The requester — Sam Driver, XYZ Trucking',
  requester_role_label: 'Carrier Driver',
  requester_company: 'XYZ Trucking (MC 1234567)',
  requester_company_suffix: ', XYZ Trucking',
  page_name: 'Freight Broker Leads',
  page_description: 'Freight broker leads, segments, invitation campaigns and their analytics.',
  page_link: `${SITE_URL}/admin/broker-leads`,
  granted_by: 'Nash Turcan',
  access_note: 'You are running the Q4 broker outreach.',
  sign_in_link: `${SITE_URL}/login`,
  requester_line: 'Sam Driver (Carrier Dispatcher, XYZ Trucking · MC 1234567)',
  order_number: 'SP-48821',
  source_order_number: '70305660',
  unit_number: 'T-114',
  commodity: 'Prefabricated building section',
  pickup_date: 'Sep 24, 2026',
  delivery_date: 'Sep 26, 2026',
  load_dimensions: `50' (600 in) long · 12'6" (150 in) wide · 13'6" (162 in) high · 48,000 lbs`,
  overall_dimensions: `78' (936 in) long · 12'6" (150 in) wide · 15'2" (182 in) high · 92,000 lbs`,
  axle_summary: `7 axles · spacings 15'6" · 4'6" · 36' · 4'6" · 4'6" · 4'6" · KPTRA 43' · axle weights 12,000 / 17,000 / 17,000 / 17,000 / 17,000 / 12,000 lbs`,
  truck_info: '2022 Peterbilt 389 · unit T-114 · VIN 1XPXD49X1ND000000',
  trailer_info: '2019 Trail King TK110HDG · unit TR-22 · VIN 1TKJ05336KM000000 · 3 axles',
  previous_permit_attachment: 'HH-00000000 — GA permit 48843549-GA.pdf',
  previous_permit_summary: `The previous Georgia permit 48843549-GA, effective Aug 04, 2026, expired Sep 03, 2026. It was issued for 50' (600 in) long · 12'6" (150 in) wide · 13'6" (162 in) high · 92,000 lbs. A copy is attached as a point of reference.`,
  rate_confirmation_summary: 'The rate confirmation for this order is attached (HH-00000000 — rate confirmation.pdf).',
  attachments_list: '- Rate confirmation: HH-00000000 — rate confirmation.pdf (212 KB)\n- Previous GA permit 48843549-GA: HH-00000000 — GA permit 48843549-GA.pdf (148 KB)',
  request_notes: 'Re-order of the expired Georgia permit 48843549-GA (expired Sep 03, 2026).',
  user_name: 'John Smith',
  user_email: 'john@abcfreight.com',
  user_phone: '(555) 987-6543',
  company_name: 'ABC Freight Brokers LLC',
  requested_role: 'Freight Broker',
  requested_access_level: 'Create trips, send intake links, request permits',
  company_match_info: 'MC 123456 · Charlotte, NC · Active authority',
  approve_link: `${SITE_URL}/company-approval/sample-token?decision=approve`,
  deny_link: `${SITE_URL}/company-approval/sample-token?decision=deny`,
  report_link: `${SITE_URL}/company-approval/sample-token?decision=report`,
  invoice_number: 'PILOT-INV-HH-2041-20260912',
  invoice_link: `${SITE_URL}/pd-trip-workspace/HH-2041?invoice=PILOT-INV-HH-2041-20260912`,
  pilot_name: 'ABC Pilot Cars',
  assignment_id: 'asg-1',
  assignment_states: 'OH',
  assignment_permits: 'OH-SL-88214, OH-SL-88301',
  amount_due: '$1,350.00',
  due_date: 'Oct 12, 2026',
  payment_instructions: 'ACH to Huntington Bank, routing 044000024, account 1234567890. Reference the invoice number.',
  preferred_payment_method: 'ACH preferred; company check accepted.',
  pilot_contact: 'Maria Lopez · (614) 555-0142 · dispatch@abcpilotcars.com',
  pilot_driver_name: 'Dana Whitfield',
  pilot_driver_phone: '(614) 555-0198',
  invitee_name: 'Maria Lopez',
  shared_access: 'OH (state)',
  signup_link: `${SITE_URL}/signup/pilot`,
  pilot_kind: 'Pilot driver',
  paperwork_list: '- W-9\n- Driver license\n- Certificate of insurance\n- Pilot car / escort certification',
}

/** Replace {{variables}} with values; unknown variables stay visible. */
/** Sample data for previews and test sends, with the role word that matches the template's audience. */
export function sampleDataFor(templateKey: string): Record<string, string> {
  const broker = templateKey.startsWith('broker_')
  return { ...TEMPLATE_SAMPLE_DATA, requested_role: broker ? 'Freight Broker' : 'Carrier Dispatcher' }
}

export function renderTemplate(text: string, data: Record<string, string>): string {
  return text.replace(/\{\{(\w+)\}\}/g, (m, key) => data[key] ?? m)
}

/**
 * Render and drop any line whose variables are missing or empty (§31: "If
 * USDOT or phone is missing, do not display null / undefined / empty
 * placeholders / broken variables. Simply omit that row"). A heading line
 * directly above a dropped block is kept only if something survives under
 * it; runs of blank lines collapse to one.
 */
export function renderTemplateClean(text: string, data: Record<string, string>): string {
  const filled = (s: string) => s.replace(/\{\{(\w+)\}\}/g, (_m, key) => (data[key] ?? '').trim())
  const lines = text.split('\n').map((line) => {
    const vars = [...line.matchAll(/\{\{(\w+)\}\}/g)].map((m) => m[1])
    const missing = vars.some((v) => !(data[v] ?? '').trim())
    return missing ? null : filled(line)
  })
  const out: string[] = []
  for (const line of lines) {
    if (line === null) continue
    if (line.trim() === '' && (out.length === 0 || out[out.length - 1].trim() === '')) continue
    out.push(line)
  }
  return out.join('\n').trim()
}

/** What each variable means — shown in the admin template manager (§33). */
export const TEMPLATE_VARIABLE_DESCRIPTIONS: Record<string, string> = {
  old_email: 'Sign-in email change: the address the account used before.',
  first_name: 'Lead campaigns: the freight broker\'s first name ("there" when unknown).',
  last_name: 'Lead campaigns: the freight broker\'s last name.',
  full_name: 'Lead campaigns: first and last name, or the email when no name is on file.',
  brokerage_name: 'Lead campaigns: the brokerage company the lead is pre-verified for.',
  join_link: 'Lead campaigns: the personal sign-up link (email code, relation pre-filled). Expires after 30 days.',
  requester_first_name: 'first name of the freight broker requesting access',
  requester_last_name: 'last name of the freight broker requesting access',
  requester_full_name: 'full name of the freight broker requesting access',
  requester_email: 'email the requester signed up with',
  page_name: 'Moderator access: the page being granted (Freight Broker Leads, Email Templates…).',
  page_description: 'Moderator access: what that page lets the person do.',
  page_link: 'Moderator access: the direct link to that page.',
  granted_by: 'Moderator access: the admin who granted it.',
  access_note: 'Moderator access: the optional note the admin typed.',
  sign_in_link: 'Moderator access: the sign-in page.',
  requester_role_label: 'Permit request: the requester\'s role in words (Freight Broker, Carrier Dispatcher, Carrier Driver).',
  requester_company: 'Permit request: the requester\'s verified company and MC, when on file.',
  requester_company_suffix: 'Permit request: ", Company" for a sentence, blank when no company is on file.',
  requester_line: 'Permit request: the requester, their role and company in one line — always filled, safe to use in a sentence.',
  permit_state_code: 'Permit request: the two-letter state code.',
  order_number: 'Permit request: Synchron\'s order number when their API returned one.',
  source_order_number: 'Permit request: the order number the trip was imported with, when any.',
  unit_number: 'Permit request: the truck unit number on the trip.',
  pickup_date: 'Permit request: pickup date on the trip.',
  delivery_date: 'Permit request: delivery date on the trip.',
  load_dimensions: 'Permit request: load L × W × H and weight, feet-inches with inches in brackets.',
  overall_dimensions: 'Permit request: overall (truck + trailer, loaded) L × W × H and gross weight.',
  axle_summary: 'Permit request: axle count, spacings, KPTRA and axle weights from the unit sheet.',
  truck_info: 'Permit request: truck year, make, model, unit and VIN.',
  trailer_info: 'Permit request: trailer year, make, model, unit, VIN and axle count.',
  previous_permit_attachment: 'Permit request: the file name of the attached permit for that state.',
  previous_permit_summary: 'Permit request: the previous permit for that state (number, dates, dimensions) or a note that this is the first one.',
  rate_confirmation_summary: 'Permit request: whether the rate confirmation is attached.',
  attachments_list: 'Permit request: the files attached to the email, one per line.',
  request_notes: 'Permit request: what the requester typed, or the automatic re-order note.',
  requester_phone: 'requester phone (omitted when unknown)',
  requested_role: 'role requested, e.g. Freight Broker',
  company_name: 'legal name of the company',
  company_display_name: 'display name of the company inside HeavyHaul Agent',
  mc_number: "the company's MC number",
  usdot_number: "the company's USDOT number (omitted when unknown)",
  request_date: 'date the request was submitted',
  verification_expiration_date: 'date the secure links stop working',
  approve_link: 'secure one-time approval link',
  reject_link: 'secure one-time rejection link',
  approve_button: 'secure approval button (approval link as a call to action)',
  reject_button: 'secure rejection button',
  support_email: 'HeavyHaul Agent support address',
  company_footer: 'footer configured on the template (omitted when empty)',
  invited_by: 'the Company Admin who sent the invitation',
  invited_by_email: 'that Company Admin\'s email address',
  invited_by_phone: 'that Company Admin\'s phone (omitted when unknown)',
  verification_link: 'one-time link that confirms a new delivery address',
  verification_code: 'six-digit one-time sign-in code',
  code_minutes: 'how many minutes the code stays valid',
  intake_link: 'the broker\'s intake page, with the secure invitation token when one was issued',
  unsubscribe_link: 'one-click unsubscribe from all updates (added automatically to every updates email)',
  preferences_link: 'the recipient\'s email preference center (added automatically to every updates email)',
  user_name: 'the person the email is about',
  user_email: 'their email',
  user_phone: 'their phone (omitted when unknown)',
  decided_by: 'who approved / rejected / revoked',
  rejection_reason: 'reason shown to the requester',
  freight_broker_dashboard_link: 'the Freight Broker Dashboard (/fb-dashboard) — use in every email to a freight broker',
  carrier_dispatch_dashboard_link: 'the Carrier Dispatch Dashboard (/cd-dashboard) — use in every email to a carrier dispatcher',
  pilot_dispatch_dashboard_link: 'the Pilot Dispatch Dashboard (/pd-dashboard) — use in every email to a pilot company',
  carrier_driver_dashboard_link: 'the Carrier Driver app (/ct-dashboard) — use in every email to a truck driver',
  pilot_driver_dashboard_link: 'the Pilot Driver app (/pc-dashboard) — use in every email to a pilot car driver',
  company_mc: "the company's MC number",
  company_dot: "the company's USDOT number",
  approve_link_note: '',
}

export const DEFAULT_TEMPLATES: TemplateDefault[] = [
  {
    key: 'permit_dimension_alert',
    name: 'Permit Dimension Alert',
    trigger_note: 'A processed permit allows less width, height, length, or weight than the trip requires.',
    recipients_note: 'Active or invited broker and carrier dispatcher contacts on the trip.',
    cc_rules: 'Each contact receives an individual Workspace transactional email.',
    subject: 'Dimension Alert - Permit {{permit_number}} {{permit_state}}, Trip {{trip_id}}',
    body: `A permit attached to trip {{trip_id}} has dimensions smaller than the trip requires.

Permit: {{permit_number}} ({{permit_state}})
Received from: {{permit_source}}

PERMIT ALLOWANCE / TRIP REQUIREMENT
{{mismatch_rows}}

Please review and correct the permit or the trip dimensions before movement.

Open trip: {{workspace_link}}`,
  },
  {
    key: 'pilot_dispatch_trip_invite',
    name: 'Pilot Dispatch Invited to Trip',
    trigger_note:
      'A pilot driver on an assignment taps "Add pilot dispatch" and picks one of their dispatchers or enters an email. Not sent yet — the email backend is a later phase.',
    recipients_note: 'To: the pilot dispatch (company) invited ({{invitee_name}}).',
    cc_rules: 'CC: the inviting pilot driver. The dispatch receives exactly the pilot driver\'s access on the trip — never more.',
    subject: '{{pilot_driver_name}} added you as pilot dispatch on trip {{trip_id}}',
    body: `Hello {{invitee_name}},

{{pilot_driver_name}} ({{pilot_driver_phone}}) added your company as the pilot dispatch on HeavyHaul Agent trip {{trip_id}} ({{pickup_location}} → {{delivery_location}}) for {{carrier_company}}.

Access shared with you: {{shared_access}}

Open the trip workspace: {{workspace_link}}

No HeavyHaul Agent account yet? Create your pilot dispatch account first — it takes three steps (account type, details, validate your email): {{signup_link}}
Once you are in, this assignment is waiting in Pending Assignments.

Questions? {{support_email}}`,
  },
  {
    key: 'pilot_additional_trip_invite',
    name: 'Additional Pilot Invited to Trip',
    trigger_note:
      'A pilot driver on an assignment taps "Add pilot" and picks a pilot linked through their companies or enters an email. Not sent yet — the email backend is a later phase.',
    recipients_note: 'To: the additional pilot driver invited ({{invitee_name}}).',
    cc_rules: 'CC: the inviting pilot driver; the pilot dispatch if connected. The invited pilot receives exactly the inviting pilot\'s access — never more.',
    subject: '{{pilot_driver_name}} invited you to pilot trip {{trip_id}}',
    body: `Hello {{invitee_name}},

{{pilot_driver_name}} ({{pilot_driver_phone}}) invited you to join HeavyHaul Agent trip {{trip_id}} ({{pickup_location}} → {{delivery_location}}) for {{carrier_company}} as an additional pilot car.

Access shared with you: {{shared_access}}

Open the assignment: {{workspace_link}}

No HeavyHaul Agent account yet? Create your pilot driver account first — three steps, then validate your email: {{signup_link}}
Your documents, vehicle and capabilities can be completed after you are in.

Questions? {{support_email}}`,
  },
  {
    key: 'pilot_invoice',
    name: 'Pilot Assignment Invoice',
    trigger_note:
      'A pilot driver or pilot company clicks Send Invoice on a pilot assignment (Pro / Pro Plus owner). Not sent yet — the email backend is a later phase.',
    recipients_note:
      'To: carrier dispatcher or carrier billing contact. Recipients are editable before sending.',
    cc_rules:
      'CC: pilot driver; pilot company dispatcher if connected. Optional: custom billing email, internal admin if needed. Broker only when the broker invited the pilot or the pilot invited the broker.',
    subject: 'Invoice for Pilot Assignment - {{trip_id}} - {{pilot_name}}',
    body: `Hello {{dispatcher_name}},

{{pilot_name}} has issued invoice {{invoice_number}} for pilot assignment {{assignment_id}} on trip {{trip_id}} ({{pickup_location}} → {{delivery_location}}).

States / permits covered: {{assignment_states}} · {{assignment_permits}}
Amount due: {{amount_due}}
Due date: {{due_date}}

View the invoice (PDF attached): {{invoice_link}}

Payment instructions:
{{payment_instructions}}
Preferred payment method: {{preferred_payment_method}}

Questions about this invoice? Contact {{pilot_contact}}.

Sent through HeavyHaul Agent · {{support_email}}`,
  },
  {
    key: 'pilot_paperwork_request',
    name: 'Pilot Paperwork Request',
    trigger_note: 'On the My Pilot tab, the person who invited a pilot clicks Request paperwork (Starter or higher, or within the first 90 days).',
    recipients_note: 'The pilot only (the pilot driver or pilot dispatch on the trip).',
    cc_rules: 'None. The request is recorded in the trip history for everyone who may see this pilot\'s paperwork.',
    subject: '{{requester_name}} is requesting your paperwork for trip {{trip_id}}',
    body: `Hello {{pilot_name}},

{{requester_name}} ({{requester_role}}) has you on HeavyHaul Agent trip {{trip_id}} ({{pickup_location}} → {{delivery_location}}) as a {{pilot_kind}} and needs your paperwork on file before the load moves.

Please upload the following:
{{paperwork_list}}

Open the trip: {{workspace_link}}

Once uploaded, the people who arranged your escort can see each document and its expiration date on the trip.

Questions? {{support_email}}`,
  },
  {
    key: 'carrier_upload_request',
    name: 'Carrier Permit Upload Request',
    trigger_note: 'Broker creates a trip and chooses: Carrier Will Upload Permits',
    recipients_note: 'Carrier dispatcher email only ({{dispatcher_email}})',
    cc_rules: 'Optional: broker receives an internal notification (not in the same email).',
    subject: '{{broker_name}} requested permit upload for your trip',
    body: `Hello {{dispatcher_name}},

{{broker_name}} created a HeavyHaul Agent trip workspace for {{carrier_company}} — trip {{trip_id}} ({{pickup_location}} → {{delivery_location}}).

The broker is requesting that you upload the carrier's existing permits into this workspace.

Secure workspace link: {{workspace_link}}
Rate confirmation: {{rate_confirmation_link}}

What to do:
- Open the workspace using the secure link.
- Upload your existing permits (and any supporting documents).
- Once permits are uploaded, the broker will be able to review permit visibility, restrictions, curfews, escorts, and route options.

Please note:
- This is an upload request — it is NOT a Synchron Permits processing request.
- Synchron Permits has not been assigned to process this permit order.
- Routes are not automatically included in this workflow. If a Google Maps route is needed, it can be requested from inside the trip workspace.

Questions? {{support_email}}`,
  },
  {
    key: 'synchron_processing_request',
    name: 'Synchron Permit Processing Request',
    trigger_note: 'Broker creates a trip and chooses: Request Permits From Synchron Permits',
    recipients_note:
      'Carrier dispatcher email ({{dispatcher_email}}) + Synchron Permits intake/order email ({{synchron_order_email}})',
    cc_rules: 'Optional: broker copied or separately notified.',
    subject: '{{broker_name}} requested Synchron Permits processing - {{payment_responsible_party}} Pays',
    body: `A new permit request was created by {{broker_name}} ({{broker_company}}).

Workspace trip reference: {{trip_id}} — {{pickup_location}} → {{delivery_location}} · Load {{load_number}}
Create ONE Synchron order for this Workspace trip. Save the Workspace trip reference on that order, and add all requested state permits as items under the same order. Return each attached permit with this reference and your eight-digit order token.
Carrier: {{carrier_company}}
Dispatcher: {{dispatcher_name}} · {{dispatcher_email}} · {{dispatcher_phone}}
Rate confirmation: {{rate_confirmation_link}}
HeavyHaul Agent workspace: {{workspace_link}}

To Synchron Permits: please begin the permit intake process for this order.
To the carrier dispatcher: you are included for coordination — please cooperate with Synchron Permits and provide any missing information.

Payment responsible party: {{payment_responsible_party}}.
(When the broker pays: payment responsibility is subject to the broker's billing agreement or approval rules, and the carrier is not the expected payer unless later changed.)

Please note:
- Permits will be uploaded into the HeavyHaul Agent workspace by Synchron Permits through API once processed.
- {{route_inclusion_statement}}
- The broker and carrier do not need to buy separate Google Maps routes for Synchron-processed permits.
- Manual permit upload is disabled for the broker and carrier unless the workflow is changed by an authorized admin.

Sent {{created_datetime}} · Questions? {{support_email}}`,
  },
  {
    key: 'permit_reorder_request',
    name: 'Permit Request to Synchron Permits',
    trigger_note:
      'A broker, dispatcher or driver clicks "Request new permit" on a trip — for an expired permit (re-order) or a state with no permit yet. Sent automatically every time (Nash, 2026-09-23).',
    recipients_note:
      'Synchron Permits intake ({{synchron_order_email}}, SYNCHRON_ORDER_EMAIL in .env, default synchronpermits@gmail.com). The requester ({{requester_email}}) is copied. Attached: the rate confirmation and the previous permit for that state when they are on file.',
    cc_rules: 'The requester is always copied so they have the same record Synchron has.',
    subject: 'New {{permit_state}} permit request — order {{trip_id}} · {{carrier_company}}',
    body: `Hello Synchron Permits,

{{requester_line}} has requested a NEW {{permit_state}} permit for order {{trip_id}} on HeavyHaul Agent. Please issue the {{permit_state}} permit with the exact dimensions and unit information below and reach out to the requester directly if anything is missing.

WHO IS ASKING (the client for this order)
Name: {{requester_name}}
Role: {{requester_role_label}}
Company: {{requester_company}}
Email: {{requester_email}}
Phone: {{requester_phone}}
Who pays for this permit: {{payer}}

THE ORDER
HeavyHaul Agent order: {{trip_id}}
Synchron order number: {{order_number}}
Original order reference: {{source_order_number}}
If a Synchron order already exists for this Workspace trip number, add this state to that SAME order. Keep this Workspace number on the Synchron order for callbacks.
Carrier: {{carrier_company}}
Commodity: {{commodity}}
Pickup: {{pickup_location}}
Delivery: {{delivery_location}}
Pickup date: {{pickup_date}}
Delivery date: {{delivery_date}}

PERMIT REQUESTED
State: {{permit_state}} ({{permit_state_code}})
{{previous_permit_summary}}
{{rate_confirmation_summary}}
Rate confirmation download link: {{rate_confirmation_url}}

DIMENSIONS — please permit exactly these
Load: {{load_dimensions}}
Overall (truck + trailer, loaded): {{overall_dimensions}}
Unit number: {{unit_number}}
Axles: {{axle_summary}}
Truck: {{truck_info}}
Trailer: {{trailer_info}}

NOTES FROM THE REQUESTER
{{request_notes}}

ATTACHED TO THIS EMAIL
{{attachments_list}}

Everything about this order — every permit, the rate confirmation, the route and the people on it — is in the HeavyHaul Agent workspace:
{{workspace_link}}

Thank you,
HeavyHaul Agent on behalf of {{requester_name}}
Sent {{created_datetime}} · Questions about this email: {{support_email}}`,
  },
  {
    key: 'moderator_access_invitation',
    name: 'Moderator Page Access Invitation',
    trigger_note: 'The HeavyHaul Agent admin grants someone access to one moderator page (Nash, 2026-09-23). Sent from that page\'s "Add moderator" button. Only the admin can grant access.',
    recipients_note: 'The person being given access.',
    cc_rules: 'None.',
    subject: 'You have been given access to {{page_name}} on HeavyHaul Agent',
    body: `Hello {{user_name}},

{{granted_by}} has given you access to the {{page_name}} page on HeavyHaul Agent.

What you can do there: {{page_description}}

Note from {{granted_by}}: {{access_note}}

Open the page: {{page_link}}

Sign in with this email address ({{user_email}}) at {{sign_in_link}}. If you do not have a password yet, choose "Email me a sign-in code" and we will send you a code.

You have access to this page only. Nothing else in the admin area opens for you, and access can be changed at any time by the HeavyHaul Agent admin.

Questions? {{support_email}}

{{company_footer}}`,
  },
  {
    key: 'company_access_approval',
    name: 'Company Access Approval Request',
    trigger_note:
      'A freight broker or carrier dispatcher clicks "Verify your company access" and enters the MC number (Task 89).',
    recipients_note:
      'Existing Company Admin in HeavyHaul Agent → verified corporate email on file → corporate-domain email → manual admin queue (article §17).',
    cc_rules: 'None. The requester is told on screen where the request went.',
    subject: 'Approve company access request for HeavyHaul Agent',
    body: `A user is requesting permission to represent your company inside HeavyHaul Agent. Approve only if this person is authorized to create trips, manage permit intake, and interact with carriers on behalf of your company.

Name: {{user_name}}
Email: {{user_email}}
Phone: {{user_phone}}
Requested company: {{company_name}}
Requested role: {{requested_role}}
Requested access level: {{requested_access_level}}
Company match: {{company_match_info}}

Approve: {{approve_link}}
Deny: {{deny_link}}
I don't know this person: {{report_link}}

This link expires in 14 days. If you did not expect this request, you can ignore it — no access is granted until you approve.

Questions? {{support_email}}`,
  },

  // ---- Account & security (2026-09-22) ----
  {
    key: 'login_email_verification',
    name: 'Sign-in Email Change Verification',
    trigger_note: 'A user changes the email they sign in with (Profile → Account). Sent to the NEW address; the change happens when the link is opened.',
    recipients_note: 'The NEW sign-in address. Transactional / account security — never blocked by marketing preferences.',
    cc_rules: 'None.',
    subject: 'Confirm your new sign-in email for HeavyHaul Agent',
    body: `Hello {{user_name}},

You asked to change the email you sign in to HeavyHaul Agent with, from {{old_email}} to this address. Open the link below to confirm. It works once and expires in 24 hours.

{{verification_link}}

After confirming, use this address to sign in. If you did not request this, ignore this email — nothing changes.

Questions? {{support_email}}`,
  },
  {
    key: 'email_verification',
    name: 'Email Address Verification',
    trigger_note: 'A user changes the address HeavyHaul Agent delivers to (Settings → Email), or an account whose address bounced enters a new one.',
    recipients_note: 'The NEW address. Transactional / account security — never blocked by marketing preferences.',
    cc_rules: 'None.',
    subject: 'Verify your email address for HeavyHaul Agent',
    body: `Hello {{user_name}},

Confirm that HeavyHaul Agent should deliver messages to this address by opening the link below. It works once and expires in 24 hours.

{{verification_link}}

If you did not request this, you can ignore this email — nothing changes.

Questions? {{support_email}}`,
  },

  {
    key: 'email_code',
    name: 'One-Time Sign-In Code',
    trigger_note: 'A visitor submits a broker intake page without being signed in and enters their email; also any email-code sign-in.',
    recipients_note: 'The address that asked for the code. Transactional / account security.',
    cc_rules: 'None.',
    subject: '{{verification_code}} is your HeavyHaul Agent code',
    body: `Your HeavyHaul Agent sign-in code is:

{{verification_code}}

It works for {{code_minutes}} minutes. Enter it on the page where you requested it to continue.

If you did not request a code, you can ignore this email.

Questions? {{support_email}}`,
  },
  {
    key: 'broker_intake_invitation',
    name: 'Broker Intake Invitation (secure link)',
    trigger_note: 'A freight broker invites a specific carrier or dispatcher to submit trip information on their intake page.',
    recipients_note: 'The invited carrier / dispatcher. The link carries a secure, expiring token tied to their email.',
    cc_rules: 'None.',
    subject: '{{broker_name}} invited you to submit trip information on HeavyHaul Agent',
    body: `Hello,

{{invited_by}} at {{broker_name}} invited you to submit your load and rate confirmation through their HeavyHaul Agent intake page.

Open your secure link (it is tied to this email address and expires in 14 days):
{{intake_link}}

You will confirm your email with a one-time code the first time — no account setup, no password.

Questions? {{support_email}}`,
  },

  // ---- Carrier Company Info: dispatcher ↔ carrier relationship (2026-09-19) ----
  // Raised as events by the Carrier Dashboard; the copy lives here so
  // HeavyHaul admins/moderators manage it, never the dashboard code.
  {
    key: 'company_relationship_requested',
    name: 'Company Relationship Requested (to Company Admins)',
    trigger_note: 'A dispatcher asks to be connected to a carrier that already has a Company Admin in HeavyHaul Agent.',
    recipients_note: 'Every verified Company Admin of the carrier; the official company email when no admin exists.',
    cc_rules: 'None.',
    subject: '{{user_name}} is requesting to join {{company_name}} on HeavyHaul Agent',
    body: `A dispatcher is requesting to be connected to your carrier company inside HeavyHaul Agent.

Name: {{user_name}}
Email: {{user_email}}
Phone: {{user_phone}}
Company: {{company_name}} (MC {{company_mc}} · USDOT {{company_dot}})
Requested role: {{requested_role}}
Requested on: {{request_date}}

Review it under Carrier Dispatch Dashboard → Company Info → Pending Verification Requests:
{{carrier_dispatch_dashboard_link}}

No access is granted until you approve. Questions? {{support_email}}`,
  },
  {
    key: 'company_relationship_approved',
    name: 'Company Relationship Approved (to the dispatcher)',
    trigger_note: 'A Company Admin or HeavyHaul admin approves a pending dispatcher request.',
    recipients_note: 'The dispatcher who requested the relationship.',
    cc_rules: 'None.',
    subject: 'You are now a verified dispatcher for {{company_name}}',
    body: `Good news — {{decided_by}} approved your relationship with {{company_name}} (MC {{company_mc}} · USDOT {{company_dot}}).

Role: {{requested_role}}
Relationship: Verified

Open your Carrier Dispatch Dashboard: {{carrier_dispatch_dashboard_link}}

Questions? {{support_email}}`,
  },
  {
    key: 'company_relationship_rejected',
    name: 'Company Relationship Rejected (to the dispatcher)',
    trigger_note: 'A Company Admin or HeavyHaul admin rejects a pending dispatcher request.',
    recipients_note: 'The dispatcher who requested the relationship. Internal notes are never included.',
    cc_rules: 'None.',
    subject: 'Your request to join {{company_name}} was not approved',
    body: `{{company_name}} did not approve your request to be connected as a {{requested_role}}.

Reason given: {{rejection_reason}}

If you believe this is a mistake, contact the company directly or reach us at {{support_email}}. You can request access again from your Carrier Dashboard: {{carrier_dispatch_dashboard_link}}`,
  },
  {
    key: 'company_relationship_revoked',
    name: 'Company Relationship Revoked (to the dispatcher)',
    trigger_note: 'A Company Admin or HeavyHaul admin revokes a verified dispatcher relationship.',
    recipients_note: 'The dispatcher whose relationship was revoked. Their HeavyHaul Agent account stays intact.',
    cc_rules: 'None.',
    subject: 'Your verified relationship with {{company_name}} was removed',
    body: `{{decided_by}} removed your verified relationship with {{company_name}} (MC {{company_mc}} · USDOT {{company_dot}}).

Your HeavyHaul Agent account is not affected — only the company relationship was revoked. You can request access to a carrier again from your Carrier Dashboard: {{carrier_dispatch_dashboard_link}}

Questions? {{support_email}}`,
  },
  {
    key: 'company_verification_reminder',
    name: 'Company Verification Reminder (to Company Admins)',
    trigger_note: 'A pending dispatcher clicks "Resend verification request", or a scheduled reminder fires (later).',
    recipients_note: 'Every verified Company Admin of the carrier; the official company email when no admin exists.',
    cc_rules: 'None.',
    subject: 'Reminder: {{user_name}} is still waiting to be verified for {{company_name}}',
    body: `{{user_name}} ({{user_email}}) requested on {{request_date}} to be connected to {{company_name}} as a {{requested_role}} and is still waiting for verification.

Approve or reject the request under Carrier Dispatch Dashboard → Company Info:
{{carrier_dispatch_dashboard_link}}

Questions? {{support_email}}`,
  },

  {
    key: 'company_dispatcher_invitation',
    name: 'Carrier Dispatcher Invitation (verified by the Company Admin)',
    trigger_note: 'A carrier Company Admin (or HeavyHaul Agent) invites a dispatcher by name and email. The relationship is verified immediately — no approval step.',
    recipients_note: 'The invited dispatcher. With a HeavyHaul Agent account the relationship is live at once; without one it activates when they create their account with this email.',
    cc_rules: 'None.',
    subject: '{{invited_by}} added you to {{company_name}} on HeavyHaul Agent',
    body: `Hello {{requester_first_name}},

{{invited_by}} invited you to HeavyHaul Agent as a verified Carrier Dispatcher for {{company_name}} (MC {{company_mc}}) and granted you access to the team.

Invited by
Name: {{invited_by}}
Email: {{invited_by_email}}
Phone: {{invited_by_phone}}
Company: {{company_name}}
MC Number: {{company_mc}}

Your relationship with {{company_name}} is already verified — no further approval is needed. Sign in with this email address ({{requester_email}}) and your Carrier Dispatch Dashboard is ready:
{{carrier_dispatch_dashboard_link}}

Questions? {{support_email}}

{{company_footer}}`,
  },

  {
    key: 'company_dispatcher_bulk_invitation',
    name: 'Carrier Dispatcher Bulk Invitation (verified by the Company Admin)',
    trigger_note: 'A carrier Company Admin pastes a list of emails and clicks Send — one message per address, same subject and body, no names needed.',
    recipients_note: 'Each pasted address, sent individually (nobody sees the other recipients). Account holders are verified at once; others when they create their account with that email.',
    cc_rules: 'None — individual sends, never a visible list.',
    subject: '{{invited_by}} invited you to join {{company_name}} on HeavyHaul Agent',
    body: `Hello,

{{invited_by}} sent you an invite to create your account on heavyhaulagent.com and granted you access to {{company_name}} (MC {{company_mc}}) as a verified Carrier Dispatcher — you are part of the team the moment you sign up.

Invited by
Name: {{invited_by}}
Email: {{invited_by_email}}
Phone: {{invited_by_phone}}
Company: {{company_name}}
MC Number: {{company_mc}}

Create your account with this email address ({{requester_email}}) — your relationship with {{company_name}} is already verified, no further approval needed:
{{carrier_dispatch_dashboard_link}}

Already have a HeavyHaul Agent account with this email? Just sign in — the company is connected.

Questions? {{support_email}}

{{company_footer}}`,
  },

  // ---- Broker Company relationships (2026-09-19). The workflow decides WHEN
  // to send; these defaults decide WHAT it says until an admin edits them. ----
  {
    key: 'broker_relationship_verification_request',
    name: 'Freight Broker Relationship Verification Request',
    trigger_note: 'A freight broker enters an MC number, identifies the company, and company / external verification is required.',
    recipients_note: 'Verified Company Admins of the broker company; otherwise the official company email on file (verification provider).',
    cc_rules: 'None. The requester is told on screen where the request went.',
    subject: 'Please verify {{requester_full_name}} for {{company_name}} on HeavyHaul Agent',
    body: `Hello,

A user has created a HeavyHaul Agent account and requested to be connected to your broker company.

Person Requesting Verification
Name: {{requester_full_name}}
Email: {{requester_email}}
Phone: {{requester_phone}}
Requested Role: {{requested_role}}

Broker Company
Company: {{company_name}}
MC Number: {{mc_number}}
USDOT Number: {{usdot_number}}

The user is stating that they currently work with or represent {{company_name}}.

Please confirm whether this relationship is valid.

Approve Request
{{approve_button}}

Reject Request
{{reject_button}}

If you recognize this person and they are authorized to represent your company, approve the request.

If you do not recognize this person or they are no longer associated with your company, reject the request.

Approving this request allows the user to access HeavyHaul Agent functionality associated with {{company_name}} according to the Freight Broker permissions assigned to them.

Approval does not automatically grant Company Owner, Billing Admin, or HeavyHaul Agent Admin authority.

Request submitted:
{{request_date}}

Verification link expires:
{{verification_expiration_date}}

Thank you,
HeavyHaul Agent
{{support_email}}

{{company_footer}}`,
  },
  {
    key: 'broker_relationship_verified',
    name: 'Broker Relationship Verified (to the freight broker)',
    trigger_note: 'The company (or HeavyHaul Agent) approves a pending freight broker request.',
    recipients_note: 'The freight broker who requested the relationship.',
    cc_rules: 'None.',
    subject: 'You are now a verified Freight Broker for {{company_name}}',
    body: `Good news — {{decided_by}} verified your relationship with {{company_name}} (MC {{mc_number}}).

Role: {{requested_role}}
Relationship: Verified

Open your Freight Broker Dashboard: {{freight_broker_dashboard_link}}

Questions? {{support_email}}`,
  },
  {
    key: 'broker_relationship_rejected',
    name: 'Broker Relationship Rejected (to the freight broker)',
    trigger_note: 'The company (or HeavyHaul Agent) rejects a pending freight broker request.',
    recipients_note: 'The freight broker who requested the relationship. Internal notes are never included.',
    cc_rules: 'None.',
    subject: 'Your request to join {{company_name}} was not approved',
    body: `{{company_name}} did not approve your request to be connected as a {{requested_role}}.

Reason given: {{rejection_reason}}

If you believe this is a mistake, contact the company directly or reach us at {{support_email}}. You can request access again from your Freight Broker Dashboard: {{freight_broker_dashboard_link}}`,
  },
  {
    key: 'broker_relationship_reminder',
    name: 'Broker Relationship Reminder (to the company)',
    trigger_note: 'A pending freight broker clicks "Resend verification request", or a scheduled reminder fires (later).',
    recipients_note: 'Same recipients as the original verification request.',
    cc_rules: 'None.',
    subject: 'Reminder: {{requester_full_name}} is still waiting to be verified for {{company_name}}',
    body: `{{requester_full_name}} ({{requester_email}}) requested on {{request_date}} to be connected to {{company_name}} (MC {{mc_number}}) as a {{requested_role}} and is still waiting for verification.

Approve Request
{{approve_button}}

Reject Request
{{reject_button}}

Verification link expires:
{{verification_expiration_date}}

Questions? {{support_email}}`,
  },
  {
    key: 'broker_lead_invitation',
    name: 'Freight Broker Lead — Invitation (campaign step 1)',
    trigger_note: 'Freight Broker Leads manager (2026-09-23): the first email of a lead campaign, or "Invite now" on selected leads. Never automatic outside a running campaign.',
    recipients_note: 'A verified freight broker lead who has no HeavyHaul Agent account yet.',
    cc_rules: 'None.',
    subject: '{{first_name}}, your HeavyHaul Agent freight broker account for {{brokerage_name}} is ready',
    body: `Hello {{first_name}},

We have worked with you as a freight broker for {{brokerage_name}} (MC {{mc_number}}), so your HeavyHaul Agent freight broker profile is already set up. Your relationship with {{brokerage_name}} is pre-verified — when you sign in you only have to confirm it.

Create your account (one email code, no password): {{join_link}}

What you get: permits, routes, pilot cars and carrier paperwork for every heavy haul load in one place, with your carriers and drivers on the same page.

Questions? {{support_email}}

{{company_footer}}`,
  },
  {
    key: 'broker_lead_reminder',
    name: 'Freight Broker Lead — Reminder (campaign step 2)',
    trigger_note: 'Freight Broker Leads manager: the follow-up step of a lead campaign, sent only if the lead has not signed up.',
    recipients_note: 'A freight broker lead who received the invitation and has not signed up.',
    cc_rules: 'None.',
    subject: 'Reminder: your {{brokerage_name}} freight broker account on HeavyHaul Agent',
    body: `Hello {{first_name}},

A quick reminder that your HeavyHaul Agent freight broker account for {{brokerage_name}} is waiting. It takes a minute: open the link, enter the code we email you, confirm your relationship with {{brokerage_name}}, and you are in.

Sign in here: {{join_link}}

Questions? {{support_email}}

{{company_footer}}`,
  },
  {
    key: 'carrier_lead_invitation',
    name: 'Carrier Lead — Invitation (campaign step 1)',
    trigger_note: 'Carrier Leads manager (2026-09-25): the first email of a carrier lead campaign, or "Invite now" on selected leads. Never automatic outside a running campaign.',
    recipients_note: 'A dispatcher or driver with no HeavyHaul Agent account. They have never used the platform, so the email sells what the free account does and never claims a past relationship.',
    cc_rules: 'None.',
    subject: '{{first_name}}, upload a permit and see what it actually says',
    body: `Hello {{first_name}},

HeavyHaul Agent is a free place to keep your oversize permits and actually read them. Upload a permit from anywhere — your dispatcher, a broker, a permit service, or straight from the state — and you get:

Free alerts. If the permit says 12'0" and your load is 12'6", you see it before the truck moves instead of at the scale. Expiring and expired permits are flagged the same way.

Provisions in plain language. "Subject to general provisions" turned into the actual rules: travel windows, metro curfews, weekend and holiday bans, flags, signs, lights and when you need an escort.

Answers on every permit. Ask the agent "can I move Sunday in Oklahoma?" or "what escorts do I need at 14 feet?" and get the answer with the line from the permit it came from.

Google Maps routes when you want one. For any permit you upload you can order a route built from that permit — Google Maps in parts, a GPX file for the truck GPS and a Hummer GPS link, with a pin for every exit. One purchase covers everyone on the load.

Create your free account with one emailed code, no password: {{join_link}}

Uploading permits, the alerts, the provisions and the questions cost nothing. You only pay when you order a route.

{{support_email}}

{{company_footer}}`,
  },
  {
    key: 'carrier_lead_reminder',
    name: 'Carrier Lead — Reminder (campaign step 2)',
    trigger_note: 'Carrier Leads manager: the follow-up step of a carrier lead campaign, sent only if the lead has not signed up.',
    recipients_note: 'A carrier lead who received the invitation and has not signed up.',
    cc_rules: 'None.',
    subject: 'Does your permit match your load, {{first_name}}?',
    body: `Hello {{first_name}},

Most oversize violations are not complicated. The permit says one width and the load is wider, the permit expired two days ago, or the provisions banned the move on a Sunday and nobody read that far.

HeavyHaul Agent checks all three for free. Upload the permit and you get the dimension and expiration alerts, the provisions written out in plain language, and an agent you can ask about that specific permit. When you want the drive laid out, you can order a Google Maps route with a GPX file and a pin for every exit.

It takes a minute to start — one emailed code, no password: {{join_link}}

{{support_email}}

{{company_footer}}`,
  },
  {
    key: 'carrier_lead_final_notice',
    name: 'Carrier Lead — Final note (campaign step 3)',
    trigger_note: 'Carrier Leads manager: the last step of a carrier lead campaign. After this the lead is not emailed again by that campaign.',
    recipients_note: 'A carrier lead who has not responded to the invitation or the reminder.',
    cc_rules: 'None.',
    subject: 'Last note, {{first_name}}',
    body: `Hello {{first_name}},

This is the last note from us. If you ever want a free place to upload an oversize permit, get an alert when the permit and the load do not match, read the provisions in plain language, ask questions about that permit and order a Google Maps route from it, the account is here whenever you need it:

{{join_link}}

If not, no further emails will follow. Safe travels.

{{support_email}}

{{company_footer}}`,
  },
  {
    key: 'broker_lead_final_notice',
    name: 'Freight Broker Lead — Final note (campaign step 3)',
    trigger_note: 'Freight Broker Leads manager: the last step of a lead campaign. After this the lead is not emailed again by that campaign.',
    recipients_note: 'A freight broker lead who has not responded to the invitation or the reminder.',
    cc_rules: 'None.',
    subject: 'Last note from HeavyHaul Agent, {{first_name}}',
    body: `Hello {{first_name}},

This is the last note from us about your pre-verified freight broker account for {{brokerage_name}}. If you would like to run your heavy haul loads with permits, routes and pilot cars in one place, your account is here whenever you are ready:

{{join_link}}

If not, no further emails will follow. Thank you for the work we have done together.

{{support_email}}

{{company_footer}}`,
  },
  {
    key: 'broker_company_admin_invitation',
    name: 'Broker Company Admin Invitation',
    trigger_note: 'A Company Admin or HeavyHaul Agent grants Company Admin permission to a verified freight broker.',
    recipients_note: 'The freight broker who was granted Company Admin.',
    cc_rules: 'None.',
    subject: 'You are now a Company Admin for {{company_name}} on HeavyHaul Agent',
    body: `{{decided_by}} made you a Company Admin for {{company_name}} (MC {{mc_number}}).

You can now manage the company profile, review freight broker requests and revoke relationships under Freight Broker Dashboard → Company Info:
{{freight_broker_dashboard_link}}

Questions? {{support_email}}`,
  },
  {
    key: 'broker_company_invitation',
    name: 'Freight Broker Invitation (verified by the Company Admin)',
    trigger_note: 'A Company Admin (or HeavyHaul Agent) invites a freight broker by name and email. The relationship is verified immediately — no approval step.',
    recipients_note: 'The invited freight broker. With a HeavyHaul Agent account the relationship is live at once; without one it activates when they sign up with this email.',
    cc_rules: 'None.',
    subject: '{{invited_by}} added you to {{company_name}} on HeavyHaul Agent',
    body: `Hello {{requester_first_name}},

{{invited_by}} invited you to HeavyHaul Agent as a verified Freight Broker for {{company_name}} (MC {{mc_number}}) and granted you access to the team.

Invited by
Name: {{invited_by}}
Email: {{invited_by_email}}
Phone: {{invited_by_phone}}
Company: {{company_name}}
MC Number: {{mc_number}}

Your relationship with {{company_name}} is already verified — no further approval is needed. Sign in with this email address ({{requester_email}}) and your Freight Broker Dashboard is ready:
{{freight_broker_dashboard_link}}

If you do not have a HeavyHaul Agent account yet, create one with this same email address and the company will be connected automatically.

Questions? {{support_email}}

{{company_footer}}`,
  },
  {
    key: 'broker_company_bulk_invitation',
    name: 'Freight Broker Bulk Invitation (verified by the Company Admin)',
    trigger_note: 'A Company Admin pastes a list of emails and clicks Send — one message per address, same subject and body, no names needed.',
    recipients_note: 'Each pasted address, sent individually (nobody sees the other recipients). Account holders are verified at once; others when they sign up with that email.',
    cc_rules: 'None — individual sends, never a visible list.',
    subject: '{{invited_by}} invited you to {{company_name}} on HeavyHaul Agent',
    body: `Hello,

{{invited_by}} sent you an invite to create your account on heavyhaulagent.com and granted you access to {{company_name}} (MC {{mc_number}}) as a verified Freight Broker — you are part of the team the moment you sign up.

Invited by
Name: {{invited_by}}
Email: {{invited_by_email}}
Phone: {{invited_by_phone}}
Company: {{company_name}}
MC Number: {{mc_number}}

Your relationship with {{company_name}} is already verified — no further approval is needed.

Already have a HeavyHaul Agent account with this email? Sign in and your Freight Broker Dashboard is ready:
{{freight_broker_dashboard_link}}

New to HeavyHaul Agent? Create your account with this same email address ({{requester_email}}) and the company will be connected automatically.

Questions? {{support_email}}

{{company_footer}}`,
  },
  {
    key: 'broker_relationship_revoked',
    name: 'Broker Relationship Revoked (to the freight broker)',
    trigger_note: 'A Company Admin or HeavyHaul Agent revokes a verified freight broker relationship.',
    recipients_note: 'The freight broker whose relationship was revoked. Their account stays intact.',
    cc_rules: 'None.',
    subject: 'Your verified relationship with {{company_name}} was removed',
    body: `{{decided_by}} removed your verified relationship with {{company_name}} (MC {{mc_number}}).

Your HeavyHaul Agent account is not affected — only the company relationship was revoked. You can connect to a broker company again from your Freight Broker Dashboard: {{freight_broker_dashboard_link}}

Questions? {{support_email}}`,
  },
  // Auto-Participants (Nash, 2026-09-30; docs/TASKS-2026-09-30-AUTO-PARTICIPANTS.md).
  {
    key: 'auto_participant_request',
    name: 'Auto-Participant Request',
    trigger_note:
      'A person asks someone to be their Personal Auto-Participant (Settings → Auto-Participants → Add Auto-Participant). Consent is required before any trip is shared, so this is an account-security email that always sends.',
    recipients_note: 'The person being asked. If the email has no HeavyHaul Agent account yet, the link leads through sign-up first.',
    cc_rules: 'None.',
    subject: '{{owner_name}} wants to automatically include you in their Trips',
    body: `Hello {{first_name}},

{{owner_name}} wants to automatically include you in Trips where {{owner_name}} participates.

Auto-Participants are people who are automatically added to applicable Trips so you do not have to be invited manually each time. You keep your own role and see only the Trips the rule applies to.

Accept or decline: {{accept_link}}

If you do not have a HeavyHaul Agent account yet, the link lets you create one and choose your role first. The link expires in 14 days.

HeavyHaul Agent
{{support_email}}`,
  },
  {
    key: 'auto_participant_company_request',
    name: 'Company Auto-Participant Request',
    trigger_note:
      'A Company Admin adds a person from OUTSIDE the company as a Company Auto-Participant. External people must accept before any trip is shared.',
    recipients_note: 'The external person being added.',
    cc_rules: 'None.',
    subject: '{{company_name}} wants to automatically include you in its Trips',
    body: `Hello {{first_name}},

{{company_name}} wants to automatically include you in Trips involving {{company_name}} ({{scope_label}}). Requested by {{requested_by}}.

You would be added as a normal Trip participant with your own role, and may receive operational notifications and access Trip information for those Trips. This does not make you a member of {{company_name}}.

Accept or decline: {{accept_link}}

The link expires in 14 days.

HeavyHaul Agent
{{support_email}}`,
  },
  {
    key: 'auto_participant_added',
    name: 'Automatically Added to a Trip',
    trigger_note:
      'An Auto-Participant rule added this person to a Trip — at Trip creation, when an invitation was accepted, when a Synchron order was imported, or when a historical Trip was claimed. One email per person per Trip.',
    recipients_note: 'The auto-added person only. Operational category: their email preferences apply.',
    cc_rules: 'None.',
    subject: 'You were automatically added to Trip {{trip_id}}',
    body: `Hello {{first_name}},

You were automatically added to Trip {{trip_id}} {{reason}}.

Route: {{trip_route}}

Open the Trip: {{workspace_link}}

You take part with your own role. To change who includes you automatically, open Settings → Auto-Participants.

HeavyHaul Agent
{{support_email}}`,
  },
]
