iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / src / Wizard.tsxmain at aacbc74

// The domain wizard: the steps listed on the left (Sidebar), the current one on the right, so every
// step starts at the top however many there are. STEPS is the list; NextButton moves along it, and
// the browser's Back and Forward do too (api.ts).
//   1 Connect a Cloudflare account (a new one by default)   2 Get it ready   3 Pick a domain   4 Deploy
//   5 Set up AI agents   6 Try
// iterate's shadcn kit (the repo /repos/ui of the iterate.com mind) for the parts, composed in ./parts.tsx.
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Badge } from "@iterate-com/ui/components/ui/badge";
import { Checkbox } from "@iterate-com/ui/components/ui/checkbox";
import { Input } from "@iterate-com/ui/components/ui/input";
import { Label } from "@iterate-com/ui/components/ui/label";
import { Spinner } from "@iterate-com/ui/components/ui/spinner";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@iterate-com/ui/components/ui/collapsible";
import { Sheet, SheetContent, SheetTitle } from "@iterate-com/ui/components/ui/sheet";
import {
  Checklist,
  ChecklistItem,
  type ChecklistState,
} from "@iterate-com/ui/components/checklist";
import { AppShell, AppShellBrand, AppShellPageHeader } from "@iterate-com/ui/components/app-shell";
import { DropdownMenuItem } from "@iterate-com/ui/components/ui/dropdown-menu";
import { CloudflareButton, CloudflareMark } from "@iterate-com/ui/components/cloudflare-button";
import { CopyButton, CopyText } from "@iterate-com/ui/components/copy-text";
import {
  SetupProgress,
  SetupSteps,
  type SetupSubstep,
} from "@iterate-com/ui/components/setup-steps";
import {
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  CircleAlert,
  CircleCheck,
  ExternalLink,
  Globe,
  LockKeyhole,
  LogOut,
  Search,
} from "lucide-react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { COUNTRIES, DIAL, homeCountry, registryPhone } from "./phone.ts";
import {
  Btn,
  ChoiceCards,
  LinkBtn,
  Notice,
  SelectField,
  TextField,
  WalkthroughOnly,
} from "./parts.tsx";
import { useDeployments } from "./your-deployments.ts";
import { track } from "./analytics.ts";
import {
  call,
  useGet,
  dashUrl,
  errorOf,
  deployPath,
  firstPasskey,
  firstPasskeyOpened,
  logEvent,
  OFFLINE,
  permissions,
  wider,
  pretend,
  mindDashUrl,
  onboardingUrl,
  setState,
  selfTestReport,
  signedOut,
  signOut,
  stackUrl,
  useLog,
  useWizard,
  type Answer,
  type DeployState,
  type Kept,
  type LogEntry,
  type Contact,
  type Domain,
  type State,
  type Zone,
} from "./api.ts";
import { CloudNav } from "./CloudNav.tsx";
import {
  PAGES,
  failedStepOf,
  notesOf,
  phaseOf,
  reportOf,
  runErrorOf,
  pagesOf,
  type Pages,
} from "./deploy-steps.ts";
import { useConnected } from "./connected.ts";
import { erasePath, eraseUndone, notFromHere, olderStack } from "./erase.ts";

export function Wizard() {
  const s = useWizard();
  const [logOpen, setLogOpen] = useState(false);
  const wide = useWide();
  const current = Math.min(s.step, STEPS.length - 1);
  const step = STEPS[current];
  useEffect(
    () => track("cloud step reached", { step: step.id, index: current }),
    [step.id, current],
  );
  // a step they moved to (not the one the page opened on) takes the focus: a screen reader says where it is
  const [seen, setSeen] = useState(step.id);
  const [moved, setMoved] = useState(false);
  if (seen !== step.id) {
    setSeen(step.id);
    setMoved(true);
  }
  const user = s.me?.user;
  return (
    <AppShell
      app="iterate Cloud"
      mind={null}
      switcher={<AppShellBrand app="iterate Cloud" />}
      commandPalette={false}
      searchRow={false}
      nav={<CloudNav />}
      account={user ? { actor: user.email, email: user.email } : false}
      accountActions={
        <DropdownMenuItem data-sign-out onClick={signOut}>
          <LogOut />
          Sign out
        </DropdownMenuItem>
      }
      locationKey="/"
    >
      <div className="relative flex min-h-0 flex-1 flex-col bg-page">
        <StepBar s={s} />
        <div id={SCROLLER} className="min-h-0 flex-1 overflow-auto">
          <h1 className="sr-only">Set up iterate</h1>
          <div className="mx-auto grid max-w-7xl gap-x-10 px-4 pb-12 lg:grid-cols-[240px_minmax(0,1fr)] lg:px-8">
            <StepsNav s={s} />
            {/* the shell's inset is the page's <main> */}
            <div data-step className="mx-auto w-full max-w-2xl min-w-0 pt-6 lg:mx-0 lg:pt-12">
              <StepSection key={step.id} s={s} step={step} first={current === 0} focus={moved} />
            </div>
          </div>
        </div>
        <LogBar open={logOpen} setOpen={setLogOpen} wide={wide} />
      </div>
      {logOpen && wide && <LogColumn close={() => setLogOpen(false)} />}
    </AppShell>
  );
}

/** The part of the page that scrolls: the shell's frame stays, the step moves under it. */
const SCROLLER = "wizard-scroll";
const toTop = () => document.getElementById(SCROLLER)?.scrollTo(0, 0);

/** One step: the way back (narrower than the step list's breakpoint), its heading, its content. */
function StepSection({
  s,
  step,
  first,
  focus,
}: {
  s: State;
  step: StepDef;
  first: boolean;
  focus: boolean;
}) {
  const heading = useRef<HTMLHeadingElement>(null);
  useEffect(() => {
    if (focus) heading.current?.focus({ preventScroll: true });
  }, [focus]);
  return (
    <section aria-labelledby="step-title">
      {!first && (
        <button
          type="button"
          onClick={() => setState((st) => ({ step: Math.max(0, st.step - 1), error: null }))}
          className="-mt-3 mb-1 -ml-2 flex min-h-10 w-fit items-center gap-1 rounded-md px-2 text-sm text-muted-foreground hover:text-foreground lg:hidden"
        >
          <ChevronLeft className="size-4" aria-hidden />
          Back
        </button>
      )}
      <h2
        id="step-title"
        ref={heading}
        tabIndex={-1}
        className="text-2xl font-semibold tracking-tight outline-none"
      >
        {step.heading(s)}
      </h2>
      {step.lead && (
        <p className="mt-2 text-muted-foreground">
          {typeof step.lead === "function" ? step.lead(s) : step.lead}
        </p>
      )}
      <div className="mt-6">
        {/* a step that works on Cloudflare, with the access to it over: connect again first */}
        {s.me?.connected === false &&
        (step.id === "ready" || (step.id === "domain" && !s.result)) ? (
          <Reconnect s={s} />
        ) : (
          step.render(s)
        )}
      </div>
    </section>
  );
}

/** Says that this page works on the pretend Cloudflare, and leads there. */
function PretendBadge() {
  const home = pretend?.home || null;
  if (!home) return null;
  return (
    <a
      href={home}
      target="_blank"
      rel="noreferrer"
      className="w-fit shrink-0 rounded bg-red-600 px-2 py-0.5 text-xs font-semibold text-white hover:bg-red-700"
    >
      Pretend Cloudflare
    </a>
  );
}

/** Narrower than the step list's breakpoint, in the shell's header row (beside the phone's sidebar
 *  trigger): the progress and "Step n of m", which opens the list of steps (to go to any they
 *  reached). Nothing on a wide screen: the list is beside the content there, and the row is gone. */
