// ---------------------------------------------------------------------------
// automation/AutomationBuilder.tsx — the BUILDER (owner item 3b, contracts
// C1/C2/C4, ruling R1: "exact layout, Loopable skin").
//
// THE ANATOMY IS AIRTABLE'S, 1:1, and it is the owner's reference (images 1-9):
// a centre column of TRIGGER → ACTIONS with a spine down the left carrying each
// step's status chip, dashed add-boxes at the end of each section, and a
// Properties panel on the right whose sections are Trigger details /
// Configuration / Test step. Every colour, size and weight is OURS (R1,
// DESIGN.md) — no Airtable blue, no caps micro-labels (R6: "TRIGGER" is
// "Trigger" here, and de-capping takes the letter-spacing with it).
//
// ⛔ IT RENDERS SYNCHRONOUSLY FROM WHAT IT WAS HANDED (C14 leg 1). No fetch, no
// effect, no second frame: the trigger comes from `automation.trigger`, the
// actions from `automation.flow`, the machine steps from `automation.graph` —
// all three already on the list payload the rail used to draw the row you
// clicked. THIS IS THE GHOST FIX. The old detail rendered Steps, then swapped to
// the Board when `/board` answered, so switching automations painted the
// PREVIOUS one's shape inside the new one's frame for as long as a fetch takes.
// A view that cannot be in two shapes cannot show you the wrong one.
//
// ⛔ NO CLIENT UNION OVER A SERVER VOCABULARY, anywhere. Trigger keys, action
// kinds, comparison operators, ending modes, review deciders and every ceiling
// ride `GET /automations`. What this file owns is pixels and wording.
//
// WHAT PERSISTS WHEN. A discrete choice writes immediately — picking a trigger,
// adding an action, flipping a switch — because a control you have to remember
// to Save is not a control (R9). FREE TEXT does not: a value, a prompt or a name
// commits on BLUR, or every keystroke would PATCH a half-typed condition and the
// server would refuse most of them out loud (the cron-string precedent in
// AutomationTrigger).
// ---------------------------------------------------------------------------
import type { ReactNode } from "react";
import { useEffect, useRef, useState } from "react";

// ⭐ WAVE 30 · ITEM 7 (R3 + R4) — connector identity, from the ONE module that owns it. Not a
// second copy of two SVGs: the directory, this menu and the trigger picker all answer "which
// company is this row about", and three answers is how a platform gets added in two of them.
import { brandForConnector, brandForKind, hasBrandKind } from "../connectors/brandMarks";

import type {
  Action,
  ActionCatalogRow,
  Automation,
  Cond,
  FlowVocab,
  GraphNode,
  OAuthStatus,
  TriggerOption,
  UserTable,
} from "./automationApi";
// ⭐ WAVE 26 · ITEM 22 / D-70 — the Run guard, imported rather than re-derived. This file and
// `AutomationDetail` each paint a Run button onto the same paid action; ONE function decides.
// ITEM 9 / R11 — `createTable` + `AutomationError` for the in-place "+ New database".
import { AutomationError, createTable, runBlock } from "./automationApi";
import CondBuilder, { condComplete } from "./CondBuilder";
import { groupActions, groupBranches, groupByPanel, numberActions, reorderList }
  from "./steps";
// ⭐ WAVE 25 item 5b (C2) — the grouped picker, and `TriggerMark` with it. The icon vocabulary
// MOVED to that file rather than being copied into it: the whole of item 5b is that the compact
// control in Properties and the big "+ Add trigger" menu are one control, and two copies of the
// marks is how they drift back into looking like two features.
import PresetPlan from "./PresetPlan";
import TriggerPicker, { TriggerMark } from "./TriggerPicker";

/**
 * ⛔ A PRIVATE MIME, AND `text/plain` IS NEVER SET (owner item 11; the wave-13 C-LAYOUT scar).
 * A drag carrying `text/plain` is a drag the whole operating system understands: drop it on any
 * input, textarea or contenteditable — this builder is full of them — and the browser TYPES the
 * payload in, so a mis-aimed reorder silently writes an action id into somebody's condition
 * value. A private type is inert everywhere except the drop targets below, which is why the nav
 * rail's own drag uses one (`Shell.tsx:90 NAV_DRAG_TYPE`).
 * ⚠ The board's card drag still uses `text/plain` (`AutomationBoard.tsx:167`) — noted, not fixed
 * here: that file belongs to another session this wave.
 */
const ACTION_DRAG_TYPE = "application/x-loopable-action";

interface Props {
  automation: Automation;
  /**
   * THE AUTOMATION'S NAME (item 15b, C-DETAIL) — it left the page header and Properties is where
   * it went, at the top, above whatever step is selected. REQUIRED, all three: an optional prop
   * degrades to "the field does not exist", which looks exactly like never having built it.
   *
   * ⚠ TEXT AND COMMIT ARE SEPARATE ON PURPOSE. This is the cron field's shape
   * (`AutomationTrigger`'s `onCronText` / `onSchedule`): free text stays controlled while typing
   * and writes ONCE on blur, because per-keystroke would PATCH a half-typed name. Folding them
   * into one callback would force a choice between a laggy controlled input and a save per
   * keystroke, and this file has already paid for both.
   */
  name: string;
  onNameText: (v: string) => void;
  onNameCommit: () => void;
  /** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
  triggers?: TriggerOption[];
  catalog: ActionCatalogRow[];
  vocab?: FlowVocab;
  tables: UserTable[];
  oauth: OAuthStatus | null;
  /** True while a write is in flight — drives the "All changes saved" stamp and disables edits. */
  busy: boolean;
  /** Write a partial definition. The caller owns the request and prints the refusal verbatim. */
  onPatch: (body: Record<string, unknown>) => void;
  onToggleNode: (nodeId: string) => void;
  /**
   * ⛔ CHOOSING A TRIGGER IS NOT A `{trigger:{key}}` PATCH, and getting that wrong is invisible.
   * `schedule` is what today's engine actually READS, so a pick has to write BOTH halves or
   * "At a scheduled time" would store a key and leave the cron switched off — a trigger that
   * says it is scheduled and never fires. The detail already owns that two-write shape
   * (`pickTrigger`); the builder calls it rather than composing a second copy of it.
   */
  onPickTrigger: (key: string) => void;
  onRunNow: () => void;
  /**
   * The MACHINE steps' config bodies (source / columns / capture / find / write). They live in
   * `AutomationDetail`, so they are passed IN rather than moved: a builder that re-implemented
   * them would be a second copy of five panels whose only job is to agree with the engine.
   *
   * ⚠ IT TAKES A PANEL KEY, NOT A NODE (item 5, C-CFG). It used to be
   * `(node: GraphNode) => ReactNode`, and the caller's whole body was `panelBody(node.panel)` —
   * so the node was only ever a wrapper around the key. Now that Properties renders the panels
   * GROUPED BY that key, taking a node would invite the caller to pass one node of a group and
   * quietly imply the body belongs to it alone.
   */
  renderNodeBody: (panel: string) => ReactNode;
  /**
   * The SCHEDULE half of the trigger face (`AutomationTrigger` with its picker hidden). Passed
   * in for the same reason the node panels are: the cron round-trip, the server's preset list
   * and the tick-honesty note exist exactly once, and both this view and the board render the
   * same element rather than two copies of three things that go wrong invisibly.
   */
  scheduleFace: ReactNode;
  /**
   * ⭐ WAVE 27 · CONTRACT C11 — is the PROPERTIES panel the one on screen?
   *
   * ⛔ THE STATE LIVES IN `AutomationDetail`, NEVER HERE, and the contract says so for a
   * structural reason: the two panels that share this column are children of DIFFERENT
   * components — Properties is this file's, the Run log is `AutomationDetail`'s — so the only
   * place that can know "exactly one is visible" is their common parent. A local boolean here
   * could hide Properties while the log was also hidden, or show both.
   * ⚠ REQUIRED. An optional flag defaulting to `true` would make an unmounted toggle look like
   * a working panel, which is the shape this repo keeps paying for.
   */
  showProperties: boolean;
  /** The Properties/Run-history switch, OWNED by `AutomationDetail` and drawn in both panel
   *  heads so it is in the same place whichever one is showing. */
  panelTabs: ReactNode;
  /** Announce that a step (or the trigger) was clicked, so the parent can bring Properties
   *  forward — C11's "clicking any step card switches to Properties". */
  onStepPicked: () => void;
  /**
   * Does the cron drive the CURRENT trigger (owner item 7)? REQUIRED, and decided by the caller
   * for the reason `AutomationTrigger.schedules` gives: which keys the cron drives is a per-key
   * fact, and no component below the detail is entitled to name trigger keys.
   */
  schedules: boolean;
  /**
   * ⭐ THE DATABASE THE FLOW'S RECORDS WALK (owner item 12a) — the trigger's table, or the
   * automation's own target, resolved by the caller the way `automation_engine._flow_table` does.
   * REQUIRED: an absent one degrades to an empty field list, which is the exact defect this prop
   * exists to fix and is indistinguishable from "this database has no columns".
   */
  walkTable: string;
  /**
   * ⭐ WAVE 26 · ITEM 9 / R11 — RE-READ THE DATABASE LIST, after an action's picker created one.
   *
   * ⛔ REQUIRED, deliberately. The wave doc's rule is "prefer a REQUIRED prop; an optional one
   * degrades silently to 'the feature does not exist'" — and here the silent degradation has a
   * particularly bad shape: the database really would be created, on the server, and simply not
   * appear in the picker that made it. The user then makes a second one with the same name
   * (duplicate names are legal), and the automation still points at neither.
   */
  onTablesChanged: () => Promise<void> | void;
  /**
   * Is there an edit the HEADER's Save still owns? REQUIRED, and it exists so the panel's
   * "All changes saved" stamp can stop being a claim about fields it does not cover — the
   * machine steps' panels moved into Properties this wave and they commit with Save, not on
   * change.
   */
  dirty: boolean;
}

/*
 * ⚠ `"node"` LEFT THIS UNION WITH THE MACHINE CARDS (item 5). It existed so a click on one of
 * those cards could open its panel; with the cards gone nothing can set it, and a variant no
 * code path can reach is a branch that reads as supported and is not.
 */
type Sel = { kind: "trigger" | "action"; id: string };

/** Airtable phrases the empty state's shortcuts; ours come from the SERVER's own list (image 1). */
const SUGGESTED = 6;

/**
 * ⭐⭐ WAVE 30 · W30-T23 / C3 — THE ENRICH KINDS, MIRRORING `automation_engine.ENRICH_KINDS`.
 *
 * ⛔ ONE PREDICATE, TWO CALL SITES, and both had to move or the ticket would have half-shipped:
 * `seedFor` decides whether the menu row can be ADDED at all, and the properties panel decides
 * whether the added step has any CONTROLS. Widening only the first yields a step a person can add
 * and cannot configure; widening only the second yields a panel for a row that is permanently
 * faded. D-79 was that pair coming apart on the Instagram side.
 * ⚠ Named as a list rather than written twice, because the server's own validator branches on a
 * TUPLE of the same two names — a third platform must be one edit here, not a grep.
 */
const ENRICH_KINDS = ["enrich_instagram", "enrich_tiktok"];
const isEnrich = (kind: string): boolean => ENRICH_KINDS.includes(kind);

/* ⛔ `TriggerMark` STOOD HERE AND MOVED TO `TriggerPicker.tsx` (wave 25 item 5b, C2).
   It is IMPORTED back for the trigger card below. Moving rather than copying is the point of
   the item: the compact control in Properties and this menu are one picker now, and the marks
   are the thing the owner noticed missing from one of them (reference/ERROR 3.png). */
function ActionMark({ kind }: { kind: string }) {
  /* ⭐⭐ WAVE 30 · ITEM 7 / R4 — the same one-line resolution `TriggerMark` carries, and for the
     same reason: this component is drawn in the add-action menu, on every step card and on every
     machine node, so a connected action must wear its company's logo in all three or it wears two
     identities on one screen. Unbranded kinds fall through to the house glyphs below, untouched. */
  const brand = brandForKind(kind);
  if (brand) return brand;
  const common = {
    width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
    strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
    "aria-hidden": true,
  };
  if (kind === "group")
    return (
      <svg {...common}>
        <path d="M2.6 8h3l2.6-3.6h5M8.2 11.6H5.6m2.6 0h5" />
        <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
      </svg>
    );
  if (kind === "create_record")
    return (
      <svg {...common}>
        <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="2" />
        <path d="M8 5.6v4.8M5.6 8h4.8" />
      </svg>
    );
  if (kind === "find_records")
    return (
      <svg {...common}>
        <circle cx="7.2" cy="7.2" r="4" />
        <path d="m10.2 10.2 3.2 3.2" />
      </svg>
    );
  /*
    ⚠ THE MACHINE KINDS ARE HERE TOO, and leaving them out was a real defect for one render:
    the engine's nodes are `source | capture | branch | write`, none of which matched above, so
    "Write to the database" and "Fetch the page" both drew the PENCIL — an edit glyph on a step
    that reads a web page and a step that writes a database. Caught by reading the screenshot,
    not by a gate ([[ui-invisible-to-assertions]]): the icon was present, legible and wrong.
    These are the shapes the retired `AutomationSteps.KindMark` used, kept with their meanings.
  */
  if (kind === "source")
    return (
      <svg {...common}>
        <circle cx="8" cy="8" r="5.6" />
        <path d="M2.6 8h10.8M8 2.4c1.5 1.7 2.2 3.6 2.2 5.6S9.5 12.3 8 13.6C6.5 12.3 5.8 10 5.8 8s.7-3.9 2.2-5.6z" />
      </svg>
    );
  if (kind === "write")
    return (
      <svg {...common}>
        <ellipse cx="8" cy="4.2" rx="4.8" ry="1.9" />
        <path d="M3.2 4.2v7.6c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9V4.2M3.2 8c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9" />
      </svg>
    );
  if (kind === "capture")
    return (
      <svg {...common}>
        <path d="M8 2.6v7.2M5.2 7l2.8 2.8L10.8 7M3 12.4h10" />
      </svg>
    );
  if (kind === "branch")
    return (
      <svg {...common}>
        <path d="M2.6 8h3.2l2.6-3.6h5M8.4 11.6H5.8m2.6 0h5" />
        <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
      </svg>
    );
  if (kind === "update_record")
    return (
      <svg {...common}>
        <path d="M11.4 2.8 13.2 4.6 6 11.8l-2.6.8.8-2.6z" />
        <path d="M3 13.6h10" />
      </svg>
    );
  if (kind === "send_email")
    return (
      <svg {...common}>
        <rect x="2.2" y="3.6" width="11.6" height="8.8" rx="1.6" />
        <path d="m2.6 4.6 5.4 3.8 5.4-3.8" />
      </svg>
    );
  if (kind === "slack")
    return (
      <svg {...common}>
        <path d="M13.4 9.4a1.6 1.6 0 0 1-1.6 1.6H5.4L2.6 13.4V4.2a1.6 1.6 0 0 1 1.6-1.6h7.6a1.6 1.6 0 0 1 1.6 1.6z" />
      </svg>
    );
  if (kind === "run_script")
    return (
      <svg {...common}>
        <path d="M5.6 5.4 3 8l2.6 2.6M10.4 5.4 13 8l-2.6 2.6M9 3.4 7 12.6" />
      </svg>
    );
  if (kind === "generate_ai")
    return (
      <svg {...common}>
        <path d="M8 2.4l1.5 3.4 3.4 1.5-3.4 1.5L8 12.2 6.5 8.8 3.1 7.3l3.4-1.5z" />
      </svg>
    );
  if (kind === "repeating_group")
    return (
      <svg {...common}>
        <path d="M3 8a5 5 0 0 1 5-5c2 0 3.4 1 4.3 2.4M13 8a5 5 0 0 1-5 5c-2 0-3.4-1-4.3-2.4" />
        <path d="M12.4 2.6v2.9h-2.9M3.6 13.4v-2.9h2.9" />
      </svg>
    );
  /*
    ⛔ THE FALLBACK IS NEUTRAL, and it was not the first time round. The default used to BE the
    pencil — a real member of the set (`update_record`) — so every kind with no arm silently
    borrowed "edit": `send_email`, `run_script` and `repeating_group` all drew it in the action
    menu, which reads as three actions that modify a record. A fallback that is a real member
    cannot be told apart from a match; this one can.
  */
  return (
    <svg {...common}>
      <rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2.2" />
      <circle cx="8" cy="8" r="1.4" />
    </svg>
  );
}

/** The label a table key reads as. A raw `ut_9f3a…` on a card is a key, not a subtitle. */
function tableLabel(tables: UserTable[], key: string): string {
  if (!key) return "";
  return tables.find((t) => t.key === key)?.label || key;
}

