// ─── template-format-editor.jsx ──────────────────────────────────────────────
// "Quiz · gaming" templates by format: the guided editor, a full screen inside
// "Layout library" › "Quiz · gaming" › "Manage templates". Part 1 is the EMAIL; part 2 (Omar, 2026-11-06,
// "[450] Part 2's plan approved") adds TEXT MESSAGES and the WEBSITE to the same editor, and the choice of
// format "New template" opens ([432]: the choice appears once there is a second format).
//
// Omar, 2026-11-04: "an Editor creates "Quiz · gaming" templates by format, without writing HTML";
// 2026-11-05: "[431] Part 1's plan approved" · "[432] … Hide "Your own HTML" as a choice for new
// templates for now (hide it, don't remove it)". Prototype 3 is the specification
// (wiki/findings/2026-11-04-quiz-gaming-template-formats.md §9–§12): its blocks in their fixed order,
// each switched on or off, its fields and limits, its samples, and beside them the page itself.
//
// What this screen owns, and what it does not:
//   · the form, the preview and the checks. The page is built by template-formats.js, the SAME code
//     for the preview and for what is saved, so the preview is the page a learner gets (plan D1);
//   · "Create template" / "Save changes" stay unavailable while a check fails or has not run yet:
//     a length that was never measured is not a length within the limit;
//   · unsaved work (plan D7): leaving the screen or the site asks first (the app's own question,
//     through `useScreenWork`), choosing a sample asks before replacing, and nothing closes on a click
//     outside, because there is no outside: the editor is the screen.
// The server keeps its own guarantees (routes/templates.ts): the page is validated like any template's,
// and the page and its form are saved together.
//
// Every top-level name starts with `Tf`: every screen file shares one scope in the browser
// (`feedback_the_in_browser_compiler_shares_helper_names_across_files`, plan D8).

// The preview shows the course player's area on a computer: 950 × 480, centred (measured 2026-11-04, finding §3).
// No other screen is offered (Omar, 2026-11-05: "The preview always shows the computer size."); the length check
// still measures every screen it covers, out of sight (`TfLengthProbes`).
const TF_AREA_WIDTH = 950;
const TF_AREA_HEIGHT = 480;

/**
 * A page as a blob: address the frame can open. Through `safeFrameSrc` and `sandbox="allow-scripts"` like every
 * template preview in the app (`resolveHtmlPreviewUrl`, html-templates.jsx): the page's scripts run, in an OPAQUE
 * origin, so they cannot reach this app. Each address is given back once its page is replaced.
 */
function useTfPageUrl(html) {
  const url = React.useMemo(() => {
    try { return URL.createObjectURL(new Blob([html], { type: 'text/html' })); } catch (_) { return ''; }
  }, [html]);
  React.useEffect(() => () => { try { if (url) URL.revokeObjectURL(url); } catch (_) { /* gone */ } }, [url]);
  return url;
}

/** The value, `ms` after it last changed: the preview and the length check follow typing, not every key. */
function useTfSettled(value, ms) {
  const [settled, setSettled] = React.useState(value);
  React.useEffect(() => {
    const t = setTimeout(() => setSettled(value), ms);
    return () => clearTimeout(t);
  }, [value, ms]);
  return settled;
}

/** How the editor names a format in its own sentences: "the website template", "New website template". */
const TF_NOUNS = { email: 'email', sms: 'text messages', web: 'website', voice: 'voice call' };

/**
 * The guided editor, for one format: the email, text messages, the website or the voice call.
 *   template — `{ _new: true, format }` for a new one, or the registry entry being edited (its `format`, `formValues`)
 *   onSave   — called with `{ _new, serverId, name, html, format, formValues }`
 *   onClose  — leave the editor (asked first by the caller's screen work when there are changes)
 * A template's format is fixed: the editor builds, checks and saves only that format's fields.
 */