function StepBar({ s }: { s: State }) {
  const current = Math.min(s.step, STEPS.length - 1);
  const [open, setOpen] = useState(false);
  const large = useMedia("(min-width: 1024px)");
  useEffect(() => {
    if (!open) return;
    const esc = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, [open]);
  if (large) return null;
  return (
    <>
      <AppShellPageHeader>
        <PretendBadge />
        <button
          type="button"
          tabIndex={-1}
          aria-hidden
          onClick={() => setOpen(!open)}
          className="min-w-0 flex-1 py-3"
        >
          <SetupProgress count={STEPS.length} current={current} finished={s.finished} />
        </button>
        <button
          type="button"
          aria-expanded={open}
          aria-controls="step-menu"
          data-step-menu
          onClick={() => setOpen(!open)}
          className="-mr-2 flex min-h-10 shrink-0 items-center gap-1 rounded-md px-2 text-sm text-muted-foreground tabular-nums hover:text-foreground"
        >
          {s.finished ? "Done" : `Step ${current + 1} of ${STEPS.length}`}
          <span className="sr-only">: all steps</span>
          <ChevronDown className={`size-4 transition ${open ? "rotate-180" : ""}`} aria-hidden />
        </button>
      </AppShellPageHeader>
      {open && (
        <>
          <button
            type="button"
            tabIndex={-1}
            aria-hidden
            onClick={() => setOpen(false)}
            className="absolute inset-0 z-10 cursor-default bg-foreground/20"
          />
          <div
            id="step-menu"
            className="absolute inset-x-0 top-0 z-20 max-h-full overflow-auto border-b bg-background shadow-lg"
          >
            <div className="mx-auto box-content max-w-2xl px-4 py-2">
              <StepList s={s} after={() => setOpen(false)} />
            </div>
          </div>
        </>
      )}
    </>
  );
}

/** The steps, in order: one entry each, so adding one is one entry. */
type StepDef = {
  id: string;
  title: string;
  heading: (s: State) => string;
  lead?: string | ((s: State) => ReactNode);
  /** What was done, for the step list once the step is behind them. */
  summary: (s: State, deploy?: DeployState["status"]) => ReactNode;
  /** They can open the step again to change what they chose. */
  change?: boolean;
  /** The parts of the step, for the step list while they are on it. */
  substeps?: (s: State) => SetupSubstep[];
  render: (s: State) => ReactNode;
};
/** A name in a step's summary (an account, a domain): it is what the eye looks for. */
const Named = ({ children }: { children: ReactNode }) => (
  <span className="font-semibold text-foreground">{children}</span>
);
const STEPS: StepDef[] = [
  {
    id: "account",
    title: "Connect Cloudflare account",
    heading: (s) => accountHeadings[accountPart(s)],
    summary: (s) =>
      !s.account || s.account === "new" ? null : (
        <>
          <CloudflareMark className="mr-1.5 inline w-4 align-[-1px]" />
          <Named>{accountName(s)}</Named>
        </>
      ),
    change: true,
    substeps: (s) => accountSubsteps(s),
    render: (s) => <AccountStep s={s} />,
  },
  {
    id: "domain",
    title: "Pick a domain",
    heading: () => "Pick a domain",
    lead: "Your agents get their own address, website and email on it.",
    summary: (s) => {
      const name = s.result?.name || toBuy(s)?.name;
      return !name ? null : (
        <>
          <Globe className="mr-1.5 inline size-3.5 align-[-2px]" aria-hidden />
          <Named>{name}</Named>
          {!s.result && " to buy"}
        </>
      );
    },
    change: true,
    render: (s) => <DomainStep s={s} />,
  },
  {
    id: "ready",
    title: "Get your account ready",
    heading: () => "Get your account ready",
    summary: (s) => {
      const items = readyItems(s.readiness);
      const ready = items.filter((i) => i.state === true).length;
      return !s.readiness ? null : readyAll(s) ? "All set" : `${ready} of ${items.length} ready`;
    },
    substeps: (s) => {
      const { next } = whatsLeft(s.readiness);
      const parts: SetupSubstep[] = readyItems(s.readiness).map((i) => ({
        id: i.id,
        title: i.title,
        state: i.state === true ? "done" : i.id === next ? "now" : "todo",
        accent: true,
      }));
      // a domain to buy is bought here, last: Cloudflare sells one to an account with a card
      const buying = toBuy(s);
      return buying
        ? [
            ...parts,
            {
              id: "buy",
              title: `Buy ${buying.name}`,
              state: readyAll(s) ? "now" : "todo",
              accent: true,
            },
          ]
        : parts;
    },
    render: (s) => <ReadyStep s={s} />,
  },
  {
    id: "deploy",
    title: "Deploy iterate",
    heading: () => "Deploy iterate",
    summary: (_s, deploy) =>
      deploy === "succeeded"
        ? "Live"
        : deploy === "running"
          ? "Deploying"
          : deploy === "failed"
            ? "Stopped"
            : null,
    render: (s) => <DeployStep s={s} />,
  },
  {
    id: "ai",
    title: "Set up AI agents",
    heading: () => "Set up AI agents",
    lead: "Your agents need an AI provider. Connect one. You can change it later.",
    // the Cloud has no access to the deployment: it cannot see which one is set
    summary: () => null,
    render: (s) => <AiStep s={s} />,
  },
  {
    id: "try",
    title: "Try iterate",
    heading: () => "Try iterate",
    summary: () => null,
    render: (s) => <TryStep s={s} />,
  },
];

/** On to the next step (and a `beforeNext` check that keeps them on the step if it throws). */
function NextButton({
  beforeNext,
  children,
  variant = "default",
  disabled,
  prominent = false,
}: {
  beforeNext?: () => void | Promise<void>;
  children: ReactNode;
  variant?: "default" | "ghost" | "outline";
  disabled?: boolean;
  /** The step's work is done and this is the one thing left to press: larger, with an arrow. */
  prominent?: boolean;
}) {
  const [busy, setBusy] = useState(false);
  const next = async () => {
    setBusy(true);
    try {
      await beforeNext?.();
      setState((s) => ({ step: Math.min(s.step + 1, STEPS.length - 1), error: null }));
      toTop();
    } catch {
      /* the check said why */
    } finally {
      setBusy(false);
    }
  };
  return (
    <Btn
      variant={variant}
      size="lg"
      className={prominent ? "h-12 px-8 text-base sm:min-w-48" : undefined}
      onClick={next}
      loading={busy}
      disabled={disabled}
    >
      {children}
      {prominent && <ChevronRight aria-hidden data-icon="inline-end" />}
    </Btn>
  );
}

/** The steps as a list: done ones checked with what was done, the current one bold with its parts
 *  under it, any reached one a way to it. Beside the content on a wide screen, and under the
 *  shell's "Step n of m" on a narrow one. */
function StepList({ s, after }: { s: State; after?: () => void }) {
  const current = Math.min(s.step, STEPS.length - 1);
  const deploy: DeployState["status"] | undefined = useGet(s.maxStep >= 3 ? deployPath(s) : null)
    .data?.state?.status;
  return (
    <SetupSteps
      current={current}
      reached={s.maxStep}
      finished={s.finished && !!s.result}
      steps={STEPS.map((st, i) => ({
        id: st.id,
        title: st.title,
        summary: i < current || s.finished ? st.summary(s, deploy) : null,
        change: st.change ? "Change" : undefined,
        substeps:
          i === current && !s.finished
            ? st.substeps?.(s).map((sub) => ({
                ...sub,
                onSelect:
                  sub.onSelect &&
                  (() => {
                    sub.onSelect!();
                    toTop();
                    after?.();
                  }),
              }))
            : undefined,
      }))}
      onSelect={(i) => {
        setState({ step: i, finished: false, error: null });
        toTop();
        after?.();
      }}
    />
  );
}

/** The step list beside the content. Hidden on a narrow screen (the shell's row has it there). */
function StepsNav({ s }: { s: State }) {
  return (
    <div className="hidden lg:block">
      <div className="sticky top-0 flex flex-col gap-4 pt-12">
        <PretendBadge />
        <StepList s={s} />
      </div>
    </div>
  );
}

const accountName = (s: State) =>
  s.me?.accounts.find((a) => a.id === s.account)?.name ||
  s.created?.name ||
  (s.account === "new" ? s.acctName || "iterate" : "your account");
/** The name they chose to buy and have not bought yet: it is bought on the account's checklist. */
const toBuy = (s: State) => (s.path === "buy" && !s.result ? s.choice : null);
const readyAll = (s: State) =>
  !!s.readiness &&
  s.readiness.paymentMethod === true &&
  s.readiness.workersPaid === true &&
  s.readiness.r2 === true &&
  !!s.readiness.workersDev;
/** How often to ask: every 2 seconds while the run goes. After it succeeded, every 5 seconds until
 *  the Cloud knows the deployment's key (a new address can take a moment to answer), for 10 minutes. */
const deployPoll = (q: { state: { data?: Answer } }) => {
  const d = q.state.data;
  if (d?.state?.status === "running") return 2_000;
  const fresh = Date.now() - (d?.state?.endedAt || 0) < 600_000;
  return d?.state?.status === "succeeded" && d.enrolled === false && fresh ? 5_000 : false;
};
/** The full consent. It asks also the scope that makes API tokens (scopes.js `TELEMETRY_SCOPE`), so
 *  that the first deploy turns on the mind's telemetry and gives the mind a Cloudflare connection.
 *  `plain` leaves that scope out: once a person chose the consent without it, they get that again. */
const authorizeHref = (
  s: State,
  plain = s.withoutTokens || (s.me?.level === "full" && !s.me.cloudflareToken),
) => `/connect?level=full${plain ? "" : "&telemetry=1&cloudflare=1"}${s.testMode ? "&test=1" : ""}`;

/** Above a way to the full consent that asks the scope that makes API tokens: the one box that
 *  Cloudflare leaves for the person to tick, why, and the consent without it. `without`: what the
 *  way without it does instead of the link (the new-account form makes the account first). */
function TokenTick({ s, without }: { s: State; without?: () => void }) {
  if (authorizeHref(s) === authorizeHref(s, true)) return null;
  return (
    <div data-token-tick className="mt-5 space-y-2 text-sm">
      <p>
        On Cloudflare's page, open <b className="font-medium">Sensitive scopes</b> and turn on{" "}
        <b className="font-medium">Account API Tokens Write</b>, then press Authorize. Cloudflare
        leaves it off, and gives no access at all without it.
      </p>
      <p className="text-muted-foreground">
        With it, the deploy turns on your mind's telemetry and gives your mind a Cloudflare
        connection. For that it makes three API tokens in your account, which stay there: two for
        telemetry, and one with which your mind's agents read the account and query its logs and
        traces. iterate Cloud keeps none of them.{" "}
        {without ? (
          <button
            type="button"
            data-without-tokens
            className="text-link hover:underline"
            onClick={without}
          >
            Authorize without it
          </button>
        ) : (
          <a
            data-without-tokens
            className="text-link hover:underline"
            href={authorizeHref(s, true)}
            onClick={() => setState({ withoutTokens: true })}
          >
            Authorize without it
          </a>
        )}
        : your mind then starts with telemetry off and with no Cloudflare connection.
      </p>
    </div>
  );
}

/** iterate keeps no lasting access to Cloudflare. When it is over, a step that needs it asks for
 *  it again; the consent brings the person back to the same step. */
function Reconnect({ s }: { s: State }) {
  return (
    <div data-reconnect>
      <Notice
        title="Connect Cloudflare again"
        description="iterate keeps no lasting access to your Cloudflare account: it ends after about an hour, and when a deploy starts. You come back to this step."
        action={
          <CloudflareButton size="sm" href={authorizeHref(s)}>
            Connect Cloudflare
          </CloudflareButton>
        }
      />
      <TokenTick s={s} />
    </div>
  );
}

/** A part to open: the same look wherever one is (the permissions, the registrar hints, Update). */
function Disclosure({
  title,
  children,
  open,
  onOpenChange,
}: {
  title: string;
  children: ReactNode;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
}) {
  return (
    <Collapsible open={open} onOpenChange={onOpenChange}>
      <CollapsibleTrigger className="group flex min-h-10 items-center gap-1.5 text-sm font-medium hover:underline sm:min-h-0">
        <ChevronDown className="size-4 transition group-data-panel-open:rotate-180" aria-hidden />
        {title}
      </CollapsibleTrigger>
      <CollapsibleContent className="pt-3">{children}</CollapsibleContent>
    </Collapsible>
  );
}

/** What iterate asks Cloudflare for, and why: shown before the consent that lists them. */
function Permissions() {
  return (
    <Disclosure title="What iterate asks Cloudflare for">
      <ul role="list" className="space-y-2 text-sm sm:space-y-1.5">
        {permissions.map(([scope, why]) => (
          <li key={scope} className="flex flex-col gap-x-2 sm:flex-row">
            <span className="shrink-0 font-mono text-xs leading-5 text-muted-foreground sm:w-44">
              {scope}
            </span>
            <span>{why}</span>
          </li>
        ))}
      </ul>
      {wider.length > 0 && (
        <div data-wider className="mt-4 space-y-2 border-t pt-3 text-sm sm:space-y-1.5">
          <p className="font-medium">And the rest of the account, in the same consent</p>
          <ul role="list" className="space-y-2">
            {wider.map(([title, why, scopes]) => (
              <li key={title}>
                <span className="font-medium">{title}.</span> {why}{" "}
                <span className="font-mono text-xs leading-5 break-words text-muted-foreground">
                  {scopes.join(" ")}
                </span>
              </li>
            ))}
          </ul>
        </div>
      )}
    </Disclosure>
  );
}

const NotListed = () => (
  <p className="text-xs text-muted-foreground">
    Don't see an account on Cloudflare's page? Its admin may have turned off access for third-party
    apps, or you're signed in to Cloudflare as someone else.
  </p>
);
const shortId = (id: string) => `…${id.slice(-6)}`;

/** A step's actions: on the step's left edge, right under what they act on, the main one first.
 *  On a phone each spans the width. */
function Footer({ children }: { children: ReactNode }) {
  return (
    <div className="mt-6 flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3 [&>*]:w-full sm:[&>*]:w-auto">
      {children}
    </div>
  );
}

/** What iterate does with a person's access to Cloudflare, in the same words wherever they give
 *  it: before Cloudflare's consent, and before the deploy that uses it. */
function KeepsNoAccess() {
  return (
    <p data-keeps-no-access className="flex gap-2 text-sm">
      <LockKeyhole aria-hidden className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
      <span>
        <b className="font-semibold">
          iterate keeps no long-lived access to your Cloudflare account:
        </b>{" "}
        the deploy uses the access you give and gives it up when it ends.
      </span>
    </p>
  );
}

/** For a step that asks Cloudflare by itself every few seconds: ask now, for a person who has
 *  just done the thing and does not want to wait for the next question. */
function CheckAgain({ check, size = "sm" }: { check: () => Promise<unknown>; size?: "sm" | "lg" }) {
  const [asking, setAsking] = useState(false);
  return (
    <Btn
      variant="outline"
      size={size}
      data-check-again
      loading={asking}
      onClick={() => {
        setAsking(true);
        void check().finally(() => setAsking(false));
      }}
    >
      Check again
    </Btn>
  );
}

/** The step's problem from the state: "Title\nWhat to do", or one sentence under a general title. */
function StateProblem({ s, title = "That didn't work" }: { s: State; title?: string }) {
  if (!s.error) return null;
  const [first, ...rest] = s.error.split("\n");
  return rest.length ? (
    <Problem title={first} text={rest.join(" ")} />
  ) : (
    <Problem title={title} text={s.error} />
  );
}

// ── 1 Account ─────────────────────────────────────────────────────────────────────────────────
// New (recommended): a light consent (who you are), we create "iterate", then one full consent for it.
// Existing: one full consent; Cloudflare's own account picker is the list of their accounts.

/** Which page of the account step: where they are between "not connected" and "authorized for one".
 *  `choosing`: they went back to the choice of new or existing, connected already. */
type AccountPart = "start" | "create" | "created" | "authorize" | "pick" | "chosen";
const accountPart = (s: State): AccountPart => {
  if (!s.me || s.choosing) return "start";
  const full = s.me.level === "full";
  if (full && s.me.accounts.some((a) => a.id === s.account)) return "chosen";
  if (s.want === "new") return s.created ? "created" : "create";
  return full ? "pick" : "authorize";
};
const accountHeadings: Record<AccountPart, string> = {
  start: "Connect a Cloudflare account",
  create: "Create a new Cloudflare account",
  created: "Give iterate access to the new account",
  authorize: "Give iterate access to your account",
  pick: "Which account should iterate use?",
  chosen: "Your Cloudflare account",
};
/** The account step's parts, for the step list. The first one is the way back to the choice. */
const accountSubsteps = (s: State): SetupSubstep[] => {
  const part = accountPart(s);
  const at = part === "pick" ? "authorize" : part;
  const fresh = s.want === "new";
  return [
    { id: "start", title: "New or existing account", done: part !== "start" },
    ...(fresh ? [{ id: "create", title: "Create a new account", done: !!s.created }] : []),
    { id: fresh ? "created" : "authorize", title: "Give iterate access", done: part === "chosen" },
  ].map(({ id, title, done }) => ({
    id,
    title,
    state: id === at ? "now" : done ? "done" : "todo",
    onSelect:
      id === "start" && part !== "start"
        ? () => setState({ choosing: true, error: null })
        : undefined,
  }));
};

function AccountStep({ s }: { s: State }) {
  const part = accountPart(s);
  if (part === "chosen") return <AccountChosen s={s} />;
  if (part === "start") return <AccountStart s={s} />;
  if (part === "create") return <AccountCreate s={s} />;
  if (part === "created") return <AccountCreated s={s} created={s.created!} />;
  if (part === "authorize") return <AccountAuthorize s={s} />;
  return <AccountPick s={s} />;
}

/** Back out of the account this page created: it stays in Cloudflare (no API deletes one). Then
 *  an existing account, or the form that makes another new one. */
const backOut = (s: State, want: State["want"]) => {
  void call("POST", "/api/account/forget"); // or a new tab would offer it again
  setState({
    want,
    abandoned: s.created,
    created: null,
    account: want === "new" ? "new" : "",
    readiness: null,
    maxStep: 0,
    step: 0,
    error: null,
    choosing: false,
  });
};

/** On from the choice of new or existing, connected already. Nothing changes if the choice didn't. */
const choose = (s: State) => {
  if (s.want === "existing" && s.created) return backOut(s, "existing");
  setState({
    choosing: false,
    error: null,
    // a new account: the one this person made here before, or the form that makes one
    ...(s.want === "new" &&
      (s.created ? { account: s.created.id } : { account: "new", readiness: null, maxStep: 0 })),
  });
};

function AbandonedNote({ s }: { s: State }) {
  if (!s.abandoned) return null;
  return (
    <Notice
      title={`“${s.abandoned.name}” stays in your Cloudflare account`}
      description="Cloudflare doesn't let apps delete accounts. Delete it in the dashboard if you don't want it: open it, then Manage Account → Configurations."
      action={<ExternalButton href={dashUrl(s.abandoned.id)}>Open it</ExternalButton>}
    />
  );
}

/** What a step settled on (the account, the domain), as a thing on the page: its name, and one line about it. */
function ChosenCard({
  name,
  note,
  ...data
}: {
  name: string;
  note: ReactNode;
  "data-account"?: string;
  "data-chosen"?: string;
}) {
  return (
    <div className="flex items-start gap-3 rounded-lg border bg-card p-4" {...data}>
      <CircleCheck className="mt-0.5 size-5 shrink-0 fill-success text-card" aria-hidden />
      <div className="min-w-0">
        <div className="truncate font-medium">{name}</div>
        <div className="text-sm text-muted-foreground">{note}</div>
      </div>
    </div>
  );
}

/** Done already (they came back to this step): what they chose, and the way to change it. */
function AccountChosen({ s }: { s: State }) {
  return (
    <div>
      <ChosenCard
        data-account={accountName(s)}
        name={accountName(s)}
        note={
          <>
            Authorized by {s.me?.user?.email} · {shortId(s.account)}
          </>
        }
      />
      <Footer>
        <NextButton>Continue</NextButton>
        <Btn
          variant="ghost"
          size="lg"
          onClick={() =>
            s.created?.id === s.account
              ? backOut(s, "existing")
              : setState({ account: "", readiness: null, maxStep: 0, step: 0 })
          }
        >
          Use a different account
        </Btn>
      </Footer>
    </div>
  );
}

/** What stands under a button that opens Cloudflare's consent page: what it asks for, and what to do when an account isn't listed. */
function ConsentNotes({ notListed = false }: { notListed?: boolean }) {
  return (
    <div className="mt-6 space-y-3 border-t pt-4">
      <KeepsNoAccess />
      <p data-why-long className="text-sm text-muted-foreground">
        Cloudflare's list is long. The account is iterate's own sandbox, so iterate asks once for
        everything that it and your agents can need there. It holds that access for an hour at most.
      </p>
      <Permissions />
      {notListed && <NotListed />}
    </div>
  );
}

/** After a sign-out: what became of iterate's access to Cloudflare (`signedOut` in api.ts). */
function SignedOut() {
  if (!signedOut) return null;
  if (signedOut === "ended" || signedOut === "none")
    return (
      <Notice
        className="mb-5"
        title={
          <span data-signed-out={signedOut}>
            {signedOut === "ended"
              ? "Signed out. Cloudflare access is ended."
              : "Signed out. iterate held no Cloudflare access."}
          </span>
        }
      />
    );
  return (
    <Notice
      className="mb-5"
      variant="destructive"
      title={
        <span data-signed-out={signedOut}>Signed out. Cloudflare did not confirm the end.</span>
      }
      description="iterate dropped its copy of the access, which ends by itself within the hour. To end it now, remove “Iterate Cloud” in the Cloudflare dashboard: your profile, then Access Management, then Connected Applications."
    />
  );
}

/** New or existing. Not connected yet: choose first, then Cloudflare. Connected already (they came
 *  back to the choice): on with it from here. */
function AccountStart({ s }: { s: State }) {
  // Signed in, with access to Cloudflare still: on from here. Signed in with the access gone (a
  // deploy took it, or it ran out) is as nobody for this step: Cloudflare comes first again.
  const connected = !!s.me && s.me.connected !== false;
  // A person whose accounts hold a deployment is not signing up: they came from the list for one
  // more. Before the list is read, nobody signed in counts as signing up, and a person whose
  // accounts are being read waits for the answer. A read that failed says nothing about what the
  // accounts hold, so it shows no notice.
  const list = useDeployments(s.me?.connected === true).data;
  const signingUp = list ? list.ok && list.deployments.length === 0 : s.me?.connected !== true;
  return (
    <div>
      {!s.me && <SignedOut />}
      {signingUp && (
        <WalkthroughOnly
          className="mb-5"
          title="New here? Sign-up is by personal walkthrough only"
        />
      )}
      <ChoiceCards
        label="Account"
        value={s.want}
        onValueChange={(v) => setState({ want: v as State["want"], error: null })}
        choices={[
          {
            value: "new",
            label: (
              <span className="flex flex-wrap items-center gap-2">
                A new Cloudflare account <Badge variant="secondary">Recommended</Badge>
              </span>
            ),
            description:
              "Free to create. It keeps iterate's Workers, domain and bills apart from your other accounts.",
          },
          {
            value: "existing",
            label: "An account I already have",
            description: "You select it on Cloudflare's next page.",
          },
        ]}
      />
      {s.error && (
        <div className="mt-5">
          <StateProblem s={s} title="Cloudflare didn't connect" />
        </div>
      )}
      {/* Cloudflare's sign-in lists accounts only to a person who has more than one, so this is
          said as a thing that can happen, on the page, and holds nobody up. */}
      {!connected && s.want === "new" && (
        <p data-any-account className="mt-5 text-sm text-muted-foreground">
          Cloudflare signs you in first. If it asks you to pick an account, pick any one: this step
          reads only your name and email, so the new account is made in your name.
        </p>
      )}
      {!connected && s.want === "existing" && <TokenTick s={s} />}
      <Footer>
        {connected ? (
          <Btn variant="default" size="lg" data-account-continue onClick={() => choose(s)}>
            Continue
          </Btn>
        ) : (
          <CloudflareButton
            href={s.want === "new" ? "/connect?level=identity" : authorizeHref(s)}
            // back from Cloudflare, the step goes on from the choice made here
            onClick={() => setState({ choosing: false })}
          >
            Continue with Cloudflare
          </CloudflareButton>
        )}
      </Footer>
      {!connected &&
        (s.want === "existing" ? (
          <ConsentNotes notListed />
        ) : (
          <div className="mt-6 border-t pt-4">
            <KeepsNoAccess />
          </div>
        ))}
    </div>
  );
}

/** Connected as who they are, for a new account: create it, then on to the full consent for it at
 *  once. What that consent asks is said here, before. */
function AccountCreate({ s }: { s: State }) {
  const [busy, setBusy] = useState(false);
  /** `withoutTokens`: then the consent without the scope that makes API tokens. */
  const create = async (withoutTokens = s.withoutTokens) => {
    if (!s.name.trim() || !/^[^@\s]+@[^@\s]+$/.test(s.email.trim()))
      return setState({
        error: "Your name or email is missing\nFill in both, then create the account.",
      });
    const key = s.acctKey || crypto.randomUUID().replace(/-/g, "");
    setState({ acctKey: key, error: null });
    setBusy(true);
    try {
      const d = await call("POST", "/api/account", { name: s.acctName.trim(), key });
      if (!d.account)
        return setState({ error: `Cloudflare didn't create the account\n${errorOf(d)}` });
      setState({ created: d.account, acctKey: null, withoutTokens });
      // on to the consent for it at once: the second consent is the next click of the same step
      location.assign(authorizeHref(s, withoutTokens || undefined));
    } finally {
      setBusy(false);
    }
  };
  return (
    <form
      className="space-y-5"
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        void create();
      }}
    >
      <AbandonedNote s={s} />
      <p className="text-muted-foreground">
        You will own it. iterate gets only the access you give on the next page.
      </p>
      <div className="grid gap-4 sm:grid-cols-2">
        <TextField
          label="Your name"
          autoComplete="name"
          value={s.name}
          onChange={(e) => setState({ name: e.target.value, error: null })}
        />
        <TextField
          label="Your email"
          type="email"
          autoComplete="email"
          value={s.email}
          onChange={(e) => setState({ email: e.target.value, error: null })}
        />
      </div>
      <TextField
        label="Account name"
        autoComplete="off"
        value={s.acctName}
        onChange={(e) => setState({ acctName: e.target.value })}
      />
      <p data-asks-twice className="text-sm text-muted-foreground">
        Then Cloudflare asks a second time, for the new account. Its page lists all your accounts:
        select only the new one, then authorize.
      </p>
      <TokenTick s={s} without={() => void create(true)} />
      <StateProblem s={s} />
      <Footer>
        <Btn type="submit" variant="default" size="lg" loading={busy}>
          Create account
        </Btn>
      </Footer>
      <ConsentNotes />
    </form>
  );
}