export default function AutomationBuilder({
  automation,
  name,
  onNameText,
  onNameCommit,
  triggers,
  catalog,
  vocab,
  tables,
  oauth,
  busy,
  onPatch,
  onToggleNode,
  onPickTrigger,
  onRunNow,
  renderNodeBody,
  scheduleFace,
  showProperties,
  panelTabs,
  onStepPicked,
  schedules,
  walkTable,
  onTablesChanged,
  dirty,
}: Props) {
  const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
  const [picking, setPicking] = useState(false);
  const [adding, setAdding] = useState(false);
  /** The trigger key awaiting confirmation (image 6) — a change that can invalidate config. */
  const [confirmKey, setConfirmKey] = useState("");
  /** The card a reorder is hovering over (item 11). `""` = nothing is being dragged. */
  const [dragOver, setDragOver] = useState("");
  /**
   * ⛔ ONE DRAG SUPPRESSES EXACTLY ONE CLICK (item 11; `AutomationBoard`'s trap 1, which this
   * repo has already paid for once). Browsers can deliver a `click` after `dragend`, and the
   * thing under the pointer here is the card's own selector — so a finished reorder would ALSO
   * change which step the Properties panel is showing, which reads as the panel jumping on its
   * own. A ref and not state, because the click arrives before a re-render would land.
   */
  const draggedRef = useRef(false);
  /**
   * ⛔ THE TRIGGER MENU IS ANCHORED TO ITS BOX, AND THAT IS A LAYOUT FACT BEFORE IT IS A
   * DISMISSAL ONE (owner's ERROR 4, 2026-08-06). `<TriggerPicker variant="menu">` was rendered at
   * the BOTTOM of this component's fragment — a sibling of `.autox-flow` and the `.autox-props`
   * aside, inside `.auto-work`, which is `display: flex`. So opening it added a THIRD COLUMN to
   * the builder: the menu landed to the right of the Properties panel, off the edge of the
   * window, and the flow column (`flex: 1 1 auto; min-width: 0`) collapsed under it until
   * "Suggested triggers" wrapped one word per line and the canvas grew a horizontal scrollbar.
   * Nothing was broken about the menu — it was in the wrong parent.
   *
   * It lives inside `.autox-main` beside its own button now, and this ref is what makes the pair
   * ONE unit: an outside mousedown must not count the button that opens it as "outside", or the
   * click would close and reopen it forever. `TriggerPicker`'s own doc says the caller owns
   * open-ness for the `menu` variant precisely because the caller owns the anchor.
   */
  const addWrap = useRef<HTMLDivElement | null>(null);

  // Escape and an outside click both close it — the `field` variant's rule, applied to the twin
  // that had neither. Without this the empty state's menu was a one-way door: every row picks a
  // trigger, so changing your mind meant picking one you did not want.
  useEffect(() => {
    if (!picking) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setPicking(false);
    };
    const onDown = (e: MouseEvent) => {
      if (!addWrap.current?.contains(e.target as Node)) setPicking(false);
    };
    window.addEventListener("keydown", onKey);
    window.addEventListener("mousedown", onDown);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("mousedown", onDown);
    };
  }, [picking]);

  const trigger = automation.trigger || null;
  const triggerKey = trigger?.key || (automation.schedule?.enabled ? "schedule" : "manual");
  const options = triggers || [];
  const picked = options.find((t) => t.key === triggerKey) || null;
  const actions = automation.flow?.actions || [];
  const nodes = (automation.graph?.nodes || []).filter((n) => n.kind !== "trigger");
  const ops = vocab?.condOps || [];
  const nullaryOps = vocab?.nullaryCondOps || [];
  const table = tables.find((t) => t.key === (trigger?.table || "")) || null;

  /**
   * ⛔ HAS ANYTHING BEEN CHOSEN? — and the first version of this line was wrong in a way only
   * a screenshot showed.
   *
   * It read `!!trigger || key === "schedule" || key === "manual"`, and `triggerKey` DERIVES
   * "manual" whenever nothing is stored — so it was true for every automation ever, and the
   * Airtable empty state (image 1) was unreachable code that every gate was happy with.
   *
   * The honest test is what the DEFINITION holds, not what the picker displays: the engine
   * deliberately stores no trigger for manual/schedule ("`schedule` already owns the cron"), so
   * `trigger === null && !schedule.enabled` IS "nobody has decided yet". Manual is what that
   * state DOES, not a thing you pick out of it — which is why the suggested list below omits
   * it: an option whose selection stores nothing would bounce straight back to this state on
   * the next reload, and a control that undoes itself is worse than no control.
   */
  const chosen = !!trigger || !!automation.schedule?.enabled;
  /**
   * ⭐⭐ 2026-08-07 (owner report, the SECOND time on this feature) — *"I still can't do
   * Enrichment, when the Trigger is Manual, it says that I need to bound it to a database, how?"*
   *
   * ⛔ THE DATABASE PICKER EXISTED AND WAS UNREACHABLE FOR THE ONE TRIGGER THAT NEEDS IT MOST,
   * and the two decisions that combined to hide it were each locally right:
   *   1. `clean_trigger` STORES NOTHING for `manual` and `schedule` (`:8389`) — "storing a no-op
   *      trigger would be a second copy of that fact". So a manual automation holds `trigger:
   *      null` forever, by design.
   *   2. `chosen` is therefore FALSE for it (the note above says so explicitly), and W25/R14 hides
   *      the whole Configuration section until a trigger is `chosen`.
   * ⇒ The picker `caee549` added for exactly this case sits INSIDE that section, so picking
   * Manual could never reveal it. `run_plain` then refused with *"pick one on the trigger, or in
   * Properties"* — a sentence naming two doors while rendering neither. MEASURED in the live
   * nurilab store: `auto_2` "Enrichment test", `kind:'plain'`, `trigger:None`,
   * `config.targetTable:''`, one `enrich_instagram` action, unrunnable.
   *
   * ⚠ AND THE SCREEN DISAGREED WITH THE STORE, which is why the owner reasonably believed they
   * had picked something: `triggerKey` DERIVES `"manual"` when nothing is stored, so the panel
   * displays "Manual" over a definition that holds no trigger at all.
   *
   * ⛔ THE FIX IS NOT TO START STORING A MANUAL TRIGGER. The note above already argued that out
   * and it is still right — a control whose selection stores nothing bounces back on reload. What
   * was wrong is treating "no trigger stored" as "nothing to configure": a `plain` automation
   * whose trigger carries no table of its own ALWAYS has one thing to configure, the database its
   * steps walk, and that is true in exactly the state where `chosen` is false. So Configuration
   * opens for that too — the trigger-specific blocks inside are each keyed off `triggerKey` and
   * stay hidden on their own. That widening lives in the Properties panel beside the picker it
   * reveals (`needsOwnTable`), not here: `chosen` still means exactly what it says.
   */
  const configured = !trigger || trigger.configured !== false;

  /** Write one key of the trigger, keeping the rest — the engine merges against `previous`. */
  const patchTrigger = (patch: Record<string, unknown>) =>
    onPatch({ trigger: { key: triggerKey, ...patch } });

  /**
   * ⭐⭐ 2026-08-07 (owner report) — PATCH THE AUTOMATION'S OWN CONFIG.
   *
   * ⛔ IT SPREADS THE EXISTING CONFIG, and that is not defensive tidiness: `clean_definition`
   * takes `raw["config"]` WHOLE when it is a dict (`cfg_raw = raw.get("config") if isinstance(...)
   * else prev.get("config")`) — it does not merge. Sending `{targetTable: x}` alone would erase
   * the discovery predicates, the lanes and the schedule face in one keystroke.
   */
  const patchConfig = (patch: Record<string, unknown>) =>
    onPatch({ config: { ...((automation.config as Record<string, unknown>) || {}), ...patch } });

  const patchFlow = (next: Action[]) => onPatch({ flow: { actions: next } });

  /**
   * ⭐ ONE TREE WALKER (wave 24, C-FORK). Rewrite or drop any action anywhere, branches included:
   * `f` returns a replacement, or `null` to remove it.
   *
   * ⛔ THIS REPLACED FOUR HAND-ROLLED WALKS, and they were four places to forget the same thing.
   * A group's children moved from `config.actions` to `config.branches[].actions` this wave, so
   * every one of them would have quietly stopped descending into a fork — editing, deleting or
   * counting nothing inside it, with `tsc` perfectly happy because `config` is
   * `Record<string, unknown>` and an absent key is just `undefined`. The failure would have been
   * "the card is there and the delete button does nothing", per action, per fork.
   */
  const mapTree = (list: Action[], f: (a: Action) => Action | null): Action[] =>
    (list || [])
      .map((a) => {
        const next = f(a);
        if (next === null) return null;
        if (next.kind !== "group") return next;
        const brs = groupBranches(next);
        if (!brs.length) return next;
        return {
          ...next,
          config: {
            ...next.config,
            branches: brs.map((br) => ({ ...br, actions: mapTree(br.actions || [], f) })),
          },
        };
      })
      .filter((a): a is Action => a !== null);

  /** Replace one action anywhere in the tree, forks included — ids are stable server-side. */
  const editAction = (id: string, change: (a: Action) => Action) =>
    patchFlow(mapTree(actions, (a) => (a.id === id ? change(a) : a)));

  const dropAction = (id: string) => {
    // ⚠ REMOVING THE LAST ACTION IN A BRANCH IS REFUSED BY THE SERVER ("a branch with no actions
    // inside it does nothing") and the refusal is printed verbatim, as every other one is. Not
    // pre-empted here: a client that predicted it would be a second validator, and the honest
    // repair — delete the branch, not its last child — is one the reader can act on.
    patchFlow(mapTree(actions, (a) => (a.id === id ? null : a)));
    if (sel.kind === "action" && sel.id === id) setSel({ kind: "trigger", id: "" });
  };

  /**
   * REORDER (owner item 11). The whole `flow.actions` list goes back through `patchFlow` — the
   * same door every other edit uses — rather than a bespoke move endpoint, because the engine
   * already validates a whole flow and a second write path would be a second thing to keep
   * agreeing with `clean_actions`.
   *
   * ⚠ TOP-LEVEL SIBLINGS ONLY, deliberately, and it is a SCOPE rather than an oversight: a card
   * inside a conditional group is not `draggable` at all, so there is no affordance that quietly
   * does nothing. Group children are about to stop living under `config.actions` and start living
   * under `config.branches[].actions` (C-FORK), and building a tree-walking reorder against a
   * shape this same wave replaces would be work done twice with a window of wrongness in between.
   */
  const moveAction = (dragId: string, dropId: string) => {
    const next = reorderList(actions, dragId, dropId);
    // `null` = same card, or one of them is not a top-level sibling. Nothing moved, so nothing
    // is written — an aborted drag must not PATCH the flow back over itself.
    if (next) patchFlow(next);
  };

  /**
   * ⛔ A NEW ACTION'S CONFIG MUST BE ONE THE SERVER ACCEPTS — and the first version of this
   * function got it wrong for FOUR of the five kinds, which is worth writing down because every
   * gate was green and the harness could not see it (SSR renders no click).
   *
   * MEASURED against `clean_actions` itself (`python -c` over the engine module, no server):
   *   `{values:{"":""}}`      -> "a value is written to a field with no name"
   *   `{table:"",values:…}`   -> the same, twice
   *   `{table:""}` (find)     -> "the find records action names no database"
   *   `{cond:…,actions:[]}`   -> "a conditional group with no actions inside it does nothing"
   * So clicking "Add → Update record" would have produced a red banner and NO CARD. This is the
   * wave-22 discovery-predicate scar reproduced exactly ([[cg-condition-builder-items]] — every
   * default must be one the server takes), in a file whose own comment cites it.
   *
   * The seeds below are built from data this component already holds, and `seedFor` returns
   * NULL when it cannot build a legal one. A kind with no legal seed is offered DISABLED with
   * the reason, rather than offered and refused: the two states look identical to a user and
   * only one of them is honest.
   */
  /**
   * ⭐ THE WALKING RECORD'S COLUMNS (item 12a). Read off `walkTable`, NOT off `table`.
   *
   * `table` is the TRIGGER's database and it answers a different question — which columns the
   * trigger may watch or test. This one answers what the ACTIONS write to and what a branch's
   * condition compares, and on any automation without an event trigger (manual, schedule,
   * `ig_profile_match`) the two are not the same table at all: the first is empty and the second
   * is where all the records are. Reading actions' fields off the trigger is why every condition
   * inside a fork offered an empty picker.
   */
  const walkFields = (tables.find((t) => t.key === walkTable) || null)?.fields || [];
  const firstField = walkFields[0]?.key || "";
  const firstTable = tables[0] || null;
  const firstTableField = firstTable?.fields?.[0]?.key || "";

  const seedFor = (kind: string): Record<string, unknown> | null => {
    if (kind === "update_record")
      return firstField ? { values: { [firstField]: "" } } : null;
    if (kind === "create_record")
      return firstTable && firstTableField
        ? { table: firstTable.key, values: { [firstTableField]: "" } }
        : null;
    if (kind === "find_records")
      return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
    /*
      ⭐⭐ WAVE 31 · T38 (contract C5, owner ruling R10) — THE WEB READ, and this branch is here
      because a gate demanded it rather than because anybody remembered.

      ⛔ FLIPPING `ready:True` ON THE SERVER IS NOT MOUNTING AN ACTION. `verify_automation_ui`'s
      seed check DERIVES its subject from the server catalog, so the moment `web_read` became
      ready it went red with `MISSING: ['web_read']` — the action would have rendered faded,
      labelled "Needs a database" (a claim about databases, which is not the problem) and been
      permanently unclickable. That is D-79's scar exactly, and the check written after it is what
      caught the repeat. A capability is reachable when the SERVER offers it, the ENGINE dispatches
      it and the CLIENT can seed it; two out of three ships an invisible feature.

      ⚠ THE SEED IS DELIBERATELY BLANK, and the server was changed to accept that. `url`,
      `selector` and `field` are what a person types in the panel, so requiring them at validation
      time would make a freshly-added step refuse itself — the wave-23 illegal-default-seed defect.
      `_clean_action_config` stores an unconfigured step and the RUNNER fails closed with a
      sentence naming what is missing, which is the same posture the enrich arm takes with
      `profileField`. The values below mirror that validator's defaults exactly.
    */
    if (kind === "web_read")
      return { url: "", selector: "", field: firstField || "",
               attr: "text", all: false, timeoutMs: 20000 };
    /*
      ⭐⭐ W31 QA — THE OTHER FOUR WEB KINDS, and the comment above predicted this exactly one
      kind early. When the owner's revocation of D-51/R5 flipped `web_goto`/`web_fill`/`web_click`/
      `web_repair` to `ready:True`, the catalog-derived seed check went red with
      `MISSING: ['web_click','web_fill','web_goto','web_repair']` — all four would have painted
      faded and PERMANENTLY UNCLICKABLE while the server, the seam and the runner all offered them.
      Three out of four is still an invisible feature.

      ⚠ BLANK FOR THE SAME REASON `web_read` IS BLANK: `url` / `selector` / `value` are what a
      person types in the panel, so seeding them with anything real would either lie or refuse
      itself at validation time. `_clean_action_config` stores the unconfigured step and the RUNNER
      fails closed naming what is missing (`WEB_REQUIRED`, per kind) — which is why these seeds
      carry no field the validator would reject and no field the runner would silently ignore.
      ⚠ `web_fill` seeds `secret: false` EXPLICITLY rather than omitting it: the flag decides
      whether the typed value is masked in the run log, and a masking control that only exists
      once somebody discovers it is a control most people never turn on.
    */
    if (kind === "web_goto")
      return { url: "", timeoutMs: 20000 };
    if (kind === "web_click")
      return { url: "", selector: "", timeoutMs: 20000 };
    if (kind === "web_fill")
      return { url: "", selector: "", value: "", secret: false, timeoutMs: 20000 };
    if (kind === "web_repair")
      return { url: "", selector: "", hint: "", timeoutMs: 20000 };
    /*
      ⭐⭐ 2026-08-07 (owner report) — THE ENRICH ACTION HAD NO BRANCH HERE, SO IT WAS
      PERMANENTLY UNCLICKABLE. `disabled={!c.ready || busy || !seedFor(c.kind)}` and this
      function's `return null` fallback meant the row rendered faded, labelled "Needs a
      database", with an EMPTY tooltip (`seedBlock` had no sentence for it either). The server
      declared it `ready:true`, its config panel was fully built and its runner was correct —
      one client-side list nobody updated made the whole capability unreachable. Owner:
      *"The enrichment action, says that it needs a database. So I can't even click it and
      assign a database? thats wicked."*

      ⛔ IT TAKES NO TABLE, AND THAT IS WHY THE OLD LABEL WAS ALSO WRONG. Enrichment acts on
      the record WALKING THE FLOW — the flow's own target database — so there is nothing to
      assign per action. `verify_automation`'s seed-coverage check now derives its subject from
      the server catalog, so the NEXT ready action added without a seed goes red instead of
      shipping invisible.

      The values mirror `clean_action_config`'s defaults exactly. A seed that disagreed with the
      validator is the wave-23 illegal-seed defect (four kinds shipped a red banner and no card).
    */
    /*
      ⭐⭐ WAVE 30 · W30-T23 / CONTRACT C3 — ONE ARM FOR BOTH ENRICH KINDS.
      The server's own validator branches on `ENRICH_KINDS = ("enrich_instagram","enrich_tiktok")`
      — ONE branch, one set of keys, with `postMetrics`/`commentMetrics` answered `False` for
      TikTok until W30-T10 wires post capture. So the seed is shared for the same reason: a seed
      that disagreed with the validator is the wave-23 illegal-seed defect (four kinds shipped a
      red banner and no card), and TWO seeds for one validator branch is that defect waiting.
      ⚠ The two metric keys are seeded `false` for BOTH, which is what the server already answers
      for TikTok — so nothing changes shape when T10 deletes its `and kind != "enrich_tiktok"`
      clause. Seeding them only for Instagram would have made T10 a client change as well.
      ⛔ THIS ARM AND ITS `seedBlock` SENTENCE HAD TO LAND TOGETHER. D-79's scar was exactly one
      of the two missing: the row rendered faded, labelled "Needs a database" — a claim about
      databases, which was not the problem — with an EMPTY tooltip.
    */
    if (isEnrich(kind))
      return {
        // ⭐ WAVE 28 · R5/R6 — `tier: "anonymous"` and `noFallback: false` are GONE from the seed.
        // R5 retired the free ladder from enrichment, so a new action must not be born naming a
        // source strategy the runner no longer consults. The server keeps ACCEPTING both keys on
        // stored definitions and ignores them (C2, D-65's law) — but a SEED is what a new step
        // starts with, and seeding a dead key is how a retired concept outlives its removal.
        // ⚠ `postMetrics`/`commentMetrics` stay `false` here and that is R6's ruling verbatim
        // ("always both off until toggled on"), matching `clean_action_config`'s reading of an
        // absent key so the seed and the validator cannot disagree.
        postMetrics: false, commentMetrics: false,
        dryRun: false, maxPosts: 10,
        fromView: "", sortField: "first_found", sortDir: "desc",
        // ⚠ `skipRecent: true` MATCHES `_ensure_enrich_step`'s server seed, deliberately. One
        // control must not have two defaults depending on whether the step was added by hand or
        // seeded onto an Instagram search — that is the split-default class this repo has paid
        // for twice ([[default-must-pass-its-own-guard]]). It also cannot surprise on first use:
        // nothing has an `Enriched at` yet, so the cooldown changes nothing until run two, which
        // is exactly when not re-paying is what you want.
        // ⛔ NOT the validator's default. `clean_action_config` reads an ABSENT key as False, so
        // every enrich action stored before today keeps the behaviour it already had — a seed is
        // what a new step starts with, never a rule applied retroactively (D-65).
        limit: 25, skipRecent: true, skipRecentDays: 30,
      };
    if (kind === "group")
      /*
        ⭐ RE-SEEDED FOR C-FORK, and the old seed would now be REFUSED. It was
        `{cond: null, actions: [child]}` — the pre-wave-24 shape, which `clean_actions` no longer
        accepts as a config: the fork's legs live under `branches` and `cond`/`actions` are gone
        from the group's own config entirely. Clicking "If / then" would have produced a red
        banner and no card, which is precisely the illegal-default-seed defect this function's
        header was written about, reproduced by the wave that quotes it.

        MEASURED against `clean_actions` rather than reasoned:
          · a branch with no actions      -> "a branch with no actions inside it does nothing"
          · so the one branch is born with the cheapest legal child, exactly as before — not a
            review, which would also mint a board stage nobody asked for by clicking "If / then".
        ⛔ `label: ""` ON PURPOSE. The SERVER letters the branches by index and calls a null-cond
        last leg "Otherwise", but it PRESERVES any label the client sends — so sending one would
        freeze it, and a branch labelled "A" would still say "A" after the branch above it was
        deleted. Sending nothing keeps the lettering correct by construction, and this fresh
        single branch reads "Otherwise" until it is given a condition, which is what it is.
      */
      return firstField
        ? {
            branches: [
              {
                id: "b1",
                label: "",
                cond: null,
                actions: [
                  { id: "", kind: "update_record", enabled: true, when: null,
                    config: { values: { [firstField]: "" } } },
                ],
              },
            ],
          }
        : null;
    return null;
  };

  /** Why a kind cannot be added yet — the server's own precondition, said before the click. */
  const seedBlock = (kind: string): string => {
    if (kind === "update_record" || kind === "group")
      return "Name the trigger's database first — this needs a column to write.";
    if (kind === "create_record" || kind === "find_records")
      return "There is no blank database to point at yet.";
    /*
      ⛔ NOT `""`. An empty string here renders "Needs a database" with NO tooltip — a disabled
      control that will not say why, which is exactly how the enrich action sat unreachable and
      unexplained. A kind that reaches this line is one somebody forgot to seed, so the fallback
      says the true thing rather than the plausible one: the label above claims a database is
      missing, and for a forgotten seed that claim is a guess.
    */
    return "This action cannot be added yet — it has no starting configuration.";
  };

  /**
   * ⚠ `into` NAMES A BRANCH NOW, not just a group (C-FORK). A fork has several legs and "add an
   * action to this group" stopped being a complete instruction the moment it did — putting it in
   * the first branch by default would silently attach work to whichever leg happens to be first.
   */
  const addAction = (kind: string, into?: { actionId: string; branchId: string }) => {
    const seed = seedFor(kind);
    if (!seed) return;
    const fresh: Action = { id: "", kind, enabled: true, when: null, config: seed };
    if (!into) {
      patchFlow([...actions, fresh]);
    } else {
      patchFlow(
        mapTree(actions, (a) => {
          if (a.id !== into.actionId) return a;
          return {
            ...a,
            config: {
              ...a.config,
              branches: groupBranches(a).map((br) =>
                br.id === into.branchId
                  ? { ...br, actions: [...(br.actions || []), fresh] }
                  : br
              ),
            },
          };
        })
      );
    }
    setAdding(false);
  };

  /** Add an empty-conditioned leg to a fork. The server letters it and enforces the ceiling. */
  const addBranch = (actionId: string) => {
    const seedChild = seedFor("update_record");
    if (!seedChild) return;
    patchFlow(
      mapTree(actions, (a) => {
        if (a.id !== actionId) return a;
        const brs = groupBranches(a);
        return {
          ...a,
          config: {
            ...a.config,
            // ⚠ APPENDED LAST, and the server refuses a null-cond branch that is not last — so a
            // fork that already ends in an Otherwise leg refuses this with its own sentence
            // rather than silently burying the catch-all in the middle, where every branch below
            // it would be dead code.
            branches: [
              ...brs,
              { id: "", label: "", cond: null,
                actions: [{ id: "", kind: "update_record", enabled: true, when: null,
                  config: seedChild }] },
            ],
          },
        };
      })
    );
  };

  const dropBranch = (actionId: string, branchId: string) =>
    patchFlow(
      mapTree(actions, (a) => {
        if (a.id !== actionId) return a;
        const kept = groupBranches(a).filter((br) => br.id !== branchId);
        // A fork with no legs at all "does nothing" — the server says so; do not send an empty
        // list dressed up as an edit.
        if (!kept.length) return a;
        return { ...a, config: { ...a.config, branches: kept } };
      })
    );

  /**
   * R8's numbers for the whole flow, computed ONCE per render rather than per card — the map is
   * built by walking the tree, so asking it per card would be quadratic in a deep fork, and more
   * importantly a per-card computation could not see its siblings and would have to re-derive
   * the position it is being told.
   */
  const stepNos = numberActions(actions);

  /**
   * ⭐ THE ACTION MENU'S GROUP ORDER, FROM THE SERVER (owner item 12b, contract C-ACT).
   *
   * ⛔ NEVER A LITERAL LIST OF GROUP NAMES HERE. The server ships `groupOrder` on every catalog
   * row (1 Web action · 2 Database · 3 Connected · 4 Advanced logic, derived server-side from one
   * table so two rows cannot disagree about their own group). A client
   * `["Web action", "Database", …]` would be a second copy of the catalog's structure, and the
   * day the engine adds or renames a group the client drops it off the end — or drops it
   * entirely — without anything going red.
   *
   * ⚠ AN UNORDERED GROUP SORTS LAST, NOT FIRST, which the server's own gate asserts. `Infinity`
   * and not `0`: a missing number meant "before everything" under a naive `|| 0`, so a server
   * older than this client would have led its menu with whatever it had failed to classify.
   * ⚠ The sort is STABLE over first appearance, so two groups sharing an order keep the payload's
   * sequence rather than an arbitrary one.
   */
  /* ⭐ WAVE 27 · ITEM 33 / C4 — the ordering above moved into `steps.ts` as `groupActions`,
     which does the SAME arithmetic and additionally nests connector rows. Two reasons it moved
     rather than gaining a clause here: `groupTriggers` already does exactly this for the trigger
     picker and the two must not drift, and a pure function in `steps.ts` is one node can run —
     `verify_steps` exercises the nest, which no amount of JSX here could be tested against. */
  const menuGroups = groupActions(catalog);

  /** ONE action row, so the nested and un-nested lists cannot render differently. */
  const actionRow = (c: ActionCatalogRow) => (
    <button
      key={c.kind}
      type="button"
      className={"autox-menu-row" + (c.ready && seedFor(c.kind) ? "" : " is-planned")}
      disabled={!c.ready || busy || !seedFor(c.kind)}
      title={c.ready && !seedFor(c.kind) ? seedBlock(c.kind) : c.detail}
      onClick={() => addAction(c.kind)}
    >
      <span className={"autox-card-mark" + (hasBrandKind(c.kind) ? " is-brand" : "")}>
        <ActionMark kind={c.kind} />
      </span>
      <span className="autox-menu-text">
        <span className="autox-menu-label">
          {c.label}
          {!c.ready ? (
            <span className="autox-soon">Coming soon</span>
          ) : !seedFor(c.kind) ? (
            /* NOT the same state as "coming soon", so not the same word: this one is built and
               waiting on THIS automation, and the title says exactly what is missing. */
            <span className="autox-soon">Needs a database</span>
          ) : null}
        </span>
        <span className="autox-menu-detail">{c.detail}</span>
      </span>
    </button>
  );

  // ── the centre column ────────────────────────────────────────────────────────────────────
  const chip = () => {
    if (!chosen) return null;
    if (!configured)
      return (
        <span className="autox-chip is-warn" title="This trigger cannot fire until it is finished">
          Finish configuration
        </span>
      );
    if (trigger?.paused)
      return <span className="autox-chip is-warn">Paused</span>;
    if (picked && picked.ready === false)
      return <span className="autox-chip is-warn">Not set up</span>;
    const last = automation.runs?.[0];
    if (last)
      return (
        <span className="autox-chip is-ok" title={last.summary}>
          {last.ok ? "Last run succeeded" : "Last run failed"}
        </span>
      );
    return null;
  };

  const actionCard = (a: Action, depth: number, hasNext = false): ReactNode => {
    const row = catalog.find((c) => c.kind === a.kind);
    const isGroup = a.kind === "group";
    const branches = isGroup ? groupBranches(a) : [];
    /**
     * ⭐ THE PERMANENT FIRST STEP (owner ruling 2026-08-06). An Instagram search produces rows
     * and has nowhere to put them until something writes them, so Create record is step 1 and
     * stays. DERIVED from the same rule the server enforces (`ig_action_pinned`) rather than
     * from a stored flag — and the control is HIDDEN rather than disabled, because the server
     * re-inserts the action on the next save, so a delete button here would appear to work and
     * then silently undo itself.
     */
    const pinned =
      automation.kind === "discover_instagram" && depth === 0 && a.id === actions[0]?.id;
    /**
     * ⭐⭐ WAVE 32 · T45 (owner item 10) — CONFIGURED / UNCONFIGURED, and the SERVER decides.
     *
     * ⛔ NOT COMPUTED HERE. The same `engine.action_needs` that fills this list also refuses the
     * run (`400 action_unconfigured`, and `run_now` for the tick and the webhook), so a card
     * cannot claim Configured over an action the run will reject. A client-side "does it look
     * filled in" test would be a second rule that agrees until one of them learns a new key.
     * ⚠ Nested cards get it too: the list is keyed by ACTION ID over the whole flow, branches
     * included, and a step inside an If / then is the one a person is least able to see.
     */
    const needs = (automation.unconfigured || []).find((u) => u.id === a.id)?.needs || [];
    /** Only TOP-LEVEL cards reorder (see `moveAction`) — depth 0, and never while a write is up. */
    const canDrag = depth === 0 && !busy && !pinned;
    return (
      <div className="autox-actionwrap" key={a.id}>
        <div
          className={
            "autox-card" +
            (sel.kind === "action" && sel.id === a.id ? " is-selected" : "") +
            (a.enabled ? "" : " is-off") +
            (isGroup ? " is-group" : "") +
            /* ⚠ THE GUARD IS NOT DECORATION. `dragOver` idles at `""` and a fresh action carries
               `id: ""` until the server names it, so a bare `dragOver === a.id` would be
               `"" === ""` — TRUE AT REST — and every new card would paint as a drop target from
               its first frame. That is wave 20's `is-folddrag` defect exactly, which shipped and
               was seen by the owner before any gate noticed. */
            (dragOver && dragOver === a.id ? " is-dropinto" : "")
          }
          draggable={canDrag}
          onDragStart={
            canDrag
              ? (e) => {
                  draggedRef.current = true;
                  e.dataTransfer.effectAllowed = "move";
                  e.dataTransfer.setData(ACTION_DRAG_TYPE, a.id);
                }
              : undefined
          }
          onDragOver={
            canDrag
              ? (e) => {
                  // Somebody else's drag — a file, a nav row, selected text — is not ours to
                  // accept. Without this test the card would light up for anything dragged over
                  // it and then swallow the drop.
                  if (!e.dataTransfer.types.includes(ACTION_DRAG_TYPE)) return;
                  e.preventDefault();
                  e.dataTransfer.dropEffect = "move";
                  setDragOver(a.id);
                }
              : undefined
          }
          onDragLeave={
            canDrag
              ? (e) => {
                  // Moving onto a CHILD of this card is not leaving it; without this the
                  // highlight flickers off every time the pointer crosses the title.
                  if (e.currentTarget.contains(e.relatedTarget as Node)) return;
                  setDragOver((cur) => (cur === a.id ? "" : cur));
                }
              : undefined
          }
          onDrop={
            canDrag
              ? (e) => {
                  const dragId = e.dataTransfer.getData(ACTION_DRAG_TYPE);
                  setDragOver("");
                  if (!dragId) return;
                  e.preventDefault();
                  moveAction(dragId, a.id);
                }
              : undefined
          }
          onDragEnd={() => {
            setDragOver("");
            // Cleared a tick later: the post-drag click arrives BEFORE this would run.
            window.setTimeout(() => {
              draggedRef.current = false;
            }, 0);
          }}
        >
          <button
            type="button"
            className="autox-card-hit"
            aria-pressed={sel.kind === "action" && sel.id === a.id}
            onClick={() => {
              // The one click a finished drag is allowed to cost is this one.
              if (draggedRef.current) return;
              setSel({ kind: "action", id: a.id });
              // ⭐ WAVE 27 · C11 — clicking a step SHOWS its Properties. The panel is
              // one of two that share the column now, and a click that configured the
              // invisible one would read as a click that did nothing.
              onStepPicked();
            }}
          >
            {/* ⭐ R8's STEP NUMBER, computed once for the whole flow (`numberActions`). The
                TRIGGER carries no number at all — that is the ruling, and it reverses wave 21's
                "Step 1 is always the Trigger" — so the numbers here start at 1 on the first
                ACTION. A fork occupies one number and its branches consume none. */}
            <span className="autox-card-n">{stepNos.get(a.id) || ""}</span>
            <span className={"autox-card-mark" + (hasBrandKind(a.kind) ? " is-brand" : "")}>
              <ActionMark kind={a.kind} />
            </span>
            <span className="autox-card-text">
              <span className="autox-card-title">
                {/* ⛔ NOT "If conditions are met" ANY MORE, and the literal was the problem
                    rather than the wording. C-ACT relabels the `group` kind to "If / then" on
                    the SERVER, so a hard-coded title here was a client paraphrase of a server
                    vocabulary — it would have gone on saying the old words after the catalog
                    changed, which is the one failure this file's header names twice. */}
                {row?.label || a.kind}
              </span>
              {isGroup ? (
                <span className="autox-card-sub">
                  {branches.length === 1
                    ? "1 branch"
                    : `${branches.length} branches`}
                </span>
              ) : (
                <span className="autox-card-sub">{actionSub(a, tables)}</span>
              )}
              {/* ⛔ THE LABEL IS ON EVERY CARD, IN BOTH STATES. Item 10 asks for
                  "Configured / Unconfigured" — showing only the bad one would make a configured
                  action indistinguishable from an action this build has no opinion about, which
                  is the question the label exists to answer. The Unconfigured one carries WHAT is
                  missing, because "Unconfigured" alone on a five-field step is a hunt. */}
              <span
                className={"autox-card-state" + (needs.length ? " is-off" : " is-on")}
                title={needs.length ? `Still needs ${needs.join(", ")}` : undefined}
              >
                {needs.length ? `Unconfigured — needs ${needs.join(", ")}` : "Configured"}
              </span>
            </span>
          </button>
          {pinned ? (
            <span className="autox-card-pin" title="Every search saves what it finds">
              Always first
            </span>
          ) : (
            <button
              type="button"
              className="autox-card-drop"
              disabled={busy}
              aria-label={`Remove ${row?.label || a.kind}`}
              title={`Remove ${row?.label || a.kind}`}
              onClick={() => dropAction(a.id)}
            >
              <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                  strokeLinecap="round" />
              </svg>
            </button>
          )}
        </div>

        {/*
          ⭐ THE FORK (owner item 12a, ruling R8, contract C-FORK). A group used to hold ONE
          nested column; it now holds a LETTERED LANE PER BRANCH, because R8 rules that a fork
          occupies one step number and its legs are alternatives rather than later steps.

          THE LETTER AND THE "Otherwise" ARE THE SERVER'S WORDS — `br.label`, printed, never
          composed. `clean_actions` letters by index and names a null-cond last leg "Otherwise",
          so the lanes re-letter themselves correctly when one is deleted.
          The nesting ceiling is still the SERVER's `maxGroupDepth`, so the add-here affordance
          disappears at exactly the depth `clean_actions` refuses.
        */}
        {isGroup ? (
          <div className="autox-branches">
            {branches.map((br) => (
              <div className="autox-branch" key={br.id || br.label}>
                <div className="autox-branch-head">
                  <span className="autox-branch-letter">{br.label}</span>
                  <span className="autox-branch-cond">
                    {/* ⚠ NOT A RENDERED CONDITION — the tree is edited in Properties, and a
                        second editable copy here would be two controls for one fact. This says
                        only WHICH leg you are looking at. A null cond is the catch-all, and the
                        server has already labelled it, so this says nothing twice. */}
                    {br.cond ? "when its conditions match" : "everything else"}
                  </span>
                  {branches.length > 1 ? (
                    <button
                      type="button"
                      className="autox-branch-x"
                      disabled={busy}
                      aria-label={`Remove branch ${br.label}`}
                      title={`Remove branch ${br.label}`}
                      onClick={() => dropBranch(a.id, br.id)}
                    >
                      <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                        <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                          strokeLinecap="round" />
                      </svg>
                    </button>
                  ) : null}
                </div>
                <div className="autox-nest">
                  {(br.actions || []).map((k) => actionCard(k, depth + 1))}
                  {depth + 1 < (vocab?.maxGroupDepth ?? 2) || !(br.actions || []).length ? (
                    <button
                      type="button"
                      className="autox-add is-nested"
                      disabled={busy || !seedFor("update_record")}
                      title={seedFor("update_record") ? undefined : seedBlock("update_record")}
                      onClick={() => addAction("update_record", { actionId: a.id, branchId: br.id })}
                    >
                      + Add an action in {br.label}
                    </button>
                  ) : null}
                </div>
              </div>
            ))}
            <button
              type="button"
              className="autox-add is-nested"
              disabled={busy || !seedFor("update_record")}
              title={seedFor("update_record") ? undefined : seedBlock("update_record")}
              onClick={() => addBranch(a.id)}
            >
              + Add a branch
            </button>
          </div>
        ) : null}

        {/*
          THE ARROW BACK INTO THE FLOW (item 12a). The lanes are alternatives and exactly one of
          them runs — the engine takes the first matching branch and breaks — so they REJOIN, and
          without a mark saying so a fork at the end of a column reads as several parallel endings.
          Drawn only when there IS a next step to rejoin: an arrow into nothing is a promise the
          flow does not keep.
        */}
        {isGroup && hasNext ? (
          <div className="autox-merge" aria-hidden="true">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor"
              strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
              <path d="M8 2.6v10.8M5.2 10.6 8 13.4l2.8-2.8" />
            </svg>
          </div>
        ) : null}
      </div>
    );
  };

  return (
    <>
      <div className="autox-flow">
        {/* ── TRIGGER ─────────────────────────────────────────────────────────────────── */}
        <div className="autox-step">
          <div className="autox-side">
            <span className="autox-tag">Trigger</span>
            {chip()}
          </div>
          <div className="autox-main">
            {chosen && options.length ? (
              <div
                className={
                  "autox-card is-trigger" + (sel.kind === "trigger" ? " is-selected" : "")
                }
              >
                <button
                  type="button"
                  className="autox-card-hit"
                  aria-pressed={sel.kind === "trigger"}
                  onClick={() => {
                    setSel({ kind: "trigger", id: "" });
                    onStepPicked();          // C11, same rule as an action card
                  }}
                >
                  <span
                    className={"autox-card-mark" + (hasBrandKind(triggerKey) ? " is-brand" : "")}
                  >
                    <TriggerMark kind={triggerKey} />
                  </span>
                  <span className="autox-card-text">
                    <span className="autox-card-title">
                      {picked?.label || triggerKey}
                    </span>
                    {trigger?.table ? (
                      <span className="autox-card-sub">
                        In {tableLabel(tables, trigger.table)}
                      </span>
                    ) : null}
                  </span>
                </button>
              </div>
            ) : (
              /*
                THE EMPTY STATE (image 1): a dashed add-box and the server's own suggested
                triggers. One line of chrome, no tour (R13) — the list IS the explanation, and
                it is the server's list so it cannot describe a trigger we removed.
              */
              <>
                {/* THE BOX AND ITS MENU ARE ONE UNIT (see `addWrap`). The menu USED to render at
                    the bottom of this component, outside `.autox-flow` entirely, and became a
                    third column of the flex row that holds the canvas and Properties — the
                    owner's ERROR 4. */}
                <div className="autox-trigadd" ref={addWrap}>
                  <button
                    type="button"
                    className="autox-add is-empty"
                    disabled={busy || !options.length}
                    aria-haspopup="listbox"
                    aria-expanded={picking}
                    onClick={() => setPicking((v) => !v)}
                  >
                    + Add trigger
                  </button>
                  {/* ⭐ WAVE 25 item 5b (C2) — `TriggerPicker`, the SAME component Properties →
                      Trigger details renders in its compact form. Category first (Time /
                      Database / Connector) with connector rows nested under their product. */}
                  {picking ? (
                    <TriggerPicker
                      variant="menu"
                      options={options}
                      value={triggerKey}
                      disabled={busy}
                      onPick={onPickTrigger}
                      onDismiss={() => setPicking(false)}
                    />
                  ) : null}
                </div>
                {options.length ? (
                  <div className="autox-suggest">
                    <p className="autox-suggest-head">Suggested triggers</p>
                    {options
                      // ⭐ 2026-08-07 (owner ruling) — MANUAL IS OFFERED AGAIN. It was excluded
                      // (`t.key !== "manual"`) because picking it stored NOTHING and bounced
                      // straight back to this empty state — "a control that undoes itself is
                      // worse than no control", correct while that was true. `clean_trigger` now
                      // STORES `{key:'manual'}`, so the pick sticks, `chosen` goes true and
                      // Configuration opens. Hiding it now would leave the one trigger a person
                      // most expects to find as the only one they cannot choose.
                      .filter((t) => t.ready !== false && !t.planned)
                      .slice(0, SUGGESTED)
                      .map((t) => (
                        <button
                          key={t.key}
                          type="button"
                          className="autox-suggest-row"
                          disabled={busy}
                          onClick={() => onPickTrigger(t.key)}
                        >
                          <span
                            className={
                              "autox-card-mark" + (hasBrandKind(t.key) ? " is-brand" : "")
                            }
                          >
                            <TriggerMark kind={t.key} />
                          </span>
                          {t.label}
                        </button>
                      ))}
                  </div>
                ) : (
                  <p className="auto-note">This server did not offer a trigger list.</p>
                )}
                {/* ONE LINE (R13), and it is what is TRUE of this state rather than a caption
                    for the box above it: with nothing chosen, Run now is the only thing that
                    starts this automation. Airtable's empty state means "it cannot run"; ours
                    does not, and saying so is the difference between a screen that is honest
                    and one that merely looks the same. */}
                <p className="auto-hint">Until then, only Run now starts it.</p>
              </>
            )}
          </div>
        </div>

        {/* ── ACTIONS ─────────────────────────────────────────────────────────────────── */}
        <div className="autox-step">
          <div className="autox-side">
            <span className="autox-tag">Actions</span>
          </div>
          <div className="autox-main">
            {actions.map((a, i) => actionCard(a, 0, i < actions.length - 1))}

            {/*
              ⛔ THE MACHINE STEPS ARE NOT CARDS ANY MORE (owner item 5, contract C-CFG). They
              were engine-derived read-only cards sitting under the owner's own actions — "fetch
              the page", "Bright Data", "Anonymous", "Write" — so the centre column mixed two
              different things: what the AUTOMATION is, which nobody chose and nobody can reorder,
              and what the OWNER added, which is the whole subject of this builder. Their
              configuration and their switches moved to Properties → Configuration →
              "How this fetches", one section per panel.

              ⚠ THE ENGINE STILL RUNS THEM. `graph()` emits the same nodes; this surface simply
              stops DRAWING them, which is why the switches had to move rather than go — R7 names
              Bright Data (money) and Write's dry run (reads and reports without writing a row) as
              controls that must survive the cards that carried them.
            */}

            <button
              type="button"
              className="autox-add"
              disabled={busy || !catalog.length}
              onClick={() => setAdding((v) => !v)}
            >
              + Add advanced logic or action
            </button>

            {/* THE ACTION MENU (images 7/8): the server's catalog, grouped by its own `group`
                key, with `ready:false` rows faded and carrying the server's reason. A shorter
                menu would imply those actions do not exist — the owner asked to see all of
                them, and `clean_actions` refuses the unready ones at the door, so faded is a
                wall rather than a decoration. */}
            {adding ? (
              <div className="autox-menu" role="menu">
                {menuGroups.map((g) => (
                  <div className="autox-menu-group" key={g.key}>
                    <p className="autox-menu-head">{g.key}</p>
                    {/* ⭐ WAVE 27 · ITEM 33 / C4 — the group's OWN rows first, then one nest per
                        connector. `<details>` rather than a hand-built disclosure: it IS the
                        chevron-and-submenu the reference shows, it opens on Enter and Space
                        without a keydown handler, and it needs no open/closed state of its own
                        to get wrong. Closed by default — the reference shows collapsed rows,
                        and a connector nobody is using should cost one line, not six. */}
                    {[...g.rows, ...g.sub].map((entry) => ("rows" in entry ? (
                      <details className="autox-menu-nest" key={`sub:${entry.key}`}>
                        <summary className="autox-menu-row autox-menu-sum">
                          {/* ⭐ WAVE 30 · ITEM 7 / R4 — THE COLLAPSED ROW GETS AN IDENTITY.
                              This is the row the owner clicks before choosing Instagram or
                              TikTok, and until now it was the only row in the menu with
                              nothing on its left: the chevron, then a bare word. The mark is
                              resolved from the connector KEY, so a connector the server adds
                              tomorrow gets a slot for free and simply renders no logo. */}
                          {brandForConnector(entry.key) ? (
                            <span className="autox-card-mark is-brand">
                              {brandForConnector(entry.key)}
                            </span>
                          ) : null}
                          <span className="autox-menu-text">
                            <span className="autox-menu-label">{entry.label}</span>
                            <span className="autox-menu-detail">
                              {entry.rows.length} action{entry.rows.length === 1 ? "" : "s"}
                            </span>
                          </span>
                        </summary>
                        {entry.rows.map((c) => actionRow(c))}
                      </details>
                    ) : actionRow(entry)))}
                  </div>
                ))}
              </div>
            ) : null}
          </div>
        </div>
      </div>

      {/* ── PROPERTIES ──────────────────────────────────────────────────────────────────── */}
      <aside
        className={"auto-panel autox-props" + (showProperties ? " is-appearing" : "")}
        aria-label="Properties"
        /* ⭐ WAVE 27 · C11 — HIDDEN, not unmounted, and that is deliberate. This panel holds
           live editing state (the name field's text, a half-typed cron); unmounting it on every
           toggle would discard whatever was in flight. `hidden` also takes it out of the
           accessibility tree, so a screen reader is not offered two panels when one is drawn. */
        hidden={!showProperties}
      >
        <div className="auto-panel-head">
          {panelTabs}
          {/*
            THREE STATES, because this panel now holds two save disciplines. The discrete choices
            (a trigger, an action, a switch, a branch) persist as they are made; the machine
            steps' fields, which moved in here with item 5, commit with the header's Save. A
            two-state stamp had to be wrong about one of them, and "All changes saved" printed
            over an unsaved column map is the direction that loses work.
          */}
          <span
            className={"autox-saved" + (busy ? " is-busy" : dirty ? " is-dirty" : "")}
          >
            {busy ? "Saving…" : dirty ? "Unsaved changes — press Save" : "All changes saved"}
          </span>
        </div>

        {/*
          ⭐ THE NAME (item 15b). It is ABOVE the selection-dependent body rather than inside the
          trigger's face, because it is a property of the AUTOMATION and not of whichever step
          happens to be selected — clicking an action card must not make the name disappear.
          It commits on blur; the caller writes it and prints any refusal.
        */}
        <div className="auto-field">
          <label htmlFor="autox-name">Name</label>
          <input
            id="autox-name"
            className="auto-input"
            value={name}
            disabled={busy}
            placeholder="Name this automation"
            onChange={(e) => onNameText(e.target.value)}
            onBlur={() => onNameCommit()}
          />
        </div>

        {sel.kind === "trigger" ? (
          <TriggerProps
            automation={automation}
            triggerKey={triggerKey}
            options={options}
            picked={picked}
            table={table}
            tables={tables}
            ops={ops}
            nullaryOps={nullaryOps}
            vocab={vocab}
            oauth={oauth}
            busy={busy}
            nodes={nodes}
            onToggleNode={onToggleNode}
            renderNodeBody={renderNodeBody}
            onAskChange={setConfirmKey}
            onPatchTrigger={patchTrigger}
            onPatchConfig={patchConfig}
            onPickTrigger={onPickTrigger}
            onRunNow={onRunNow}
            scheduleFace={scheduleFace}
            schedules={schedules}
            /* ⭐ R14 — THE SAME `chosen` THE FLOW COLUMN USES, passed rather than recomputed.
               Both halves of one screen answer "has a trigger been picked": the centre column
               draws the empty state, Properties hides Configuration. Two derivations of that
               would eventually disagree, and the screen would then show an empty-state add-box
               beside a filled-in Configuration section — which is not a state the product has. */
            chosen={chosen}
          />
        ) : (
          <ActionProps
            action={findAction(actions, sel.id)}
            /* ⭐ THE SAME RULE `actionCard` DERIVES AND THE SERVER ENFORCES (`ig_action_pinned`),
               passed down rather than re-derived a third time. The panel needs it because the
               pinned step is the one action in the product whose value map the ENGINE NEVER
               READS — see `ActionProps`. */
            pinned={
              automation.kind === "discover_instagram" && sel.id === actions[0]?.id
            }
            catalog={catalog}
            tables={tables}
            onTablesChanged={onTablesChanged}
            walkFields={walkFields}
            /* ⭐ WAVE 26 · ITEM 5 / R10 — REQUIRED, and it is NOT the same question as
               `walkFields`. An empty field list has two causes that need opposite answers: this
               flow has no record walking it at all (say so, point at the trigger), or it has one
               whose database has no columns yet (an empty picker is then correct). Passing only
               the list forced the panel to guess, which is how the empty picker that produced
               "the condition names no field" got shipped in the first place. */
            walkTable={walkTable}
            ops={ops}
            nullaryOps={nullaryOps}
            vocab={vocab}
            busy={busy}
            onEdit={(change) => editAction(sel.id, change)}
          />
        )}
      </aside>

      {/* THE CONFIRM (image 6). A trigger change can invalidate the configuration under it, so
          it ASKS — and it says what it will cost rather than "are you sure". */}
      {confirmKey ? (
        <div className="autox-confirm" role="dialog" aria-label="Change the trigger">
          <p className="autox-confirm-title">Change the trigger?</p>
          <p className="autox-confirm-body">
            Anything configured for {picked?.label || triggerKey} is dropped.
          </p>
          <div className="autox-confirm-acts">
            <button type="button" className="auto-btn" onClick={() => setConfirmKey("")}>
              Cancel
            </button>
            <button
              type="button"
              className="auto-btn is-danger"
              onClick={() => {
                onPickTrigger(confirmKey);
                setConfirmKey("");
              }}
            >
              Change trigger
            </button>
          </div>
        </div>
      ) : null}

      {/* ⛔ THE PICKER USED TO RENDER HERE, and here is outside both columns. `.auto-work` is a
          flex row of `.autox-flow` + `.autox-props`, so a third child was laid out as a third
          COLUMN — the menu appeared past the right edge of the Properties panel and squeezed the
          canvas until the suggested triggers wrapped one word per line (owner's ERROR 4). It is
          rendered beside its own "+ Add trigger" box now; see `addWrap`. */}
    </>
  );
}

