'use client';

import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import type { EmailTemplate } from '@/features/inbox/types';
import { cloneTemplate } from '@/features/message-templates/api.client';
import { getSequenceAbResults } from '@/features/sequences/api.client';
import type { SequenceAbVersionResult, SequenceStep } from '@/features/sequences/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { ChevronDown, DropMenu } from './DropMenu';
import {
  EmailCardBody,
  PencilIcon,
  StepIcon,
  TokenText,
  WeekendsHint,
  useStepStats,
} from './DynamicSequenceCanvas';
import {
  AddEmailDrawer,
  EmailTypeDrawer,
  type EmailStepOption,
  type EmailThreading,
  REP_KINDS,
  TaskStepDrawer,
  StepEmailEditor,
  TemplatePickerDrawer,
  repKindOf,
} from './DynamicStepDrawers';
import { SequenceStartPicker, StepChoiceGrid, type FirstStepKind } from './SequenceStartPicker';
import { asEmailTemplate } from './SequenceTemplateEditor';
import { useSendTestEmail } from './useSendTestEmail';
import { BusinessDaysPopover, DEFAULT_STEP_DELAY, displayStepNumber } from './shared';

type Wait = Extract<SequenceStep, { type: 'wait' }>;
type AutoEmail = Extract<SequenceStep, { type: 'automated_email' }>;
type AbResult = { a: SequenceAbVersionResult | null; b: SequenceAbVersionResult | null };

/** The wait put before every step added after the first (HubSpot: 1 business day). */
const GAP_WAIT: Wait = { type: 'wait', amount: DEFAULT_STEP_DELAY, unit: 'business_days' };

/**
 * The Steps view of a standard sequence (design: the same cards and drawers as a dynamic
 * sequence, in one column). Step 1 is picked from the start card; later steps are added with +,
 * each after a wait. Edits go to `onStepsChange`; the editor's Save button saves them.
 */
const isEmail = (s: SequenceStep) => s.type === 'automated_email' || s.type === 'manual_email';

/**
 * An email sent as a reply needs an earlier email to reply to: after a remove or a move, the one
 * that became the first email goes back to a new email (else the sequence can't enroll anyone).
 */
function withoutOrphanReplies(steps: SequenceStep[]): SequenceStep[] {
  const first = steps.findIndex(isEmail);
  return steps.map((s, i) =>
    i <= first && s.type === 'automated_email' && s.threadAsReply
      ? { ...s, threadAsReply: false }
      : s,
  );
}