/** Created, and back from Cloudflare with no consent for it (cancelled, or a new tab): one consent
 *  with everything, for it. The account is the thing on the page; what to do next is under it,
 *  with its button. "Make another account" leaves it in Cloudflare and goes back to the form; the
 *  step list's "New or existing account" leads to an existing one instead. */
function AccountCreated({ s, created }: { s: State; created: { id: string; name: string } }) {
  return (
    <div>
      <ChosenCard
        data-account={created.name}
        name={created.name}
        note={<>New account, created for {s.email || s.me?.user?.email}</>}
      />
      <p className="mt-5 text-muted-foreground">
        Cloudflare's next page lists all your accounts. Select only{" "}
        <b className="font-semibold text-foreground">{created.name}</b>, then authorize.
      </p>
      <TokenTick s={s} />
      {s.error && (
        <div className="mt-5">
          <StateProblem s={s} />
        </div>
      )}
      <Footer>
        <CloudflareButton href={authorizeHref(s)}>Authorize iterate</CloudflareButton>
        <Btn variant="ghost" size="lg" onClick={() => backOut(s, "new")}>
          Make another account
        </Btn>
      </Footer>
      <ConsentNotes />
    </div>
  );
}

/** An existing account, not authorized for it yet. */
function AccountAuthorize({ s }: { s: State }) {
  return (
    <div>
      <div className="space-y-4">
        <AbandonedNote s={s} />
        <p className="text-muted-foreground">
          On Cloudflare's next page, select the account iterate should use, then authorize.
        </p>
        <StateProblem s={s} title="Cloudflare didn't connect" />
      </div>
      <TokenTick s={s} />
      <Footer>
        <CloudflareButton href={authorizeHref(s)}>Authorize iterate</CloudflareButton>
      </Footer>
      <ConsentNotes notListed />
    </div>
  );
}

/** They selected several on Cloudflare's page: which one. */
function AccountPick({ s }: { s: State }) {
  const reach = s.me?.accounts || [];
  return (
    <div>
      <div className="space-y-5">
        <AbandonedNote s={s} />
        <ChoiceCards
          label="Which account should iterate use?"
          value={s.account}
          onValueChange={(v) => setState({ account: v, readiness: null })}
          choices={reach.map((a) => ({ value: a.id, label: a.name, description: shortId(a.id) }))}
        />
        <StateProblem s={s} title="Cloudflare didn't connect" />
      </div>
      <Footer>
        <NextButton disabled={!reach.some((a) => a.id === s.account)}>Continue</NextButton>
      </Footer>
      <p className="mt-6 border-t pt-4 text-sm text-muted-foreground">
        Another account?{" "}
        <a className="text-link hover:underline" href={authorizeHref(s)}>
          Authorize it on Cloudflare
        </a>{" "}
        and select it there.
      </p>
      <TokenTick s={s} />
    </div>
  );
}

// ── 3 Ready (after the domain) ───────────────────────────────────────────────────────────────────────────────────

/** The accounts this tab gave a workers.dev address by itself: once each, then the person's button. */
const workersDevTried = new Set<string>();

/** Cloudflare's answers for the checklist. Asked again every 3 seconds while something is missing,
 *  and when they come back to the tab; one question at a time (Cloudflare can take 20 seconds). */
function useReadiness(s: State) {
  const all = readyAll(s);
  const q = useQuery({
    queryKey: ["readiness", s.account],
    enabled: !!s.account && s.account !== "new",
    queryFn: async () => {
      let d = await call("GET", `/api/readiness?account=${s.account}`);
      // no workers.dev address: the Cloud gives it the account's name from their email, unasked
      if (d.ok && d.workersDev === false && !workersDevTried.has(s.account)) {
        workersDevTried.add(s.account);
        const made = await call("POST", "/api/subdomain", { account: s.account });
        if (made.subdomain) d = { ...d, workersDev: made.subdomain };
      }
      setState({
        readiness: d.ok
          ? {
              workersPaid: d.workersPaid,
              r2: d.r2,
              paymentMethod: d.paymentMethod,
              card: d.card,
              workersDev: d.workersDev,
            }
          : {
              workersPaid: null,
              r2: null,
              paymentMethod: null,
              card: null,
              workersDev: null,
            },
      });
      return Date.now();
    },
    refetchInterval: all ? false : 3_000,
    refetchOnWindowFocus: !all,
    staleTime: 0,
  });
  const checked = q.data
    ? new Date(q.data).toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      })
    : null;
  return { all, checked, check: () => q.refetch() };
}

function ReadyStep({ s }: { s: State }) {
  const { all, checked, check } = useReadiness(s);
  const r = s.readiness;
  const { blockers, next, unknown } = whatsLeft(r);
  const said = useDoneAnnouncement(r);
  // Cloudflare said no to none and left one unanswered: they can go on, warned. Until then the
  // next item's button is the thing to press.
  const open = !!r && unknown && blockers.length === 0;
  return (
    <>
      <NotGranted s={s} />
      <ReadyList s={s} next={next} check={check} />
      <p className="sr-only" role="status">
        {said}
      </p>
      {!all && (
        <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-2">
          <p className="text-xs text-muted-foreground">
            Each item turns green by itself.{checked ? ` Last checked ${checked}.` : ""}
          </p>
          <CheckAgain check={check} />
        </div>
      )}
      {open && (
        <p className="mt-4 text-sm text-muted-foreground">
          Cloudflare didn't answer every check. A deploy can fail if one of these is missing.
        </p>
      )}
      <ReadyDomain s={s} mayGoOn={all || open} />
      <ReadyOnward s={s} all={all} open={open} />
    </>
  );
}

/** The domain, once the account is ready (or may go on, warned): the purchase of the name chosen
 *  in the step before, or the way back to that step when none is chosen. */
function ReadyDomain({ s, mayGoOn }: { s: State; mayGoOn: boolean }) {
  // The step before this one chose the domain. One to buy is bought here, once the account can pay.
  const buying = toBuy(s);
  if (buying)
    return mayGoOn ? (
      <BuyChosen s={s} />
    ) : (
      <p data-buy-waits className="mt-4 text-sm text-muted-foreground">
        You buy <span className="text-foreground">{buying.name}</span> here when every item is
        green.
      </p>
    );
  if (s.result || !mayGoOn) return null;
  return (
    <div className="mt-6">
      <Notice
        title="Pick a domain first"
        description="iterate goes on a domain of yours."
        action={
          <Btn variant="outline" size="sm" onClick={() => setState({ step: DOMAIN_STEP })}>
            Pick a domain
          </Btn>
        }
      />
    </div>
  );
}

/** The way on from a ready account with a domain: Continue, or Continue anyway when Cloudflare
 *  left a check unanswered. */
function ReadyOnward({ s, all, open }: { s: State; all: boolean; open: boolean }) {
  if (!s.result) return null;
  return (
    <>
      {all && (
        <div
          data-ready-done
          className="mt-6 flex flex-col gap-4 rounded-lg border bg-card p-4 sm:flex-row sm:items-center sm:justify-between"
        >
          <p className="flex items-center gap-2.5 font-medium">
            <CircleCheck aria-hidden className="size-5 shrink-0 fill-success text-card" />
            Your account is ready.
          </p>
          <NextButton prominent>Continue</NextButton>
        </div>
      )}
      {open && (
        <Footer>
          <NextButton variant="outline">Continue anyway</NextButton>
        </Footer>
      )}
    </>
  );
}

/** The purchase of the name chosen in the domain step: the name with the way back to that step,
 *  then who it is registered to and the button that buys it. */
function BuyChosen({ s }: { s: State }) {
  const chosen = s.choice!;
  return (
    <div data-buy-chosen className="mt-6 space-y-4">
      <dl className="divide-y border-y text-sm">
        <TrailRow
          label="Domain"
          chosen={chosen.name}
          change={() => setState({ step: DOMAIN_STEP, choice: null, error: null })}
        >
          <span className="break-all">{chosen.name}</span>
          <span className="block font-normal text-muted-foreground sm:ml-3 sm:inline">
            {money(chosen)} a year
          </span>
        </TrailRow>
      </dl>
      <Purchase s={s} finish={(result) => settleDomain(result, DEPLOY_STEP)} />
    </div>
  );
}

/** Cloudflare's billing pages refuse the owner of an account for its first minute or two, in
 *  words that name an administrator the owner does not have. Said on an account the wizard made. */
const NEW_ACCOUNT_BILLING =
  " On a new account, Cloudflare's billing page can say “contact your administrator” for a minute or two. Wait a minute, then open it again.";

type Next = "card" | "paid" | "r2" | "dev" | null;
/** The checklist's items in order, each with Cloudflare's answer: yes, no, null (it didn't say) or
 *  undefined (not asked yet). The page's list and the step list's parts both read this. */
const readyItems = (r: State["readiness"]) =>
  [
    { id: "card", title: "Payment method", state: r?.paymentMethod },
    { id: "paid", title: "Workers Paid", state: r?.workersPaid },
    { id: "r2", title: "R2 storage", state: r?.r2 },
    {
      id: "dev",
      title: "workers.dev address",
      state: !r ? undefined : r.workersDev === null ? null : !!r.workersDev,
    },
  ] satisfies { id: Next; title: string; state: boolean | null | undefined }[];

/** What stops a deploy (Cloudflare said no to these: it fails part way), the first item to do (its
 *  button is the one to press), and whether Cloudflare left a check unanswered (that doesn't hold
 *  them here: they can go on, warned). */
function whatsLeft(r: State["readiness"]): { blockers: string[]; next: Next; unknown: boolean } {
  if (!r) return { blockers: ["the checks"], next: null, unknown: false };
  const items = readyItems(r);
  return {
    blockers: items.filter((i) => i.state === false).map((i) => i.title),
    next: items.find((i) => i.state === false)?.id ?? null,
    unknown: items.some((i) => i.state === null),
  };
}

/** For a screen reader: an item's name, said once when it turns done (not at every check). */
function useDoneAnnouncement(r: State["readiness"]) {
  const done = !r
    ? null
    : readyItems(r)
        .filter((i) => i.state)
        .map((i) => i.title)
        .join(", ");
  const [seen, setSeen] = useState(done);
  const [said, setSaid] = useState("");
  if (seen !== done) {
    setSeen(done);
    const had = new Set((seen || "").split(", "));
    const fresh = (done || "").split(", ").filter((n) => n && !had.has(n));
    // oxlint-disable-next-line iterate/simple-truthiness-check -- seen "" (a readiness with nothing done) must announce what turns done; only null (no readiness yet) stays silent
    if (seen !== null && fresh.length) setSaid(`Done: ${fresh.join(", ")}`);
  }
  return said;
}

/** The permissions Cloudflare didn't grant (they unticked some on its page), and the way to fix it. */
function NotGranted({ s }: { s: State }) {
  const missing = s.me?.missing || [];
  if (!missing.length) return null;
  const whys = missing.map((scope) => permissions.find(([id]) => id === scope)?.[1] || scope);
  return (
    <div className="mb-4">
      <Notice
        variant="destructive"
        icon={<CircleAlert />}
        title="Cloudflare didn't grant every permission"
        description={
          <>
            Without these, some checks below can't work:
            <ul role="list" className="mt-1 list-disc pl-4">
              {whys.map((w) => (
                <li key={w}>{w}</li>
              ))}
            </ul>
          </>
        }
        action={
          <LinkBtn variant="outline" size="sm" href={authorizeHref(s)}>
            Authorize again
          </LinkBtn>
        }
      />
    </div>
  );
}