/** One action's subtitle — what it will DO, composed from its own config. */
function actionSub(a: Action, tables: UserTable[]): string {
  const cfg = a.config || {};
  if (a.kind === "update_record") {
    const keys = Object.keys((cfg as { values?: Record<string, unknown> }).values || {})
      .filter(Boolean);
    return keys.length ? `Sets ${keys.join(", ")}` : "No values yet";
  }
  if (a.kind === "create_record") {
    const t = String((cfg as { table?: string }).table || "");
    return t ? `Into ${tableLabel(tables, t)}` : "No database yet";
  }
  if (a.kind === "find_records") {
    const t = String((cfg as { table?: string }).table || "");
    return t ? `In ${tableLabel(tables, t)}` : "No database yet";
  }
  return "";
}

function findAction(list: Action[], id: string): Action | null {
  for (const a of list) {
    if (a.id === id) return a;
    // ⚠ THROUGH THE BRANCHES (C-FORK). This read `config.actions`, which a fork no longer has —
    // so selecting any action inside one would have found nothing and the Properties panel would
    // have said "that action is no longer part of this flow" about a card visibly on screen.
    if (a.kind === "group")
      for (const br of groupBranches(a)) {
        const hit = findAction(br.actions || [], id);
        if (hit) return hit;
      }
  }
  return null;
}

