'use client';

// Sequences #58 / SEQ-R-B3 / SEQ-R-B4: the one enroll review every entry point uses (the
// sequence's Enroll contacts drawer, the contact record's Sequences card and More > Enroll, a
// lead, the contacts bulk bar). Design DES-5 "Enroll contacts", step "Review": Start at, Time
// zone, Send the first step, Send emails from, Email preview with "Preview for", and the
// per-contact email edit HubSpot offers before enrolling. `useEnrollReview` holds its state and
// calls (preview as the choices change, then enroll once with an idempotency key).
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { ComposeRichText } from '@/components/crm/ComposeRichText';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { getMyMailbox, getSendUsage, previewEmailTemplate } from '@/features/inbox/api.client';
import { newIdempotencyKey } from '@/features/inbox/format';
import { previewTemplateDraft } from '@/features/message-templates/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { currentZoneName } from '@/features/settings/ui/accountDefaultsZones';
import {
  enrollInSequence,
  previewEnrollment,
  validateSequence,
} from '@/features/sequences/api.client';
import {
  ALREADY_ENROLLED_TEXT,
  ASAP_LABEL,
  LATER_LABEL,
  MANUAL_EMAIL_TEXT,
  NOT_READY_TEXT,
  PAST_DATE_TEXT,
  SEND_TIMES,
  defaultEnrollOptions,
  sequenceBlock,
  emailStepsFrom,
  formatIn,
  isEmailType,
  myZoneText,
  sendPaceNote,
  senderZone,
  startAtOf,
  startStepChoices,
  zoneLabel,
  type EnrollOptions,
  type SenderDailyLimit,
} from '@/features/sequences/enrollReview';
import type {
  EnrollResult,
  EnrollStepEdit,
  EnrollmentPreview,
  Sequence,
  SequenceProblem,
} from '@/features/sequences/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { safeEmailHtml } from '@/lib/utils/safe-html';
import {
  REFUSAL_LABELS,
  SequenceProblemsList,
  displayStepNumber,
  stepTitle,
  stepTypeLabel,
} from './shared';

/**
 * Sequences QA BUG-02: the zone "My time zone" names and the API sends in (profile, else the
 * business's account default), not the prefs' browser fallback.
 */
export function useSenderZone(): string {
  const { profileTimeZone } = useUserPrefs();
  return senderZone(profileTimeZone, useCurrentUser().business.timezone);
}

export interface EnrollContact {
  id: string;
  name: string;
  email: string | null;
}

export interface EnrollSender {
  mailboxId: string | null;
  /** Connected and ready to send. */
  ready: boolean;
  /** "<user name> (<mailbox email>)": the one "Send emails from" choice. */
  label: string;
}

/**
 * The user's own connected mailbox as the one sender (HUB-195: only your own mailbox), loaded
 * on each opening. `problem`: why there is none.
 */
export function useMySender(open: boolean): { sender: EnrollSender; problem: string | null } {
  const me = useCurrentUser();
  const [mailbox, setMailbox] = useState<{ id: string; email: string | null } | null>(null);
  const [problem, setProblem] = useState<string | null>(null);
  useEffect(() => {
    if (!open) return;
    // No mailbox until this opening's check says so (a failed check must not reuse the last).
    setMailbox(null);
    setProblem(null);
    let cancelled = false;
    getMyMailbox().then(
      (m) => {
        if (cancelled) return;
        if (m.connected && m.status === 'connected' && m.id) {
          setMailbox({ id: m.id, email: m.emailAddress ?? null });
        } else setProblem(NO_MAILBOX_TEXT);
      },
      () => {
        if (!cancelled) setProblem('Your mailbox could not be loaded. Try again in a moment.');
      },
    );
    return () => {
      cancelled = true;
    };
  }, [open]);
  return {
    sender: {
      mailboxId: mailbox?.id ?? null,
      ready: Boolean(mailbox),
      label: mailbox?.email ? `${me.user.name} (${mailbox.email})` : me.user.name,
    },
    problem,
  };
}