/** The four things, each with what makes it so; the next one to do in Cloudflare's orange. */
function ReadyList({ s, next, check }: { s: State; next: Next; check: () => Promise<unknown> }) {
  const r = s.readiness;
  const state = (v: boolean | null | undefined) => (r ? v : undefined);
  return (
    <Checklist>
      <Item
        next={next === "card"}
        state={state(r?.paymentMethod)}
        title="Payment method"
        text={
          r?.paymentMethod
            ? `${cap(r.card?.brand || "Card")} ending ${r.card?.last4 || "····"}`
            : `Pays for Workers and the domain.${s.created?.id === s.account ? NEW_ACCOUNT_BILLING : ""}`
        }
        action={
          <ExternalButton
            next={next === "card"}
            href={dashUrl(`${s.account}/billing/subscriptions?paymentMethod=add`)}
          >
            Add card
          </ExternalButton>
        }
      />
      <Item
        next={next === "paid"}
        state={state(r?.workersPaid)}
        title="Workers Paid"
        text={
          r?.workersPaid
            ? "Subscribed"
            : "Cloudflare's $5-a-month plan. iterate's servers and sandboxes need it. On Cloudflare's page, Workers Paid can look selected before you have it: press its purchase button. Your bank may ask you to confirm. Do that, then come back here."
        }
        action={
          <ExternalButton next={next === "paid"} href={dashUrl(`${s.account}/workers/plans`)}>
            Subscribe
          </ExternalButton>
        }
      />
      <Item
        next={next === "r2"}
        state={state(r?.r2)}
        title="R2 storage"
        text={r?.r2 ? "On" : "Where iterate keeps files. Free up to 10 GB a month."}
        action={
          <ExternalButton next={next === "r2"} href={dashUrl(`${s.account}/r2/overview`)}>
            Turn on
          </ExternalButton>
        }
      />
      <Item
        next={next === "dev"}
        state={state(r?.workersDev === null ? null : !!r?.workersDev)}
        title="workers.dev address"
        text={
          r?.workersDev ? `${r.workersDev}.workers.dev` : "A free web address for your account."
        }
        action={<WorkersDev s={s} next={next === "dev"} onDone={check} />}
      />
    </Checklist>
  );
}

/** The account's workers.dev name, set from here: a name from the account, another if it's taken. */
function WorkersDev({
  s,
  onDone,
  next = false,
}: {
  s: State;
  onDone: () => unknown;
  next?: boolean;
}) {
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);
  const base =
    (s.name.split(" ")[0] || accountName(s))
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-|-$/g, "") || "iterate";
  const create = async () => {
    setBusy(true);
    setProblem(null);
    try {
      for (const name of [
        `${base}-iterate`,
        ...[1, 2, 3].map(() => `${base}-${Math.random().toString(36).slice(2, 6)}`),
      ]) {
        const d = await call("POST", "/api/subdomain", { account: s.account, name });
        if (d.subdomain) return onDone();
        if (!d.taken) return setProblem(errorOf(d));
      }
      setProblem("Every name we tried was taken.");
    } finally {
      setBusy(false);
    }
  };
  if (problem)
    return (
      <Aside note={problem}>
        <ExternalButton next={next} href={dashUrl(`${s.account}/workers/onboarding`)}>
          Create in Cloudflare
        </ExternalButton>
      </Aside>
    );
  return (
    <Btn variant={next ? "default" : "outline"} size="sm" onClick={create} loading={busy}>
      Create address
    </Btn>
  );
}

/** An item's action with a line under it: why it moved to Cloudflare, or what happens next. */
function Aside({ note, children }: { note: string; children?: ReactNode }) {
  return (
    <div className="flex flex-col gap-1 sm:items-end">
      {children}
      <span className="text-xs text-muted-foreground sm:max-w-48 sm:text-right" role="status">
        {note}
      </span>
    </div>
  );
}

/** A readiness item: Cloudflare's yes (done), no (todo), no answer yet (checking) or no answer at all. */
function Item({
  state,
  title,
  text,
  action,
  next = false,
}: {
  state: boolean | null | undefined;
  title: string;
  text: string;
  action?: ReactNode;
  next?: boolean;
}) {
  const st: ChecklistState =
    state === undefined
      ? "checking"
      : state === true
        ? "done"
        : state === null
          ? "unknown"
          : "todo";
  return (
    <ChecklistItem
      state={st}
      data-item={title}
      data-next={next || undefined}
      className={next ? "bg-cloudflare/5" : undefined}
      title={title}
      action={action}
      description={`${state === null ? "Cloudflare didn't say. " : ""}${text}`}
    />
  );
}

const cap = (t: string) => t.charAt(0).toUpperCase() + t.slice(1);

/** After a link that opens another tab: the arrow, and the same in words for a screen reader. */
const NewTab = ({ className = "size-3.5" }: { className?: string }) => (
  <>
    <ExternalLink className={`inline ${className}`} aria-hidden />
    <span className="sr-only"> (opens in a new tab)</span>
  </>
);

/** A link into Cloudflare's dashboard, in a new tab. The next thing to do is in Cloudflare's orange. */
const ExternalButton = ({
  href,
  children,
  next = false,
}: {
  href: string;
  children: ReactNode;
  next?: boolean;
}) =>
  next ? (
    <CloudflareButton size="sm" href={href} target="_blank" rel="noreferrer">
      {children}
      <NewTab />
    </CloudflareButton>
  ) : (
    <LinkBtn href={href} target="_blank" rel="noreferrer" variant="outline" size="sm">
      <span className="inline-flex items-center gap-1.5">
        {children}
        <NewTab className="size-3.5 text-muted-foreground" />
      </span>
    </LinkBtn>
  );

// ── 2 Domain ──────────────────────────────────────────────────────────────────────────────────

/** Pick a domain, one decision at a time: where it comes from, then which one, then (to buy one)
 *  who it's registered to. A decision made is one line with the way back to it; the others are gone. */
function DomainStep({ s }: { s: State }) {
  const start = { path: null, choice: null, zone: null, result: null, error: null };
  // done already (they came back to this step): the domain, and the way to another
  const buying = toBuy(s);
  if (s.result || buying)
    return (
      <div>
        {s.result ? (
          <ChosenCard
            data-chosen={s.result.name}
            name={s.result.name}
            note="iterate goes on this domain."
          />
        ) : (
          <ChosenCard
            data-chosen={buying!.name}
            data-to-buy
            name={buying!.name}
            note={`${money(buying!)} a year. You buy it in the next step, when your account can pay for it.`}
          />
        )}
        <Footer>
          <NextButton>Continue</NextButton>
          <Btn variant="ghost" size="lg" onClick={() => setState(start)}>
            Use a different domain
          </Btn>
        </Footer>
      </div>
    );
  if (!s.path) return <DomainHow />;
  return (
    <div className="space-y-6">
      <Trail s={s} />
      {s.path === "buy" ? (
        <DomainSearch s={s} finish={settleDomain} />
      ) : s.path === "have" ? (
        <Have s={s} finish={settleDomain} />
      ) : (
        <Elsewhere s={s} finish={settleDomain} />
      )}
    </div>
  );
}

/** The steps that another step sends the person to, by their place in STEPS. */
const DOMAIN_STEP = 1;
const READY_STEP = 2;
const DEPLOY_STEP = 3;

/** What a change of domain starts again: everything after the step the person is sent to. */
const afterDomain = (step: number) => ({ maxStep: step, tried: {}, finished: false });

/** A domain that iterate can go on: on to the account's checklist, or past it when Cloudflare has
 *  said yes to every item already (`to` says where, for the purchase that the checklist ends on). */
function settleDomain(result: State["result"], to?: number) {
  if (result) logEvent(`Using the domain ${result.name}`);
  setState((st) => {
    const step = to ?? (readyAll(st) ? DEPLOY_STEP : READY_STEP);
    return {
      result,
      step,
      error: null,
      choice: null,
      ...(st.result?.name === result?.name ? {} : afterDomain(step)),
    };
  });
  toTop();
}

/** A name to buy: chosen here, and bought on the account's checklist, which is the next step. */
function chooseToBuy(choice: Domain) {
  logEvent(`Chose ${choice.name} to buy`);
  setState({ choice, result: null, error: null, step: READY_STEP, ...afterDomain(READY_STEP) });
  toTop();
}

const HOW: { id: NonNullable<State["path"]>; title: string; text: string }[] = [
  { id: "buy", title: "Buy a new domain", text: "From about $10 a year. Ready at once." },
  {
    id: "have",
    title: "Use a domain already in this account",
    text: "One that is on Cloudflare already.",
  },
  {
    id: "elsewhere",
    title: "Use a domain I have elsewhere",
    text: "At GoDaddy, Namecheap or anywhere. You change its nameservers.",
  },
];

/** The first decision: where the domain comes from. Pressing one goes on. */
function DomainHow() {
  return (
    <ul role="list" aria-label="Where the domain comes from" className={ROWS}>
      {HOW.map((h) => (
        <li key={h.id}>
          <button
            type="button"
            data-how={h.id}
            className={`${ROW_BUTTON} py-4`}
            onClick={() =>
              setState({ path: h.id, result: null, choice: null, zone: null, error: null })
            }
          >
            <span className="min-w-0 flex-1">
              <span className="flex flex-wrap items-center gap-2 font-medium">
                {h.title}
                {h.id === "buy" && <Badge variant="secondary">Recommended</Badge>}
              </span>
              <span className="mt-0.5 block text-sm text-muted-foreground">{h.text}</span>
            </span>
            <ChevronRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />
          </button>
        </li>
      ))}
    </ul>
  );
}

/** The decisions made so far in this step, one line each, with the way back to each. */
function Trail({ s }: { s: State }) {
  const domain = s.choice?.name || s.zone?.name;
  return (
    <dl className="divide-y border-y text-sm">
      <TrailRow
        label="How"
        change={() => setState({ path: null, choice: null, zone: null, result: null, error: null })}
      >
        {HOW.find((h) => h.id === s.path)?.title}
      </TrailRow>
      {domain && (
        <TrailRow
          label="Domain"
          chosen={domain}
          change={() => setState({ choice: null, zone: null, result: null, error: null })}
        >
          <span className="break-all">{domain}</span>
          {s.choice && (
            <span className="block font-normal text-muted-foreground sm:ml-3 sm:inline">
              {money(s.choice)} a year
            </span>
          )}
        </TrailRow>
      )}
    </dl>
  );
}

function TrailRow({
  label,
  chosen,
  change,
  children,
}: {
  label: string;
  chosen?: string;
  change: () => void;
  children: ReactNode;
}) {
  return (
    <div
      className="flex items-center gap-3 py-1.5 sm:py-2.5"
      data-trail={label}
      data-chosen={chosen}
    >
      <dt className="w-16 shrink-0 text-muted-foreground">{label}</dt>
      <dd className="min-w-0 flex-1 font-medium">{children}</dd>
      <button
        type="button"
        className="flex min-h-10 shrink-0 items-center text-link hover:underline sm:min-h-0"
        onClick={change}
      >
        Change
        <span className="sr-only"> {label === "How" ? "how you get a domain" : "the domain"}</span>
      </button>
    </div>
  );
}

type Finish = (result: State["result"]) => void;
const money = (d: Domain) => (d.price ? `$${Number(d.price).toFixed(2)}` : "");
const SHOWN = 6;
const Loading = ({ children }: { children: ReactNode }) => (
  <p className="flex items-center gap-2 text-muted-foreground">
    <Spinner className="size-4" />
    {children}
  </p>
);
/** A row of a list to pick from (domains, zones): the whole row is the button. */
const ROW = "flex w-full items-center gap-3 px-4 py-3 text-left";
const ROW_BUTTON = `${ROW} hover:bg-muted focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground`;
const ROWS = "divide-y overflow-hidden rounded-lg border bg-card";

/** A year's price, and the renewal's when it differs. */
const Price = ({ d }: { d: Domain }) => (
  <span className="shrink-0 text-right text-sm">
    <span className="font-semibold">{money(d)}</span>
    <span className="text-muted-foreground">/yr</span>
    {d.renewal && d.renewal !== d.price && (
      <span className="block text-xs text-muted-foreground">
        renews at ${Number(d.renewal).toFixed(2)}/yr
      </span>
    )}
  </span>
);

/** Available first, cheapest first; .com before others at the same price. */
const byPrice = (domains: Domain[]) =>
  [...domains].sort(
    (a, b) =>
      Number(b.available) - Number(a.available) ||
      Number(a.price || 1e9) - Number(b.price || 1e9) ||
      Number(b.name.endsWith(".com")) - Number(a.name.endsWith(".com")),
  );

/** One field: a name with a dot is looked up; words (or nothing) give ideas from their name and the words. */
function DomainSearch({ s, finish }: { s: State; finish: Finish }) {
  const words = s.words.trim();
  const zones: Zone[] = useGet(`/api/zones?account=${s.account}`).data?.zones || []; // a search can find a domain that is already theirs
  const names = useQuery({
    queryKey: ["names", s.account, s.mode, words],
    queryFn: () =>
      words.includes(".")
        ? call(
            "GET",
            `/api/search?account=${s.account}&mode=${s.mode}&q=${encodeURIComponent(words)}`,
          )
        : call("POST", "/api/suggest", { account: s.account, mode: s.mode, name: s.name, words }),
  });
  const d = names.isFetching ? undefined : names.data;
  const problem = d && (!d.ok || (d.errors || []).length) ? errorOf(d) : null;
  const search = (typed: string) => {
    if (typed === words) void names.refetch();
    else setState({ words: typed });
  };
  return (
    <div className="space-y-4">
      <form
        className="flex items-end gap-2"
        onSubmit={(e) => {
          e.preventDefault();
          search(String(new FormData(e.currentTarget).get("words") || "").trim());
        }}
      >
        <div className="min-w-0 flex-1">
          <TextField
            label="Search for a name"
            placeholder="example.com, or words like agents studio"
            name="words"
            defaultValue={s.words}
            autoCapitalize="none"
            autoCorrect="off"
            spellCheck={false}
            enterKeyHint="search"
          />
        </div>
        <Btn type="submit" variant="outline" size="lg">
          Search
        </Btn>
      </form>
      {!d && <Loading>Checking names with Cloudflare…</Loading>}
      {problem && (
        <Problem
          title="Cloudflare didn't answer the search"
          text={problem}
          retry={() => void names.refetch()}
        />
      )}
      {d && !problem && (
        <DomainList key={words} list={byPrice(d.domains || [])} zones={zones} finish={finish} />
      )}
    </div>
  );
}

function DomainList({ list, zones, finish }: { list: Domain[]; zones: Zone[]; finish: Finish }) {
  const [all, setAll] = useState(false);
  if (!list.length)
    return <p className="text-sm text-muted-foreground">Nothing found. Try other words.</p>;
  return (
    <div>
      <ul role="list" aria-label="Domains" className={ROWS}>
        {(all ? list : list.slice(0, SHOWN)).map((d) => (
          <DomainRow
            key={d.name}
            d={d}
            zone={zones.find((z) => z.name === d.name)}
            finish={finish}
          />
        ))}
      </ul>
      {!all && list.length > SHOWN && (
        <Btn variant="ghost" size="sm" className="mt-2" onClick={() => setAll(true)}>
          Show {list.length - SHOWN} more
        </Btn>
      )}
    </div>
  );
}

/** A domain in the list: one to buy (press it), one that is theirs already (use it), or a taken one (not pressable). */
function DomainRow({ d, zone, finish }: { d: Domain; zone?: Zone; finish: Finish }) {
  const name = <span className="min-w-0 flex-1 truncate text-sm">{d.name}</span>;
  if (zone)
    return (
      <li>
        <button
          type="button"
          data-domain={d.name}
          data-yours
          className={ROW_BUTTON}
          onClick={() => {
            setState({ path: "have", zone, choice: null });
            if (zone.status === "active") finish({ name: zone.name, how: "have" });
          }}
        >
          {name}
          <span className="shrink-0 text-sm text-link">Already yours: use it</span>
          <ChevronRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />
        </button>
      </li>
    );
  if (!d.available)
    return (
      <li data-domain={d.name} data-taken className={`${ROW} text-muted-foreground`}>
        {name}
        <span className="shrink-0 text-xs">Taken</span>
        <span className="size-4 shrink-0" />
      </li>
    );
  return (
    <li>
      <button
        type="button"
        data-domain={d.name}
        className={ROW_BUTTON}
        onClick={() => chooseToBuy(d)}
      >
        {name}
        <Price d={d} />
        <ChevronRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />
      </button>
    </li>
  );
}

/** Who the domain is registered to, then the purchase: on the account's checklist, once the
 *  account can pay. The contact is asked only when buying, and only when Cloudflare has none on
 *  file for the account (one that already holds domains has one). */