function TfTemplateEditor({ template, busy, error, onSave, onClose }) {
  const TF = window.DynamoTemplateFormats;
  const ConfirmDialog = window.ConfirmDialog;
  const fmt = template.format || 'email';
  const noun = TF_NOUNS[fmt] || fmt;
  const isEmail = fmt === 'email';
  const isNew = !!template._new;
  const [name, setName] = React.useState(isNew ? '' : (template.name || ''));
  const [values, setValues] = React.useState(() => (isNew
    ? TF.normalise(fmt, TF.sampleFor(TF.DEFAULT_SAMPLES[fmt], fmt).v)
    : TF.normalise(fmt, template.formValues)));
  const [open, setOpen] = React.useState(() => new Set([TF.groupsOf(fmt)[0].id]));
  const [askSample, setAskSample] = React.useState(null);     // a sample key waiting for "Replace"
  const [pictureError, setPictureError] = React.useState(null);  // { key, message }
  // The sample the form last started from: "Start from a sample" shows it, it is saved with the template, and a
  // picture's "Sample" puts that sample's picture back. A template saved before 2026-11-05 names none (null).
  const [sampleKey, setSampleKey] = React.useState(isNew ? TF.DEFAULT_SAMPLES[fmt] : TF.sampleOf(template.formValues, fmt));

  // ★ Unsaved changes, against what was opened. Read at the moment of leaving (`useScreenWork`), never a copy.
  // The sample's name is saved with the template, so choosing another one is a change too (review, 2026-11-05).
  const baseline = React.useRef(JSON.stringify({ name: isNew ? '' : (template.name || ''), values, sampleKey }));
  const dirty = JSON.stringify({ name, values, sampleKey }) !== baseline.current;
  window.useScreenWork('template-' + fmt + '-editor', 'the ' + noun + ' template', () => dirty, isNew ? 'Create template' : 'Save changes');

  const setValue = React.useCallback((k, v) => setValues(prev => ({ ...prev, [k]: v })), []);

  // ── what would be saved, and its checks ──
  const pageHtml = React.useMemo(() => TF.buildTemplate(fmt, values), [values]);
  const pageBytes = TF.sizeBytes(pageHtml);
  const settledValues = useTfSettled(values, 450);
  const [measured, setMeasured] = React.useState({ build: -1, metrics: {} });
  const build = React.useRef(0);
  const probeBuild = React.useMemo(() => { build.current += 1; return build.current; }, [settledValues]);
  // Only the email's length is measured: text messages have no limit (his round 3), and the website none ([454]).
  const lengthed = TF.lengthChecked(fmt);
  const lengthPending = lengthed && (measured.build !== probeBuild
    || TF.LIMIT_SCREENS.some(s => !measured.metrics[s.w]));
  // While the length is measured again, the last complete measurement stands: otherwise the checks vanished on every
  // pause in typing and came back, and the preview jumped with them (review, 2026-11-05). Saving waits either way.
  const lastLength = React.useRef({});
  if (!lengthPending) lastLength.current = measured.metrics;
  const problems = TF.problems(values, lengthPending ? lastLength.current : measured.metrics, fmt);
  if (!name.trim()) problems.unshift({ key: 'name', where: 'Name', text: 'Give the template a name, so authors can find it in “Pick a template”.' });
  if (pageBytes > TF.MAX_PAGE_BYTES) {
    problems.push({ key: 'size', where: 'Too big', text: `the template is ${Math.round(pageBytes / 1024)} KB with its pictures; the limit is 256 KB. Please use smaller pictures.` });
  }
  const typing = settledValues !== values;
  // A file still being prepared ("Preparing…") or uploaded ("Uploading…"): saving then sent the form without it and
  // closed the editor, and the file arrived when nothing was left to name it (review round 3, measured with the upload
  // held open). The editor keeps which fields are at work, so saving waits, and a part closed and opened again in the
  // meantime still shows its field at work (the re-check, measured).
  const [working, setWorking] = React.useState(() => new Set());
  const fileWorking = React.useCallback((key, on) => setWorking(prev => {
    const next = new Set(prev);
    if (on) next.add(key); else next.delete(key);
    return next;
  }), []);
  const blocked = busy || problems.length > 0 || lengthPending || typing || working.size > 0;

  const save = () => {
    if (blocked) return;
    onSave({
      _new: isNew, serverId: template.serverId, name: name.trim(),
      html: TF.buildTemplate(fmt, values), format: fmt, formValues: TF.formValuesFor(values, sampleKey, fmt),
    });
  };
  const leave = () => {
    if (!dirty || typeof window.dynamoConfirmLeave !== 'function') { onClose(); return; }
    window.dynamoConfirmLeave('screen').then(ok => { if (ok) onClose(); });
  };

  // ── the learner's places: inserted where the cursor was ──
  const lastFocus = React.useRef(null);   // { kind: 'input', el, key } | { kind: 'rich', el }
  // Each text box's setter, refreshed on every render: a place goes in through the box's CURRENT setter, never one
  // kept from the moment the box got the cursor, which wrote back the list of messages or rows of that moment and
  // dropped any added or removed since (review of part 2, 2026-11-06; the email's rows since part 1).
  const setters = React.useRef({});
  const insertPlace = (place) => {
    const f = lastFocus.current;
    if (!f || !f.el || !document.body.contains(f.el)) return;
    if (f.kind === 'rich') {
      f.el.focus();
      document.execCommand('insertText', false, place);
      return;
    }
    const el = f.el, set = setters.current[f.key];
    if (!set) return;
    const s = el.selectionStart ?? el.value.length, e = el.selectionEnd ?? s;
    const next = el.value.slice(0, s) + place + el.value.slice(e);
    set(next);
    requestAnimationFrame(() => { try { el.focus(); el.setSelectionRange(s + place.length, s + place.length); } catch (_) { /* gone */ } });
  };
  // A field the learner's places can go into: the chips insert where its cursor was. `key` names the box; `set`, as of
  // this render, writes its new text.
  const track = (key, set) => {
    setters.current[key] = set;
    return { onFocus: (e) => { lastFocus.current = { kind: 'input', el: e.currentTarget, key }; } };
  };

  const replaceWithSample = (key) => {
    setAskSample(null);
    setValues(TF.normalise(fmt, TF.sampleFor(key, fmt).v, key));
    setSampleKey(key);
    setPictureError(null);
  };

  const toggleBlock = (id) => setOpen(prev => { const n = new Set(prev); if (n.has(id)) n.delete(id); else n.add(id); return n; });

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--bg)' }}
      data-screen-label={'Surface · Layout library · Manage templates · ' + TF.FORMATS[fmt].name + ' template'}>
      {/* Top bar: back, where this is, and the two actions */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '14px 28px',
        borderBottom: '1px solid var(--border)', background: 'var(--surface)', minHeight: 56,
      }}>
        <button className="btn sm ghost" onClick={leave} title="Back to Manage templates" aria-label="Back to Manage templates">
          <I.ArrowLeft size={14} />
        </button>
        <nav style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, minWidth: 0 }}>
          <span style={{ color: 'var(--text-muted)' }}>Manage templates</span>
          <I.ChevronRight size={12} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
          <span style={{ fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {isNew ? 'New ' + noun + ' template' : (template.name || TF.FORMATS[fmt].name + ' template')}
          </span>
        </nav>
        <div style={{ flex: 1 }} />
        {dirty && <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>Not saved yet</span>}
        <button className="btn sm ghost" onClick={leave}>Cancel</button>
        <button className="btn sm primary" onClick={save} disabled={blocked}
          title={problems.length && !busy ? 'Please change what the checks list before saving.' : undefined}>
          {busy ? 'Saving…' : (isNew ? 'Create template' : 'Save changes')}
        </button>
      </div>

      {error && (
        <div role="alert" style={{
          margin: '12px 28px 0', padding: '10px 14px', background: 'var(--error-bg, #fef2f2)',
          border: '1px solid var(--error-text)', borderRadius: 'var(--radius-md)',
          fontSize: 12.5, color: 'var(--error-text)', lineHeight: 1.5,
        }}>{error}</div>
      )}

      <div style={{ flex: 1, minHeight: 0, display: 'grid', gridTemplateColumns: 'minmax(360px, 460px) 1fr' }}>
        {/* ── the form ── */}
        <div style={{ overflow: 'auto', padding: '18px 20px 48px', borderRight: '1px solid var(--border)',
          display: 'flex', flexDirection: 'column', gap: 14 }} data-tf-form="">
          <TfLabeled label="Name" htmlFor="tf-name">
            <input id="tf-name" className="field" value={name} placeholder="For example: Bank security check"
              onChange={e => setName(e.target.value)}
              onFocus={() => { lastFocus.current = null; }} style={{ width: '100%' }} />
          </TfLabeled>

          {fmt === 'voice' ? (
            // No learner details in a call (V6, part 3): a recording cannot say the learner's name. Its sound is the
            // template's own, in the "Sound" section below ("Call sound").
            null
          ) : (
          <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
            Learner details: click to insert at the cursor. The course player fills them from the
            “Learner details form”. The preview shows them for a sample learner, Robin Ashdale.
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
              {TF.PLACES.map(p => (
                <button key={p} type="button" className="btn sm ghost" data-tf-place={p}
                  onMouseDown={e => { e.preventDefault(); insertPlace(p); }}
                  style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, border: '1px solid var(--border)' }}>{p}</button>
              ))}
            </div>
          </div>
          )}

          <TfLabeled label="Start from a sample" htmlFor="tf-sample">
            <select id="tf-sample" className="field" value={sampleKey || ''}
              onChange={e => { if (e.target.value) setAskSample(e.target.value); }} style={{ width: '100%' }}>
              <option value="">Choose a sample…</option>
              {Object.keys(TF.samplesOf(fmt)).map(k => (
                <option key={k} value={k}>{TF.samplesOf(fmt)[k].label}</option>
              ))}
            </select>
          </TfLabeled>

          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', fontWeight: 600, letterSpacing: '.02em',
            textTransform: 'uppercase', marginTop: 4 }}>{isEmail ? 'Blocks, top to bottom' : 'Parts, top to bottom'}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {/* The email's blocks are each switched on or off; the other formats' parts are always there. */}
            {TF.groupsOf(fmt).map((b, i) => (
              <TfBlock key={b.id} n={i + 1} block={isEmail ? b : { ...b, always: true }} noSwitch={!isEmail} fmt={fmt}
                values={values} setValue={setValue}
                open={open.has(b.id)} onToggle={() => toggleBlock(b.id)}
                track={track} lastFocus={lastFocus} sampleKey={sampleKey}
                pictureError={pictureError} setPictureError={setPictureError} working={working} fileWorking={fileWorking} />
            ))}
          </div>
        </div>

        {/* ── the page, and the checks ── */}
        <div style={{ overflow: 'auto', padding: '18px 24px 48px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <TfChecks problems={problems} />
          <TfPreview values={values} fmt={fmt} />
        </div>
      </div>

      {lengthed && <TfLengthProbes values={settledValues} build={probeBuild} onMeasured={setMeasured} fmt={fmt} />}

      {askSample && ConfirmDialog && (
        <ConfirmDialog icon="Info" tone="primary" iconTone="neutral"
          title={`Replace everything below with the “${TF.samplesOf(fmt)[askSample].label}” sample?`}
          body={isEmail ? "Every block takes the sample's words, pictures and colours. The name stays as it is."
            : "Every part takes the sample's words and pictures. The name stays as it is."}
          confirmLabel="Replace"
          onCancel={() => setAskSample(null)}
          onConfirm={() => replaceWithSample(askSample)} />
      )}
    </div>
  );
}