/*
 * ⛔ `nodePanel()` IS GONE (item 5). It rendered ONE machine node's panel, chosen by the card the
 * reader had clicked, and included a "that step is no longer part of this automation" branch for
 * a selection the graph had since dropped. Both facts died with the cards: the panels are now
 * rendered together under "How this fetches", keyed by PANEL rather than by node id, so there is
 * no selection left to go stale.
 */

// ── the Properties panel's two faces ─────────────────────────────────────────────────────────

function TriggerProps({
  automation,
  triggerKey,
  options,
  picked,
  table,
  tables,
  ops,
  nullaryOps,
  vocab,
  oauth,
  busy,
  nodes,
  onToggleNode,
  renderNodeBody,
  onAskChange,
  onPatchTrigger,
  onPatchConfig,
  onPickTrigger,
  onRunNow,
  scheduleFace,
  schedules,
  chosen,
}: {
  automation: Automation;
  triggerKey: string;
  options: TriggerOption[];
  picked: TriggerOption | null;
  table: UserTable | null;
  tables: UserTable[];
  ops: string[];
  nullaryOps: string[];
  vocab?: FlowVocab;
  oauth: OAuthStatus | null;
  busy: boolean;
  /** The engine's machine steps (item 5) — their switches and bodies live under Configuration. */
  nodes: GraphNode[];
  onToggleNode: (nodeId: string) => void;
  renderNodeBody: (panel: string) => ReactNode;
  /** Ask before a trigger change that can invalidate the config under it (image 6). */
  onAskChange: (key: string) => void;
  onPatchTrigger: (patch: Record<string, unknown>) => void;
  /** Writes the automation's OWN config — the database a table-less trigger has nowhere
   *  else to name (owner report 2026-08-07). Spreads on the way in; see `patchConfig`. */
  onPatchConfig: (patch: Record<string, unknown>) => void;
  onPickTrigger: (key: string) => void;
  onRunNow: () => void;
  scheduleFace: ReactNode;
  schedules: boolean;
  /**
   * ⭐ WAVE 25 item 5b (ruling R14) — HAS A TRIGGER BEEN PICKED AT ALL?
   *
   * REQUIRED and passed IN, never re-derived: it is the same `chosen` the centre column gates its
   * empty state on, and the honest test is what the DEFINITION holds rather than what the picker
   * displays (`triggerKey` derives "manual" whenever nothing is stored, so anything computed from
   * it is true for every automation ever — a mistake this file already made once and only a
   * screenshot caught).
   */
  chosen: boolean;
}) {
  const trigger = automation.trigger || null;
  const provider = picked?.connect?.provider || "";
  const connected = !!(provider && oauth?.[provider]?.connected);
  const startUrl = picked?.connect?.startUrl || "";
  const needsTable = !!trigger && "table" in trigger;
  /**
   * ⭐⭐ 2026-08-07 — DOES THIS AUTOMATION HAVE TO NAME ITS OWN DATABASE?
   *
   * True for a `plain` automation whose trigger carries no table — which INCLUDES the state where
   * no trigger is stored at all, and that inclusion is the whole fix. `clean_trigger` stores
   * nothing for `manual`/`schedule` by design, so those automations hold `trigger: null`, `chosen`
   * is false, and W25/R14's "Configuration does not render until a trigger is picked" hid the
   * Database picker below from the exact automations that cannot get a database any other way.
   * The owner hit it twice: *"when the Trigger is Manual, it says that I need to bound it to a
   * database, how?"* — and the honest answer was that there was no how.
   *
   * ⚠ It is the SAME condition the picker itself renders on, named once and used twice, so the
   * section cannot open without the control or the control appear without its section.
   */
  const needsOwnTable = automation.kind === "plain" && !needsTable;
  const last = automation.runs?.[0];
  /** ITEM 22 / D-70 / R12 — the shared Run guard (see `runBlock`). */
  const runState = runBlock(automation);

  return (
    <>
      <h3>Trigger details</h3>
      <div className="auto-field">
        {/*
          ⭐ WAVE 25 item 5b (C2) — THE NATIVE `<select>` IS GONE, AND THIS IS THE OWNER'S ITEM.
          `reference/ERROR 3.png`: eleven triggers listed flat, in `<optgroup>`s captioned
          "Standard" and "Sources", with NO ICONS — four inches from a "+ Add trigger" menu that
          draws every one of them with a mark. It is the same `TriggerPicker` in both places now,
          category first, connector rows nested under Gmail / Webhooks / Scraper / TikTok.

          ⚠ `<label>` WITHOUT `htmlFor`, DELIBERATELY. The control is a `<button>` opening a
          listbox, not a form field with an id to point at; an `htmlFor` naming an element that
          is not a labelable control is a relationship a screen reader is told about and cannot
          use. The button carries its own accessible name from its content and `aria-haspopup`.

          ⛔ THE CONFIRM RULE STAYS HERE, where the automation is. A trigger change can invalidate
          the configuration under it, so it ASKS when there IS something configured (image 6) —
          and that is a fact about this automation, not about a picker. `TriggerPicker` reports a
          choice; what a choice COSTS is the builder's to know.
        */}
        {/* ⚠ NO CLASS. `.auto-field > label` already styles every label in this panel
            (3xs / 600 / muted), and `.auto-field-label` adds a 12px top margin for the
            headings that are NOT inside an `.auto-field`. Using it here would put this one
            label 12px lower than the six beside it — DESIGN.md 2's "a panel matches its
            SIBLING's rendered values", which is a rule about pixels, not about tokens. */}
        <label>Trigger type</label>
        <TriggerPicker
          variant="field"
          options={options}
          value={triggerKey}
          disabled={busy}
          onPick={(next) => {
            if (next === triggerKey) return;
            if (trigger && trigger.configured !== false) onAskChange(next);
            else onPickTrigger(next);
          }}
        />
      </div>
      {/*
        ⭐ THE DESCRIPTION IS THE SERVER'S, AND IT RIDES NOW (wave 24, C-TYPES). This block used
        to be a comment explaining why there was NO paragraph here: Airtable prints two sentences
        under this select (image 3), ours would have been a client paraphrase of a server
        vocabulary, and the note said "when `detail` rides, it renders here and cannot disagree
        with the engine". `TriggerOption.detail` landed this wave, so the paragraph is the
        engine's own sentence, printed verbatim and never composed with anything.
      */}
      {picked?.detail ? <p className="auto-hint">{picked.detail}</p> : null}
      {picked && picked.ready === false && !picked.planned ? (
        <div className="autob-needs">
          <span className="autob-needs-text">
            {connected
              ? "Connected — this trigger is still being switched on for this deployment."
              : "This trigger is not set up yet."}
          </span>
          {!connected && startUrl ? (
            <a className="auto-btn is-primary autob-connect" href={startUrl}>
              Connect
            </a>
          ) : null}
        </div>
      ) : null}

      {/*
        ⭐ WAVE 25 item 5b (ruling R14) — CONFIGURATION DOES NOT RENDER UNTIL A TRIGGER IS PICKED.
        Owner, verbatim: *"let's not show Configuration at the first creation (this is
        overwhelming for first time users)"*. A brand-new automation opens on the trigger picker
        with nothing chosen, and every control below is a question ABOUT a trigger — a Database
        select, watched columns, a view, a Gmail query, a hook URL. Asking them before there is a
        trigger to ask them about is a form for a decision nobody has made.

        ⛔ ONCE PICKED IT RENDERS EXPANDED, and that is the other half of the ruling rather than an
        omission: at that point the section is REQUIRED (`configured:false` rides the wire and the
        card says "finish configuration"), so a collapsed heading would hide the thing the surface
        is simultaneously telling the reader to go and do.

        ⚠ THE WHOLE SECTION, HEADING INCLUDED. Rendering the `<h3>` over nothing is the state R13
        forbids — a heading over an empty region says "there should be something here", which is a
        different and false statement. This is `null`, not an empty fragment.
      */}
      {/* ⭐ 2026-08-07 — `|| needsOwnTable`: R14's rule was "do not render Configuration before a
          trigger is picked", and it is intact for every trigger that stores one. What it must not
          also mean is "a manual automation has nothing to configure" — it has exactly one thing,
          the database its steps walk, and no other surface can name it. See `needsOwnTable`. */}
      {!chosen && !needsOwnTable ? null : (
      <>
      <h3>Configuration</h3>
      {needsTable ? (
        <div className="auto-field">
          <label htmlFor="autox-ttable">
            <span className="autox-req">*</span> Database
          </label>
          <select
            id="autox-ttable"
            className="auto-input"
            value={trigger?.table || ""}
            disabled={busy}
            onChange={(e) => onPatchTrigger({ table: e.target.value })}
            data-role="trigger-table"
          >
            <option value="">Select a database…</option>
            {trigger?.table && !tables.some((t) => t.key === trigger.table) ? (
              <option value={trigger.table}>{trigger.table} (not visible to you)</option>
            ) : null}
            {tables.map((t) => (
              <option key={t.key} value={t.key}>
                {t.label}
              </option>
            ))}
          </select>
        </div>
      ) : null}

      {/*
        ⭐⭐ 2026-08-07 (owner report) — THE DATABASE A TABLE-LESS TRIGGER HAS NOWHERE ELSE TO NAME.
        Owner: *"how come, enrich instagram when standalone 'manual' trigger, doesn't have a
        database that it should point to? dont make this mistake again."*

        MEASURED across the trigger vocabulary: `manual`, `schedule` and `email` carry NO `table`,
        so `needsTable` is false and the picker above never rendered — while `AutomationDetail`'s
        Properties picker is gated to `scrape_db` / `field_instagram`, BOTH RETIRED KINDS. So
        **nothing in the client wrote `config.targetTable` for a `plain` automation**, and
        `run_plain` answered *"no database is bound yet — pick one on the trigger, or in
        Properties"*: a refusal naming two doors, neither of which existed. Every scheduled or
        manual flow — the owner's *"on a schedule, enrich these sets of influencer names"* — was
        unbuildable.

        ⛔ `plain` ONLY, and that is what keeps it from being a second control for one fact. Every
        other kind names its database somewhere of its own: an Instagram search through the pinned
        Create record (W25/R2 made that action authoritative and `targetTable` follows it), and the
        two retired kinds through their own Properties panels. Widening this would put two pickers
        on one key and let them disagree, which is the exact defect R2 was written to end.
      */}
      {needsOwnTable ? (
        <div className="auto-field">
          <label htmlFor="autox-cfgtable">
            <span className="autox-req">*</span> Database
          </label>
          <select
            id="autox-cfgtable"
            className="auto-input"
            data-role="config-table"
            value={String(
              (automation.config as { targetTable?: string } | undefined)?.targetTable || ""
            )}
            disabled={busy}
            onChange={(e) => onPatchConfig({ targetTable: e.target.value })}
          >
            <option value="">Select a database…</option>
            {tables.map((t) => (
              <option key={t.key} value={t.key}>
                {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
              </option>
            ))}
          </select>
          <p className="auto-hint">
            The records this automation&rsquo;s steps walk. A trigger like Manual or a schedule does
            not name one on its own.
          </p>
        </div>
      ) : null}

      {triggerKey === "event_field" ? (
        <>
          {/*
            ⛔ "WATCHED COLUMN" IS GONE (owner item 7, C-TRIG law 4). "When a record matches
            conditions" is a FILTER, and a watched column was a second, different question
            answered in the same box — the trigger fired on a column changing AND on the
            conditions holding, which is two triggers wearing one name.
            ⚠ THE SERVER WENT FIRST, and that ordering was the point: `clean_trigger` stopped
            reading `field` (C posted law 4 done) BEFORE this control came out. Deleting the
            control while the validator still read the key would have left a stored watched
            column that nothing displays and nothing can clear — and deleting the key while the
            control still showed it would have made every Save silently drop what the user
            picked. The CONDITION is what completes this trigger now: with none, it rides
            `configured:false` and says so.
          */}
          <p className="auto-field-label">
            <span className="autox-req">*</span> Conditions
          </p>
          <CondBuilder
            cond={trigger?.when || null}
            onChange={(next) => onPatchTrigger({ when: next })}
            fields={table?.fields || []}
            ops={ops}
            nullaryOps={nullaryOps}
            maxDepth={vocab?.maxCondDepth ?? 3}
            maxChildren={vocab?.maxCondChildren ?? 12}
            disabled={busy}
          />
        </>
      ) : null}

      {triggerKey === "record_updated" ? (
        <div className="auto-field">
          <label htmlFor="autox-twatch">Watched columns</label>
          <select
            id="autox-twatch"
            className="auto-input"
            multiple
            size={5}
            value={trigger?.fields || []}
            disabled={busy}
            onChange={(e) =>
              onPatchTrigger({
                fields: Array.from(e.target.selectedOptions).map((o) => o.value),
              })
            }
          >
            {(table?.fields || []).map((f) => (
              <option key={f.key} value={f.key}>
                {f.label}
              </option>
            ))}
          </select>
          <p className="auto-hint">Select none to fire on any column.</p>
        </div>
      ) : null}

      {triggerKey === "enters_view" ? (
        <div className="auto-field">
          <label htmlFor="autox-tview">
            <span className="autox-req">*</span> View
          </label>
          {/*
            ⭐ FOUR STATES, AND THREE OF THEM ARE SENTENCES (owner item 8, C-TYPES).
            `views` now rides `GET /automations/tables`, so this control is live — but "drop the
            note" would have collapsed it to two states and rebuilt the exact defect the contract
            forbids. Absent and empty are DIFFERENT FACTS:
              · no database chosen        -> choose one first
              · `views` ABSENT            -> the server offered nothing (a server older than this
                                             client). Saying "no views" here would be a claim
                                             nobody measured.
              · `views` present and []    -> this database genuinely has none. That IS measured,
                                             and it is the one that tells the reader to go and
                                             make a view rather than to go and find an admin.
              · non-empty                 -> the picker.
          */}
          {!table ? (
            <p className="auto-note">Choose a database first.</p>
          ) : !table.views ? (
            <p className="auto-note">This server did not offer a view list for that database.</p>
          ) : !table.views.length ? (
            <p className="auto-note">
              That database has no saved views yet — make one on its grid and it appears here.
            </p>
          ) : (
            <select
              id="autox-tview"
              className="auto-input"
              value={trigger?.viewId || ""}
              disabled={busy}
              onChange={(e) => onPatchTrigger({ viewId: e.target.value })}
            >
              <option value="">Select a view…</option>
              {/*
                ⚠ THE STORED VALUE IS ALWAYS AN OPTION, and this control did not have that guard.
                A <select> whose `value` matches no <option> renders the FIRST one — here
                "Select a view…", whose value is `""` — so an `enters_view` trigger pointed at a
                view that has since been deleted, or at one the server deliberately withholds
                (another user's personal view, a share that does not name this viewer), would have
                LOOKED unconfigured and the next patch would have written the blank over it. This
                repo has paid for that twice; the two "(not in this database)" options elsewhere
                in this file exist for the same reason.
              */}
              {trigger?.viewId && !table.views.some((v) => v.id === trigger.viewId) ? (
                <option value={trigger.viewId}>{trigger.viewId} (not offered here)</option>
              ) : null}
              {table.views.map((v) => (
                <option key={v.id} value={v.id}>
                  {v.label}
                </option>
              ))}
            </select>
          )}
        </div>
      ) : null}

      {triggerKey === "email" ? (
        <div className="auto-field">
          <label htmlFor="autox-tquery">Gmail search</label>
          <input
            id="autox-tquery"
            className="auto-input"
            defaultValue={trigger?.query || ""}
            disabled={busy}
            placeholder="from:orders@example.com"
            // FREE TEXT COMMITS ON BLUR — per-keystroke would PATCH a half-typed query.
            onBlur={(e) => onPatchTrigger({ query: e.target.value })}
          />
        </div>
      ) : null}

      {triggerKey === "webhook" && trigger?.token ? (
        <div className="auto-field">
          <label htmlFor="autox-thook">Hook URL</label>
          <input
            id="autox-thook"
            className="auto-input is-mono"
            readOnly
            value={`/api/v1/automations/hook/${trigger.token}`}
          />
          <p className="auto-hint">Minted once. It survives every other change to this trigger.</p>
        </div>
      ) : null}

      {/* THE SCHEDULE, rendered by the one component that owns the cron round-trip.
          ⚠ NOT `triggerKey === "schedule"` ANY MORE (item 7, C-TRIG). `ig_profile_match` watches
          nothing — it MAKES rows, on the cron — so its Configuration carries these controls
          "always", and the caller says which keys those are. */}
      {schedules ? scheduleFace : null}
      {triggerKey === "manual" ? (
        <p className="auto-hint">
          It runs when you press Run once now, and nothing else starts it.
        </p>
      ) : null}
      </>
      )}

      {/*
        ⭐ HOW THIS FETCHES (owner item 5, contract C-CFG) — the machine steps' switches and
        config bodies, below the trigger's own fields, under ONE sub-heading.

        ⛔ ONE SECTION PER PANEL, NOT PER NODE (`groupByPanel`, and its note is the reason). Four
        of `field_instagram`'s nodes share `panel: "capture"` and both of `discover_instagram`'s
        share `panel: "find"`, so a section per node would print one body four times and mount the
        discovery filter twice against a single `preds` array.

        ⛔ AND THE SWITCHES ARE THE POINT, not a leftover. R7: Bright Data buys exact counts with
        MONEY and Write's switch is the difference between a run that writes rows and one that
        reads and reports. They were on the cards this wave deleted, so deleting the cards without
        moving them would have retired two shipped controls silently. Each still posts to the
        node-toggle door — the server decides what a switch means, this only says which node.

        `plain` automations have no machine nodes at all, so the whole section is absent for them
        rather than an empty heading (R6 makes that the common case from now on).

        ⭐ WAVE 26 · ITEM 17 / R15 — THE PROSE IS GONE AND THE SWITCHES STAYED, which is the whole
        ruling. The owner quoted this section back verbatim — *"How this fetches / Find profiles /
        Bio contains skincare… / Collect results / Takes about 20 minutes / Up to 10 profiles ·
        about $0.025"* — and asked for it gone. Every line of that quote is server-composed
        (`automation_engine.graph`), and it maps EXACTLY onto three renderers, which is why the
        deletion could be surgical rather than a section removal:
          · `n.subtitle`        -> "Bio contains skincare…" and "Takes about 20 minutes" (`:5030`, `:5036`)
          · `g.nodes[0].detail` -> "Up to 10 profiles · about $0.025" (`:5032`) — the ESTIMATE LINE
          · `n.title`/`<h3>`    -> "How this fetches", "Find profiles", "Collect results" — KEPT
        ⛔ THE HEADING WAS A SYMPTOM, NOT THE SUBJECT. Deleting the section would have retired the
        Bright Data MONEY switch and the write node's DRY RUN with it — the two controls that were
        moved here precisely so deleting the cards would not retire them silently. They are the
        `n.toggle` block below and they are untouched.
        ⚠ `AutomationFind`'s "What it costs" estimate is NOT this line and is NOT in scope: it is
        the ANSWER to a button a person pressed, and it is the only surface carrying D-23's
        SPEC-basis caveat. The read-only paragraph went; the control did not.
      */}
      {nodes.length ? (
        <>
          <h3>How this fetches</h3>
          {groupByPanel(nodes).map((g) => (
            <div className="autox-machine" key={g.panel}>
              {g.nodes.map((n) => (
                <div className="autox-machine-row" key={n.id}>
                  <span
                    className={"autox-card-mark" + (hasBrandKind(n.kind) ? " is-brand" : "")}
                  >
                    <ActionMark kind={n.kind} />
                  </span>
                  <span className="autox-machine-text">
                    <span className="autox-machine-title">{n.title}</span>
                  </span>
                  {/* ⭐ ITEM 18 / R14 — the per-node status dot stood here and is deleted. The
                      node already carries its own `ActionMark` above; a coloured dot beside it was
                      the second thing on one row claiming to say what this step is. */}
                  {n.toggle ? (
                    <button
                      type="button"
                      className={"auto-step-switch" + (n.enabled ? " is-on" : "")}
                      disabled={busy}
                      aria-pressed={n.enabled}
                      aria-label={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
                      title={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
                      onClick={() => onToggleNode(n.id)}
                    >
                      <span className="auto-step-switch-knob" />
                    </button>
                  ) : null}
                </div>
              ))}
              {/* ⭐ ITEM 17 / R15 — THE ESTIMATE LINE STOOD HERE. `g.nodes[0].detail` is where
                  "Up to 10 profiles · about $0.025" reached the screen (composed at
                  `automation_engine.py:5032`), and the owner named it. It was the engine's own
                  sentence rather than a client paraphrase, which is why it was defensible and
                  why it still had to go: an accurate paragraph nobody asked for is still the
                  architecture explaining itself (DESIGN.md §4).
                  ⚠ The COST question keeps a home — "What it costs" in the Find panel below,
                  behind a press, carrying its own SPEC caveat. This line stated a price nobody
                  had asked for beside a control that was not about price. */}
              {renderNodeBody(g.panel)}
            </div>
          ))}
        </>
      ) : null}

      <h3>Test step</h3>
      {/*
        ⛔ HONEST TO OUR SEMANTICS, not to Airtable's. Airtable's "Test step" replays one step
        against a chosen record. Ours has no step-replay: the engine runs a whole automation. So
        the control says what it actually does — RUN IT — and the results below are the last
        real run's, from the run log, rather than a rehearsal nobody performed.
      */}
      {/* ⭐ ITEM 22 / D-70 / R12 — THE SECOND DOOR ONTO THE SAME MONEY, guarded by the SAME
          function. It was `!!automation.running`, which is process state and therefore false for
          the entire 20-30 minute vendor wait; `runBlock` is the one definition both buttons read,
          so a fix cannot land on one and miss the other. */}
      <button type="button" className="auto-btn" disabled={busy || runState.blocked}
        title={runState.why || undefined}
        onClick={onRunNow}>
        {runState.blocked ? runState.label : "Run once now"}
      </button>
      {runState.blocked && !automation.running ? (
        <p className="auto-hint">{runState.why}</p>
      ) : null}
      {last ? (
        <>
          <p className={"autox-result is-" + (last.ok ? "ok" : "bad")}>
            {last.ok ? "Last run succeeded" : "Last run failed"}
          </p>
          <p className="auto-hint">
            {last.ts.replace("T", " ").slice(0, 16)} — {last.summary}
          </p>
        </>
      ) : (
        <p className="auto-hint">It has not run yet.</p>
      )}
    </>
  );
}

/**
 * ⭐ WAVE 26 · ITEM 9 / R11 — "+ New database", INSIDE the action's own database picker.
 *
 * Owner ruling R11, verbatim: *"name it and go. No dialog stack; columns follow what the action
 * writes (how the IG presets already work)."* So this is a name box and a button, in place, and
 * it selects what it creates — never a modal over a modal, and never a trip to another surface
 * that loses the action being configured.
 *
 * ⛔ IT DOES NOT INVENT THE ROW IT JUST MADE. `POST /tables` answers `{key}` alone, so the
 * component asks the caller to RE-LIST and only then selects the key. Splicing a client-built
 * `UserTable` in would put a guessed `rowCount` and an empty `fields` on screen beside real ones,
 * and the picker renders `rowCount` — a fabricated measurement, which is the one thing this
 * codebase refuses everywhere else.
 *
 * ⚠ THE REFUSAL IS THE SERVER'S, PRINTED VERBATIM. `POST /tables` has real refusals a person can
 * hit — an empty name, the `MAX_TABLES` ceiling, an unavailable store — and each answers with its
 * own sentence. Re-deriving "you have too many databases" here would be a second copy of a rule
 * that lives on the other side of the wall ([[schema-role-is-not-a-value-wall]]: find the line
 * that ENFORCES it, and let that line do the talking).
 */
function NewDatabase({
  disabled,
  onCreated,
}: {
  disabled: boolean;
  /**
   * Called with the new key AFTER the caller's table list has been re-read.
   * ⚠ IT MAY RETURN A PROMISE AND THE CALLER MUST AWAIT IT. Selecting the key before the list
   * contains it makes the picker's own "stored value is always an option" guard paint
   * "(not visible to you)" about the database the user just created — the guard doing exactly its
   * job, on a race, and saying something alarming and false.
   */
  onCreated: (key: string) => Promise<void> | void;
}) {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  const create = () => {
    const label = name.trim();
    if (!label || busy) return;
    setBusy(true);
    setErr("");
    createTable(label)
      .then(async (r) => {
        setOpen(false);
        setName("");
        // AWAITED: the caller re-reads the table list, and only then may the key be selected.
        await onCreated(r.key);
      })
      .catch((e) => {
        // The server's own words. `AutomationError` carries the composed sentence; anything else
        // is a transport failure and says so rather than blaming the name.
        setErr(
          e instanceof AutomationError && e.message
            ? e.message
            : "could not create it — the workspace did not answer"
        );
      })
      .finally(() => setBusy(false));
  };

  if (!open) {
    return (
      <button
        type="button"
        className="autoc-add"
        disabled={disabled}
        onClick={() => setOpen(true)}
      >
        + New database
      </button>
    );
  }
  return (
    <div className="autox-newdb">
      <input
        className="auto-input is-small"
        aria-label="Name for the new database"
        placeholder="Name it"
        autoFocus
        value={name}
        disabled={busy}
        onChange={(e) => setName(e.target.value)}
        // Enter creates, Escape backs out — the two keys a one-field form owes its user.
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            create();
          } else if (e.key === "Escape") {
            setOpen(false);
            setErr("");
          }
        }}
      />
      <button
        type="button"
        className="auto-btn is-small"
        disabled={busy || !name.trim()}
        onClick={create}
      >
        {busy ? "Creating…" : "Create"}
      </button>
      <button
        type="button"
        className="auto-btn is-small"
        disabled={busy}
        onClick={() => {
          setOpen(false);
          setErr("");
        }}
      >
        Cancel
      </button>
      {err ? <p className="autoc-bad">{err}</p> : null}
    </div>
  );
}