function Purchase({ s, finish }: { s: State; finish: Finish }) {
  const empty: Contact = {
    name: s.name,
    email: s.email,
    phone: "",
    street: "",
    city: "",
    postal: "",
    country: homeCountry(),
  };
  const [c, setContact] = useState<Contact>({ ...empty, ...(s.contact || {}) });
  const [busy, setBusy] = useState<string | null>(null);
  const [problem, setProblem] = useState<Trouble | null>(null);
  const [form, setForm] = useState(false); // they chose to give other details
  const file = useGet(`/api/registrar/contact?account=${s.account}&mode=${s.mode}`).data;
  const onFile: { domains: number } | null | undefined = !file
    ? undefined
    : file.ok && file.onFile
      ? { domains: file.domains }
      : null; // undefined: still asking
  // oxlint-disable-next-line iterate/simple-truthiness-check -- onFile null (no contact on file) shows the form; undefined (still asking) must not
  const useForm = form || onFile === null;
  // the list they picked from is gone: the focus goes to what replaced it
  const heading = useRef<HTMLHeadingElement>(null);
  useEffect(() => {
    heading.current?.focus({ preventScroll: true });
  }, []);
  const domain = s.choice!.name;
  const real = s.mode === "production";
  const buy = async () => {
    let contacts: unknown;
    if (useForm) {
      const checked = registrantOf(c);
      if ("title" in checked) return setProblem(checked);
      setState({ contact: checked.contact });
      contacts = checked.contacts;
    }
    setProblem(null);
    setBusy("Registering…");
    try {
      const outcome = await register(s, domain, contacts, setBusy);
      if (outcome === "no contact") {
        setForm(true);
        return setProblem({
          title: "Cloudflare has no contact on file",
          text: "Fill in who the domain is registered to, then buy again.",
        });
      }
      if (outcome !== "registered") return setProblem(outcome);
      finish({ name: domain, how: real ? "bought" : "sandbox" });
    } finally {
      setBusy(null);
    }
  };
  return (
    <form
      className="space-y-4"
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        void buy();
      }}
    >
      <h3 ref={heading} tabIndex={-1} className="text-lg font-semibold outline-none">
        Register {domain}
      </h3>
      <Registrant
        onFile={onFile}
        useForm={useForm}
        other={() => setForm(true)}
        c={c}
        setC={(next) => {
          setContact(next);
          setProblem(null);
        }}
        invalid={problem?.fields}
      />
      {s.testMode && (
        <Label className="gap-2 font-normal">
          <Checkbox
            checked={!real}
            onCheckedChange={(on) => setState({ mode: on ? "sandbox" : "production" })}
          />
          Test mode: Cloudflare's sandbox, no charge, no real domain
        </Label>
      )}
      {problem && (
        <Problem
          title={problem.title}
          text={problem.text}
          href={problem.href}
          label={problem.label}
        />
      )}
      {/* a problem that is fixed in Cloudflare: its button is the one to press, not Buy */}
      <BuyBar
        busy={busy}
        // oxlint-disable-next-line iterate/simple-truthiness-check -- onFile undefined means still asking; null (no contact on file) is ready
        ready={onFile !== undefined}
        label={real ? `Buy for ${money(s.choice!)}` : "Buy in test mode"}
        quiet={!!problem?.href}
        note={
          real && !problem?.href
            ? `Cloudflare charges ${s.readiness?.card ? `your ${cap(s.readiness.card.brand || "card")} ending ${s.readiness.card.last4}` : "the card on your account"} when you press it. A registration can't be refunded.`
            : null
        }
      />
    </form>
  );
}

/** Who it's registered to: the contact Cloudflare holds already, or the form when it holds none. */
function Registrant({
  onFile,
  useForm,
  other,
  c,
  setC,
  invalid,
}: {
  onFile: { domains: number } | null | undefined;
  useForm: boolean;
  other: () => void;
  c: Contact;
  setC: (c: Contact) => void;
  invalid?: (keyof Contact)[];
}) {
  // oxlint-disable-next-line iterate/simple-truthiness-check -- onFile undefined means still asking; null (no contact on file) shows the form below
  if (onFile === undefined) return <Loading>Asking Cloudflare for your contact details…</Loading>;
  if (useForm || !onFile) return <ContactFields c={c} setC={setC} invalid={invalid} />;
  return (
    <p className="text-sm text-muted-foreground">
      Cloudflare registers it to the contact already on file for your {onFile.domains}{" "}
      {onFile.domains === 1 ? "domain" : "domains"}.{" "}
      <button type="button" className="text-link hover:underline" onClick={other}>
        Use other details
      </button>
    </p>
  );
}

/** The buy button (it submits the form) and, beside it, what a real purchase charges; while it works, what Cloudflare is doing. */
function BuyBar({
  busy,
  ready,
  label,
  note,
  quiet,
}: {
  busy: string | null;
  ready: boolean;
  label: string;
  note: string | null;
  quiet: boolean;
}) {
  return (
    <>
      <p className="sr-only" role="status">
        {busy}
      </p>
      <div className="flex flex-col gap-2 pt-2 sm:flex-row sm:items-center sm:gap-4">
        <Btn
          type="submit"
          variant={quiet ? "outline" : "default"}
          size="lg"
          className="w-full sm:w-auto"
          loading={!!busy}
          disabled={!ready}
        >
          {label}
        </Btn>
        {busy ? (
          <span className="text-sm text-muted-foreground" aria-hidden>
            {busy}
          </span>
        ) : (
          note && <p className="text-xs text-pretty text-muted-foreground">{note}</p>
        )}
      </div>
    </>
  );
}

const CONTACT_LABELS = {
  name: "Full name",
  email: "Email",
  phone: "Phone",
  street: "Street",
  city: "City",
  postal: "Postcode",
} as const;
type ContactField = keyof typeof CONTACT_LABELS;

/** The registrant, as Cloudflare's registrar takes it, or what to fix first (and in which fields). */
function registrantOf(c: Contact): { contact: Contact; contacts: unknown } | Trouble {
  const contact = { ...c, country: c.country.trim().toUpperCase() };
  const missing = (Object.keys(CONTACT_LABELS) as ContactField[]).filter((k) => !contact[k].trim());
  if (missing.length)
    return {
      title: "A few details are missing",
      text: `Fill in: ${missing.map((k) => CONTACT_LABELS[k]).join(", ")}.`,
      fields: missing,
    };
  const phone = registryPhone(contact.phone, contact.country);
  if (!phone)
    return {
      title: "Check the phone number",
      text: `We couldn't read it as a ${COUNTRIES[contact.country] || contact.country} number. Pick the country it belongs to.`,
      fields: ["phone"],
    };
  const address = {
    street: contact.street,
    city: contact.city,
    state: contact.city,
    postal_code: contact.postal,
    country_code: contact.country,
  };
  return {
    contact,
    contacts: {
      registrant: { email: contact.email, phone, postal_info: { name: contact.name, address } },
    },
  };
}

/** Who the domain is registered to: asked only when Cloudflare has no contact on file. */
function ContactFields({
  c,
  setC,
  invalid = [],
}: {
  c: Contact;
  setC: (c: Contact) => void;
  invalid?: (keyof Contact)[];
}) {
  const field = (k: ContactField, extra: Record<string, unknown> = {}) => (
    <TextField
      label={CONTACT_LABELS[k]}
      value={c[k]}
      onChange={(e) => setC({ ...c, [k]: e.target.value })}
      aria-invalid={invalid.includes(k) || undefined}
      {...extra}
    />
  );
  return (
    <>
      <p className="text-sm text-muted-foreground">
        Who the domain is registered to. Cloudflare hides it from public WHOIS.
      </p>
      <div className="grid gap-3 sm:grid-cols-2">
        {field("name", { autoComplete: "name" })}
        {field("email", { type: "email", autoComplete: "email" })}
        <SelectField
          label="Country"
          autoComplete="country"
          value={c.country}
          onChange={(v) => setC({ ...c, country: v || homeCountry() })}
          items={COUNTRIES}
        />
        {field("phone", {
          type: "tel",
          inputMode: "tel",
          autoComplete: "tel",
          placeholder: c.country === "GB" ? "07700 900123" : `+${DIAL[c.country] || ""} …`,
        })}
        {field("street", { autoComplete: "street-address", className: "sm:col-span-2" })}
        {field("city", { autoComplete: "address-level2" })}
        {field("postal", { autoComplete: "postal-code" })}
      </div>
    </>
  );
}

type Trouble = {
  title: string;
  text: string;
  href?: string;
  label?: string;
  fields?: (keyof Contact)[];
};

/** Buy it: register, wait for Cloudflare to finish, then make sure its zone is there. Says what
 *  Cloudflare is doing through `say`. "no contact" when it has none on file and none was given. */
async function register(
  s: State,
  domain: string,
  contacts: unknown,
  say: (text: string) => void,
): Promise<"registered" | "no contact" | Trouble> {
  const real = s.mode === "production";
  const d = await call("POST", "/api/register", {
    account: s.account,
    mode: s.mode,
    domain,
    ...(real && { confirm: domain }),
    contacts,
  });
  if (!d.ok && !contacts && /no registrant contact|address book/i.test(errorOf(d)))
    return "no contact";
  if (!d.ok) return registrarProblem(s, errorOf(d));
  let st = d;
  let registered = false;
  for (let i = 0; i < 40 && !registered; i++) {
    const state = String(st.result?.state || "");
    if (/succeeded|registered|active/.test(state) || (d.status === 201 && !state)) {
      registered = true;
      break;
    }
    if (/failed|action_required|blocked/.test(state)) {
      const e = st.result?.error || {};
      return registrarProblem(s, `${e.code || ""} ${e.message || state}`);
    }
    say(`Cloudflare says: ${state.replace(/_/g, " ") || "working"}…`);
    await new Promise((r) => setTimeout(r, 2500));
    st = await call(
      "GET",
      `/api/registration?account=${s.account}&mode=${s.mode}&domain=${domain}`,
    );
  }
  if (!registered)
    return {
      title: `Cloudflare is still registering ${domain}`,
      text: "Some registries take longer. Don't buy it again: open Registrations in Cloudflare, and come back when it shows there.",
      href: dashUrl(`${s.account}/domains/registrations`),
      label: "Open Registrations",
    };
  if (real) {
    const z = await call("GET", `/api/zone?account=${s.account}&name=${domain}`);
    setState({
      zone:
        z.zone ||
        (await call("POST", "/api/zone", { account: s.account, name: domain })).zone ||
        null,
    });
  }
  return "registered";
}

/** What the person does next, for the registrar refusals seen on a fresh account (10 Nov 2026). */
function registrarProblem(s: State, text: string) {
  if (/no registrant contact|address book/i.test(text))
    return {
      title: "Cloudflare needs a registrant contact",
      text,
      href: dashUrl(`${s.account}/domains/registrations`),
      label: "Open Registrations",
    };
  if (/billing_quote_failed|failed to create a quote/i.test(text))
    return {
      title: "Add a card to buy this domain",
      text: "This account has no card yet. Add one, then buy again.",
      href: dashUrl(`${s.account}/billing/subscriptions?paymentMethod=add`),
      label: "Add card",
    };
  if (/agreement/i.test(text))
    return {
      title: "Accept the Domain Registration Agreement",
      text,
      href: dashUrl(`${s.account}/domains/registrations`),
      label: "Open Registrations",
    };
  return { title: "Cloudflare refused the purchase", text };
}

function Have({ s, finish }: { s: State; finish: Finish }) {
  const q = useGet(`/api/zones?account=${s.account}`);
  const d = q.isFetching ? undefined : q.data;
  const problem = d && (!d.ok || (d.errors || []).length) ? errorOf(d) : null;
  if (s.zone && s.zone.status !== "active") return <Nameservers s={s} finish={finish} />;
  if (!d) return <Loading>Asking Cloudflare…</Loading>;
  if (problem)
    return (
      <Problem
        title="Cloudflare didn't list the domains"
        text={problem}
        retry={() => void q.refetch()}
      />
    );
  const zones: Zone[] = d.zones || [];
  if (!zones.length)
    return (
      <Notice
        title="No domains here yet"
        description="This account has no domains. Buy one, or add one you have elsewhere."
      />
    );
  return <ZoneList zones={zones} finish={finish} />;
}

/** The account's domains, all of them. More than a screenful gets a filter above the list. */
function ZoneList({ zones, finish }: { zones: Zone[]; finish: Finish }) {
  const [filter, setFilter] = useState("");
  const words = filter.trim().toLowerCase();
  const shown = words ? zones.filter((z) => z.name.includes(words)) : zones;
  return (
    <div className="space-y-3">
      {zones.length > 8 && (
        <div className="relative">
          <Search
            className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"
            aria-hidden
          />
          <Input
            type="search"
            aria-label="Filter your domains"
            placeholder={`Filter ${zones.length} domains`}
            className="h-10 bg-background pl-9"
            autoComplete="off"
            autoCapitalize="none"
            spellCheck={false}
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
          />
        </div>
      )}
      {!shown.length && (
        <p className="px-1 text-sm text-muted-foreground" role="status">
          No domain in this account matches “{filter.trim()}”.
        </p>
      )}
      {!!shown.length && <ZoneRows zones={shown} finish={finish} />}
    </div>
  );
}

function ZoneRows({ zones, finish }: { zones: Zone[]; finish: Finish }) {
  return (
    <ul role="list" aria-label="Your domains" className={ROWS}>
      {zones.map((z) => (
        <li key={z.id}>
          <button
            type="button"
            data-zone={z.name}
            className={ROW_BUTTON}
            onClick={() =>
              z.status === "active"
                ? (setState({ zone: z }), finish({ name: z.name, how: "have" }))
                : setState({ zone: z })
            }
          >
            <span className="min-w-0 flex-1 truncate text-sm">{z.name}</span>
            <Badge variant={z.status === "active" ? "secondary" : "outline"}>
              {z.status === "active" ? "Active" : "Needs nameservers"}
            </Badge>
            <ChevronRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />
          </button>
        </li>
      ))}
    </ul>
  );
}

function Elsewhere({ s, finish }: { s: State; finish: Finish }) {
  const [name, setName] = useState(s.zone?.name || "");
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);
  // a zone still waiting for its nameservers: the two to set. An active one: done, they can pick again.
  if (s.zone && s.zone.status !== "active") return <Nameservers s={s} finish={finish} />;
  const add = async () => {
    const domain = name
      .trim()
      .toLowerCase()
      .replace(/^https?:\/\//, "")
      .replace(/\/.*$/, "")
      .replace(/^www\./, "");
    if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(domain))
      return setProblem(
        `${domain ? `“${domain}”` : "That"} isn't a domain name. It looks like example.com.`,
      );
    setBusy(true);
    setProblem(null);
    let zone: Zone | null = null;
    let offline = false;
    try {
      const found = await call(
        "GET",
        `/api/zone?account=${s.account}&name=${encodeURIComponent(domain)}`,
      );
      offline = found.status === 0;
      zone =
        found.zone ||
        (offline
          ? null
          : (await call("POST", "/api/zone", { account: s.account, name: domain })).zone) ||
        null;
    } finally {
      setBusy(false);
    }
    if (!zone)
      return setProblem(
        offline ? OFFLINE : "Cloudflare didn't add it. The bar at the bottom shows what it said.",
      );
    setState({ zone });
    if (zone.status === "active") finish({ name: zone.name, how: "elsewhere" });
  };
  return (
    <form
      className="space-y-3"
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        void add();
      }}
    >
      <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
        <div className="min-w-0 flex-1">
          <TextField
            label="Your domain"
            placeholder="example.com"
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              setProblem(null);
            }}
            autoComplete="off"
            autoCapitalize="none"
            autoCorrect="off"
            spellCheck={false}
            inputMode="url"
          />
        </div>
        <Btn type="submit" variant="default" size="lg" loading={busy}>
          Add to Cloudflare
        </Btn>
      </div>
      {problem && <Problem title="That didn't work" text={problem} />}
    </form>
  );
}