function TfLabeled({ label, htmlFor, count, children }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
        <label htmlFor={htmlFor} style={{ fontSize: 12, color: 'var(--text)', fontWeight: 600 }}>{label}</label>
        <div style={{ flex: 1 }} />
        {count}
      </div>
      {children}
    </div>
  );
}

/** "n / max", red when over: the limit is the editor saying so, never the field refusing a key ([412]). */
function TfCount({ n, max }) {
  if (!max) return null;
  const over = n > max;
  return (
    <span data-tf-count="" style={{ fontSize: 11, fontFamily: 'var(--font-mono)',
      color: over ? 'var(--error-text)' : 'var(--text-faint)', fontWeight: over ? 700 : 400 }}>{n} / {max}</span>
  );
}

function TfBlock({ n, block, noSwitch, fmt, values, setValue, open, onToggle, track, lastFocus, sampleKey, pictureError, setPictureError, working, fileWorking }) {
  const on = block.always || !!values[block.on];
  const hasFields = block.fields.length > 0;
  return (
    <div data-tf-block={block.id} style={{
      border: '1px solid var(--border)', borderRadius: 'var(--radius-md)', background: 'var(--surface)',
      opacity: on ? 1 : 0.72,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px' }}>
        <span style={{ width: 18, fontSize: 11, color: 'var(--text-faint)', fontFamily: 'var(--font-mono)' }}>{n}</span>
        {noSwitch ? null : block.always ? (
          <input type="checkbox" checked disabled aria-label={`${block.name}: always on`} />
        ) : (
          <input type="checkbox" checked={on} aria-label={`${block.name}: on or off`}
            onChange={e => setValue(block.on, e.target.checked)}
            style={{ accentColor: 'var(--accent)' }} />
        )}
        <button type="button" onClick={hasFields ? onToggle : undefined} aria-expanded={hasFields ? open : undefined}
          style={{ flex: 1, textAlign: 'left', border: 0, background: 'transparent', padding: 0, fontFamily: 'inherit',
            fontSize: 13, fontWeight: 600, color: 'var(--text)', cursor: 'default',
            display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ flex: 1 }}>{block.name}</span>
          {hasFields && (open ? <I.ChevronDown size={13} /> : <I.ChevronRight size={13} />)}
        </button>
      </div>
      {hasFields && open && (
        <div style={{ padding: '4px 12px 12px', display: 'flex', flexDirection: 'column', gap: 10,
          borderTop: '1px solid var(--border)' }}>
          {block.note && <div style={{ fontSize: 11.5, color: 'var(--text-faint)', paddingTop: 6 }}>{block.note}</div>}
          {block.fields.filter(f => !f.if || f.if(values)).map(f => (
            <TfField key={f.k} field={f} fmt={fmt} values={values} setValue={setValue} track={track} lastFocus={lastFocus}
              sampleKey={sampleKey} pictureError={pictureError} setPictureError={setPictureError} working={working} fileWorking={fileWorking} />
          ))}
        </div>
      )}
    </div>
  );
}

function TfField({ field: f, fmt, values, setValue, track, lastFocus, sampleKey, pictureError, setPictureError, working, fileWorking }) {
  const TF = window.DynamoTemplateFormats;
  const id = 'tf-' + f.k;
  const v = values[f.k];
  const hint = f.hint ? <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 4 }}>{f.hint}</div> : null;
  switch (f.t) {
    case 'text':
      return (
        <TfLabeled label={f.label} htmlFor={id} count={<TfCount n={String(v || '').length} max={f.max} />}>
          <input id={id} className="field" value={v || ''} onChange={e => setValue(f.k, e.target.value)}
            {...track('f:' + f.k, x => setValue(f.k, x))} style={{ width: '100%' }} />
          {hint}
        </TfLabeled>
      );
    case 'area':
      return (
        <TfLabeled label={f.label} htmlFor={id} count={<TfCount n={String(v || '').length} max={f.max} />}>
          <textarea id={id} className="field" value={v || ''} rows={3} onChange={e => setValue(f.k, e.target.value)}
            {...track('f:' + f.k, x => setValue(f.k, x))} style={{ width: '100%', resize: 'vertical', fontFamily: 'inherit' }} />
          {hint}
        </TfLabeled>
      );
    case 'tip':
      return (
        <TfLabeled label={f.label} htmlFor={id} count={<TfCount n={String(v || '').length} max={f.max} />}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span aria-hidden="true" style={{ width: 18, height: 18, borderRadius: 4, background: '#1a1a1a', color: '#fff',
              fontSize: 11, fontWeight: 700, lineHeight: '18px', textAlign: 'center', flexShrink: 0 }}>?</span>
            <input id={id} className="field" value={v || ''} placeholder="Empty: no tooltip"
              onChange={e => setValue(f.k, e.target.value)} {...track('f:' + f.k, x => setValue(f.k, x))} style={{ width: '100%' }} />
          </div>
        </TfLabeled>
      );
    case 'check':
      return (
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5 }}>
          <input type="checkbox" checked={!!v} onChange={e => setValue(f.k, e.target.checked)}
            style={{ accentColor: 'var(--accent)' }} />
          {f.label}
        </label>
      );
    case 'color':
      return window.ColorField
        ? <window.ColorField label={f.label} value={v || '#000000'} onChange={c => setValue(f.k, c)} />
        : null;
    case 'seg':
    case 'align': {
      const opts = f.t === 'align' ? [['left', 'Left'], ['center', 'Centred']] : f.opts;
      return (
        <div>
          <div style={{ fontSize: 12, color: 'var(--text)', fontWeight: 600, marginBottom: 4 }}>{f.label || 'Alignment'}</div>
          <window.SegmentedControl value={v || opts[0][0]} onChange={x => setValue(f.k, x)}
            options={opts.map(o => ({ id: o[0], label: o[1] }))} />
        </div>
      );
    }
    case 'img':
      return <TfPictureField field={f} fmt={fmt} value={v} setValue={setValue} sampleKey={sampleKey}
        error={pictureError && pictureError.key === f.k ? pictureError.message : null} setError={setPictureError}
        working={working} fileWorking={fileWorking} />;
    case 'rich':
      return (
        <TfLabeled label={f.label} count={<TfCount n={TF.textLen(v)} max={f.max} />}>
          <window.RichTextEditor value={v || ''} onChange={html => setValue(f.k, html)} minHeight={72}
            tips colours={TF.RICH_COLOURS} lists={!!f.bullets} underline={false}
            onEditorFocus={el => { lastFocus.current = { kind: 'rich', el }; }} />
          <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 4 }}>
            Select words, then: bold, italic, a colour, a link, or a tooltip (the learner sees your text when pointing at them).
          </div>
        </TfLabeled>
      );
    case 'rows':
      return <TfRows field={f} rows={v || []} setValue={setValue} track={track} />;
    case 'messages':
      return <TfMessages messages={v || []} setValue={x => setValue(f.k, x)} track={track} lastFocus={lastFocus} />;
    case 'sound':
      return <TfSoundField field={f} value={v} setValue={setValue} working={working} fileWorking={fileWorking} />;
    default:
      return null;
  }
}