/**
 * ⭐ WAVE 28 — EXPORTED so the include-row render suite can mount the real panel.
 *
 * ⛔ THE EXPORT IS THE POINT, not a convenience. R6's three include rows are markup whose defect
 * modes are invisible to a source grep: a row that renders with no key attached, a Profile
 * checkbox that paints unchecked, two rows bound to the same key. `ReviewProps` below is already
 * exported for the same reason, so this is the file's existing shape rather than a new one.
 * `_test/` never ships (`deploy_web.py` excludes `_test/` and `_`-prefixed files both).
 */
export function ActionProps({
  action,
  pinned,
  catalog,
  tables,
  onTablesChanged,
  walkFields,
  walkTable,
  ops,
  nullaryOps,
  vocab,
  busy,
  onEdit,
}: {
  action: Action | null;
  /**
   * ⭐ THE PERMANENT STEP 1 OF AN INSTAGRAM SEARCH (owner report, 2026-08-06). It is the ONE
   * action whose `values` and `uniqueOn` the engine never reads: `apply_actions` drops
   * `actions[0]` for `discover_instagram` and the runner does the writing itself, upserting the
   * profile columns on `(handle, created_by)`.
   *
   * The card stays — "this search puts what it finds in a database" is true and worth showing —
   * but a `* Values` editor above `{{column_key}} reads that column off the record walking the
   * flow` is a required-looking control over a step nothing walks, and the owner spent a session
   * trying to make sense of it. Worse, it was ANSWERABLE: remapping it to `name: {{handle}}`
   * saved cleanly, changed nothing, and left the panel describing a write the engine does not
   * perform. A picture of the engine that disagrees with the engine is the defect this file
   * refuses in five other places.
   */
  pinned: boolean;
  catalog: ActionCatalogRow[];
  tables: UserTable[];
  /** ITEM 9 / R11 — re-read the list after this panel's picker creates one. REQUIRED; see Props. */
  onTablesChanged: () => Promise<void> | void;
  /**
   * ⛔ THE WALKING RECORD'S COLUMNS — the trigger's database, resolved by the builder.
   *
   * These three surfaces were built with `fields={[]}` and it made R3's headline feature
   * unauthorable: a conditional group's condition, an action's `when`, and `update_record`'s
   * column picker all offered "Choose a field…" and nothing else. An empty list is not a
   * neutral default here — it is a picker with no options, which reads as "this database has
   * no columns".
   */
  walkFields: { key: string; label: string; type: string }[];
  /**
   * ⭐ WAVE 26 · ITEM 5 / R10 — DOES A RECORD WALK THIS FLOW AT ALL? The key of the database it
   * walks, or `""`.
   *
   * ⛔ REQUIRED, and it answers a question `walkFields` structurally cannot. Both a flow with no
   * walking record and a flow walking an empty database hand this panel `[]`, and R10 wants
   * OPPOSITE renderings for them: a sentence pointing at the trigger for the first, an ordinary
   * (empty) picker for the second.
   * ⚠ VERIFIED AGAINST THE RUNNER, not inferred from the trigger list — which C4 forbids by name
   * ([[loopable-wave24]]: `CRON_DRIVEN_TRIGGERS` was exactly that mistake and became D-55).
   * `run_flow` returns immediately on `if not table_key` and otherwise walks that table's rows
   * evaluating `lane_match(act["when"], row)`, so a non-empty table key is EXACTLY the condition
   * under which `when` is ever consulted. The builder derives it from `_flow_table`'s own
   * precedence (`AutomationDetail.tsx`'s `walkTable`, whose comment carries that rule).
   */
  walkTable: string;
  ops: string[];
  nullaryOps: string[];
  vocab?: FlowVocab;
  busy: boolean;
  onEdit: (change: (a: Action) => Action) => void;
}) {
  if (!action) return <p className="auto-note">That action is no longer part of this flow.</p>;
  const row = catalog.find((c) => c.kind === action.kind);
  const cfg = action.config || {};
  const setCfg = (patch: Record<string, unknown>) =>
    onEdit((a) => ({ ...a, config: { ...a.config, ...patch } }));
  const values = (cfg as { values?: Record<string, string | number> }).values || {};
  const target = tables.find((t) => t.key === String((cfg as { table?: string }).table || ""));
  const valueFields = action.kind === "create_record" ? target?.fields || [] : walkFields;
  /**
   * The saved views of the database the flow's records WALK — the enrich step's optional filter.
   *
   * ⚠ Read off `walkTable`, never off `target`: `target` is the Create-record action's own
   * destination and answers a different question, and on an Instagram discovery flow the two are
   * routinely different tables. Same trap `walkFields` carries its own note about.
   * ⚠ `undefined` is a THIRD STATE and is preserved as one (`UserTable.views` is absent until the
   * server sends it) — the panel says "no view list was offered" rather than drawing an empty
   * picker that reads as "this database has no views".
   */
  const walkViews = (tables.find((t) => t.key === walkTable) || null)?.views;

  return (
    <>
      <h3>{row?.label || action.kind}</h3>
      {row?.detail ? <p className="auto-hint">{row.detail}</p> : null}

      <h3>Configuration</h3>

      {action.kind === "group" ? (
        <>
          {/*
            ⭐ ONE CONDITION EDITOR PER BRANCH (C-FORK). The group's own `config.cond` is GONE —
            a fork has a condition per leg, not one for the whole thing — so an editor bound to
            `cfg.cond` would now write a key `clean_actions` drops on the floor: the tree would
            look saved, survive a reload from local state, and be absent the next time anyone
            opened the automation.
            THE HEADING IS THE SERVER'S LABEL. The last leg may carry no condition, and the
            server has already named it "Otherwise" — giving it one here turns it into a lettered
            branch, which is a real thing to want and needs no separate control.
          */}
          {groupBranches(action).map((br, i) => (
            <div key={br.id || i}>
              <p className="auto-field-label">
                {br.label}
                {br.cond ? " — run these actions if…" : " — everything that reaches here"}
              </p>
              <CondBuilder
                cond={br.cond}
                onChange={(next) =>
                  onEdit((a) => ({
                    ...a,
                    config: {
                      ...a.config,
                      branches: groupBranches(a).map((x) =>
                        x.id === br.id ? { ...x, cond: next } : x
                      ),
                    },
                  }))
                }
                fields={walkFields}
                ops={ops}
                nullaryOps={nullaryOps}
                maxDepth={vocab?.maxCondDepth ?? 3}
                maxChildren={vocab?.maxCondChildren ?? 12}
                lead=""
                disabled={busy}
              />
            </div>
          ))}
          <p className="auto-hint">
            The first branch whose conditions match is the one that runs — the record does not go
            down two of them.
          </p>
        </>
      ) : null}

      {action.kind === "create_record" ? (
        <div className="auto-field">
          <label htmlFor="autox-atable">
            <span className="autox-req">*</span> Database
          </label>
          <select
            id="autox-atable"
            className="auto-input"
            value={String((cfg as { table?: string }).table || "")}
            disabled={busy}
            onChange={(e) => setCfg({ table: e.target.value })}
          >
            <option value="">Select a database…</option>
            {/* ⚠ THE STORED VALUE IS ALWAYS AN OPTION — the scar this file carries in three other
                places. A `<select>` whose `value` matches no `<option>` renders the FIRST one, so
                an action pointed at a database the reader cannot see would LOOK unset and the
                next edit would write the blank over it. */}
            {(cfg as { table?: string }).table
              && !tables.some((t) => t.key === (cfg as { table?: string }).table) ? (
              <option value={String((cfg as { table?: string }).table)}>
                {String((cfg as { table?: string }).table)} (not visible to you)
              </option>
            ) : null}
            {tables.map((t) => (
              <option key={t.key} value={t.key}>
                {t.label}
              </option>
            ))}
          </select>
          {/* ITEM 9 / R11 — mint one without leaving the action being configured. */}
          <NewDatabase
            disabled={busy}
            onCreated={async (key) => {
              await onTablesChanged();
              setCfg({ table: key });
            }}
          />
          {/*
            ⭐ WAVE 25 item 4 (ruling R2b, contract C1, wiring W25-4) — WHAT POINTING IT HERE DOES.
            The two lists are the SERVER's (`GET /automations/presets`), diffed against whatever
            database this action names — R2 makes `config.table` authoritative, so a hand-made one
            answers exactly like a spawned one.
          */}
          <PresetPlan table={String((cfg as { table?: string }).table || "")} />
        </div>
      ) : null}

      {/* WHAT THE SEARCH ACTUALLY WRITES, in place of the two controls below that do not apply to
          it. ⚠ THE LIST IS `_candidate_row`'s, field for field: a shorter "the profile columns"
          would be safe and useless, and a list that drifts from what the engine writes would be
          the same lie the value map was. */}
      {pinned ? (
        <p className="auto-hint">
          The search writes one row per profile it finds — handle, profile link, name, followers,
          following, average engagement, bio, link in bio, verified and category — into that
          database. It matches on the handle, so a profile found again updates its row instead of
          adding another. There is nothing to map: the columns come from the search.
        </p>
      ) : null}

      {/*
        ⭐ WAVE 25 item 2 (ruling R1a, contract C5, wiring W25-5) — KEEP RECORDS UNIQUE.
        Today's Create record APPENDS FOREVER: `_commit_action_writes` mints `max(id)+1`, so any
        scheduled flow using it duplicates a row per run — every night, silently, until somebody
        looks at the table. `uniqueOn` names the column to upsert on instead.

        ⛔ `""` IS A REAL CHOICE AND IT IS THE DEFAULT, so no stored automation changes meaning the
        day this ships. That is why the empty option is worded as a behaviour ("Add a new record
        every time") rather than as an absence ("None"): it describes what will happen, which is
        the thing the reader is choosing between.

        ⚠ THE COLUMN LIST IS THE TARGET DATABASE'S, not the walking record's — `valueFields`
        already resolves that for `create_record`. And the server REFUSES a `uniqueOn` this action
        does not write ("it writes: …"), so the honest client move is to offer the columns it
        writes FIRST while still allowing the rest: pre-empting the refusal here would be a second
        copy of a server rule, and this file's law is that the server owns legality.
      */}
      {action.kind === "create_record" && !pinned ? (
        <div className="auto-field">
          <label htmlFor="autox-aunique">Keep records unique on</label>
          <select
            id="autox-aunique"
            className="auto-input"
            value={String((cfg as { uniqueOn?: string }).uniqueOn || "")}
            disabled={busy}
            onChange={(e) => setCfg({ uniqueOn: e.target.value })}
          >
            <option value="">Add a new record every time</option>
            {(cfg as { uniqueOn?: string }).uniqueOn
              && !valueFields.some((f) => f.key === (cfg as { uniqueOn?: string }).uniqueOn) ? (
              <option value={String((cfg as { uniqueOn?: string }).uniqueOn)}>
                {String((cfg as { uniqueOn?: string }).uniqueOn)} (not in this database)
              </option>
            ) : null}
            {valueFields.map((f) => (
              <option key={f.key} value={f.key}>
                {f.label}
              </option>
            ))}
          </select>
          <p className="auto-hint">
            {String((cfg as { uniqueOn?: string }).uniqueOn || "")
              ? "A run that finds a matching record updates it instead of adding another."
              : "Every run adds a row, even if the same one is already there."}
          </p>
        </div>
      ) : null}

      {/*
        ⭐ WAVE 25 item 1 (rulings R3/R4, contract C4) — THE ENRICH ACTION'S CONFIGURATION.
        It replaces the whole `field_instagram` KIND: enriching a profile is something you do TO a
        record, not a species of automation. The switches are that kind's, unchanged in meaning,
        because they are the ones that decide what a run COSTS.

        ⛔ NO `profileField` PICKER HERE, DELIBERATELY, and it is not an omission. C3's profile
        FLAG on the column is what binds this action (R7 — one flagged text field per table), and
        the server resolves it at run time; an empty `profileField` is the A3 stored-inert state,
        not an error. A second picker would let a reader choose a column the flag does not name,
        which is two sources of truth for one binding — and the flag is the one the engine reads.
      */}
      {isEnrich(action.kind) ? (
        <>
          {/*
            ⭐⭐ 2026-08-07 (owner ruling) — WHICH RECORDS THIS STEP SPENDS ON.
            Owner: *"how many records with what sort, based on a Filtered view or maybe top N
            enrichment sorted by date"*. Every enrichment is a vendor call, so an enrich step
            without this panel bills for EVERY record in the database on EVERY run — which is why
            these controls shipped in the same change as the fix that made the action clickable at
            all, rather than after it.

            ⛔ THE LIMIT IS A QUOTA OF WORK DONE, NOT A WINDOW OF ROWS READ — the owner's own
            clarification: *"if a user choose to enrich 30 and from that sorted list of 30, 20 is
            enriched last 30 days, then it goes to next list"*. The server walks PAST every skipped
            record until the quota is filled, so the number in this box is a cost ceiling that
            means the same thing every run. `enrich_selection` owns the rule; this panel never
            re-implements it.
          */}
          <p className="auto-field-label">Records to enrich</p>
          <div className="auto-field">
            <label htmlFor="autox-aview">From view</label>
            <select
              id="autox-aview"
              className="auto-input"
              value={String((cfg as { fromView?: string }).fromView || "")}
              disabled={busy || !walkViews}
              onChange={(e) => setCfg({ fromView: e.target.value })}
            >
              <option value="">Every record in the database</option>
              {(walkViews || []).map((v) => (
                <option key={v.id} value={v.id}>{v.label}</option>
              ))}
            </select>
            {/* ⚠ ABSENT vs EMPTY, the `UserTable.views` third state. "This server did not offer a
                view list" is a different fact from "this database has no views", and rendering an
                empty picker for the first one is the silent-empty defect wave 23 gated. */}
            {!walkViews ? (
              <p className="auto-hint">No view list was offered for that database.</p>
            ) : null}
          </div>
          <div className="auto-field">
            <label htmlFor="autox-asort">Sort by</label>
            <select
              id="autox-asort"
              className="auto-input"
              value={String((cfg as { sortField?: string }).sortField || "first_found")}
              disabled={busy}
              onChange={(e) => setCfg({ sortField: e.target.value })}
            >
              {walkFields.length === 0 ? (
                <option value="first_found">First found</option>
              ) : null}
              {walkFields.map((f) => (
                <option key={f.key} value={f.key}>{f.label}</option>
              ))}
            </select>
          </div>
          <div className="auto-field">
            <label htmlFor="autox-asortdir">Order</label>
            <select
              id="autox-asortdir"
              className="auto-input"
              value={String((cfg as { sortDir?: string }).sortDir || "desc")}
              disabled={busy}
              onChange={(e) => setCfg({ sortDir: e.target.value })}
            >
              <option value="desc">Newest / highest first</option>
              <option value="asc">Oldest / lowest first</option>
            </select>
          </div>
          <div className="auto-field">
            <label htmlFor="autox-alimit">Limit</label>
            <input
              id="autox-alimit"
              className="auto-input"
              type="number"
              min={1}
              max={100}
              defaultValue={Number((cfg as { limit?: number }).limit || 25)}
              disabled={busy}
              // Commits on blur, like `maxPosts` above and for the same reason: "3" on the way to
              // "30" is a legal number the server would happily store.
              onBlur={(e) => setCfg({ limit: Number(e.target.value) || 25 })}
            />
            <p className="auto-hint">
              Records enriched per run, at most 100. Skipped records do not use up the limit &mdash;
              the run keeps going down the list until it has enriched this many.
            </p>
          </div>
          <label className="auto-check">
            <input
              type="checkbox"
              checked={!!(cfg as { skipRecent?: boolean }).skipRecent}
              disabled={busy}
              onChange={(e) => setCfg({ skipRecent: e.target.checked })}
            />
            Skip records enriched recently
          </label>
          {/* ⛔ THE DAYS BOX ONLY EXISTS WHILE THE RULE IS ON. A number that configures nothing is
              worse than a missing one ([[wrong-parent-not-broken-control]]) — and this one would
              read as a cost guard that is running while it is switched off. */}
          {(cfg as { skipRecent?: boolean }).skipRecent ? (
            <div className="auto-field">
              <label htmlFor="autox-acool">Enriched within</label>
              <input
                id="autox-acool"
                className="auto-input"
                type="number"
                min={1}
                defaultValue={Number((cfg as { skipRecentDays?: number }).skipRecentDays || 30)}
                disabled={busy}
                onBlur={(e) => setCfg({ skipRecentDays: Number(e.target.value) || 30 })}
              />
              <p className="auto-hint">
                Days. A profile enriched inside this window is passed over, and the run moves on to
                the next one &mdash; so you never pay twice for the same profile, and the history
                still gains a point once the window closes.
              </p>
            </div>
          ) : null}

          {/*
            ⭐⭐ WAVE 28 · R5 / R6 / R7 — THE SOURCE QUESTION IS GONE, AND THREE INCLUDE AXES
            REPLACE IT. What stood here was a `Source` select writing `config.tier`
            (Anonymous / Paid provider) plus a sibling `noFallback` checkbox — ONE control in two
            pieces, asking the user to choose a VENDOR STRATEGY.

            ⛔ R5 RETIRED THE QUESTION, not just the control. Enrichment routes per capability to
            the paid providers and reports blocked on a refusal; there is no thin anonymous row to
            fall back to, so "which source" and "stop if it fails" no longer have answers a person
            could give. `tier` and `noFallback` are accepted-and-ignored in stored configs (C2,
            and D-65's law: never 400 a definition that was legal when it was written) — which is
            why this panel simply stops writing them rather than migrating anything.

            ⛔ THE ROWS BELOW ARE A TRANSFORM, NOT AN ADDITION, and that distinction is the whole
            defect risk in this change. `postMetrics` and `commentMetrics` ALREADY had checkboxes
            34 lines below this point ("Also capture per-post engagement" / "…per-comment…").
            Building three NEW rows and leaving those would have put TWO controls on each key —
            which compiles, renders, and satisfies any check asking whether a Post-data switch
            exists. The old pair is deleted; these carry their keys.

            ⚠ KEYS UNCHANGED ON PURPOSE (C2). Every stored enrich action round-trips untouched;
            only the labels move. R7: no cost sentence anywhere in this panel — the run log keeps
            honest spend reporting, and a warning printed permanently is chrome the eye stops
            reading (DESIGN.md §4).
          */}
          {/* ⚠ A GROUP HEADING, NOT A `<label htmlFor>`. The first cut pointed it at the Post-data
              input, which is wrong twice over: it claims one row is "the" control for a group of
              three, and clicking the heading would toggle Posts. `auto-field-label` is this
              panel's own idiom for naming a group ("Records to enrich" above uses it). */}
          <p className="auto-field-label">Include</p>
          {/* ⛔ DISPLAY-ONLY, AND IT IS NOT DECORATION. The profile IS the unit of enrichment —
              there is no run that skips it — so a switch here would be a control that cannot be
              off ([[wrong-parent-not-broken-control]]). It carries NO config key: rendering it
              as state would invent a flag no cleaner reads.
              ⚠ `readOnly` beside `disabled`: a `checked` input with no `onChange` is a React
              warning, and `readOnly` says the honest thing about why. */}
          <label className="auto-check">
            <input id="autox-inc-profile" type="checkbox" checked readOnly disabled />
            Profile
          </label>
          <label className="auto-check">
            <input
              id="autox-inc-posts"
              type="checkbox"
              checked={!!(cfg as { postMetrics?: boolean }).postMetrics}
              disabled={busy}
              onChange={(e) => setCfg({ postMetrics: e.target.checked })}
            />
            Post data
          </label>
          <label className="auto-check">
            <input
              id="autox-inc-comments"
              type="checkbox"
              checked={!!(cfg as { commentMetrics?: boolean }).commentMetrics}
              disabled={busy}
              onChange={(e) => setCfg({ commentMetrics: e.target.checked })}
            />
            Comment data
          </label>
          {/*
            ⭐ WAVE 26 · ITEM 7 / R2 + C5 — TWO CONTROLS, AND THEY ARE INDEPENDENT.
            R2 splits them deliberately: how many posts to KEEP is FREE and rides the profile
            pull, while per-post engagement is a SEPARATE, PAID scrape (one extra vendor record
            per post per run — roughly 13x). They were nested here, so the free control was only
            reachable by first switching the paid one on: a person who wanted 5 posts instead of
            24 had to agree to buy engagement metrics to say so.
          */}
          <div className="auto-field">
            <label htmlFor="autox-aposts">Posts per profile</label>
            <input
              id="autox-aposts"
              className="auto-input"
              type="number"
              min={1}
              /* ⛔ 12, AND IT IS THE VENDOR'S — MEASURED, not a policy we chose (C5, and
                 `automation_engine.py:2165`: a Profiles row carries the TOP 12, "a cap, not a
                 count"). It read 200. `clean_max_posts` REFUSES a value the panel SENT above the
                 cap, so the old box could produce a 400 by typing a number it invited. */
              max={12}
              /* ⚠ 10, NOT 24 — the same number twice over. `DEFAULT_POSTS_PER_PULL` is 10, and 24
                 is now ABOVE the ceiling, so an empty box used to fall back to a value the save
                 door refuses. [[default-must-pass-its-own-guard]]: a law added later turns
                 yesterday's safe default into a value the product rejects. */
              defaultValue={Number((cfg as { maxPosts?: number }).maxPosts || 10)}
              disabled={busy}
              // FREE TEXT COMMITS ON BLUR — per-keystroke would PATCH a half-typed number, and
              // "2" on the way to "24" is a legal value the server would happily store.
              onBlur={(e) => setCfg({ maxPosts: Number(e.target.value) || 10 })}
            />
            <p className="auto-hint">
              At most 12 — the provider returns a profile&rsquo;s top 12 posts and no more.
            </p>
          </div>
          {/*
            ⭐⭐ W29-T09 (owner item 11: *"the last 12 reels"*) — THE ONLY DOOR TO `config.postGroups`.
            The server side has been whole since wave 28 — `clean_post_groups` validates it, the
            enrich runner applies it — and `postGroups` had **zero occurrences** anywhere in
            `web/src`, so NO USER COULD ASK FOR REELS-ONLY AT ALL. That is why this is a blocker for
            the reels routing work and not a nicety: those tickets' negative controls need a config
            a person can actually produce.

            ⛔ THE KEYS ARE THE SERVER'S AND SO ARE THE WORDS. `vocab.postTypes` carries both; a
            client that translated `video` into "Reels" locally would be a second copy of a
            vocabulary `clean_post_groups` refuses deviations from. Absent vocabulary renders
            NOTHING rather than three guessed names.

            ⛔ ABSENT IS OFF, AND OFF IS THE DEFAULT FOREVER. An enrich action stored before this
            control carries no `postGroups`, and the runner returns the post list unchanged when the
            key is missing — so unchecking every box must DELETE the key, never store `[]`-with-
            meaning or a group of zero. Deleting it is what keeps an old automation capturing
            exactly what it always captured.

            ⚠ ONE WRITER FOR ONE KEY [W-12]. This is the only control in `web/src` that writes
            `postGroups`; the `maxPosts` box above writes `maxPosts` and nothing else. The two are
            related only in that a group cannot keep more posts than the pull captures — which is
            the server's rule, printed here rather than re-implemented.
          */}
          {(vocab?.postTypes || []).length ? (
            <div className="auto-field">
              <p className="auto-field-label">Keep only certain posts</p>
              {(vocab?.postTypes || []).map((pt) => {
                const groups =
                  ((cfg as { postGroups?: { type: string; limit: number }[] }).postGroups) || [];
                const mine = groups.find((g) => g && g.type === pt.key);
                const cap = Math.max(
                  1,
                  Number((cfg as { maxPosts?: number }).maxPosts || 10) || 10
                );
                /* ⛔ WRITE THROUGH ONE FUNCTION, so the "no groups left ⇒ remove the key" rule
                   exists once. Two call sites each deciding it is how `[]` starts meaning
                   "capture nothing". */
                const write = (next: { type: string; limit: number }[]) =>
                  setCfg({ postGroups: next.length ? next : undefined });
                return (
                  <label className="auto-check" key={pt.key}>
                    <input
                      type="checkbox"
                      checked={!!mine}
                      disabled={busy}
                      onChange={(e) =>
                        write(
                          e.target.checked
                            ? [...groups.filter((g) => g.type !== pt.key),
                               { type: pt.key, limit: Math.min(cap, 12) }]
                            : groups.filter((g) => g.type !== pt.key)
                        )
                      }
                    />
                    {pt.label}
                    {mine ? (
                      <input
                        className="auto-input auto-input-inline"
                        type="number"
                        min={1}
                        max={cap}
                        aria-label={`How many ${pt.label} to keep`}
                        /* Commits on BLUR, exactly like `maxPosts` above and for the identical
                           reason: "1" on the way to "12" is a value the server would store. */
                        defaultValue={mine.limit}
                        disabled={busy}
                        onBlur={(e) =>
                          write([
                            ...groups.filter((g) => g.type !== pt.key),
                            {
                              type: pt.key,
                              limit: Math.max(1, Number(e.target.value) || 1),
                            },
                          ])
                        }
                      />
                    ) : null}
                  </label>
                );
              })}
              <p className="auto-hint">
                Leave these unticked to keep every post. Ticked, only the kinds you name are
                kept — and a group cannot keep more than the {" "}
                {Number((cfg as { maxPosts?: number }).maxPosts || 10) || 10} posts this
                enrichment captures.
              </p>
            </div>
          ) : null}
          {/*
            ⭐ WAVE 28 · R6/R7 — THE TWO CHECKBOXES THAT STOOD HERE MOVED UP INTO THE INCLUDE
            GROUP, KEYS AND ALL (`postMetrics`, `commentMetrics`). They are not deleted features:
            they are the SAME two switches, relabelled "Post data" and "Comment data" and grouped
            with the always-on Profile row so the three capture axes read as one decision.
            ⛔ THEIR CONDITIONAL COST HINTS WENT WITH THEM AND DID NOT COME BACK (R7): "Billed per
            post, not per profile" and "Billed by the separate Comments dataset". R7 puts spend
            reporting in the RUN LOG, where it is a measured fact about work already done, rather
            than in the panel, where it was a permanent caption on a switch.
            ⚠ Leaving them here as well as above is the duplicate-writer trap this wave's item 1
            was one literal reading away from shipping — two controls on one key, both correct,
            neither authoritative.
          */}
          <label className="auto-check">
            <input
              type="checkbox"
              checked={!!(cfg as { dryRun?: boolean }).dryRun}
              disabled={busy}
              onChange={(e) => setCfg({ dryRun: e.target.checked })}
            />
            Dry run — read and report, write nothing
          </label>
        </>
      ) : null}

      {(action.kind === "update_record" || action.kind === "create_record") && !pinned ? (
        <>
          <p className="auto-field-label">
            <span className="autox-req">*</span> Values
          </p>
          {Object.entries(values).map(([key, val], i) => (
            <div className="autoc-row" key={i}>
              <button
                type="button"
                className="autoc-drop"
                disabled={busy}
                aria-label="Remove this value"
                onClick={() => {
                  const next = { ...values };
                  delete next[key];
                  setCfg({ values: next });
                }}
              >
                <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                  <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                    strokeLinecap="round" />
                </svg>
              </button>
              <select
                className="auto-input is-tiny"
                value={key}
                disabled={busy}
                aria-label="Column"
                onChange={(e) => {
                  const next: Record<string, string | number> = {};
                  for (const [k, v] of Object.entries(values))
                    next[k === key ? e.target.value : k] = v;
                  setCfg({ values: next });
                }}
              >
                <option value="">Choose a column…</option>
                {/* ⚠ WHICH RECORD'S COLUMNS depends on the action: `create_record` writes into
                    the database it NAMES, `update_record` writes onto the record walking the
                    flow — the trigger's. Offering the target's columns for both would list the
                    wrong database's columns for every update action. */}
                {key && !valueFields.some((f) => f.key === key) ? (
                  <option value={key}>{key}</option>
                ) : null}
                {valueFields.map((f) => (
                  <option key={f.key} value={f.key}>
                    {f.label}
                  </option>
                ))}
              </select>
              <input
                className="auto-input is-tiny autoc-value"
                defaultValue={String(val ?? "")}
                disabled={busy}
                aria-label="Value"
                placeholder="Value or {{column}}"
                onBlur={(e) => setCfg({ values: { ...values, [key]: e.target.value } })}
              />
            </div>
          ))}
          <button
            type="button"
            className="autoc-add"
            disabled={busy}
            onClick={() => setCfg({ values: { ...values, "": "" } })}
          >
            + Add a value
          </button>
          {/* ⭐ THE SENTENCE THE OWNER COULD NOT PARSE, 2026-08-06. `{{column_key}}` is a
              PLACEHOLDER standing for a placeholder, and "the record walking the flow" is this
              module's internal noun for the row a step is currently running on — two layers of
              indirection in eleven words, above a box the reader is already unsure how to fill.
              It says what to TYPE, using a column this database actually has, and names the two
              choices as choices. `walkFields` is the walking record's columns for both action
              kinds, which is what a placeholder resolves against. */}
          <p className="auto-hint">
            Type a fixed value, or{" "}
            <code>{`{{${walkFields[0]?.key || "column"}}}`}</code> to copy{" "}
            {walkFields[0]?.label ? <>“{walkFields[0].label}”</> : "a column"} from the record this
            step is running on.
          </p>
        </>
      ) : null}

      {action.kind === "find_records" ? (
        <>
          <div className="auto-field">
            <label htmlFor="autox-ftable">
              <span className="autox-req">*</span> Database
            </label>
            <select
              id="autox-ftable"
              className="auto-input"
              value={String((cfg as { table?: string }).table || "")}
              disabled={busy}
              onChange={(e) => setCfg({ table: e.target.value })}
            >
              <option value="">Select a database…</option>
              {/* ⚠ THE STORED VALUE IS ALWAYS AN OPTION — the same scar its `create_record`
                  sibling carries three lines up, and this picker did NOT have the guard. A
                  `<select>` whose `value` matches no `<option>` renders the FIRST one, so a
                  find_records pointed at a database this reader cannot see looked unset, and the
                  next edit wrote the blank over it. Sibling surfaces written from one template
                  diverge exactly this way and nothing greps for "the other one" (D-10). */}
              {(cfg as { table?: string }).table
                && !tables.some((t) => t.key === (cfg as { table?: string }).table) ? (
                <option value={String((cfg as { table?: string }).table)}>
                  {String((cfg as { table?: string }).table)} (not visible to you)
                </option>
              ) : null}
              {tables.map((t) => (
                <option key={t.key} value={t.key}>
                  {t.label}
                </option>
              ))}
            </select>
            {/* ITEM 9 / R11 — "every action's database picker", so this one too. */}
            <NewDatabase
              disabled={busy}
              onCreated={async (key) => {
                await onTablesChanged();
                setCfg({ table: key });
              }}
            />
          </div>
          <p className="auto-field-label">Conditions</p>
          <CondBuilder
            cond={(cfg as { cond?: Cond | null }).cond || null}
            onChange={(next) => setCfg({ cond: next })}
            fields={target?.fields || []}
            ops={ops}
            nullaryOps={nullaryOps}
            maxDepth={vocab?.maxCondDepth ?? 3}
            maxChildren={vocab?.maxCondChildren ?? 12}
            disabled={busy}
          />
          <div className="auto-field">
            <label htmlFor="autox-flimit">How many at most</label>
            <input
              id="autox-flimit"
              className="auto-input"
              type="number"
              min={1}
              defaultValue={Number((cfg as { limit?: number }).limit || 25)}
              disabled={busy}
              onBlur={(e) => setCfg({ limit: Number(e.target.value) || 25 })}
            />
          </div>
          <p className="auto-hint">
            What it found opens from the run log. Piping the rows into a later step is not built
            yet.
          </p>
        </>
      ) : null}

      {/*
        ⭐ WAVE 26 · ITEM 5 — OWNER RULINGS R9 AND R10, and they are two different fixes to one
        symptom (*"the condition on action act_1 names no field"*).

        R9 — A `create_record` HAS NO CONDITIONS AT ALL. The owner corrected their own first
        answer mid-grill: *"if it is Create Record, I don't think you can even add Conditions at
        all. That's not how the Create Record works."* Airtable agrees and so does the shape:
        every other action operates ON the record the flow is walking, so "run this only when
        <that record> …" is a question about something that exists. Create record MAKES one.
        There is nothing to test yet — which is why the picker on this panel was always empty and
        why every condition saved against it named no field.
        ⛔ THE SERVER DROPS A STORED `when` RATHER THAN REFUSING IT (C4), and this removal is what
        makes that silent drop defensible: `clean_actions` has no disclosure channel, so the drop
        is only safe while there is no control whose value could appear to be ignored. Deleting
        the editor and dropping the value are ONE change in two files — if this editor ever comes
        back for `create_record`, the drop becomes silent data loss (booked by A).

        R10 — NO WALKING RECORD ⇒ A SENTENCE, NEVER AN EMPTY PICKER. A picker with no options
        reads as "this database has no columns", and anything saved through it names no field,
        which is the refusal the owner kept meeting. The sentence points at the surface that CAN
        answer: the trigger.
        ⚠ The test is `walkTable`, not `walkFields.length` — see the prop's own note. A flow
        walking a database that genuinely has no columns yet keeps its (empty) picker, because
        for that flow the picker is the right control and adding a column is the fix.
      */}
      {action.kind === "create_record" ? null : !walkTable ? (
        <>
          <h3>Run this only when</h3>
          <p className="auto-note">
            This flow has no record to test — set conditions on the trigger instead.
          </p>
        </>
      ) : (
        <>
          <h3>Run this only when</h3>
          <CondBuilder
            cond={action.when || null}
            onChange={(next) => onEdit((a) => ({ ...a, when: next }))}
            fields={walkFields}
            ops={ops}
            nullaryOps={nullaryOps}
            maxDepth={vocab?.maxCondDepth ?? 3}
            maxChildren={vocab?.maxCondChildren ?? 12}
            disabled={busy}
          />
          {!condComplete(action.when || null, nullaryOps) ? null : (
            <p className="auto-hint">Leave empty to run it every time.</p>
          )}
        </>
      )}
    </>
  );
}