function Nameservers({ s, finish }: { s: State; finish: Finish }) {
  const zone = s.zone!;
  // ask Cloudflare to look again every 15 seconds, and when they press Check again
  const q = useQuery({
    queryKey: ["zone-check", zone.id],
    enabled: zone.status !== "active",
    queryFn: async () => {
      const d = await call("PUT", `/api/zone/check?id=${zone.id}`);
      if (d.zone) {
        setState({ zone: d.zone });
        if (d.zone.status === "active")
          finish({ name: d.zone.name, how: s.path === "have" ? "have" : "elsewhere" });
      }
      return Date.now();
    },
    refetchInterval: 15_000,
    staleTime: 0,
  });
  return (
    <div className="space-y-4">
      <h3 className="text-lg font-semibold">Point {zone.name} at Cloudflare</h3>
      <p className="text-sm text-muted-foreground">
        At your registrar, replace all its nameservers with these two.
      </p>
      <div className="grid gap-2">
        {zone.nameServers.map((n, i) => (
          <CopyText key={n} text={n} label={`nameserver ${i + 1}`} />
        ))}
      </div>
      <Disclosure title="Where to find the setting">
        <ul role="list" className="space-y-1 text-sm text-muted-foreground">
          <li>
            <b>GoDaddy:</b> My Products → the domain → DNS → Nameservers → Change → “I'll use my own
            nameservers”.
          </li>
          <li>
            <b>Namecheap:</b> Domain List → Manage → Nameservers → Custom DNS.
          </li>
          <li>
            <b>Squarespace (Google Domains):</b> DNS → Domain nameservers → Use custom nameservers.
          </li>
          <li>
            <b>Porkbun:</b> Domain Management → Details → Authoritative Nameservers.
          </li>
          <li>If the domain uses DNSSEC, turn it off at the registrar first.</li>
        </ul>
      </Disclosure>
      <p className="text-sm text-muted-foreground">
        This usually takes minutes, sometimes up to a day. We check every 15 seconds. You can come
        back later: the domain stays in this account.
      </p>
      <Footer>
        <CheckAgain size="lg" check={() => q.refetch()} />
      </Footer>
    </div>
  );
}

// ── 4 Deploy ──────────────────────────────────────────────────────────────────────────────────

const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

/** Deploy iterate on the chosen domain: start the run, then watch it. One deployment owns one
 *  domain, so the domain names it. The run takes iterate's access to Cloudflare with it. */
function DeployStep({ s }: { s: State }) {
  const queryClient = useQueryClient();
  const path = deployPath(s);
  // the same cache entry as the step list and the try step: they all see it change
  const deploy = useGet(path, { refetchInterval: deployPoll, staleTime: 0 });
  const [starting, setStarting] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);
  const zone = s.zone && s.zone.name === s.result?.name ? s.zone : null;
  /** `recover`: the owner lost every passkey, so this update also makes a link that signs them in. */
  const start = async (recover = false) => {
    if (!zone || !path) return;
    setStarting(true);
    setProblem(null);
    try {
      const d = await call("POST", "/api/deploy", {
        account: s.account,
        zone: zone.name,
        zoneId: zone.id,
        email: s.email.trim(),
        ...(recover && { recover: true }),
      });
      if (d.status === 401) return; // the access is over: the button to connect again is there now
      if (!d.ok) return setProblem(errorOf(d));
      queryClient.setQueryData([path], d);
      setState((st) => ({
        me: st.me && { ...st.me, connected: !!d.connected },
        recovering: false,
      }));
    } finally {
      setStarting(false);
    }
  };
  const toDomain = (
    <Btn
      variant="outline"
      size="sm"
      onClick={() =>
        setState({ step: DOMAIN_STEP, path: null, choice: null, zone: null, result: null })
      }
    >
      Pick a domain
    </Btn>
  );
  if (!s.result)
    return (
      <Notice
        title="Pick a domain first"
        description="iterate goes on a domain of yours."
        action={toDomain}
      />
    );
  if (!path)
    return (
      <Notice
        title={`${s.result.name} is a test-mode domain`}
        description="Cloudflare's sandbox registers no real domain, so iterate can't go on it. Pick a real domain to deploy."
        action={toDomain}
      />
    );
  const d = deploy.data;
  if (!d) return <Loading>Asking how the deploy is going…</Loading>;
  if (!d.ok)
    return s.me?.connected === false ? (
      <Reconnect s={s} />
    ) : (
      <Problem
        title="We couldn't check the deploy"
        text={errorOf(d)}
        retry={() => void deploy.refetch()}
      />
    );
  const state: DeployState = { lines: [], steps: [], result: null, ...d.state };
  if (state.status === "idle")
    return (
      <DeploySetup
        s={s}
        zone={zone}
        start={() => void start()}
        starting={starting}
        problem={problem}
      />
    );
  return (
    <DeployProgress
      s={s}
      state={state}
      owner={d.owner || s.email}
      unanswered={state.status === "succeeded" && d.enrolled === false}
      retry={() => void start()}
      recover={() => void start(true)}
      starting={starting}
      problem={problem}
    />
  );
}

/** Before it starts: who signs in, where it goes, and what it takes. */
function DeploySetup({
  s,
  zone,
  start,
  starting,
  problem,
}: {
  s: State;
  zone: Zone | null;
  start: () => void;
  starting: boolean;
  problem: string | null;
}) {
  const domain = s.result!.name;
  const connected = s.me?.connected !== false;
  const active = zone?.status === "active";
  const emailOk = EMAIL.test(s.email.trim());
  const [asked, setAsked] = useState(false);
  return (
    <form
      className="space-y-5"
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        setAsked(true);
        if (connected && active && emailOk) start();
      }}
    >
      <div className="space-y-1.5">
        <TextField
          label="Your email"
          type="email"
          value={s.email}
          onChange={(e) => setState({ email: e.target.value })}
          error={asked && !emailOk ? "Give an email address you can read." : null}
          autoComplete="email"
          autoCapitalize="none"
          spellCheck={false}
        />
        <p className="text-sm text-muted-foreground">
          This address is the owner of your iterate. You sign in with a passkey, which you add right
          after the deploy. There is no password.
        </p>
      </div>
      <dl className="divide-y rounded-lg border bg-card text-sm">
        <SummaryRow label="Account">{accountName(s)}</SummaryRow>
        <SummaryRow label="Domain">{domain}</SummaryRow>
        <SummaryRow label="iterate's address">iterate.{domain}</SummaryRow>
      </dl>
      {s.result!.how !== "bought" && (
        <Notice
          icon={<CircleAlert />}
          title={`iterate takes all of ${domain}`}
          description="Every address on it, and its mail. Use a domain that serves nothing else."
        />
      )}
      {!active && connected && <ZoneWait s={s} />}
      {problem && <Problem title="The deploy didn't start" text={problem} />}
      <KeepsNoAccess />
      {!connected && <TokenTick s={s} />}
      <Footer>
        {connected ? (
          <Btn type="submit" variant="default" size="lg" loading={starting} disabled={!active}>
            Deploy iterate
          </Btn>
        ) : (
          <CloudflareButton href={authorizeHref(s)}>Connect Cloudflare to deploy</CloudflareButton>
        )}
        <span className="text-center text-sm text-muted-foreground sm:text-left">
          {connected ? "Takes a few minutes." : "iterate has no access to Cloudflare now."}
        </span>
      </Footer>
    </form>
  );
}

/** A domain Cloudflare hasn't finished (one just bought takes a moment): ask until it is active. */
function ZoneWait({ s }: { s: State }) {
  const domain = s.result!.name;
  const q = useGet(`/api/zone?account=${s.account}&name=${domain}`, {
    refetchInterval: 5_000,
    staleTime: 0,
  });
  const zone: Zone | undefined = q.data?.zone;
  useEffect(() => {
    if (zone?.status === "active") setState({ zone });
  }, [zone]);
  return (
    <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
      <Loading>Cloudflare is getting {domain} ready…</Loading>
      <CheckAgain check={() => q.refetch()} />
    </div>
  );
}

function SummaryRow({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="flex justify-between gap-4 px-4 py-2.5">
      <dt className="shrink-0 text-muted-foreground">{label}</dt>
      <dd className="min-w-0 truncate font-medium">{children}</dd>
    </div>
  );
}

/** While it runs and after: the steps ticking off, then the result. The raw log is there on request. */
function DeployProgress({
  s,
  state,
  owner,
  unanswered,
  retry,
  recover,
  starting,
  problem,
}: {
  s: State;
  state: DeployState;
  /** The address that signs in to the deployment. */
  owner: string;
  /** The run is done, and its address has not answered the Cloud yet. */
  unanswered: boolean;
  retry: () => void;
  /** An update that also makes the owner's one-use way in: they lost every passkey. */
  recover: () => void;
  starting: boolean;
  problem: string | null;
}) {
  const connected = s.me?.connected !== false;
  const [updating, setUpdating] = useState<boolean | null>(null);
  const waiting = useAnswerWait(state, unanswered);
  if (state.status === "succeeded" && !waiting)
    return (
      <Deployed domain={s.result!.name} notes={notesOf(state)}>
        <DeployLog state={state} domain={s.result!.name} />
        {/* closed until asked for; open when they come back from Cloudflare's page to run it */}
        <Disclosure
          title="Update iterate"
          open={updating ?? (s.me?.connected === true && !s.recovering)}
          onOpenChange={setUpdating}
        >
          <div className="space-y-3 text-sm" data-update>
            <p className="text-muted-foreground">
              Deploys the newest iterate with the settings your deployment keeps. It needs your
              access to Cloudflare again, and gives it up when the update ends.
            </p>
            <WithCloudflare s={s} connected={connected} run={retry} starting={starting}>
              Update iterate
            </WithCloudflare>
          </div>
        </Disclosure>
        <Disclosure
          title="Lost your passkey?"
          open={s.recovering}
          onOpenChange={(recovering) => setState({ recovering })}
        >
          <div className="space-y-3 text-sm" data-recover>
            <p className="text-muted-foreground">
              A passkey is the only way to sign in. This updates iterate and gives you a link that
              signs you in as <b className="font-medium text-foreground">{owner}</b> once, to add a
              new passkey. It needs your access to Cloudflare again: your Cloudflare account is the
              way back in, and mail is not.
            </p>
            <WithCloudflare s={s} connected={connected} run={recover} starting={starting}>
              Update and get a new link
            </WithCloudflare>
          </div>
        </Disclosure>
        {problem && <Problem title="The update didn't start" text={problem} />}
      </Deployed>
    );
  const failed = state.status === "failed";
  return (
    <div className="space-y-5">
      {failed && <DeployStopped state={state} again={problem} />}
      <DeployPhases state={state} />
      <DeployLog key={state.status} state={state} domain={s.result!.name} />
      {failed ? (
        <AfterFailure s={s} state={state} connected={connected} retry={retry} starting={starting} />
      ) : (
        <p className="flex items-center gap-2 text-sm text-muted-foreground">
          <Spinner className="size-4" />
          {waiting ? (
            <span data-waiting>Waiting for iterate.{s.result!.name} to answer…</span>
          ) : (
            "Takes a few minutes. You can leave this page open."
          )}
        </p>
      )}
    </div>
  );
}

/** A new name takes a moment to answer. Wait for it, a minute at most, before the page says
 *  "live" and sends anyone there: a browser that asks too early remembers that the name is unknown. */
function useAnswerWait(state: DeployState, unanswered: boolean): boolean {
  const until = unanswered ? (state.endedAt || 0) + 60_000 : 0;
  const [now, setNow] = useState(Date.now);
  useEffect(() => {
    if (until <= Date.now()) return;
    const timer = setTimeout(() => setNow(Date.now()), until - Date.now() + 50);
    return () => clearTimeout(timer);
  }, [until]);
  return until > now;
}

/** A button that starts a run with the person's access to Cloudflare, or the way to connect it
 *  again when the access is gone: the plain consent, which has nothing to tick. An update keeps the
 *  telemetry and the Cloudflare connection that the stack has. */
function WithCloudflare({
  s,
  connected,
  run,
  starting,
  children,
}: {
  s: State;
  connected: boolean;
  run: () => void;
  starting: boolean;
  children: ReactNode;
}) {
  return connected ? (
    <Btn variant="outline" size="sm" onClick={run} loading={starting}>
      {children}
    </Btn>
  ) : (
    <CloudflareButton size="sm" href={authorizeHref(s, true)}>
      Connect Cloudflare
    </CloudflareButton>
  );
}

/** Under a failed run: the one way on from it. */
function AfterFailure({
  s,
  state,
  connected,
  retry,
  starting,
}: {
  s: State;
  state: DeployState;
  connected: boolean;
  retry: () => void;
  starting: boolean;
}) {
  if (eraseUndone(state))
    return (
      <Footer>
        <LinkBtn
          variant="default"
          size="lg"
          href={erasePath(s.account, s.result!.name)}
          data-erase-again
        >
          Look at the list again
        </LinkBtn>
      </Footer>
    );
  if (olderStack(state))
    return (
      <Footer>
        <LinkBtn
          variant="default"
          size="lg"
          href={erasePath(s.account, s.result!.name)}
          data-erase-older
        >
          Erase and replace
        </LinkBtn>
      </Footer>
    );
  if (notFromHere(state))
    return (
      <Footer>
        <LinkBtn variant="default" size="lg" href="/deployments" data-back-to-list>
          Your deployments
        </LinkBtn>
      </Footer>
    );
  if (connected)
    return (
      <Footer>
        <Btn variant="default" size="lg" onClick={retry} loading={starting}>
          Try again
        </Btn>
      </Footer>
    );
  return (
    <>
      <TokenTick s={s} />
      <Footer>
        <CloudflareButton href={authorizeHref(s)}>Connect Cloudflare to try again</CloudflareButton>
        <span className="text-center text-sm text-muted-foreground sm:text-left">
          {state.failedAt === "forget"
            ? "Remove “Iterate Cloud” in Cloudflare first: a new consent does not end the old access."
            : "The deploy gave up iterate's access to Cloudflare when it stopped."}
        </span>
      </Footer>
    </>
  );
}

/** It failed: at which step, and what the deploy said went wrong there (deploy-steps.ts). Giving
 *  up the access is every run's last step, so it is the step named here only when the access
 *  still works after it. (Or why a second try didn't start.) */
function DeployStopped({ state, again }: { state: DeployState; again: string | null }) {
  if (again) return <Problem title="The deploy didn't start again" text={again} />;
  const at = failedStepOf(state);
  const step = state.steps.find((p) => p.id === at)?.label;
  return (
    <div data-deploy-failed={at || "start"}>
      <Problem
        title={step ? `The deploy failed at “${step}”` : "The deploy did not run"}
        text={
          <>
            <span className="block break-words whitespace-pre-line" data-deploy-error>
              {runErrorOf(state) || "The deploy log has the details."}
            </span>
            <span className="mt-1 block">{whatNowAfter(state, at)}</span>
          </>
        }
      />
    </div>
  );
}

/** What the person does after a run that failed at `at`. */
function whatNowAfter(state: DeployState, at: ReturnType<typeof failedStepOf>): string {
  if (eraseUndone(state)) return "Nothing was deployed. Look at the list of what is erased again.";
  if (olderStack(state)) return "Erase and replace shows what is erased before it erases anything.";
  if (notFromHere(state)) return "Another try from iterate Cloud stops at the same place.";
  if (at === "forget")
    return "iterate itself was deployed. Remove the access, then try again: the next run goes on from what this one made.";
  // a run that got as far as the deploy has made things in the account: the next run finds them
  if (at === "deploy" || at === "answer" || at === "verify")
    return "What it made so far stays in your Cloudflare account. Try again: the next run goes on from there.";
  return "Nothing was made in your Cloudflare account. Try again.";
}