function TfPictureField({ field: f, fmt, value, setValue, sampleKey, error, setError, working, fileWorking }) {
  const TF = window.DynamoTemplateFormats;
  const inputRef = React.useRef(null);
  const busy = working.has(f.k);
  const sample = sampleKey ? (TF.sampleFor(sampleKey, fmt).v[f.k] || '') : '';
  const onFile = (file) => {
    if (!file) return;
    fileWorking(f.k, true);
    setError(null);
    TF.fitPicture(file, f.k, fmt)
      .then(url => { setValue(f.k, url); })
      .catch(e => { setError({ key: f.k, message: String((e && e.message) || e) }); })
      .finally(() => { fileWorking(f.k, false); if (inputRef.current) inputRef.current.value = ''; });
  };
  return (
    <div data-tf-picture={f.k}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
        <span style={{ fontSize: 12, color: 'var(--text)', fontWeight: 600 }}>{f.label}</span>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{f.shape}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 96, height: 40, borderRadius: 4, border: '1px solid var(--border)', background: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', flexShrink: 0 }}>
          {value
            ? <img src={value} alt="" style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />
            : <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>None</span>}
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          <button type="button" className="btn sm" disabled={busy} onClick={() => inputRef.current && inputRef.current.click()}>
            {busy ? 'Preparing…' : 'Upload…'}
          </button>
          {sample && value !== sample && (
            <button type="button" className="btn sm ghost" onClick={() => { setError(null); setValue(f.k, sample); }}>Sample</button>
          )}
          {value && (
            <button type="button" className="btn sm ghost" onClick={() => { setError(null); setValue(f.k, ''); }}>Remove</button>
          )}
        </div>
        <input ref={inputRef} type="file" accept="image/*" hidden aria-label={`Upload ${f.label}`}
          onChange={e => onFile(e.target.files && e.target.files[0])} />
      </div>
      <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 4 }}>
        {f.hint ? f.hint + ' ' : ''}Any picture is fitted to this shape and made smaller; it is never stretched.
      </div>
      {error && <div role="alert" style={{ fontSize: 12, color: 'var(--error-text)', marginTop: 4 }}>{error}</div>}
    </div>
  );
}