export function StandardSequenceCanvas({
  sequenceId,
  timezone,
  steps,
  canEdit,
  templates,
  meName,
  ownerNameOf,
  onTemplateCreated,
  onTemplateUpdated,
  onStepsChange,
  initialPick = null,
}: {
  /** A first step picked on the create page: its drawer opens once (QA 16 Oct #107). */
  initialPick?: FirstStepKind | null;
  sequenceId: string;
  timezone: string;
  steps: SequenceStep[];
  canEdit: boolean;
  templates: EmailTemplate[] | null;
  meName: string;
  ownerNameOf: (userId: string | undefined) => string | null;
  onTemplateCreated: (template: EmailTemplate) => void;
  /** A template changed with Edit email › Update existing template. */
  onTemplateUpdated?: (template: EmailTemplate) => void;
  onStepsChange: (steps: SequenceStep[]) => void;
}) {
  const toast = useToast();
  const testEmail = useSendTestEmail();
  /** The email the template drawer is for: an index, null = a new one at the end. */
  const [emailTarget, setEmailTarget] = useState<number | null | undefined>(undefined);
  /** The email step open in Edit email (QA 14 Oct #43). */
  const [editEmail, setEditEmail] = useState<number | null>(null);
  const [task, setTask] = useState<{
    kind: (typeof REP_KINDS)[number]['key'];
    index: number | null;
  } | null>(null);
  const [expanded, setExpanded] = useState<Set<number>>(new Set());
  /** Sequences #82: steps folded to their header (the design's collapse arrow). */
  const [collapsed, setCollapsed] = useState<Set<number>>(new Set());
  /** Sequences #82: the email step open in "Choose email type" (Edit threading). */
  const [threadTarget, setThreadTarget] = useState<number | null>(null);
  /** HUB-712 / #34: the email step whose version B is being added or edited. */
  const [abTarget, setAbTarget] = useState<{ index: number; isNew: boolean } | null>(null);
  /** EDT-03: where the "+" card is open (a `steps` index to insert at), and where a pick goes. */
  const [gap, setGap] = useState<number | null>(null);
  const [slot, setSlot] = useState<number | null>(null);
  /** EDT-08: the wait whose "Business days" popover is open. */
  const [delayEdit, setDelayEdit] = useState<number | null>(null);
  /** The step whose version B is edited in the template editor. */
  const [editB, setEditB] = useState<number | null>(null);
  const stats = useStepStats(sequenceId, timezone);
  const abStats = useAbResults(sequenceId);

  const picked = useRef(false);
  useEffect(() => {
    if (!initialPick || picked.current) return;
    picked.current = true;
    if (initialPick === 'automated_email') setEmailTarget(null);
    else setTask({ kind: initialPick, index: null });
  }, [initialPick]);

  const set = (next: SequenceStep[]) => onStepsChange(withoutOrphanReplies(next));
  /** Indexes of the steps that do something (not waits), in order. */
  const actions = steps.flatMap((s, i) => (s.type === 'wait' ? [] : [i]));
  const lastAction = actions[actions.length - 1] ?? -1;
  const automated = steps.filter((s) => s.type === 'automated_email').length;
  const days = steps.reduce((sum, s) => sum + (s.type === 'wait' ? s.amount : 0), 0) + 1;
  /** The day a step runs on, counting the waits before it (HubSpot's "Day N", QA 16 Oct #110). */
  const dayOf = (index: number) =>
    steps.slice(0, index).reduce((sum, s) => sum + (s.type === 'wait' ? s.amount : 0), 0) + 1;

  /** Adds a step where the "+" was clicked (`slot`), after the wait it brings; null: the end. */
  const append = (step: SequenceStep) => {
    const at = slot !== null && slot < steps.length ? slot : steps.length;
    if (!actions.length) set([...steps, step]);
    else set([...steps.slice(0, at), { ...GAP_WAIT }, step, ...steps.slice(at)]);
    setSlot(null);
  };

  const pick = (kind: FirstStepKind) => {
    setSlot(gap);
    setGap(null);
    if (kind === 'automated_email') setEmailTarget(null);
    else setTask({ kind, index: null });
  };

  /** Changes one automated email step. */
  const patchEmail = (index: number, patch: (s: AutoEmail) => AutoEmail) =>
    set(steps.map((s, i) => (i === index && s.type === 'automated_email' ? patch(s) : s)));

  /** Edit threading (either email kind): replies go to the email before it. */
  const setReply = (index: number, reply: boolean) =>
    set(
      steps.map((s, i) =>
        i === index && (s.type === 'automated_email' || s.type === 'manual_email')
          ? { ...s, threadAsReply: reply }
          : s,
      ),
    );

  /** "Step N: <subject>" of the emails before `before` (a `steps` index), for the reply-to list. */
  const emailsBefore = (before: number): EmailStepOption[] =>
    steps.flatMap((s, i) => {
      if (i >= before || !isEmail(s) || !('subject' in s)) return [];
      const subject = s.subject?.trim() || templateOf(s.templateId)?.subject?.trim() || '';
      return [{ id: String(i), label: `Step ${displayStepNumber(steps, i)}: ${subject}` }];
    });

  /** Change template (Replace template): the step keeps its threading and its version B. */
  const replaceEmail = (index: number, template: EmailTemplate) => {
    set(
      steps.map((s, i) =>
        i === index && s.type === 'automated_email'
          ? { ...s, templateId: template.id, subject: null, bodyHtml: null }
          : s,
      ),
    );
    setEmailTarget(undefined);
  };

  /** Add email: the chosen template and, for a follow-up, its email type. */
  const addEmail = (template: EmailTemplate, threading: EmailThreading) => {
    append({
      type: 'automated_email',
      templateId: template.id,
      subject: null,
      bodyHtml: null,
      threadAsReply: threading.reply,
    });
    setEmailTarget(undefined);
  };

  /** #34: ends the A/B test keeping version A, or keeping version B (B becomes the email). */
  const endAbTest = (index: number, keep: 'A' | 'B') => {
    patchEmail(index, (s) =>
      keep === 'A' || !s.variantB
        ? { ...s, variantB: null }
        : {
            ...s,
            templateId: s.variantB.templateId,
            subject: s.variantB.subject,
            bodyHtml: s.variantB.bodyHtml,
            variantB: null,
          },
    );
    toast(`A/B test removed. Version ${keep} is kept`, 'success');
  };

  /** HubSpot's "Clone template" (the version's … menu): the step gets its own copy. */
  const cloneVersionTemplate = async (index: number, template: EmailTemplate) => {
    try {
      const copy = asEmailTemplate(await cloneTemplate(template.id, {}));
      onTemplateCreated(copy);
      patchEmail(index, (s) => ({ ...s, templateId: copy.id, subject: null, bodyHtml: null }));
      toast(`Template "${copy.name}" saved`, 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const saveTask = (step: SequenceStep) => {
    if (!task) return;
    if (task.index === null) append(step);
    else set(steps.map((s, i) => (i === task.index ? step : s)));
    setTask(null);
  };

  /** A step goes with the wait before it (or after it, for the first step). */
  const remove = (index: number) => {
    const drop = new Set([index]);
    if (steps[index - 1]?.type === 'wait') drop.add(index - 1);
    else if (steps[index + 1]?.type === 'wait') drop.add(index + 1);
    set(steps.filter((_, i) => !drop.has(i)));
    // Sequences QA steps BUG-03: the design's toast (sequences-steps.js).
    toast('Step deleted', 'success');
  };

  /** Swaps a step with the previous / next one; the waits stay where they are. */
  const move = (index: number, by: -1 | 1) => {
    const at = actions.indexOf(index);
    const other = actions[at + by];
    if (other === undefined) return;
    const next = [...steps];
    [next[index], next[other]] = [next[other]!, next[index]!];
    set(next);
    // Sequences QA steps BUG-03: the design's "Step moved up" / "Step moved down".
    toast(`Step moved ${by === -1 ? 'up' : 'down'}`, 'success');
  };

  const setWait = (index: number, patch: Partial<Wait>) =>
    set(steps.map((s, i) => (i === index && s.type === 'wait' ? { ...s, ...patch } : s)));

  const templateOf = (id: string | null) => templates?.find((t) => t.id === id) ?? null;
  const toggleSet = (setter: typeof setCollapsed, index: number) =>
    setter((cur) => {
      const next = new Set(cur);
      if (next.has(index)) next.delete(index);
      else next.add(index);
      return next;
    });

  /** The card's head: collapse arrow, icon, "N. Type - Day D" (#82, design and HubSpot). */
  const head = (
    index: number,
    n: number,
    icon: Parameters<typeof StepIcon>[0]['kind'],
    title: string,
    extra: ReactNode,
    menu: ReactNode,
  ) => {
    const folded = collapsed.has(index);
    return (
      <header className="dyn-card__head">
        <button
          type="button"
          className="dyn-card__toggle"
          aria-expanded={!folded}
          aria-label={`${folded ? 'Expand' : 'Collapse'} step ${n}`}
          onClick={() => toggleSet(setCollapsed, index)}
        >
          <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
            <path
              d="m6 9 6 6 6-6"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </button>
        <StepIcon kind={icon} />
        <span className="dyn-card__title">
          <strong>
            {n}. {title} - Day {dayOf(index)}
            {extra}
          </strong>
        </span>
        {menu}
      </header>
    );
  };

  /** HubSpot's "Actions ▾" text dropdown in a step's header (EDT-11). */
  const actionsMenu = (label: string, items: Parameters<typeof DropMenu>[0]['items']) =>
    canEdit ? (
      <DropMenu
        trigger={
          <>
            Actions <ChevronDown size={12} />
          </>
        }
        triggerClassName="dyn-link-btn seq-actions"
        ariaLabel={label}
        items={items}
      />
    ) : null;

  const card = (step: SequenceStep, index: number) => {
    const n = actions.indexOf(index) + 1;
    const folded = collapsed.has(index);
    const moveItems = [
      { key: 'up', label: 'Move up', disabled: n === 1, onSelect: () => move(index, -1) },
      {
        key: 'down',
        label: 'Move down',
        disabled: n === actions.length,
        onSelect: () => move(index, 1),
      },
      { key: 'remove', label: 'Delete', separated: true, onSelect: () => remove(index) },
    ];
    if (step.type === 'automated_email') {
      const template = templateOf(step.templateId);
      // Not before its template is loaded (else the editor would open empty).
      const editBlocked = Boolean(step.templateId) && !template;
      const canAb = Boolean(step.templateId || step.subject);
      return (
        <article key={index} className={cn('dyn-card', folded && 'is-collapsed')}>
          {head(
            index,
            n,
            'send',
            'Automated Email',
            step.threadAsReply ? <span className="badge seq-pill crm-ms-2">↩ Reply</span> : null,
            canEdit ? (
              <>
                {step.variantB ? null : (
                  <button
                    type="button"
                    className="dyn-link-btn"
                    disabled={!canAb}
                    title={canAb ? undefined : 'Add the email first'}
                    onClick={() => setAbTarget({ index, isNew: true })}
                  >
                    + Add A/B test
                  </button>
                )}
                {actionsMenu('Automated email actions', [
                  {
                    key: 'thread',
                    label: 'Edit threading',
                    onSelect: () => setThreadTarget(index),
                  },
                  ...moveItems.slice(0, 2),
                  {
                    key: 'test',
                    label: 'Send test to me',
                    disabled: Boolean(testEmail.blocked(step, template)),
                    title: testEmail.blocked(step, template) ?? undefined,
                    onSelect: () => void testEmail.send(step, template),
                  },
                  ...moveItems.slice(2),
                ])}
              </>
            ) : null,
          )}
          {folded ? null : step.variantB ? (
            <AbBlock
              n={n}
              step={step}
              templateA={template}
              templateB={templateOf(step.variantB.templateId)}
              result={abStats?.get(index) ?? null}
              canEdit={canEdit}
              editBlocked={editBlocked}
              onEdit={(ver) => (ver === 'A' ? setEditEmail(index) : setEditB(index))}
              onDelete={(ver) => endAbTest(index, ver === 'A' ? 'B' : 'A')}
              onRemove={() => endAbTest(index, 'A')}
            />
          ) : (
            <EmailCardBody
              step={step}
              template={template}
              templatesLoading={templates === null}
              row={stats.get(index)}
              open={expanded.has(index)}
              onToggle={() => toggleSet(setExpanded, index)}
              versionTools={
                canEdit ? (
                  <span className="dyn-email__tools">
                    <button
                      type="button"
                      className="dyn-icon-btn"
                      aria-label="Edit version A"
                      title={editBlocked ? 'Template not available' : 'Edit'}
                      disabled={editBlocked}
                      onClick={() => setEditEmail(index)}
                    >
                      <PencilIcon />
                    </button>
                    <DropMenu
                      trigger={<span aria-hidden>…</span>}
                      triggerClassName="dyn-icon-btn"
                      ariaLabel="Version A options"
                      items={[
                        {
                          key: 'replace',
                          label: 'Replace template',
                          onSelect: () => setEmailTarget(index),
                        },
                        {
                          key: 'clone',
                          label: 'Clone template',
                          disabled: !template,
                          title: template ? undefined : 'This email has no template',
                          onSelect: () => {
                            if (template) void cloneVersionTemplate(index, template);
                          },
                        },
                      ]}
                    />
                  </span>
                ) : null
              }
            />
          )}
        </article>
      );
    }
    const kind = repKindOf(step);
    if (!kind) return null;
    const meta = REP_KINDS.find((k) => k.key === kind)!;
    const title =
      step.type === 'manual_email'
        ? step.subject?.trim() ||
          templateOf(step.templateId)?.subject ||
          step.title ||
          'No template attached'
        : 'title' in step && step.title
          ? step.title
          : meta.label;
    const pauses = 'pauseUntilDone' in step && step.pauseUntilDone;
    return (
      <article key={index} className={cn('dyn-card dyn-card--rep', folded && 'is-collapsed')}>
        {head(
          index,
          n,
          kind,
          // Sequences QA steps BUG-01: HubSpot's card name ("Call Task"), as "Automated Email".
          meta.heading,
          <>
            {step.type === 'manual_email' && step.threadAsReply ? (
              <span className="badge seq-pill crm-ms-2">↩ Reply</span>
            ) : null}
            {pauses ? <span className="badge seq-pill crm-ms-2">Pauses sequence</span> : null}
          </>,
          actionsMenu(`${meta.label} actions`, [
            { key: 'edit', label: 'Edit task', onSelect: () => setTask({ kind, index }) },
            ...(step.type === 'manual_email'
              ? [
                  {
                    key: 'thread',
                    label: 'Edit threading',
                    onSelect: () => setThreadTarget(index),
                  },
                ]
              : []),
            ...moveItems,
          ]),
        )}
        {folded ? null : (
          <p className="dyn-card__note">
            <strong>{step.type === 'manual_email' ? 'Subject:' : 'Task title:'}</strong>{' '}
            <TokenText text={title} />
          </p>
        )}
      </article>
    );
  };

  /** EDT-07/08: "Delay: N business days" opens HubSpot's "Business days" popover (unit: Settings). */
  const waitChip = (step: Wait, index: number) => (
    <div key={index} className="dyn-gap">
      <span className="dyn-gap__line" aria-hidden />
      <span className="seq-bdp-wrap">
        <button
          type="button"
          className="dyn-gap__chip dyn-gap__chip--btn"
          disabled={!canEdit}
          aria-haspopup="dialog"
          aria-expanded={delayEdit === index}
          onClick={() => setDelayEdit(index)}
        >
          {/* Sequences QA steps BUG-02: HubSpot's and the design's "Delay: N business days". */}
          <span aria-hidden>⏱</span> Delay: {step.amount}{' '}
          {step.unit === 'days' ? 'day' : 'business day'}
          {step.amount === 1 ? '' : 's'}
          {step.unit === 'business_days' ? <WeekendsHint /> : null}
        </button>
        {delayEdit === index ? (
          <BusinessDaysPopover
            value={step.amount}
            unit={step.unit}
            onSave={(amount) => {
              setWait(index, { amount });
              setDelayEdit(null);
            }}
            onCancel={() => setDelayEdit(null)}
          />
        ) : null}
      </span>
      <span className="dyn-gap__line" aria-hidden />
    </div>
  );

  /** EDT-03/04: the "+" under a step, or its inline "Step N" card once clicked. */
  const addGap = (at: number, after: number) => {
    if (!canEdit) return null;
    if (gap !== at)
      return (
        <>
          <span className="seqc-step__line" aria-hidden />
          <button
            type="button"
            className="dyn-add"
            aria-label="Add a step"
            onClick={() => setGap(at)}
          >
            +
          </button>
        </>
      );
    return (
      <>
        <span className="seqc-step__line" aria-hidden />
        <section className="seqc-step std-insert" aria-label={`Step ${after + 1}`}>
          <div className="std-insert__head">
            <h3>Step {after + 1}</h3>
            <button type="button" className="dyn-link-btn" onClick={() => setGap(null)}>
              Remove step
            </button>
          </div>
          <p>Choose the next action that the sequence will perform</p>
          <StepChoiceGrid onPick={pick} />
        </section>
      </>
    );
  };

  const abStep = abTarget ? steps[abTarget.index] : null;
  const threadStep = threadTarget !== null ? (steps[threadTarget] ?? null) : null;
  /** Version B opens in the same template editor as an email step: B's fields in A's place. */
  const editBStep = editB !== null ? steps[editB] : null;
  const editBSteps =
    editB !== null && editBStep?.type === 'automated_email' && editBStep.variantB
      ? steps.map((s, i) => (i === editB ? { ...editBStep, ...editBStep.variantB } : s))
      : steps;

  return (
    <div className="dyn">
      {actions.length === 0 ? (
        <SequenceStartPicker disabled={!canEdit} onPick={pick} />
      ) : (
        <>
          <section className="dyn-stats" aria-label="Sequence summary">
            <div>
              <span>Total steps</span>
              <strong>{actions.length}</strong>
            </div>
            <div>
              <span>Days to complete</span>
              <strong>{days}</strong>
            </div>
            <div>
              <span>Automated steps</span>
              <strong>{Math.round((automated / actions.length) * 100)}%</strong>
            </div>
            <div>
              <span>
                Unenroll criteria{' '}
                <span
                  className="seqa-info"
                  title="Contacts leave the sequence when they reply or book a meeting."
                >
                  ⓘ
                </span>
              </span>
              <strong>2</strong>
            </div>
          </section>
          <div className="std-steps">
            <span className="seqc-step__line" aria-hidden />
            {steps.map((step, index) =>
              step.type === 'wait' ? (
                waitChip(step, index)
              ) : (
                <Fragment key={index}>
                  {card(step, index)}
                  {/* The last step's "+" is also the one before Completed. */}
                  {index === lastAction
                    ? addGap(steps.length, actions.length)
                    : addGap(index + 1, actions.indexOf(index) + 1)}
                </Fragment>
              ),
            )}
            <span className="seqc-step__line seqc-step__line--arrow" aria-hidden />
            <span className="dyn-done" aria-hidden>
              ✓
            </span>
            <span className="std-steps__done">Completed</span>
          </div>
        </>
      )}

      <StepEmailEditor
        steps={steps}
        index={editEmail}
        templates={templates}
        meName={meName}
        onClose={() => setEditEmail(null)}
        onTemplateCreated={onTemplateCreated}
        onTemplateUpdated={onTemplateUpdated}
        onStepsChange={onStepsChange}
      />
      <AddEmailDrawer
        open={emailTarget === null}
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        emailSteps={emailsBefore(slot ?? steps.length)}
        onClose={() => setEmailTarget(undefined)}
        onTemplateCreated={onTemplateCreated}
        onTemplateUpdated={onTemplateUpdated}
        onAdd={addEmail}
      />
      <TemplatePickerDrawer
        open={typeof emailTarget === 'number'}
        title="Choose email template"
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        currentId={
          typeof emailTarget === 'number' ? (steps[emailTarget] as AutoEmail).templateId : null
        }
        onClose={() => setEmailTarget(undefined)}
        onTemplateCreated={onTemplateCreated}
        onPick={(template) =>
          typeof emailTarget === 'number' && replaceEmail(emailTarget, template)
        }
      />
      <TemplatePickerDrawer
        open={abTarget !== null && abStep?.type === 'automated_email'}
        title="Choose email template"
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        currentId={abStep?.type === 'automated_email' ? abStep.templateId : null}
        tip="A/B tests work best when testing one variable at a time. Some variables to try testing: subject lines, email copy, personalization tokens, or CTA placements."
        onClose={() => setAbTarget(null)}
        onTemplateCreated={onTemplateCreated}
        onPick={(template) => {
          if (!abTarget) return;
          patchEmail(abTarget.index, (s) => ({
            ...s,
            variantB: { templateId: template.id, subject: null, bodyHtml: null },
          }));
          toast(
            abTarget.isNew
              ? 'A/B test added. Contacts will be split between Version A and B'
              : 'Version B updated',
            'success',
          );
          setAbTarget(null);
        }}
      />
      <StepEmailEditor
        steps={editBSteps}
        index={editB}
        templates={templates}
        meName={meName}
        onClose={() => setEditB(null)}
        onTemplateCreated={onTemplateCreated}
        onTemplateUpdated={onTemplateUpdated}
        onStepsChange={(next) => {
          const edited = editB === null ? null : next[editB];
          if (editB === null || !edited || !('templateId' in edited)) return;
          patchEmail(editB, (s) => ({
            ...s,
            variantB: {
              templateId: edited.templateId,
              subject: edited.subject,
              bodyHtml: edited.bodyHtml,
            },
          }));
        }}
      />
      <EmailTypeDrawer
        open={threadStep !== null && 'threadAsReply' in threadStep}
        emailSteps={emailsBefore(threadTarget ?? 0)}
        value={{
          reply: threadStep && 'threadAsReply' in threadStep ? threadStep.threadAsReply : false,
          replyToStepId: emailsBefore(threadTarget ?? 0).at(-1)?.id ?? null,
        }}
        onClose={() => setThreadTarget(null)}
        onSave={(value) => {
          if (threadTarget !== null) setReply(threadTarget, value.reply);
          toast('Email threading updated', 'success');
          setThreadTarget(null);
        }}
      />
      <TaskStepDrawer
        open={task !== null}
        standard
        kind={task?.kind ?? 'call_task'}
        initial={task && task.index !== null ? (steps[task.index] ?? null) : null}
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        emailSteps={emailsBefore(task?.index ?? slot ?? steps.length)}
        onTemplateCreated={onTemplateCreated}
        onTemplateUpdated={onTemplateUpdated}
        onClose={() => setTask(null)}
        onSave={saveTask}
      />
    </div>
  );
}

/** A version's subject and body: its own, else its template's. */
function versionContent(
  v: { subject: string | null; bodyHtml: string | null },
  template: EmailTemplate | null,
): { subject: string; bodyHtml: string } {
  return {
    subject: v.subject ?? template?.subject ?? '',
    bodyHtml: v.bodyHtml ?? template?.bodyHtml ?? '',
  };
}

/** HUB-712: per-step A/B results, by step index; null while loading or when there are none. */
function useAbResults(sequenceId: string): Map<number, AbResult> | null {
  const [byStep, setByStep] = useState<Map<number, AbResult> | null>(null);
  useEffect(() => {
    // SEQ-R-B2: a sequence not saved yet (/sequences/new/edit) has no id and no results; asking
    // anyway called GET /sequences//ab-results, a 404.
    if (!sequenceId) return;
    let alive = true;
    getSequenceAbResults(sequenceId).then(
      (res) => alive && setByStep(new Map(res.data.map((r) => [r.stepIndex, r]))),
      () => alive && setByStep(null),
    );
    return () => {
      alive = false;
    };
  }, [sequenceId]);
  return byStep;
}

const pct = (v: number | null | undefined) =>
  v === null || v === undefined ? '0%' : `${Math.round(v * 100)}%`;

/**
 * HUB-712 / #34 (design sequences-steps.js `abBlock`): version A and B side by side, each with
 * its subject, numbers and Edit, the version ahead on replies marked; "Remove test" keeps A.
 * Deleting a version keeps the other (deleting A makes B the email): how a winner is picked.
 */
function AbBlock({
  n,
  step,
  templateA,
  templateB,
  result,
  canEdit,
  editBlocked,
  onEdit,
  onDelete,
  onRemove,
}: {
  n: number;
  step: AutoEmail;
  templateA: EmailTemplate | null;
  templateB: EmailTemplate | null;
  result: AbResult | null;
  canEdit: boolean;
  editBlocked: boolean;
  onEdit: (ver: 'A' | 'B') => void;
  onDelete: (ver: 'A' | 'B') => void;
  onRemove: () => void;
}) {
  const ra = result?.a?.replyRate ?? null;
  const rb = result?.b?.replyRate ?? null;
  const leader = ra !== null && rb !== null && ra !== rb ? (ra > rb ? 'A' : 'B') : null;
  const plain = (html: string) =>
    html
      .replace(/<br\s*\/?>|<\/p>/gi, ' ')
      .replace(/<[^>]*>/g, '')
      .replace(/&nbsp;/g, ' ')
      .replace(/\s+/g, ' ')
      .trim();
  const version = (ver: 'A' | 'B') => {
    const content =
      ver === 'A'
        ? versionContent(step, templateA)
        : versionContent(step.variantB ?? { subject: null, bodyHtml: null }, templateB);
    const r = ver === 'A' ? result?.a : result?.b;
    return (
      <div className="seq-ab__ver" key={ver}>
        <div className="seq-ab__vhead">
          <span className={`seq-ab__tag seq-ab__tag--${ver.toLowerCase()}`}>Version {ver}</span>
          {leader === ver ? <span className="seq-ab__win">Leading on replies</span> : null}
          {canEdit ? (
            <span className="seq-ab__edit">
              <button
                type="button"
                className="dyn-link-btn"
                disabled={ver === 'A' && editBlocked}
                onClick={() => onEdit(ver)}
              >
                Edit
              </button>
              <DropMenu
                trigger={<span aria-hidden>…</span>}
                triggerClassName="dyn-icon-btn"
                ariaLabel={`Version ${ver} options`}
                items={[
                  {
                    key: 'delete',
                    label: `Delete Version ${ver}`,
                    onSelect: () => onDelete(ver),
                  },
                ]}
              />
            </span>
          ) : null}
        </div>
        <p className="seq-ab__line">
          <strong>Subject:</strong>{' '}
          {step.threadAsReply ? (
            <span className="crm-text-muted">Re: the earlier email (sent in its thread)</span>
          ) : (
            <TokenText text={content.subject} />
          )}
        </p>
        {content.bodyHtml ? (
          <p className="seq-ab__prev">
            <TokenText text={plain(content.bodyHtml)} />
          </p>
        ) : null}
        <dl className="dyn-email__stats seq-ab__stats">
          <div>
            <dt>{(r?.sent ?? 0).toLocaleString()}</dt>
            <dd>Sent</dd>
          </div>
          <div>
            <dt>{pct(r?.openRate)}</dt>
            <dd>Opens</dd>
          </div>
          <div>
            <dt>{pct(r?.clickRate)}</dt>
            <dd>Clicks</dd>
          </div>
          <div>
            <dt>{pct(r?.replyRate)}</dt>
            <dd>Replies</dd>
          </div>
        </dl>
      </div>
    );
  };
  return (
    <div className="seq-ab" role="group" aria-label={`A/B test for step ${n}`}>
      <div className="seq-ab__bar">
        <span className="seq-ab__title">A/B test</span>
        <span className="seq-ab__split">50% get A · 50% get B</span>
        {canEdit ? (
          <button type="button" className="dyn-link-btn" onClick={onRemove}>
            Remove test
          </button>
        ) : null}
      </div>
      <div className="seq-ab__grid">
        {version('A')}
        {version('B')}
      </div>
    </div>
  );
}