/** Done: the one thing on the page, with the way on directly under it. */
function Deployed({
  domain,
  notes = [],
  children,
}: {
  domain: string;
  /** What the run wants the person to know (deploy-steps.ts `notesOf`). */
  notes?: string[];
  children: ReactNode;
}) {
  // right after a first deploy: the owner's one-use way in (worker/first-owner.js). Its time runs,
  // so the passkey is the next step here, before anything else. The link leads nowhere after the
  // passkey: the person comes back to this tab, because the agents have no AI yet.
  const ticket = firstPasskey(domain);
  const todo = ticket && !ticket.added;
  return (
    <div className="space-y-6">
      <div className="rounded-xl border bg-card p-5 sm:p-6" data-deployed={domain}>
        <div className="flex items-start gap-3">
          <CircleCheck className="mt-0.5 size-7 shrink-0 fill-success text-card" aria-hidden />
          <div className="min-w-0">
            <p className="text-xl font-semibold tracking-tight">iterate is live</p>
            <p className="text-muted-foreground [overflow-wrap:anywhere]">
              On {domain}, in your Cloudflare account. iterate has no access to it.
            </p>
            {notes.map((note) => (
              <p key={note} className="mt-3 text-sm text-muted-foreground" data-deploy-note>
                {note}
              </p>
            ))}
            {ticket?.added && (
              <p className="mt-3" data-passkey-added>
                Passkey added. Next, set up your AI agents.
              </p>
            )}
            {todo && (
              <p className="mt-3" data-next-passkey>
                Next, add your passkey. It is the only way to sign in, and you approve what your
                agents ask for with it. Add two: one in your password manager, and one on a YubiKey
                or another device. This link works once, for a day. Then come back to this tab.
              </p>
            )}
          </div>
        </div>
        <div className="mt-5 flex flex-col gap-2 sm:flex-row sm:pl-10 [&>*]:w-full sm:[&>*]:w-auto">
          {todo && (
            <LinkBtn
              variant="default"
              href={ticket.href}
              target="_blank"
              rel="noreferrer"
              onClick={() => firstPasskeyOpened(domain)}
              data-first-passkey
            >
              Add your passkey
              <NewTab />
            </LinkBtn>
          )}
          <NextButton variant={todo ? "outline" : "default"}>Set up AI agents</NextButton>
        </div>
      </div>
      {children}
    </div>
  );
}

/** What the deploy printed: open while the run goes and when it failed, closed after a success.
 *  Its copy button takes the whole run, with what went wrong, for a coding agent to read. */
function DeployLog({ state, domain }: { state: DeployState; domain: string }) {
  const [open, setOpen] = useState(state.status !== "succeeded");
  const logRef = useRef<HTMLPreElement>(null);
  const lines = state.lines || [];
  useEffect(() => {
    logRef.current?.scrollTo({ top: logRef.current.scrollHeight });
  }, [lines.length, open]);
  return (
    <Collapsible open={open} onOpenChange={setOpen}>
      <CollapsibleTrigger render={<Btn variant="outline" size="sm" />} data-deploy-log-toggle>
        <ChevronDown className={`transition ${open ? "rotate-180" : ""}`} aria-hidden />
        {open ? "Hide the deploy log" : "Show the deploy log"}
      </CollapsibleTrigger>
      <CollapsibleContent className="relative mt-3">
        <pre
          ref={logRef}
          tabIndex={0}
          aria-label="Deploy log"
          className="max-h-80 overflow-auto rounded-lg bg-foreground p-4 font-mono text-2xs text-background"
          data-deploy-log
        >
          {lines.length
            ? lines
                .map((l) => (l.startsWith("== step") ? `\n› ${l.slice(8)}` : l))
                .join("\n")
                .trim()
            : "Starting the container…"}
        </pre>
        <CopyButton
          text={reportOf(state, domain)}
          label="the deploy log, with what went wrong"
          variant="secondary"
          size="xs"
          className="absolute top-2 right-2 shadow-sm"
          data-copy-deploy-log
        >
          Copy for an agent
        </CopyButton>
      </CollapsibleContent>
    </Collapsible>
  );
}

function DeployPhases({ state }: { state: DeployState }) {
  return (
    <ol className="grid gap-1.5" aria-label="Deploy steps">
      {state.steps.map(({ id, label }) => {
        const phase = phaseOf(state, id);
        const [done, now, failed] = [phase === "done", phase === "now", phase === "failed"];
        return (
          <li
            key={id}
            className="flex items-center gap-2 text-sm"
            data-phase={id}
            data-state={phase}
          >
            <span className="grid size-5 place-items-center">
              {done ? (
                <CircleCheck className="size-5 fill-success text-card" />
              ) : now ? (
                <Spinner className="size-4" />
              ) : failed ? (
                <CircleAlert className="size-5 text-destructive" />
              ) : (
                <span className="size-4 rounded-full border-2 border-dashed border-muted-foreground/50" />
              )}
            </span>
            <span
              className={done || now ? "" : failed ? "text-destructive" : "text-muted-foreground"}
            >
              <span className="sr-only">
                {done ? "Done: " : now ? "In progress: " : failed ? "Failed: " : "To do: "}
              </span>
              {label}
            </span>
          </li>
        );
      })}
    </ol>
  );
}

// ── 5 AI agents ───────────────────────────────────────────────────────────────────────────────

/** The deployment on the chosen domain, once it is live: the steps after Deploy need it. Until then,
 *  why not, and the way back to Deploy. */
function WhenDeployed({ s, children }: { s: State; children: (d: Answer) => ReactNode }) {
  const path = deployPath(s);
  const q = useGet(path, { refetchInterval: deployPoll });
  if (path && !q.data) return <Loading>Loading your deployment…</Loading>;
  if (q.data && !q.data.ok)
    return s.me?.connected === false ? (
      <Reconnect s={s} />
    ) : (
      <Problem
        title="We couldn't load your deployment"
        text={errorOf(q.data)}
        retry={() => void q.refetch()}
      />
    );
  if (!q.data || q.data.state?.status !== "succeeded")
    return (
      <Notice
        title="Nothing is deployed yet"
        description="Deploy iterate first. Then come back to this step."
        action={
          <Btn variant="outline" size="sm" onClick={() => setState({ step: DEPLOY_STEP })}>
            Go to Deploy
          </Btn>
        }
      />
    );
  return children(q.data);
}

/** The AI provider the agents use. The deploy took iterate's access to Cloudflare, and the Cloud
 *  has none to the deployment: the person sets one up themselves. The page shows no mark for it,
 *  except when `iterate chatgpt connect` ended on this Cloud's `/connected` page (connected.ts). */
function AiStep({ s }: { s: State }) {
  return (
    <WhenDeployed s={s}>
      {(d) => <AiChoices s={s} domain={s.result!.name} state={d.state} />}
    </WhenDeployed>
  );
}

/** Which pages of the deployment answer, for the buttons that lead to them. A page is there when
 *  its run saw it answer (deploy-steps.ts `pagesOf`), or when the Worker sees it answer now: the
 *  Worker is asked for a run that looked at none, and for a page that the run did not see (a new
 *  deployment publishes its apps seconds after it answers, so the run can be too early for one).
 *  `pages` is null until one of the two is known, and `{}` when nobody could look. */
function usePages(s: State, state: DeployState) {
  const seen = pagesOf(state);
  const lacking = !seen || PAGES.some((id) => seen[id] !== "works");
  const looked = useGet(lacking ? `/api/pages?account=${s.account}&zone=${s.result!.name}` : null, {
    staleTime: 60_000,
  });
  const now: Pages | null | undefined = looked.data?.pages;
  const either: Pages = Object.fromEntries(
    PAGES.map((id) => [id, seen?.[id] === "works" || now?.[id] === "works" ? "works" : "missing"]),
  );
  return {
    pages: seen || now ? either : looked.isPending ? null : {},
    /** The run looked at none, and the look from here gave no answer either. */
    unknown: !seen && !looked.isPending && !now,
    look: () => looked.refetch(),
  };
}

function AiChoices({ s, domain, state }: { s: State; domain: string; state: DeployState }) {
  const note = (text: string) => <p className="text-sm text-muted-foreground">{text}</p>;
  // the key is typed on a page that an agent of the deployment gives: say which app has that
  // agent, and name none that did not answer
  const { pages } = usePages(s, state);
  const chatgpt = useConnected("chatgpt", domain);
  const whereToAsk =
    pages?.dash === "works"
      ? " Ask the agent in onboarding, at the end of this wizard: it gives you a page on your own deployment where you type the key."
      : "";
  const choices: TryItem[] = [
    {
      id: "chatgpt",
      title: (
        <span className="flex flex-wrap items-center gap-2">
          Use your ChatGPT plan <Badge variant="secondary">Recommended</Badge>
        </span>
      ),
      text: "Your agents' requests use your ChatGPT Plus or Pro plan. There is no API key and no extra bill.",
      body: (
        <div className="space-y-2">
          <CopyText
            label="the command that connects your ChatGPT plan"
            // the whole command on a phone too: the domain at its end says which deployment
            className="[&_code]:break-words [&_code]:whitespace-normal"
            text={`npx iterate@latest chatgpt connect iterate.${domain}`}
          />
          {note(
            "It opens ChatGPT in your browser. When your plan is connected, this page says so.",
          )}
          <p className="text-xs text-muted-foreground">
            For a deployment that one person uses. Your plan pays for your own requests only.
          </p>
        </div>
      ),
    },
    {
      id: "openai",
      title: "Use an OpenAI API key",
      text: `Your agents' requests are billed to your OpenAI API account.${whereToAsk}`,
      body: note("iterate Cloud never sees the key."),
    },
    {
      id: "cloudflare",
      title: "Use Cloudflare credits",
      text: "Prepaid AI Gateway credit in your Cloudflare account. Cloudflare bills your card.",
      action: (
        <ExternalButton href={dashUrl(`${s.account}/ai/ai-gateway`)}>
          Add credit in Cloudflare
        </ExternalButton>
      ),
    },
  ];
  return (
    <div data-ai>
      {chatgpt && (
        <div
          className="mb-6 rounded-xl border bg-card p-5 sm:p-6"
          data-ai-connected="chatgpt"
          role="status"
        >
          <div className="flex items-start gap-3">
            <CircleCheck className="mt-0.5 size-7 shrink-0 fill-success text-card" aria-hidden />
            <div className="min-w-0">
              <p className="text-xl font-semibold tracking-tight">ChatGPT is connected</p>
              <p className="text-muted-foreground [overflow-wrap:anywhere]">
                Your mind on {domain} uses your ChatGPT plan now. Continue to try it.
              </p>
            </div>
          </div>
          <Footer>
            <NextButton prominent>Continue</NextButton>
          </Footer>
        </div>
      )}
      <TryItems items={choices} />
      <p className="mt-4 text-sm text-muted-foreground">
        Your agents use the first of these that is set: your plan, then your key, then Cloudflare
        credit.
      </p>
      {!chatgpt && (
        <Footer>
          <NextButton>Continue</NextButton>
        </Footer>
      )}
    </div>
  );
}

// ── 6 Try ─────────────────────────────────────────────────────────────────────────────────────

function TryStep({ s }: { s: State }) {
  return (
    <WhenDeployed s={s}>
      {(d) => <TryList s={s} domain={s.result!.name} email={d.owner || s.email} state={d.state} />}
    </WhenDeployed>
  );
}

type TryItem = {
  id: string;
  title: ReactNode;
  text: ReactNode;
  body?: ReactNode;
  action?: ReactNode;
};

/** In the browser first (the mind, a passkey, more people), then from their computer, then
 *  what iterate Cloud keeps. Right after a first deploy the passkey comes first: the run made a
 *  ticket (worker/first-owner.js) that signs the owner in once, so they wait for no mailed code. */
/** What each page that the Try step links to is, for the line that says which ones did not answer. */
const PAGE_WORDS: Record<keyof Pages, string> = {
  dash: "the Dash",
  keys: "the page for your passkeys",
  "self-test": "the self-test page",
  members: "the page where you add people",
  mcp: "the address for Claude Code",
};

/** Whether the page a Try item leads to answered. */
type Works = (id: keyof Pages) => boolean;
/** Where the wizard ends: the onboarding chat on the stack's own Dash. */
type TryApp = { href: string; host: string; label: string };

/** NO BUTTON LEADS TO A DEAD PAGE: an item is here only when the page it leads to answered
 *  (`usePages`). The pages that did not answer are named in one line under the list, with the way
 *  to get them: an update, which also looks again. */
function TryList({
  s,
  domain,
  email,
  state,
}: {
  s: State;
  domain: string;
  email: string;
  state: DeployState;
}) {
  const { pages, unknown, look } = usePages(s, state);
  if (!pages) return <Loading>Looking at the pages of your deployment…</Loading>;
  const works: Works = (id) => pages[id] === "works";
  const app = tryAppOf(domain, works);
  const first = [...signInItems(domain, email, app, works), ...pageItems(domain, works)];
  const onComputer = works("mcp") ? [mcpItem(domain)] : [];
  const absent = PAGES.filter((id) => !works(id));
  return (
    <div className="space-y-6" data-try>
      {first.length > 0 && <TryItems items={first} />}
      {onComputer.length > 0 && (
        <section className="space-y-2">
          <h3 className="text-lg font-semibold">On your computer</h3>
          <TryItems items={onComputer} />
        </section>
      )}
      {absent.length > 0 && (
        <AbsentPages domain={domain} absent={absent} unknown={unknown} look={look} />
      )}
      <KeptRecords s={s} domain={domain} />
    </div>
  );
}

/** Where the wizard ends: the onboarding chat on the stack's own Dash, when the Dash answers.
 *  The passkey link asks the stack to send the owner there after the passkey. */
function tryAppOf(domain: string, works: Works): TryApp | null {
  if (!works("dash")) return null;
  return { href: onboardingUrl(domain), host: `dash.${domain}`, label: "Open onboarding" };
}

/** The first items: the passkey and the app to start in. Right after a first deploy the passkey
 *  comes first, by the run's one-use link, until the person comes back from it; after that the app
 *  comes first, and a second passkey after. */
function signInItems(domain: string, email: string, app: TryApp | null, works: Works): TryItem[] {
  const ticket = firstPasskey(domain, app?.href);
  const added = !!ticket?.added;
  const owner = <b className="font-medium text-foreground">{email}</b>;
  const open = app && <OpenApp app={app} afterPasskey={!!ticket && !added} />;
  const start = app && <StartWords app={app} />;
  if (ticket && !added)
    return [
      {
        id: "passkey",
        title: "Add your passkey",
        text: (
          <>
            A passkey is the only way to sign in as {owner}: your fingerprint, your face or a
            YubiKey. Add two, on two devices: the page asks for the second. This link works once,
            for a day.
          </>
        ),
        action: (
          <LinkBtn
            variant="default"
            size="sm"
            href={ticket.href}
            target="_blank"
            rel="noreferrer"
            onClick={() => firstPasskeyOpened(domain)}
            data-first-passkey
          >
            Add your passkey
            <NewTab />
          </LinkBtn>
        ),
      },
      ...(open
        ? [
            {
              id: "open",
              title: "Start with your agent",
              text: <>{start} Your passkey signs you in.</>,
              action: open,
            },
          ]
        : []),
    ];
  return [
    ...(open
      ? [
          {
            id: "open",
            title: "Start with your agent",
            text: added ? (
              <>{start} Your passkey signs you in.</>
            ) : (
              <>
                {start} Sign in as {owner} with your passkey. With no passkey yet, a six-digit code
                from sign-in@{domain} signs you in once, and your stack asks you to add one.
              </>
            ),
            action: open,
          },
        ]
      : []),
    ...(works("keys") ? [secondPasskeyItem(domain, app, added)] : []),
  ];
}