// ── "Call sound": the voice call's sound, the TEMPLATE's ──────────────────────────────────────────────────────────
// Omar, 2026-11-07, after his QA check of part 3: "Move the upload into the "New voice call template" editor: besides
// editing "Caller" and "Background", I must be able to upload the sound file there. The sound then belongs to the
// template: every course using it hears the same sound"; [462] a separate file, never inside the page (so no 256 KB);
// [465] up to 20 MB. Until one is uploaded the built-in sample plays, with no subtitles ([459]); each course makes its
// own subtitles from the template's sound in "Localisation". Saving the template saves the choice, through the
// "Update every course that uses this template?" pop-up when courses use it.
const TF_SOUND_NOT_A_SOUND = 'This file could not be used. Please choose an MP3, M4A or WAV sound.';
const TF_SOUND_TOO_LARGE = 'This sound is larger than 20 MB. Please choose a smaller one.';
/** A playable address for a call's sound, the sample's when it has none ('' when it cannot be had). */
function tfSoundAddress(ref) {
  if (typeof ref === 'string' && ref.startsWith('asset://')) {
    return window.resolveAssetUrl ? Promise.resolve(window.resolveAssetUrl(ref)).then(u => (/^https?:/.test(u || '') ? u : '')) : Promise.resolve('');
  }
  const p = window.placeholderSoundSrc ? window.placeholderSoundSrc('placeholder:call') : null;
  return Promise.resolve(p ? window.location.origin + p : '');
}
function TfSoundField({ field: f, value, setValue, working, fileWorking }) {
  const own = typeof value === 'string' && value.startsWith('asset://');
  const fileName = window.useAssetFileName ? window.useAssetFileName(own ? value : '') : '';
  const [src, setSrc] = React.useState('');
  const busy = working.has(f.k);
  const [error, setError] = React.useState('');
  const input = React.useRef(null);
  React.useEffect(() => {
    let cancelled = false;
    tfSoundAddress(value).then(u => { if (!cancelled) setSrc(u); });
    return () => { cancelled = true; };
  }, [value]);
  const upload = async (file) => {
    if (!file) return;
    setError('');
    if (file.size > (window.TEMPLATE_SOUND_MAX_BYTES || 20 * 1024 * 1024)) { setError(TF_SOUND_TOO_LARGE); return; }
    fileWorking(f.k, true);
    try {
      if (!(await window.looksLikeASound(file))) { setError(TF_SOUND_NOT_A_SOUND); return; }
      setValue(f.k, await window.uploadTemplateSound(file));
    } catch (err) {
      // The server decides which sounds it takes and how large; a refusal is its 400 or 422, and its reason says which.
      const refused = err && (err.status === 400 || err.status === 422);
      setError(!refused ? 'The upload did not finish. Please try again.'
        : /limit/i.test(String(err.serverMessage || '')) ? TF_SOUND_TOO_LARGE : TF_SOUND_NOT_A_SOUND);
    } finally { fileWorking(f.k, false); }
  };
  return (
    // One column no wider than the part ([485]): a long file name shortens with "…" instead of widening the column, which
    // pushed "Use the sample", the player and the sentence past the part's edge (his QA check, 2026-11-08, measured).
    <div data-tf-sound="" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 6 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 12, color: 'var(--text)', fontWeight: 600 }}>{f.label}</span>
        <span style={{ flex: 1, minWidth: 0, fontSize: 12, color: 'var(--text-muted)' }} className="truncate" data-tf-sound-name="">
          {own ? (fileName || (window.assetLabel ? window.assetLabel(value) : 'Uploaded sound')) : 'Sample sound'}
        </span>
        <input ref={input} type="file" accept=".mp3,.m4a,.wav,audio/mpeg,audio/mp4,audio/x-m4a,audio/wav" hidden
          aria-label={`Upload ${f.label}`}
          onChange={e => { const file = e.target.files && e.target.files[0]; e.target.value = ''; upload(file); }} />
        <button type="button" className="btn sm" disabled={busy} onClick={() => input.current && input.current.click()}>
          <I.Upload size={12} />{busy ? 'Uploading…' : (own ? 'Replace' : 'Upload a sound')}
        </button>
        {own && (
          <button type="button" className="btn sm ghost" disabled={busy}
            onClick={() => { setError(''); setValue(f.k, ''); }}>Use the sample</button>
        )}
      </div>
      {/* "metadata": the player reads the sound's length when it appears, so it shows it ([484]). With "none" it read
          nothing until played and showed "0:00 / 0:00" (measured: playing worked, and learned the length only then). */}
      {src ? <audio controls preload="metadata" src={src} style={{ width: '100%', height: 32 }} data-tf-sound-player="" /> : null}
      {error && <div role="alert" style={{ fontSize: 12, color: 'var(--error-text)' }}>{error}</div>}
      <div style={{ fontSize: 11, color: 'var(--text-faint)', lineHeight: 1.45 }}>
        {own
          ? 'Every course that uses this template plays this sound. Each course makes its own subtitles in “Localisation”.'
          : 'The sample sound plays until you upload your own: MP3, M4A or WAV, up to 20 MB. The sample has no subtitles.'}
      </div>
    </div>
  );
}