/** Master's sentence when the user has no connected mailbox. */
export const NO_MAILBOX_TEXT =
  'Connect your mailbox in Settings > Email before enrolling contacts.';

type EditKey = `${string}:${number}`;
const editKey = (contactId: string, stepIndex: number): EditKey => `${contactId}:${stepIndex}`;

export interface EnrollReviewState {
  options: EnrollOptions;
  setOptions: (patch: Partial<EnrollOptions>) => void;
  /** The zone "At a specific time" and the planned times are read in. */
  zone: string;
  preview: EnrollmentPreview | null;
  loading: boolean;
  error: string | null;
  /** "Pick a date in the future." is showing. */
  whenInvalid: boolean;
  edits: ReadonlyMap<EditKey, { subject: string; bodyHtml: string }>;
  setEdit: (
    contactId: string,
    stepIndex: number,
    value: { subject: string; bodyHtml: string } | null,
  ) => void;
  enrolling: boolean;
  /** Enrolls the eligible contacts; null when nothing was sent (the review says why). */
  submit: () => Promise<EnrollResult | null>;
  /** For a caller with no preview (bulk): the start step and time zone, and the start time. */
  requestOptions: () => {
    startAt?: string;
    startStep?: number;
    timezone: EnrollOptions['timezone'];
  } | null;
  /** Why the sequence can't take enrollments (sequenceBlock); null when it can. */
  block: string | null;
  /** D-5: the sequence's step problems (POST /validate); null while they load. */
  problems: SequenceProblem[] | null;
}

/**
 * The review's state and calls. `contacts` empty (a bulk selection): no preview, `submit` is not
 * used and `requestOptions` gives the choices to the caller.
 */