/** The button to the app the wizard ends in. After the passkey's own button it is the smaller one. */
function OpenApp({ app, afterPasskey }: { app: TryApp; afterPasskey: boolean }) {
  return (
    <LinkBtn
      variant={afterPasskey ? "outline" : "default"}
      size={afterPasskey ? "sm" : "default"}
      href={app.href}
      target="_blank"
      rel="noreferrer"
      data-onboarding
    >
      {app.label}
      <NewTab />
    </LinkBtn>
  );
}

/** What the app the wizard ends in is. */
function StartWords({ app }: { app: TryApp }) {
  return (
    <>One chat with an agent, on {app.host}. It tests your mail with you and connects your tools.</>
  );
}

/** `added`: they came back from the first passkey's link in this tab. */
const secondPasskeyItem = (domain: string, app: TryApp | null, added: boolean): TryItem => ({
  id: "passkey",
  title: added ? "Passkey added" : "Add a second passkey",
  text: `${added ? "Add a second one on another device or a YubiKey." : "On another device or a YubiKey."} If you lose every passkey, “Lost your passkey?” on the Deploy step is the way back in.`,
  action: (
    <LinkBtn
      variant="outline"
      size="sm"
      href={stackUrl(domain, `/keys${app ? `?next=${encodeURIComponent(app.href)}` : ""}`)}
      target="_blank"
      rel="noreferrer"
      data-keys
    >
      Add a passkey
      <NewTab />
    </LinkBtn>
  ),
});

/** The items for the stack's own pages, each only when its page answered. */
const pageItems = (domain: string, works: Works): TryItem[] => [
  ...(works("dash") ? [dashItem(domain)] : []),
  ...(works("self-test") ? [selfTestItem(domain)] : []),
  ...(works("members") ? [peopleItem(domain)] : []),
];

const dashItem = (domain: string): TryItem => ({
  id: "dash",
  title: "Open the Dash",
  text: "Your mind from above: its events, files, secrets and settings, and the way to every app.",
  action: (
    <LinkBtn
      variant="outline"
      size="sm"
      href={mindDashUrl(domain)}
      target="_blank"
      rel="noreferrer"
      data-dash
    >
      Open the Dash
      <NewTab />
    </LinkBtn>
  ),
});

const selfTestItem = (domain: string): TryItem => ({
  id: "self-test",
  title: "Check that everything works",
  text: <SelfTestText domain={domain} />,
  action: (
    <LinkBtn
      variant="outline"
      size="sm"
      href={stackUrl(domain, "/self-test")}
      target="_blank"
      rel="noreferrer"
      data-self-test
    >
      Run the self-test
      <NewTab />
    </LinkBtn>
  ),
});

const peopleItem = (domain: string): TryItem => ({
  id: "people",
  title: "Add people",
  text: "Each person proves the address you add with a mailed code, once, and then signs in with a passkey.",
  action: (
    <LinkBtn
      variant="outline"
      size="sm"
      href={stackUrl(domain, "/members")}
      target="_blank"
      rel="noreferrer"
      data-members
    >
      Add people
      <NewTab />
    </LinkBtn>
  ),
});

const mcpItem = (domain: string): TryItem => ({
  id: "mcp",
  title: "Connect Claude Code",
  text: "Claude Code can then build in iterate.",
  body: (
    <>
      <CopyText
        label="the Claude Code command"
        text={`claude mcp add --transport http ${domain.replaceAll(".", "-")} https://iterate.${domain}/mcp`}
      />
      <p className="text-sm text-muted-foreground" data-mcp-next>
        Then run <code>claude</code>, type <code>/mcp</code>, choose{" "}
        <code>{domain.replaceAll(".", "-")}</code> and sign in with your passkey. Ask it to change
        your homepage.
      </p>
    </>
  ),
});

/** Under the list: the pages that did not answer, and the way to get them. */
function AbsentPages({
  domain,
  absent,
  unknown,
  look,
}: {
  domain: string;
  absent: (keyof Pages)[];
  /** The Cloud could not look at the pages at all. */
  unknown: boolean;
  look: () => Promise<unknown>;
}) {
  if (unknown)
    return (
      <Notice
        className="bg-transparent"
        icon={<CircleAlert />}
        title="iterate could not look at the pages of your deployment"
        description="So no button for them is shown. Look again in a moment."
        action={<CheckAgain check={look} />}
      />
    );
  return (
    <Notice
      className="bg-transparent"
      icon={<CircleAlert />}
      title={`Not on ${domain} yet: ${listOf(absent.map((id) => PAGE_WORDS[id]))}`}
      description="No button is shown for a page that does not answer. Update iterate on the Deploy step: the update brings what a newer iterate has, and looks again."
      action={
        <Btn variant="outline" size="sm" onClick={() => setState({ step: DEPLOY_STEP })}>
          Go to Deploy
        </Btn>
      }
    />
  );
}

/** "a", "a and b", "a, b and c". */
const listOf = (words: string[]) =>
  words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;

/** The self-test runs on the deployment, as its signed-in owner: iterate Cloud has no access to
 *  run it. Its page sends the owner back here with its result, which is shown as it was said. */
function SelfTestText({ domain }: { domain: string }) {
  const report = selfTestReport?.domain === domain ? selfTestReport : null;
  if (!report)
    return "Your mind checks itself as you: mail out and back, a request out, a throwaway secret, one question to the agents' model, and a connection as Claude Code makes it. Each check that fails says what to do.";
  return report.failed.length ? (
    <span data-self-test-result="failed">
      The last self-test: {report.passed} checks passed and {report.failed.length} failed (
      {report.failed.join(", ")}). Open it again to see what to do.
    </span>
  ) : (
    <span data-self-test-result="passed">
      The last self-test: all {report.passed} checks passed.
    </span>
  );
}

/** Every record iterate Cloud keeps about this person and this deployment, as the Worker lists them. */
function KeptRecords({ s, domain }: { s: State; domain: string }) {
  const [open, setOpen] = useState(false);
  const q = useGet(open ? `/api/kept?account=${s.account}&zone=${domain}` : null);
  const records: Kept[] = q.data?.records || [];
  return (
    <Disclosure title="What iterate Cloud keeps" open={open} onOpenChange={setOpen}>
      <p className="mb-3 text-sm text-muted-foreground">
        iterate Cloud keeps no way in to your deployment and no lasting access to your Cloudflare
        account. These are all its records about you and this deployment.
      </p>
      {!q.data ? (
        <Loading>Asking…</Loading>
      ) : !q.data.ok ? (
        <Problem title="We couldn't ask" text={errorOf(q.data)} retry={() => void q.refetch()} />
      ) : (
        <ul role="list" className={`${ROWS} text-sm`} data-kept>
          {records.map((r) => (
            <li key={`${r.where} ${r.key}`} className="space-y-0.5 px-4 py-2.5">
              <div className="font-mono text-xs break-all">{r.key}</div>
              <div>{r.what}</div>
              <div className="text-xs text-muted-foreground">{r.where}</div>
            </li>
          ))}
        </ul>
      )}
    </Disclosure>
  );
}

function TryItems({ items }: { items: TryItem[] }) {
  return (
    <ul role="list" className={ROWS}>
      {items.map((i) => (
        <li key={i.id} className="space-y-3 p-4" data-try-item={i.id}>
          <div className="flex flex-wrap items-start gap-3">
            <div className="min-w-0 flex-1 basis-48">
              <div className="font-medium">{i.title}</div>
              <div className="text-sm text-muted-foreground">{i.text}</div>
            </div>
            {i.action && <div className="shrink-0">{i.action}</div>}
          </div>
          {i.body}
        </li>
      ))}
    </ul>
  );
}

/** Something went wrong: what, what to do, and the way to do it. A fix in Cloudflare is the next
 *  thing to press (its orange); a question that can be asked again gets "Try again". */
function Problem({
  title,
  text,
  href,
  label,
  retry,
}: {
  title: string;
  text?: ReactNode;
  href?: string;
  label?: string;
  retry?: () => void;
}) {
  const action = href ? (
    <ExternalButton next href={href}>
      {label}
    </ExternalButton>
  ) : retry ? (
    <Btn variant="outline" size="sm" onClick={retry}>
      Try again
    </Btn>
  ) : undefined;
  return (
    <Notice
      variant="destructive"
      icon={<CircleAlert />}
      title={title}
      description={text}
      action={action}
    />
  );
}

// ── the log ───────────────────────────────────────────────────────────────────────────────────
// A bar along the bottom with the newest thing that happened; it opens into all of them, newest
// first: what the page did, in words, with Cloudflare's answers and a deploy's output under each.

const LOG = "Activity log";

/** Wide enough for the log to sit beside the wizard without touching it (Tailwind's 2xl). */
const useWide = () => useMedia("(min-width: 1536px)");
function useMedia(query: string) {
  const [wide, setWide] = useState(
    // oxlint-disable-next-line iterate/simple-truthiness-check -- typeof guards a global that may not exist; a truthiness read of an undeclared matchMedia would throw
    () => typeof matchMedia !== "undefined" && matchMedia(query).matches,
  );
  useEffect(() => {
    const m = matchMedia(query);
    const on = () => setWide(m.matches);
    m.addEventListener("change", on);
    return () => m.removeEventListener("change", on);
  }, [query]);
  return wide;
}

function LogEntries() {
  const log = useLog();
  return (
    <ol className="divide-y divide-border" data-log>
      {log.length === 0 && (
        <li className="px-4 py-3 text-sm text-muted-foreground">Nothing has happened yet.</li>
      )}
      {log.map((e) => (
        <LogEntryRow key={e.id} e={e} />
      ))}
    </ol>
  );
}

function LogHeading({ close, sheet = false }: { close: () => void; sheet?: boolean }) {
  return (
    <div className="flex items-center gap-2 border-b border-border px-4 py-3">
      <div className="min-w-0 flex-1">
        {sheet ? (
          <SheetTitle className="font-medium">{LOG}</SheetTitle>
        ) : (
          <div className="font-medium">{LOG}</div>
        )}
        <div className="text-xs text-muted-foreground">
          What this page did, and what Cloudflare answered.
        </div>
      </div>
      <Btn variant="ghost" size="sm" onClick={close}>
        Close
      </Btn>
    </div>
  );
}

/** Wide: the log as a panel at the right edge, over the empty margin. The step doesn't move. */
function LogColumn({ close }: { close: () => void }) {
  return (
    <aside
      className="fixed top-4 right-4 bottom-14 z-10 flex w-[400px] flex-col overflow-hidden rounded-xl border bg-card shadow-lg"
      aria-label={LOG}
    >
      <LogHeading close={close} />
      <div className="min-h-0 flex-1 overflow-auto">
        <LogEntries />
      </div>
    </aside>
  );
}

/** How an entry went, as a dot: fine, a problem, or still going. */
function LogDot({ e }: { e?: LogEntry }) {
  if (e?.busy) return <Spinner className="size-3 shrink-0" aria-hidden />;
  return (
    <span
      aria-hidden
      className={`size-2 shrink-0 rounded-full ${!e ? "bg-border" : e.ok ? "bg-success" : "bg-destructive"}`}
    />
  );
}

/** The bar across the bottom: the newest thing that happened, and the way into the log.
 *  Narrower than 2xl, the log opens as a sheet over the page, closed to carry on. Its content lines
 *  up with the page's: centred with the step when there is no step list, else with the page's edges. */
function LogBar({
  open,
  setOpen,
  wide,
}: {
  open: boolean;
  setOpen: (o: boolean) => void;
  wide: boolean;
}) {
  const last = useLog()[0];
  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(!open)}
        aria-expanded={open}
        aria-label={LOG}
        data-log-bar
        className="z-20 w-full shrink-0 border-t bg-background hover:bg-muted"
      >
        <div className="mx-auto box-content flex max-w-2xl items-center gap-2.5 px-4 py-2.5 text-left text-sm lg:box-border lg:max-w-7xl lg:px-8">
          <LogDot e={last} />
          {last ? (
            <span className={`min-w-0 flex-1 truncate ${last.ok ? "" : "text-destructive"}`}>
              {last.text}
            </span>
          ) : (
            <span className="flex-1 text-muted-foreground">Nothing has happened yet</span>
          )}
          {last && (
            <span className="hidden shrink-0 font-mono text-2xs text-muted-foreground tabular-nums sm:inline">
              {last.at}
            </span>
          )}
          <span className="shrink-0 text-xs text-muted-foreground">Log</span>
          <ChevronUp
            className={`size-4 shrink-0 text-muted-foreground transition ${open ? "rotate-180" : ""}`}
            aria-hidden
          />
        </div>
      </button>
      <Sheet open={open && !wide} onOpenChange={setOpen}>
        <SheetContent
          side="bottom"
          showCloseButton={false}
          className="mx-auto max-h-[85dvh] max-w-3xl gap-0 rounded-t-2xl p-0"
        >
          <div className="mx-auto mt-2 h-1 w-10 rounded-full bg-border" />
          <LogHeading close={() => setOpen(false)} sheet />
          <div className="min-h-0 flex-1 overflow-auto pb-[env(safe-area-inset-bottom)]">
            <LogEntries />
          </div>
        </SheetContent>
      </Sheet>
    </>
  );
}

/** One thing that happened: when, what (in words), Cloudflare's answers under it, and the raw text on request. */
function LogEntryRow({ e }: { e: LogEntry }) {
  return (
    <li className="flex gap-3 px-4 py-2.5" data-entry={e.title || e.text} data-kind={e.kind}>
      <span className="w-14 shrink-0 pt-0.5 font-mono text-2xs leading-5 text-muted-foreground tabular-nums">
        {e.at}
      </span>
      <div className="min-w-0 flex-1">
        <p className={`flex items-baseline gap-2 text-sm ${e.ok ? "" : "text-destructive"}`}>
          {e.busy && <Spinner className="size-3 shrink-0 self-center" aria-hidden />}
          <span className="min-w-0 break-words">
            {e.text}
            {e.count ? <span className="text-muted-foreground"> ×{e.count}</span> : null}
          </span>
        </p>
        {e.cloudflare.length > 0 && (
          <ul role="list" className="mt-1 space-y-0.5">
            {e.cloudflare.map((c) => {
              const refused = !c.success && !e.expected && !c.expected;
              return (
                <li
                  key={c.id || `${c.method} ${c.path}`}
                  className="flex min-w-0 gap-2 font-mono text-2xs text-muted-foreground"
                >
                  <span className={`shrink-0 tabular-nums ${refused ? "text-destructive" : ""}`}>
                    {c.status}
                  </span>
                  <span className="min-w-0 truncate" title={`${c.method} ${c.path}`}>
                    {c.method} {c.path.replace(/[0-9a-f]{32}/g, (id) => shortId(id))}
                  </span>
                  {!c.success && (
                    <span className={`shrink-0 truncate ${refused ? "text-destructive" : ""}`}>
                      {e.expected
                        ? "not set up yet"
                        : c.errors
                            .map((x) => x.message)
                            .join("; ")
                            .slice(0, 60)}
                    </span>
                  )}
                </li>
              );
            })}
          </ul>
        )}
        {e.detail && (
          <details className="mt-1">
            <summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground">
              {e.kind === "deploy" ? "Output" : "Request and answer"}
            </summary>
            <pre
              tabIndex={0}
              className={`mt-2 max-h-64 overflow-auto rounded-md p-3 text-2xs break-words whitespace-pre-wrap ${e.kind === "deploy" ? "bg-foreground text-background" : "bg-muted"}`}
            >
              {e.detail}
            </pre>
          </details>
        )}
      </div>
    </li>
  );
}