function TfRows({ field: f, rows, setValue, track }) {
  const set = (i, patch) => setValue(f.k, rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
        <span style={{ fontSize: 12, color: 'var(--text)', fontWeight: 600 }}>Rows (label · value)</span>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>up to {f.max}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {rows.map((r, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr auto auto', gap: 6, alignItems: 'center' }}>
            <input className="field" value={r.label} maxLength={40} aria-label={`Label ${i + 1}`}
              onChange={e => set(i, { label: e.target.value })} {...track('row:' + i + ':label', x => set(i, { label: x }))} />
            <input className="field" value={r.value} maxLength={50} aria-label={`Value ${i + 1}`}
              onChange={e => set(i, { value: e.target.value })} {...track('row:' + i + ':value', x => set(i, { value: x }))} />
            <label style={{ fontSize: 11.5, display: 'flex', alignItems: 'center', gap: 4 }}>
              <input type="checkbox" checked={!!r.red} onChange={e => set(i, { red: e.target.checked })} />red
            </label>
            <button type="button" className="btn sm ghost" disabled={rows.length <= 1}
              onClick={() => setValue(f.k, rows.filter((_, j) => j !== i))}>Remove</button>
          </div>
        ))}
      </div>
      <button type="button" className="btn sm" disabled={rows.length >= f.max} style={{ marginTop: 6 }}
        onClick={() => setValue(f.k, [...rows, { label: 'Label', value: 'Value', red: false }])}>Add a row</button>
    </div>
  );
}


// ── Text messages: each message a card that opens and closes ([452]) ──
/**
 * A "From them" message's words as plain text: a new line for each paragraph and each line break, and nothing else. A
 * message typed in the box has its words, links and tooltips side by side with no paragraph around them, and they stay
 * on one line (QA test, 2026-11-06: each piece had become a line of its own).
 */