export function useEnrollReview({
  open,
  sequence,
  contacts,
  sender,
}: {
  open: boolean;
  sequence: Sequence | null;
  contacts: readonly EnrollContact[];
  sender: EnrollSender;
}): EnrollReviewState {
  const myZone = useSenderZone();
  const steps = useMemo(() => sequence?.steps ?? [], [sequence]);
  const dynamic = Boolean(sequence?.settings.dynamic);
  const [options, setAll] = useState<EnrollOptions>(() => defaultEnrollOptions(steps, myZone));
  const [preview, setPreview] = useState<EnrollmentPreview | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [whenInvalid, setWhenInvalid] = useState(false);
  const [edits, setEdits] = useState<Map<EditKey, { subject: string; bodyHtml: string }>>(
    () => new Map(),
  );
  const [enrolling, setEnrolling] = useState(false);
  const [problems, setProblems] = useState<SequenceProblem[] | null>(null);
  const keyRef = useRef(newIdempotencyKey());
  const sequenceId = sequence?.id ?? null;
  const archived = sequence?.status === 'archived';

  // D-5: no draft status; the steps decide whether the sequence takes enrollments. Checked again
  // when the sequence is saved (updatedAt). A failed check doesn't block: enrolling checks too.
  useEffect(() => {
    setProblems(null);
    if (!open || !sequenceId || archived) return;
    let alive = true;
    validateSequence(sequenceId).then(
      (check) => alive && setProblems(check.problems),
      () => alive && setProblems([]),
    );
    return () => {
      alive = false;
    };
  }, [open, sequenceId, archived, sequence?.updatedAt]);
  const mailboxId = sender.ready ? sender.mailboxId : null;
  const ids = contacts.map((c) => c.id).join(',');

  // Each opening (or another sequence) starts over, with a new idempotency key.
  useEffect(() => {
    if (!open) return;
    setAll(defaultEnrollOptions(steps, myZone));
    setPreview(null);
    setError(null);
    setWhenInvalid(false);
    setEdits(new Map());
    keyRef.current = newIdempotencyKey();
    // Only on opening or another sequence: the prefs are read as they are then.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, sequenceId]);

  // Other contacts: the last preview no longer says who can be enrolled.
  useEffect(() => setPreview(null), [ids]);

  // "At a specific time" is read in the sending zone: the contact's when one contact is
  // enrolled in its own zone, else the user's. Times shown follow the same zone.
  const single = contacts.length === 1 ? preview?.data[0] : undefined;
  const zone = options.timezone === 'contact' && single?.timezone ? single.timezone : myZone;
  const when = startAtOf(options, zone);
  const startStep = !dynamic && options.startStep > 0 ? options.startStep : undefined;

  useEffect(() => {
    if (!open || !sequenceId || !mailboxId || !ids || when.error) return;
    if (archived || problems === null || problems.length) return;
    let cancelled = false;
    setLoading(true);
    const timer = window.setTimeout(() => {
      previewEnrollment(sequenceId, {
        contactIds: ids.split(','),
        senderMailboxId: mailboxId,
        timezone: options.timezone,
        ...(when.startAt && { startAt: when.startAt }),
        ...(startStep !== undefined && { startStep }),
      })
        .then((res) => {
          if (!cancelled) {
            setPreview(res);
            setError(null);
          }
        })
        .catch((err) => {
          if (!cancelled) setError(errorText(err));
        })
        .finally(() => {
          if (!cancelled) setLoading(false);
        });
    }, 200);
    return () => {
      cancelled = true;
      window.clearTimeout(timer);
    };
  }, [
    open,
    sequenceId,
    archived,
    problems,
    mailboxId,
    ids,
    options.timezone,
    when.startAt,
    when.error,
    startStep,
  ]);

  const setOptions = useCallback((patch: Partial<EnrollOptions>) => {
    setWhenInvalid(false);
    setAll((current) => ({ ...current, ...patch }));
  }, []);

  const setEdit = useCallback<EnrollReviewState['setEdit']>((contactId, stepIndex, value) => {
    setEdits((current) => {
      const next = new Map(current);
      if (value) next.set(editKey(contactId, stepIndex), value);
      else next.delete(editKey(contactId, stepIndex));
      return next;
    });
  }, []);

  const requestOptions = useCallback<EnrollReviewState['requestOptions']>(() => {
    if (when.error) {
      setWhenInvalid(true);
      return null;
    }
    return {
      timezone: options.timezone,
      ...(when.startAt && { startAt: when.startAt }),
      ...(startStep !== undefined && { startStep }),
    };
  }, [options.timezone, when.error, when.startAt, startStep]);

  const submit = useCallback(async (): Promise<EnrollResult | null> => {
    if (!sequenceId || !mailboxId || enrolling) return null;
    const choices = requestOptions();
    if (!choices) return null;
    if (!preview || loading) return null;
    const eligible = preview.data.filter((d) => d.eligible).map((d) => d.contactId);
    if (eligible.length === 0) {
      setError(
        preview.data.every((d) => d.reason === 'already_enrolled')
          ? ALREADY_ENROLLED_TEXT
          : 'None of these contacts can be enrolled.',
      );
      return null;
    }
    const keep = new Set(eligible);
    const stepEdits: EnrollStepEdit[] = [...edits]
      .map(([key, value]) => {
        const [contactId, index] = key.split(':');
        return { contactId: contactId!, stepIndex: Number(index), ...value };
      })
      .filter((e) => keep.has(e.contactId) && e.stepIndex >= (startStep ?? 0));
    setEnrolling(true);
    setError(null);
    try {
      return await enrollInSequence(sequenceId, {
        contactIds: eligible,
        senderMailboxId: mailboxId,
        ...choices,
        ...(stepEdits.length && { stepEdits }),
        // Same key for a retry after a failed response: contacts are never enrolled twice.
        idempotencyKey: keyRef.current,
      });
    } catch (err) {
      setError(errorText(err));
      return null;
    } finally {
      setEnrolling(false);
    }
  }, [sequenceId, mailboxId, enrolling, requestOptions, preview, loading, edits, startStep]);

  return {
    options,
    setOptions,
    zone,
    preview,
    loading,
    error,
    // Shown as soon as the picked time is not ahead: the review can't check or enroll until then.
    whenInvalid: (whenInvalid || options.sendWhen === 'later') && Boolean(when.error),
    edits,
    setEdit,
    enrolling,
    submit,
    requestOptions,
    block: sequence ? sequenceBlock(sequence, problems) : null,
    problems,
  };
}

/** The review's body (design "Review" step). The caller renders the footer. */
export function EnrollReview({
  idPrefix,
  sequence,
  contacts,
  count = contacts.length,
  sender,
  review,
}: {
  /** Unique per entry point, for the fields' ids. */
  idPrefix: string;
  sequence: Sequence;
  contacts: readonly EnrollContact[];
  /** Contacts being enrolled when they are not listed (a bulk selection). */
  count?: number;
  sender: EnrollSender;
  review: EnrollReviewState;
}) {
  const myZone = useSenderZone();
  const { options, setOptions, preview } = review;
  const dynamic = Boolean(sequence.settings.dynamic);
  const startStep = dynamic ? 0 : options.startStep;
  const emailSteps = emailStepsFrom(sequence.steps, startStep);
  const [previewFor, setPreviewFor] = useState<string>(contacts[0]?.id ?? '');
  const [stepPick, setStepPick] = useState<number | null>(null);
  const contact = contacts.find((c) => c.id === previewFor) ?? contacts[0] ?? null;
  const shownStep =
    stepPick !== null && emailSteps.includes(stepPick) ? stepPick : (emailSteps[0] ?? null);
  const first = sequence.steps[startStep];
  const item = contact ? preview?.data.find((d) => d.contactId === contact.id) : undefined;
  const refused = preview?.data.filter((d) => !d.eligible) ?? [];
  const nameOf = (id: string) => contacts.find((c) => c.id === id)?.name ?? 'A contact';
  const emails = first?.type === 'automated_email' ? (preview ? preview.eligible : count) : 0;
  // Sequences: the sender's daily send limit (HubSpot: over it, "the contact won't enroll").
  // Without a preview (bulk), the sender's use of it from the inbox.
  const [usage, setUsage] = useState<SenderDailyLimit | null>(null);
  useEffect(() => {
    if (preview) return;
    let alive = true;
    getSendUsage().then(
      (u) => {
        if (alive) {
          setUsage({
            dailyLimit: u.daily.limit,
            sentLast24h: u.daily.used,
            scheduledNext24h: null,
          });
        }
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [preview]);
  const pace = sendPaceNote(
    preview ?? usage,
    first?.type === 'automated_email',
    emails,
    refused.filter((d) => d.reason === 'send_limit').length,
  );

  useEffect(() => {
    if (!contacts.some((c) => c.id === previewFor)) setPreviewFor(contacts[0]?.id ?? '');
  }, [contacts, previewFor]);

  return (
    <div className="seq-enrol__review">
      <p className="seq-enrol__sum">
        Enrolling{' '}
        <strong>
          {count} contact{count === 1 ? '' : 's'}
        </strong>{' '}
        in <strong>{sequence.name}</strong>. Check the details below before you enroll.
      </p>
      {review.error ? <Alert tone="danger">{review.error}</Alert> : null}
      {refused.length ? (
        <Alert tone="warning">
          {refused.length === 1
            ? '1 contact cannot be enrolled:'
            : `${refused.length} contacts cannot be enrolled:`}
          <ul className="crm-mb-0 crm-ps-4">
            {refused.map((d) => (
              <li key={d.contactId}>
                {nameOf(d.contactId)}:{' '}
                {d.message ?? (d.reason ? REFUSAL_LABELS[d.reason] : 'Cannot be enrolled')}
              </li>
            ))}
          </ul>
        </Alert>
      ) : null}
      <div className="seq-enrol__grid">
        {!dynamic ? (
          <div className="field">
            <label className="field__label" htmlFor={`${idPrefix}Start`}>
              Start at
            </label>
            <select
              className="input"
              id={`${idPrefix}Start`}
              value={options.startStep}
              disabled={review.enrolling}
              onChange={(e) => setOptions({ startStep: Number(e.target.value) })}
            >
              {startStepChoices(sequence.steps).map((choice) => (
                <option key={choice.value} value={choice.value}>
                  {choice.label}
                </option>
              ))}
            </select>
          </div>
        ) : null}
        <div className="field">
          <label className="field__label" htmlFor={`${idPrefix}Tz`}>
            Time zone
          </label>
          <select
            className="input"
            id={`${idPrefix}Tz`}
            value={options.timezone}
            disabled={review.enrolling}
            onChange={(e) =>
              setOptions({ timezone: e.target.value === 'sender' ? 'sender' : 'contact' })
            }
          >
            <option value="contact">Contact&apos;s time zone (recommended)</option>
            <option value="sender">{myZoneText(myZone)}</option>
          </select>
        </div>
        <div className="field">
          <label className="field__label" htmlFor={`${idPrefix}From`}>
            Send emails from
          </label>
          <select className="input" id={`${idPrefix}From`} disabled={!sender.ready}>
            <option>{sender.ready ? sender.label : 'No mailbox connected'}</option>
          </select>
        </div>
        <fieldset className={cn('field seq-enrol__send', review.whenInvalid && 'is-invalid')}>
          <legend className="field__label">Send the first step</legend>
          <label className="seq-radio">
            <input
              type="radio"
              name={`${idPrefix}SendWhen`}
              value="now"
              checked={options.sendWhen === 'now'}
              disabled={review.enrolling}
              onChange={() => setOptions({ sendWhen: 'now' })}
            />
            <span className="seq-radio__dot" aria-hidden="true" />
            <span>{ASAP_LABEL}</span>
          </label>
          <label className="seq-radio">
            <input
              type="radio"
              name={`${idPrefix}SendWhen`}
              value="later"
              checked={options.sendWhen === 'later'}
              disabled={review.enrolling}
              onChange={() => setOptions({ sendWhen: 'later' })}
            />
            <span className="seq-radio__dot" aria-hidden="true" />
            <span>{LATER_LABEL}</span>
          </label>
          {options.sendWhen === 'later' ? (
            <div className="seq-enrol__when">
              <input
                className="input"
                type="date"
                aria-label="Send date"
                value={options.date}
                disabled={review.enrolling}
                onChange={(e) => setOptions({ date: e.target.value })}
              />
              <select
                className="input"
                aria-label="Send time"
                value={options.time}
                disabled={review.enrolling}
                onChange={(e) => setOptions({ time: e.target.value })}
              >
                {SEND_TIMES.map((t) => (
                  <option key={t.value} value={t.value}>
                    {t.label}
                  </option>
                ))}
              </select>
            </div>
          ) : null}
          <span className="field__error">{PAST_DATE_TEXT}</span>
          <span className="crm-fs-8 crm-text-muted">
            {item?.eligible && item.plannedSteps[0]
              ? `First step ${formatIn(item.plannedSteps[0].at, item.timezone)}. `
              : ''}
            Times in {currentZoneName(item?.timezone ?? review.zone)} (
            {zoneLabel(item?.timezone ?? review.zone)}).
          </span>
        </fieldset>
      </div>
      {pace ? <Alert tone="info">{pace}</Alert> : null}
      <div className="seq-enrol__preview">
        <div className="seq-enrol__phead">
          <strong>Email preview</strong>
          <span className="crm-d-flex crm-gap-2 crm-flex-wrap">
            {emailSteps.length > 1 ? (
              <select
                className="input input--sm"
                aria-label="Email step"
                value={shownStep ?? ''}
                onChange={(e) => setStepPick(Number(e.target.value))}
              >
                {emailSteps.map((i) => (
                  <option key={i} value={i}>
                    Step {displayStepNumber(sequence.steps, i)}:{' '}
                    {stepTypeLabel(sequence.steps[i]!.type)}
                  </option>
                ))}
              </select>
            ) : null}
            {contacts.length > 0 ? (
              <>
                <label className="crm-visually-hidden" htmlFor={`${idPrefix}PrevFor`}>
                  Preview for
                </label>
                <select
                  className="input input--sm"
                  id={`${idPrefix}PrevFor`}
                  value={contact?.id ?? ''}
                  onChange={(e) => setPreviewFor(e.target.value)}
                >
                  {contacts.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </>
            ) : null}
          </span>
        </div>
        <div className="seq-enrol__pbody" aria-live="polite">
          {first && !isEmailType(first.type) ? (
            <p className="seq-enrol__note">
              Step {displayStepNumber(sequence.steps, startStep)} is a {stepTypeLabel(first.type)}:
              “{stepTitle(first)}”. No email goes out at enrollment; a task is created for you
              instead.
            </p>
          ) : null}
          {shownStep !== null ? (
            <EmailStepPreview
              key={`${contact?.id ?? 'any'}:${shownStep}`}
              sequence={sequence}
              stepIndex={shownStep}
              contact={contact}
              review={review}
            />
          ) : null}
        </div>
      </div>
    </div>
  );
}

type MailView = { subject: string; bodyHtml: string; missing: string[] };

/** One email step as it goes out to `contact` (merge fields filled in), and its edit. */
function EmailStepPreview({
  sequence,
  stepIndex,
  contact,
  review,
}: {
  sequence: Sequence;
  stepIndex: number;
  contact: EnrollContact | null;
  review: EnrollReviewState;
}) {
  const step = sequence.steps[stepIndex]!;
  const reply =
    (step.type === 'automated_email' || step.type === 'manual_email') && step.threadAsReply;
  const edit = contact ? review.edits.get(editKey(contact.id, stepIndex)) : undefined;
  const [view, setView] = useState<MailView | 'loading' | { error: string }>('loading');
  const [editing, setEditing] = useState<{ subject: string; bodyHtml: string } | null>(null);
  const subject =
    step.type === 'automated_email' || step.type === 'manual_email' ? step.subject : null;
  const bodyHtml =
    step.type === 'automated_email' || step.type === 'manual_email' ? step.bodyHtml : null;
  const templateId =
    step.type === 'automated_email' || step.type === 'manual_email' ? step.templateId : null;

  useEffect(() => {
    if (!contact) {
      setView({ subject: subject ?? '', bodyHtml: bodyHtml ?? '', missing: [] });
      return;
    }
    let cancelled = false;
    setView('loading');
    const inline = edit ?? (subject?.trim() || bodyHtml || !templateId ? null : undefined);
    const call =
      inline !== undefined
        ? previewTemplateDraft({
            contactId: contact.id,
            subject: (inline ?? { subject: subject ?? '' }).subject,
            bodyHtml: (inline ?? { bodyHtml: bodyHtml ?? '' }).bodyHtml,
          })
        : previewEmailTemplate(templateId!, { contactId: contact.id });
    call.then(
      (p) => {
        if (!cancelled)
          setView({ subject: p.subject, bodyHtml: p.bodyHtml, missing: p.missingFields });
      },
      (err) => {
        if (!cancelled) setView({ error: errorText(err) });
      },
    );
    return () => {
      cancelled = true;
    };
  }, [contact, edit, subject, bodyHtml, templateId]);

  if (view === 'loading') return <p className="seq-enrol__note">Loading…</p>;
  if ('error' in view) return <Alert tone="danger">{view.error}</Alert>;

  if (editing && contact) {
    return (
      <div className="seq-enrol__edit">
        {!reply ? (
          <div className="field crm-mb-0">
            <label className="field__label" htmlFor="seqEnrolEditSubject">
              Subject
            </label>
            <input
              id="seqEnrolEditSubject"
              className="input"
              value={editing.subject}
              maxLength={998}
              onChange={(e) => setEditing({ ...editing, subject: e.target.value })}
            />
          </div>
        ) : null}
        <ComposeRichText
          openKey={`${contact.id}:${stepIndex}`}
          value={editing.bodyHtml}
          onChange={(html) => setEditing({ ...editing, bodyHtml: html })}
          label="Email"
          minHeight={160}
        />
        <div className="seq-enrol__actions">
          <button
            type="button"
            className="btn-crm btn-crm--primary btn-crm--sm"
            onClick={() => {
              review.setEdit(contact.id, stepIndex, {
                subject: reply ? '' : editing.subject.replace(/[\r\n]+/g, ' ').trim(),
                bodyHtml: editing.bodyHtml,
              });
              setEditing(null);
            }}
          >
            Save for {contact.name}
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setEditing(null)}
          >
            Cancel
          </button>
        </div>
      </div>
    );
  }

  return (
    <>
      {contact ? (
        <p className="seq-enrol__meta">
          <span>To:</span> {contact.name}
          {contact.email ? ` <${contact.email}>` : ''}
        </p>
      ) : null}
      <p className="seq-enrol__meta">
        <span>Subject:</span>{' '}
        <strong>{reply ? 'Reply in the same thread' : view.subject || '(no subject)'}</strong>
      </p>
      <div
        className="seq-enrol__mail"
        dangerouslySetInnerHTML={{
          __html: safeEmailHtml(view.bodyHtml) || '<em>No email body</em>',
        }}
      />
      {edit ? (
        <p className="seq-enrol__note">Edited for {contact?.name ?? 'this contact'}.</p>
      ) : null}
      {step.type === 'manual_email' ? <p className="seq-enrol__note">{MANUAL_EMAIL_TEXT}</p> : null}
      {!contact ? (
        <p className="seq-enrol__note">
          Merge fields are filled in for each contact when it is sent.
        </p>
      ) : null}
      {view.missing.length && contact ? (
        <p className="seq-enrol__note">
          No value for {contact.name}: {view.missing.join(', ')}. Edit the email for this contact,
          or the step will fail.
        </p>
      ) : null}
      {contact ? (
        <div className="seq-enrol__actions">
          <button
            type="button"
            className="link"
            disabled={review.enrolling}
            onClick={() =>
              setEditing({
                subject: edit?.subject ?? view.subject,
                bodyHtml: edit?.bodyHtml ?? view.bodyHtml,
              })
            }
          >
            Edit email for {contact.name}
          </button>
          {edit ? (
            <button
              type="button"
              className="link"
              disabled={review.enrolling}
              onClick={() => review.setEdit(contact.id, stepIndex, null)}
            >
              Use the sequence&apos;s email
            </button>
          ) : null}
        </div>
      ) : null}
    </>
  );
}

/**
 * Why the sequence can't take enrollments (`review.block`). D-5: for step problems, they are
 * listed in the editor's words (POST /validate, `review.problems`).
 */
export function SequenceBlockAlert({
  sequence,
  text,
  problems,
}: {
  sequence: Pick<Sequence, 'id' | 'steps'>;
  text: string;
  problems: SequenceProblem[] | null;
}) {
  return (
    <Alert tone="warning">
      {text}
      {text === NOT_READY_TEXT && problems?.length ? (
        <SequenceProblemsList problems={problems} sequenceId={sequence.id} steps={sequence.steps} />
      ) : null}
    </Alert>
  );
}
