import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Loading, ErrorState } from '../../../components/PageState.jsx'
import { api } from '../../../api/client.js'
import { getEmailBlock, listEmailBlocks, newEmailBlock } from '../../../emailBlocks/index.js'
// Admin → Engagement → Templates (ENGAGEMENT.md §4.6.2, Phase 5b).
//
// Phase 5a moved every subject and body out of `mailer.js` into rows. This is the
// screen that lets someone change one, and its whole shape follows from a single
// fact about email:
//
// **the server renders the mail, so the server renders the preview.**
//
// There is no React renderer for an `email.*` block anywhere in this client. The
// preview is HTML the server produced with the same call the send path uses,
// dropped into a sandboxed iframe. That costs a round trip per edit — debounced
// below — and buys the only property that matters on a screen like this: what is
// on screen is what will arrive, not a second implementation's opinion of it.
//
// **The sandbox is a security boundary, not a nicety.** The preview is
// operator-authored HTML. It renders with `sandbox` and no `allow-scripts`, from
// `srcdoc` (an opaque origin), so it can neither run script nor reach this page's
// cookies even if someone stores markup that gets past `sanitizeHtml`. The
// attributes are asserted in `client/test/emailTemplates.test.js` for the same
// reason the server's checks are asserted: this is the kind of attribute someone
// removes while debugging and does not put back.
//
// What the operator can do here is deliberately bounded (settled with the org
// lead at the start of the phase):
//
// • **A shipped default is edited in place.** `protected` blocks deletion and
// nothing else; saving sets `customized = 1`, which is what stops the next
// seed bump from taking the edit back.
// • **Duplicate is the only way to a new template**, so every template on a
// deployment descends from one that renders.
const DANGER = { color: '#d98b84', borderColor: '#5b2020' }
// Three widths, because a mail body has to survive all of them and the failures
// are different: 640 is a desktop client's reading pane, 360 is a phone, and the
// plain-text part is what a text-only client and every screen reader gets.
const WIDTHS = [
['desktop', 'Desktop', 640],
['mobile', 'Mobile', 360],
]
/** Short, human label for a template's channel. */
const CHANNEL_LABEL = { email: 'Email', inapp: 'On the site', push: 'Push' }
// ── The preview frame ──────────────────────────────────────────────────────
/**
* The rendered HTML, in a sandboxed frame.
*
* `dark` applies a CSS inversion to the FRAME, not to the mail: it approximates
* what Apple Mail and Outlook do to a light-only message, which is the failure
* §4.6.2 asks this control to expose ("a light-only template renders as unreadable
* dark-on-dark in about a third of inboxes"). It is an approximation and says so
* on screen — the alternative, rendering a second dark palette server-side, would
* be a preview of a mail this system does not send.
*/
function PreviewFrame({ html, width, dark }) {
return (
)
}
// ── The editor ─────────────────────────────────────────────────────────────
function TemplateEditor({ template, triggers, onDone, onCancel }) {
const [name, setName] = useState(template.name)
const [subject, setSubject] = useState(template.subject || '')
const [blocks, setBlocks] = useState(template.blocks || [])
const [textBody, setTextBody] = useState(template.text_body || '')
const [status, setStatus] = useState(template.status)
const [triggerId, setTriggerId] = useState(template.trigger_id || '')
const [selected, setSelected] = useState(template.blocks?.[0]?.id || null)
const [preview, setPreview] = useState(null)
const [previewError, setPreviewError] = useState(null)
const [tab, setTab] = useState('html')
const [width, setWidth] = useState('desktop')
const [dark, setDark] = useState(false)
const [saving, setSaving] = useState(false)
const [errors, setErrors] = useState([])
const [saved, setSaved] = useState(false)
const [testTo, setTestTo] = useState('')
const [testState, setTestState] = useState(null)
// The variable palette. It comes from the server with the row and is refreshed
// by every preview, because re-pointing the template at another trigger changes
// it and the server is the one that knows what that trigger declares.
const [variables, setVariables] = useState(template.variables || [])
const draft = useMemo(
() => ({ name, subject, blocks, textBody: textBody || null, status, triggerId: triggerId || null }),
[name, subject, blocks, textBody, status, triggerId],
)
// Debounced preview. The delay is not about server load — it is one small
// render — but about the frame: re-mounting an iframe on every keystroke makes
// the preview flicker and steals nothing back.
const timer = useRef(null)
useEffect(() => {
if (timer.current) clearTimeout(timer.current)
timer.current = setTimeout(async () => {
try {
const body = { subject: draft.subject, blocks: draft.blocks, textBody: draft.textBody, triggerId: draft.triggerId }
const result = await api.admin.previewEngagementTemplate(template.id, body)
setPreview(result)
setPreviewError(null)
if (Array.isArray(result.variables)) setVariables(result.variables)
} catch (err) {
// A preview failure is expected while a block is half-edited, so it is
// shown where the preview would be rather than as a page-level error.
setPreviewError(err.body?.errors?.join(' · ') || err.message)
}
}, 400)
return () => timer.current && clearTimeout(timer.current)
}, [draft, template.id])
const selectedBlock = blocks.find((b) => b.id === selected) || null
const selectedDef = selectedBlock ? getEmailBlock(selectedBlock.type) : null
const updateBlock = (id, props) =>
setBlocks((bs) => bs.map((b) => (b.id === id ? { ...b, props } : b)))
const addBlock = (type) => {
const block = newEmailBlock(type)
if (!block) return
setBlocks((bs) => [...bs, block])
setSelected(block.id)
}
const move = (id, delta) =>
setBlocks((bs) => {
const i = bs.findIndex((b) => b.id === id)
const j = i + delta
if (i < 0 || j < 0 || j >= bs.length) return bs
const next = [...bs]
;[next[i], next[j]] = [next[j], next[i]]
return next
})
const removeBlock = (id) =>
setBlocks((bs) => {
const next = bs.filter((b) => b.id !== id)
if (selected === id) setSelected(next[0]?.id || null)
return next
})
async function save() {
setSaving(true)
setErrors([])
setSaved(false)
try {
await api.admin.updateEngagementTemplate(template.id, draft)
setSaved(true)
onDone()
} catch (err) {
setErrors(err.body?.errors?.length ? err.body.errors : [err.message])
} finally {
setSaving(false)
}
}
async function sendTest() {
setTestState({ busy: true })
try {
const body = { ...draft, to: testTo }
const result = await api.admin.testSendEngagementTemplate(template.id, body)
setTestState({ ok: true, message: `Sent to ${result.to}.` })
} catch (err) {
setTestState({ ok: false, message: err.body?.errors?.join(' · ') || err.message })
}
}
const widthPx = WIDTHS.find(([id]) => id === width)?.[2] || 640
return (
{template.name}
{template.key} · {CHANNEL_LABEL[template.channel] || template.channel}
{template.protected && ' · part of the system'}
setSelected(b.id)}
>
{def?.icon || '?'}
{/* An unknown type is a client/server version skew, and saying
so beats rendering a blank row the operator cannot act on. */}
{def ? def.label : `${b.type} (not known to this client)`}
An approximation of how a client that inverts a light-only message will show it.
)}
>
) : (
{preview.text || '(empty — a published template is refused with no text part)'}
)}
{preview?.missing?.length > 0 && (
No example value for: {preview.missing.join(', ')} — these render as nothing here and
will carry real values when the message is actually sent.
)}
Send a test
Sends what is on screen, saved or not, through the configured transport.
setTestTo(e.target.value)} style={{ flex: 1 }} />
{testState && !testState.busy && (
{testState.message}
)}
)
}
/** The variable tokens, for the two fields that are not block props. */
function VariableButtons({ variables, onInsert }) {
if (!variables?.length) return null
return (
Every message this deployment sends. The shipped ones are editable — your edits survive
upgrades — and cannot be deleted, because the system breaks without them. To make a new
template, duplicate one that already works.
)
}
/**
* The three warnings a row can carry. Each is a different fact and they are worded
* as what an operator should DO, not as the flag name: "dormant" and "behind" mean
* nothing to someone who has not read the design document.
*/
function Flags({ template }) {
const notes = []
if (template.dormant) {
notes.push(`No installed module declares ${template.trigger_id} — nothing will send this.`)
}
if (template.triggerBehind) {
notes.push('Its trigger has changed since this was written; check the variables still exist.')
}
if (template.seedBehind) {
notes.push('A newer version of the shipped default exists. Your edits were kept, so it was not applied.')
}
if (!notes.length) return null
return (