function tfRichToPlain(html) {
  const d = document.createElement('div');
  d.innerHTML = window.sanitizeRichText(String(html || ''), { tips: true, formatting: false });
  const lines = [];
  let line = '';
  const walk = (node) => {
    Array.from(node.childNodes).forEach(c => {
      if (c.nodeType === 3) { line += c.nodeValue; return; }
      if (c.nodeType !== 1) return;
      if (c.tagName === 'BR') { lines.push(line); line = ''; return; }
      if (c.tagName === 'P' || c.tagName === 'DIV') {
        if (line) { lines.push(line); line = ''; }
        walk(c);
        lines.push(line); line = '';
        return;
      }
      walk(c);   // a link or marked words: their words, on the same line
    });
  };
  walk(d);
  if (line) lines.push(line);
  return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
/** Plain words as a "From them" message: escaped, each line its own line. */
function tfPlainToRich(text) {
  const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const t = String(text || '');
  return t ? '<p>' + esc(t).replace(/\r?\n/g, '<br>') + '</p>' : '';
}
/**
 * Omar, 2026-11-06 [452]: ""From them" becomes rich text … with only the tooltip and link buttons (no bold or the
 * others). "From the learner" stays plain text. Change nothing else in the interface" and "Make the message cards
 * expandable and collapsible". Each card shows its number, who sends it and its first words while closed.
 */
function TfMessages({ messages, setValue, track, lastFocus }) {
  const TF = window.DynamoTemplateFormats;
  // A key per message that survives a removal above it: an index key would hand one message's text box to the next.
  const ids = React.useRef([]);
  const nextId = React.useRef(1);
  while (ids.current.length < messages.length) ids.current.push(nextId.current++);
  if (ids.current.length > messages.length) ids.current.length = messages.length;
  const [open, setOpen] = React.useState(() => new Set());
  // Switching a message to "From the learner" makes it plain text; switching straight back gives its links and
  // tooltips back, as long as its words were not changed in between.
  const before = React.useRef(new Map());
  const toggle = (id) => setOpen(prev => { const n = new Set(prev); if (n.has(id)) n.delete(id); else n.add(id); return n; });
  const setAt = (i, m) => setValue(messages.map((x, j) => (j === i ? m : x)));
  const setSide = (i, me) => {
    const m = messages[i], id = ids.current[i];
    if (!!m.me === me) return;
    if (me) {
      const t = tfRichToPlain(m.html);
      before.current.set(id, { html: m.html, t });
      setAt(i, { me: true, t });
    } else {
      const kept = before.current.get(id);
      setAt(i, { me: false, html: kept && kept.t === m.t ? kept.html : tfPlainToRich(m.t) });
      before.current.delete(id);
    }
  };
  const remove = (i) => {
    const id = ids.current[i];
    ids.current.splice(i, 1);
    before.current.delete(id);
    setValue(messages.filter((_, j) => j !== i));
  };
  const add = () => {
    const id = nextId.current++;
    ids.current.push(id);
    setOpen(prev => new Set(prev).add(id));
    setValue([...messages, { me: false, html: '' }]);
  };
  const firstWords = (m) => {
    const t = (m.me ? String(m.t || '') : tfRichToPlain(m.html)).replace(/\s+/g, ' ').trim();
    return t ? (t.length > 48 ? t.slice(0, 47) + '…' : t) : 'No words yet';
  };
  return (
    <div data-tf-messages="">
      <div style={{ fontSize: 12, color: 'var(--text)', fontWeight: 600, marginBottom: 6 }}>Messages</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {messages.map((m, i) => {
          const id = ids.current[i], isOpen = open.has(id);
          return (
            <div key={id} data-tf-message={i + 1} style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-md)', background: 'var(--surface)' }}>
              <button type="button" onClick={() => toggle(id)} aria-expanded={isOpen}
                style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 8, padding: '7px 10px', border: 0,
                  background: 'transparent', fontFamily: 'inherit', textAlign: 'left', cursor: 'default', color: 'var(--text)' }}>
                <span style={{ width: 18, fontSize: 11, color: 'var(--text-faint)', fontFamily: 'var(--font-mono)' }}>{i + 1}</span>
                <span style={{ fontSize: 12, fontWeight: 600, flexShrink: 0 }}>{m.me ? 'From the learner' : 'From them'}</span>
                <span style={{ flex: 1, minWidth: 0, fontSize: 12, color: 'var(--text-muted)', whiteSpace: 'nowrap',
                  overflow: 'hidden', textOverflow: 'ellipsis' }}>{isOpen ? '' : firstWords(m)}</span>
                {isOpen ? <I.ChevronDown size={13} /> : <I.ChevronRight size={13} />}
              </button>
              {isOpen && (
                <div style={{ padding: '4px 10px 10px', display: 'flex', flexDirection: 'column', gap: 8, borderTop: '1px solid var(--border)' }}>
                  <div style={{ paddingTop: 6 }}>
                    <window.SegmentedControl value={m.me ? 'me' : 'them'} onChange={x => setSide(i, x === 'me')}
                      options={[{ id: 'them', label: 'From them' }, { id: 'me', label: 'From the learner' }]} />
                  </div>
                  {m.me ? (
                    <textarea className="field" value={m.t || ''} rows={3} aria-label={`Message ${i + 1}`}
                      onChange={e => setAt(i, { me: true, t: e.target.value })}
                      {...track('msg:' + id, x => setAt(i, { me: true, t: x }))} style={{ width: '100%', resize: 'vertical', fontFamily: 'inherit' }} />
                  ) : (
                    <div>
                      <window.RichTextEditor value={m.html || ''} onChange={html => setAt(i, { me: false, html })} minHeight={60}
                        tips formatting={false} lists={false} underline={false}
                        onEditorFocus={el => { lastFocus.current = { kind: 'rich', el }; }} />
                      <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 4 }}>
                        Select words, then: a link, or a tooltip (the learner sees your text when pointing at them).
                      </div>
                    </div>
                  )}
                  <div>
                    <button type="button" className="btn sm ghost" disabled={messages.length <= 1} onClick={() => remove(i)}>Remove</button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
        <button type="button" className="btn sm" onClick={add}>Add a message</button>
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>Add as many messages as you need; no length limit for now.</span>
      </div>
    </div>
  );
}

// ── "New template": the choice of format ([432]: it appears once there is a second format) ──
// Each format's icon; a question's card shows the same one beside its template's name ([479]).
const TF_FORMAT_ICONS = { email: 'Mail', sms: 'Smartphone', web: 'Globe', voice: 'Phone' };
function TfFormatChoice({ onChoose, onClose }) {
  const TF = window.DynamoTemplateFormats;
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--bg)' }}
      data-screen-label="Surface · Layout library · Manage templates · New template">
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '14px 28px',
        borderBottom: '1px solid var(--border)', background: 'var(--surface)', minHeight: 56,
      }}>
        <button className="btn sm ghost" onClick={onClose} title="Back to Manage templates" aria-label="Back to Manage templates">
          <I.ArrowLeft size={14} />
        </button>
        <nav style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, minWidth: 0 }}>
          <span style={{ color: 'var(--text-muted)' }}>Manage templates</span>
          <I.ChevronRight size={12} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
          <span style={{ fontWeight: 600 }}>New template</span>
        </nav>
        <div style={{ flex: 1 }} />
        <button className="btn sm ghost" onClick={onClose}>Cancel</button>
      </div>
      <div style={{ overflow: 'auto', padding: '24px 28px 48px' }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Choose a format</div>
        <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginBottom: 16 }}>
          A template keeps its format: you fill in its parts, and the page is built for you.
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 12, maxWidth: 900 }}>
          {TF.offeredFormats().map(k => {
            const F = TF.FORMATS[k], Icon = I[TF_FORMAT_ICONS[k]] || I.FileText;
            return (
              <button key={k} type="button" data-tf-format={k} onClick={() => onChoose(k)} className="card"
                style={{ textAlign: 'left', padding: 16, display: 'flex', flexDirection: 'column', gap: 8, cursor: 'pointer',
                  fontFamily: 'inherit', color: 'var(--text)', border: '1px solid var(--border)', background: 'var(--surface)' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5, fontWeight: 600 }}>
                  <Icon size={16} style={{ color: 'var(--text-muted)' }} />{F.name}
                </span>
                <span style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>{F.blurb}</span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/** What must change before saving; nothing at all when nothing must (Omar's QA check, 2026-11-05). */
function TfChecks({ problems }) {
  if (!problems.length) return null;
  return (
    <div data-tf-checks="" role="status" style={{
      padding: '12px 14px', borderRadius: 'var(--radius-md)', fontSize: 12.5, lineHeight: 1.5,
      background: 'var(--surface)', border: '1px solid var(--error-text)',
    }}>
      <strong>Please change {problems.length === 1 ? 'this' : 'these'} before saving:</strong>
      <ul style={{ margin: '6px 0 0', paddingLeft: 18 }}>
        {problems.map((p, i) => <li key={p.key + i}>{p.where ? <><strong>{p.where}</strong>: </> : null}{p.text}</li>)}
      </ul>
    </div>
  );
}

/** The page, as the course player shows it on a computer: inside its area, and nothing else around it. */
function TfPreview({ values, fmt }) {
  const TF = window.DynamoTemplateFormats;
  const settled = useTfSettled(values, 220);
  // Text messages: the conversation plays out once, on the page the editor opens with. A page rebuilt after a change
  // shows it as it ends, at once, or every pause in typing would start it again from the first message (Omar,
  // 2026-11-15; prototype 4 did the same, and its "Replay the messages" is not offered).
  const openedWith = React.useRef(settled);
  const boxRef = React.useRef(null);
  const [boxW, setBoxW] = React.useState(0);
  React.useEffect(() => {
    const el = boxRef.current;
    if (!el) return undefined;
    const measure = () => setBoxW(el.clientWidth || 0);
    measure();
    const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
    if (ro) ro.observe(el);
    return () => { if (ro) ro.disconnect(); };
  }, []);
  const scale = boxW ? Math.min(1, boxW / TF_AREA_WIDTH) : 1;
  // A voice call plays the template's own sound ("Call sound"), the sample until it has one.
  const soundRef = fmt === 'voice' ? (settled && settled.sound) || '' : '';
  const [callSound, setCallSound] = React.useState(null);
  React.useEffect(() => {
    if (fmt !== 'voice') return undefined;
    let cancelled = false;
    tfSoundAddress(soundRef).then(u => { if (!cancelled) setCallSound(u || null); });
    return () => { cancelled = true; };
  }, [fmt, soundRef]);
  const page = React.useMemo(() => TF.buildTemplate(fmt || 'email', settled,
    { mode: 'preview', metricsId: 'main', still: settled !== openedWith.current, ...(callSound ? { callSound } : {}) }), [settled, callSound]);
  const pageUrl = useTfPageUrl(page);
  // Keep the learner's place while the page is rebuilt: the frame reports its scroll (it is in an opaque origin,
  // so this screen cannot read it), and gets it back once the new page has loaded.
  const frameRef = React.useRef(null);
  const lastTop = React.useRef(0);
  React.useEffect(() => {
    const onMessage = (e) => {
      const m = e.data || {};
      if (m.kind === 'tpl-scroll' && frameRef.current && e.source === frameRef.current.contentWindow) lastTop.current = +m.top || 0;
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, []);
  const restoreScroll = () => {
    try { frameRef.current.contentWindow.postMessage({ kind: 'scroll-to', top: lastTop.current }, '*'); } catch (_) { /* gone */ }
  };
  return (
    <div data-tf-preview="">
      <div ref={boxRef} style={{ width: '100%' }}>
        <div style={{ width: Math.round(TF_AREA_WIDTH * scale), margin: '0 auto' }}>
          <div style={{ width: Math.round(TF_AREA_WIDTH * scale), height: Math.round(TF_AREA_HEIGHT * scale), overflow: 'hidden',
            outline: '1px dashed var(--border-strong)', background: '#eef0f3' }}>
            <iframe ref={frameRef} title="The template, as the learner sees it" onLoad={restoreScroll}
              src={window.safeFrameSrc(pageUrl)} sandbox="allow-scripts"
              /* allow-scripts WITHOUT allow-same-origin: the page runs its own tooltips and date in an OPAQUE
                 origin, so it cannot reach this app. Never add allow-same-origin here. */
              style={{ width: TF_AREA_WIDTH, height: TF_AREA_HEIGHT, border: 0, display: 'block',
                transform: `scale(${scale})`, transformOrigin: 'top left', background: '#eef0f3' }} />
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * The "Too long" check: the page in a frame of each of the four widths, 480 px high, out of sight. Each frame
 * reports its own height; a report from an older version of the page, or from a frame that is not one of these,
 * is ignored, so the check can only ever describe the page that would be saved.
 */
function TfLengthProbes({ values, build, onMeasured, fmt }) {
  const TF = window.DynamoTemplateFormats;
  const frames = React.useRef({});
  React.useEffect(() => {
    const got = {};
    const onMessage = (e) => {
      const m = e.data || {};
      if (m.kind !== 'tpl-metrics' || typeof m.id !== 'string') return;
      const parts = m.id.split(':');
      if (parts[0] !== 'chk' || +parts[2] !== build) return;
      const w = +parts[1];
      const frame = frames.current[w];
      if (!frame || e.source !== frame.contentWindow) return;
      got[w] = { scrollH: +m.scrollH || 0, clientH: +m.clientH || 0 };
      onMeasured({ build, metrics: { ...got } });
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, [build]);
  return (
    <div aria-hidden="true" style={{ position: 'fixed', left: -12000, top: 0, width: 1, height: 1, overflow: 'hidden' }}>
      {TF.LIMIT_SCREENS.map(s => (
        <TfProbeFrame key={s.w + ':' + build} w={s.w} build={build} values={values} fmt={fmt}
          frameRef={el => { frames.current[s.w] = el; }} />
      ))}
    </div>
  );
}
function TfProbeFrame({ w, build, values, fmt, frameRef }) {
  const TF = window.DynamoTemplateFormats;
  const page = React.useMemo(() => TF.buildTemplate(fmt || 'email', values, { mode: 'preview', metricsId: 'chk:' + w + ':' + build }), [values, w, build]);
  const url = useTfPageUrl(page);
  return (
    <iframe ref={frameRef} title={`Length check, ${w} px`} data-tf-width={w} data-tf-build={build}
      tabIndex={-1} src={window.safeFrameSrc(url)} sandbox="allow-scripts"
      style={{ width: w, height: TF_AREA_HEIGHT, border: 0, position: 'absolute', left: 0, top: 0 }} />
  );
}

Object.assign(window, { TfTemplateEditor, TfFormatChoice, TF_FORMAT_ICONS });