export function ReviewProps({
  cfg,
  vocab,
  busy,
  setCfg,
}: {
  cfg: Record<string, unknown>;
  vocab?: FlowVocab;
  busy: boolean;
  setCfg: (patch: Record<string, unknown>) => void;
}) {
  const by = String(cfg.decidedBy || "user");
  const next = Array.isArray(cfg.next) ? (cfg.next as string[]) : [];
  const aiReady = vocab?.aiReady !== false;
  return (
    <>
      <div className="auto-field">
        <label htmlFor="autox-rby">Decided by</label>
        <select
          id="autox-rby"
          className="auto-input"
          value={by}
          disabled={busy}
          onChange={(e) => setCfg({ decidedBy: e.target.value })}
        >
          {(vocab?.reviewDeciders || ["user"]).map((d) => (
            <option key={d} value={d}>
              {d === "ai" ? "AI" : "A person"}
            </option>
          ))}
        </select>
      </div>
      {/*
        ⚠ `aiReady` IS A MEASUREMENT OF THIS DEPLOYMENT, and it is stated rather than styled
        around. With no LLM key the engine holds every card for a human — so an AI review that
        looked configured would promise a decision nothing will make (C6's fail-closed path).
      */}
      {by === "ai" && !aiReady ? (
        <p className="auto-note">
          No AI provider is configured here, so these cards wait for a person.
        </p>
      ) : null}
      {by === "ai" ? (
        <div className="auto-field">
          <label htmlFor="autox-rprompt">What should it decide?</label>
          <textarea
            id="autox-rprompt"
            className="auto-input"
            rows={3}
            defaultValue={String(cfg.prompt || "")}
            disabled={busy}
            placeholder="Approve suppliers with a UK address and more than 20 reviews."
            onBlur={(e) => setCfg({ prompt: e.target.value })}
          />
        </div>
      ) : null}
      <div className="auto-field">
        <label htmlFor="autox-rlabel">Stage name</label>
        <input
          id="autox-rlabel"
          className="auto-input"
          defaultValue={String(cfg.label || "Review")}
          disabled={busy}
          onBlur={(e) => setCfg({ label: e.target.value })}
        />
      </div>
      <p className="auto-field-label">Where it can go next</p>
      {next.map((n, i) => (
        <div className="autoc-row" key={i}>
          <button
            type="button"
            className="autoc-drop"
            disabled={busy}
            aria-label={`Remove ${n}`}
            onClick={() => setCfg({ next: next.filter((_x, j) => j !== i) })}
          >
            <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                strokeLinecap="round" />
            </svg>
          </button>
          <input
            className="auto-input is-tiny"
            defaultValue={n}
            disabled={busy}
            aria-label="Stage this review can send a record to"
            onBlur={(e) =>
              setCfg({ next: next.map((x, j) => (j === i ? e.target.value : x)) })
            }
          />
        </div>
      ))}
      <button
        type="button"
        className="autoc-add"
        disabled={busy}
        onClick={() => setCfg({ next: [...next, ""] })}
      >
        + Add an exit
      </button>
      <p className="auto-hint">
        Each exit is a lane on the board. A card waits here until it is moved to one of them.
      </p>
    </>
  );
}
