iterate.com / cloud

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

cloud / internal-packages / installer / pretend / pages.jsmain at aacbc74

// The pages of the pretend Cloudflare, as HTML strings: the consent page, the dashboard pages the
// wizard links to, the home page with its scenarios and control panel, and the stand-in for a
// deployed iterate. They look like Cloudflare's (grey page, white panels, a left menu), and every
// one carries a red bar that says they are not. No page asks for a password or a card number.
import { TAGS, TRIGGERS } from "./scenarios.js";

const esc = (s) =>
  String(s ?? "").replace(
    /[&<>"']/g,
    (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c],
  );
const money = (cents) => `$${(cents / 100).toFixed(2)}`;

const CLOUD = `<svg class="cloud" viewBox="0 0 66 32" aria-hidden="true"><circle cx="54" cy="23" r="7.5" fill="#fbad41"/><g fill="#f6821f"><circle cx="19" cy="20" r="10"/><circle cx="32" cy="14" r="12"/><circle cx="44" cy="21" r="9"/><rect x="19" y="21" width="26" height="9"/></g></svg>`;

const CSS = `
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;overflow-wrap:break-word;background:#f2f2f2;color:#313131;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,Roboto,Helvetica,Arial,sans-serif}
a{color:#0051c3;text-decoration:none}a:hover{text-decoration:underline}
h1{font-size:24px;line-height:1.25;font-weight:600;margin:0 0 6px}
h2{font-size:16px;font-weight:600;margin:0 0 8px}
h3{font-size:14px;font-weight:600;margin:0}
p{margin:0 0 12px}
code,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px}
code{background:#f2f2f2;border:1px solid #e0e0e0;border-radius:3px;padding:1px 4px}
td:first-child code{white-space:nowrap}
.muted{color:#595959}.small{font-size:12.5px}
.pretend{position:sticky;top:0;z-index:10;display:flex;flex-wrap:wrap;gap:2px 12px;align-items:center;justify-content:center;padding:9px 16px;color:#fff;text-align:center;
  background:repeating-linear-gradient(135deg,#c8102e 0 24px,#ab0d27 24px 48px);font-size:13.5px;line-height:1.35;box-shadow:0 1px 0 rgba(0,0,0,.25)}
.pretend b{font-size:15px;letter-spacing:.06em;white-space:nowrap}
.top{display:flex;align-items:center;gap:12px;background:#fff;border-bottom:1px solid #d9d9d9;padding:0 20px;min-height:56px}
.brand{display:flex;align-items:center;gap:8px;color:#313131;font-weight:700;letter-spacing:.04em;font-size:15px}
.brand:hover{text-decoration:none}
.cloud{width:44px;height:22px;flex:none}
.pill{display:inline-block;border-radius:999px;padding:1px 8px;font-size:11.5px;font-weight:600;line-height:1.5;white-space:nowrap}
.pill.red{background:#c8102e;color:#fff;letter-spacing:.04em}
.pill.on{background:#e3f6e9;color:#12692f}.pill.off{background:#ececec;color:#595959}.pill.wait{background:#fff1d6;color:#8a5200}.pill.bad{background:#fde7ea;color:#a10d24}
.top .who{margin-left:auto;display:flex;flex-wrap:wrap;gap:2px 14px;justify-content:flex-end;align-items:center;font-size:13px;min-width:0;padding:8px 0}
.top .who span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:46vw}
.shell{display:flex;align-items:flex-start;min-height:calc(100vh - 100px)}
.nav{flex:none;width:244px;align-self:stretch;background:#fff;border-right:1px solid #d9d9d9;padding:16px 0}
.nav .acct{padding:0 20px 14px;border-bottom:1px solid #e6e6e6;margin-bottom:8px}
.nav .acct b{display:block;overflow-wrap:anywhere}
.nav a.item{display:block;padding:8px 20px;color:#313131;border-left:3px solid transparent}
.nav a.item:hover{background:#f5f5f5;text-decoration:none}
.nav a.item[aria-current]{border-left-color:#f6821f;background:#fef4ea;font-weight:600}
.nav .back{margin:12px 20px 0;padding-top:12px;border-top:1px solid #e6e6e6;font-size:13px}
.main{flex:1;min-width:0;padding:28px 32px 56px;max-width:980px}
.crumb{font-size:12.5px;color:#595959;margin-bottom:6px}
.lead{color:#595959;max-width:68ch;margin-bottom:20px}
.panel{background:#fff;border:1px solid #d9d9d9;border-radius:6px;padding:18px 20px;margin:0 0 16px}
.panel>:last-child{margin-bottom:0}
.row{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;justify-content:space-between;padding:12px 0;border-top:1px solid #ececec}
.row:first-of-type{border-top:0;padding-top:0}.row:last-child{padding-bottom:0}
.row .what{min-width:0;flex:1 1 220px}.row .what .muted{display:block;font-size:13px}
.row .act{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
form{margin:0}
.btn{display:inline-flex;align-items:center;justify-content:center;min-height:36px;padding:0 14px;border-radius:5px;border:1px solid #0051c3;background:#0051c3;color:#fff;font:600 14px/1 inherit;font-family:inherit;cursor:pointer;white-space:nowrap}
.btn:hover{background:#003e96;border-color:#003e96;text-decoration:none}
.btn.ghost{background:#fff;color:#0051c3}.btn.ghost:hover{background:#eef4fc}
.btn.quiet{background:#fff;color:#313131;border-color:#c4c4c4;font-weight:500}.btn.quiet:hover{background:#f5f5f5}
.btn.danger{background:#fff;color:#a10d24;border-color:#d9a3ab}.btn.danger:hover{background:#fde7ea}
.btn.small{min-height:30px;padding:0 10px;font-size:13px}
input[type=text],input[type=email]{min-height:36px;border:1px solid #b0b0b0;border-radius:5px;padding:0 10px;font:inherit;font-size:16px;background:#fff;color:#313131;min-width:0}
input:focus-visible,.btn:focus-visible,a:focus-visible{outline:2px solid #0051c3;outline-offset:2px}
.flash{border-radius:6px;padding:12px 16px;margin:0 0 16px;border:1px solid}
.flash.ok{background:#e9f7ee;border-color:#9ed4b0;color:#0f5a28}
.flash.err{background:#fde7ea;border-color:#eaa3ad;color:#8f0b20}
.note{background:#fff8e6;border:1px solid #f0d48a;border-radius:6px;padding:10px 14px;font-size:13px;color:#5c4300;margin:0 0 12px}
.tablewrap{overflow-x:auto;margin:0 -4px}
table{border-collapse:collapse;width:100%}
th{text-align:left;font-size:12px;font-weight:600;color:#595959;text-transform:uppercase;letter-spacing:.04em;padding:6px 10px 6px 4px;border-bottom:1px solid #d9d9d9;white-space:nowrap}
td{padding:9px 10px 9px 4px;border-bottom:1px solid #ececec;vertical-align:top}
tr:last-child td{border-bottom:0}
.center{max-width:600px;margin:0 auto;padding:36px 16px 64px}
.card{background:#fff;border:1px solid #d9d9d9;border-radius:8px;padding:28px 28px 24px;box-shadow:0 1px 3px rgba(0,0,0,.06)}
.card p,.card h1{overflow-wrap:anywhere}
.card .logo{display:flex;align-items:center;gap:8px;font-weight:700;letter-spacing:.04em;margin-bottom:18px}
.sect{margin:20px 0 0;padding-top:16px;border-top:1px solid #ececec}
label.acct,label.perm{display:flex;gap:10px;align-items:flex-start;padding:9px 12px;border:1px solid #d9d9d9;border-radius:5px;margin:0 0 6px;cursor:pointer;background:#fff}
label.acct:hover{background:#f7f9fc}
label.acct:has(input:checked){border-color:#0051c3;background:#f2f7fe}
label.acct span{min-width:0;overflow-wrap:anywhere}
label input[type=checkbox]{width:16px;height:16px;margin:2px 0 0;flex:none;accent-color:#0051c3}
.perms{max-height:232px;overflow:auto;border:1px solid #d9d9d9;border-radius:5px;background:#fafafa;padding:4px 0}
label.perm{border:0;border-radius:0;margin:0;padding:6px 12px;background:none;cursor:default}
label.perm span{min-width:0}
.buttons{display:flex;gap:10px;justify-content:flex-end;margin-top:22px}
.wide{max-width:1040px;margin:0 auto;padding:28px 20px 64px}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px}
.grid form{display:flex}.grid form>button{flex:1}
.preset{display:flex;flex-direction:column;justify-content:flex-start;width:100%;height:100%;text-align:left;background:#fff;border:1px solid #c4c4c4;border-radius:6px;padding:12px 14px;font:inherit;color:inherit;cursor:pointer}
.preset:hover{border-color:#0051c3;background:#f7faff}
.preset b{display:block;color:#0051c3;overflow-wrap:anywhere;margin-bottom:2px}
.login{display:flex;gap:8px;flex-wrap:wrap}.login input{flex:1 1 220px}
.plans{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}
.plan{border:1px solid #d9d9d9;border-radius:6px;padding:16px}.plan.cur{border-color:#f6821f;box-shadow:inset 0 3px 0 #f6821f}
.plan .price{font-size:22px;font-weight:600;margin:4px 0 8px}
.site{max-width:640px;margin:0 auto;padding:56px 20px;text-align:center}
@media (max-width:760px){
  .top{padding:0 14px}.brand .word{display:none}
  .shell{display:block}
  .nav{width:auto;border-right:0;border-bottom:1px solid #d9d9d9;padding:10px 0 0}
  .nav .acct{padding:0 16px 8px;margin:0;border:0}
  .nav .items{display:flex;overflow-x:auto;gap:2px;padding:0 8px;scrollbar-width:none}
  .nav a.item{flex:none;padding:10px 10px;border-left:0;border-bottom:3px solid transparent;white-space:nowrap}
  .nav a.item[aria-current]{border-bottom-color:#f6821f;background:none}
  .nav .back{display:none}
  .main{padding:20px 16px 48px}
  .card{padding:22px 18px 20px}
  .center{padding:20px 12px 48px}.wide{padding:20px 14px 48px}
  .buttons .btn{flex:1}
  h1{font-size:21px}
  th{white-space:normal}
  table.stack thead{display:none}
  table.stack tr{display:block;padding:10px 0;border-bottom:1px solid #ececec}
  table.stack tr:last-child{border-bottom:0;padding-bottom:0}table.stack tr:first-child{padding-top:0}
  table.stack td{display:block;border:0;padding:2px 4px}table.stack td:empty{display:none}
  table.stack td:last-child{padding-top:6px}
}`;

function shell(view, title, body) {
  const w = view.world;
  const who = w
    ? `<div class="who"><span title="${esc(w.user.email)}">${esc(w.user.email)}</span><a href="/">Scenarios &amp; controls</a>${view.deployed ? `<a href="/logout">Switch email</a>` : ""}</div>`
    : `<div class="who"><a href="/">Scenarios</a></div>`;
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
<title>${esc(title)} · Pretend Cloudflare</title><style>${CSS}</style></head><body>
<div class="pretend" role="note"><b>⚠ PRETEND CLOUDFLARE</b><span>This is not Cloudflare. Nothing here is real: no charges, no real domains, no real accounts.</span></div>
<header class="top"><a class="brand" href="/" aria-label="Pretend Cloudflare, home">${CLOUD}<span class="word">CLOUDFLARE</span><span class="pill red">PRETEND</span></a>${who}</header>
${body}</body></html>`;
}

const pill = (on, yes, no) => `<span class="pill ${on ? "on" : "off"}">${on ? yes : no}</span>`;
const backLink = (view, text = "Back to the iterate wizard") =>
  view.wizard ? `<a href="${esc(view.wizard)}">${text}</a>` : "";

// ── consent ─────────────────────────────────────────────────────────────────────────────────────

const ALWAYS = ["user-details.read"];
/** A scope the way Cloudflare's consent page names it: "Workers Scripts" + what it may do. */
function scopeName(scope) {
  const [thing, level = "read"] = scope.split(".");
  const short = {
    aig: "AI Gateway",
    d1: "D1",
    dns: "DNS",
    ai: "Workers AI",
    "workers-kv-storage": "Workers KV Storage",
    "workers-r2": "Workers R2 Storage",
  };
  const name =
    short[thing] ||
    thing
      .split("-")
      .map((x) => x.charAt(0).toUpperCase() + x.slice(1))
      .join(" ");
  return [name, { read: "Read", write: "Edit", admin: "Admin" }[level] || level];
}

/** The consent page: which accounts, which permissions, Cancel or Authorize. */
export function consent(view, q, error) {
  const w = view.world;
  const scopes = (q.get("scope") || "").split(" ").filter(Boolean);
  const identityOnly = scopes.every((x) => ALWAYS.includes(x));
  const ticked = q.getAll("account");
  const cancel = q.get("redirect_uri")
    ? `${q.get("redirect_uri")}?${new URLSearchParams({ error: "access_denied", error_description: "You cancelled at Cloudflare", state: q.get("state") || "" })}`
    : "/";
  const hidden = [
    "client_id",
    "redirect_uri",
    "state",
    "scope",
    "code_challenge",
    "code_challenge_method",
  ]
    .map((k) => `<input type="hidden" name="${k}" value="${esc(q.get(k) || "")}">`)
    .join("");
  return shell(
    view,
    "Authorize iterate",
    `<div class="center"><form class="card" method="post" action="/oauth2/consent">
    <div class="logo">${CLOUD}<span>CLOUDFLARE</span><span class="pill red">PRETEND</span></div>
    <h1>Authorize iterate</h1>
    <p class="muted"><b>iterate</b> wants ${identityOnly ? "to know who you are" : "access to your Cloudflare account"}. Signed in as <b>${esc(w.user.email)}</b>.${view.deployed ? ` <a href="/logout">Not you?</a>` : ""}</p>
    ${error ? `<div class="flash err" role="alert">${esc(error)}</div>` : ""}
    ${hidden}<input type="hidden" name="grants" value="1">
    <div class="sect">
      <h2>Accounts</h2>
      <p class="muted small">${identityOnly ? "iterate asks only for your name and email now. It can't read or change anything in these accounts." : "iterate can reach only the accounts you tick. An account you make later needs this page again."}</p>
      ${w.accounts.length ? w.accounts.map((a) => `<label class="acct"><input type="checkbox" name="account" value="${a.id}"${ticked.includes(a.id) ? " checked" : ""}> <span>${esc(a.name)}</span></label>`).join("") : `<p class="muted">You have no accounts.</p>`}
    </div>
    <div class="sect">
      <h2><span data-permissions="${scopes.length}">${scopes.length} permission${scopes.length === 1 ? "" : "s"}</span></h2>
      <p class="muted small">Untick one to see what iterate does without it.</p>
      <div class="perms">${scopes
        .map((x) => {
          const [name, level] = scopeName(x);
          return `<label class="perm"><input type="checkbox" name="grant" value="${esc(x)}" checked${ALWAYS.includes(x) ? " disabled" : ""}> <span>${esc(name)} <span class="muted">· ${esc(level)}</span></span></label>`;
        })
        .join("")}</div>
    </div>
    <div class="buttons"><a class="btn quiet" href="${esc(cancel)}">Cancel</a><button class="btn" type="submit">Authorize</button></div>
  </form></div>`,
  );
}

// ── the dashboard ───────────────────────────────────────────────────────────────────────────────

const NAV = [
  ["", "Account home"],
  ["domains/registrations", "Domains"],
  ["workers/onboarding", "Workers & Pages"],
  ["workers/plans", "Workers plans"],
  ["r2/overview", "R2 object storage"],
  ["ai/ai-gateway", "AI Gateway"],
  ["billing/subscriptions", "Billing"],
  ["manage/configurations", "Manage account"],
];
const PRETEND_CARD = `<p class="note">Nothing to type: the pretend card is a Visa ending 4242. Never enter a real card here.</p>`;
const post = (button, hidden = "") => `<form method="post">${hidden}${button}</form>`;
const off = (label) =>
  post(`<button class="btn quiet small" name="do" value="off">${label}</button>`);

function dashPage(view, a, page) {
  const w = view.world;
  const base = `/dash/${a.id}`;
  const ex = a.existing || {};
  const zones = w.zones.filter((z) => z.account === a.id);
  if (page === "billing/subscriptions")
    return [
      "Billing",
      "Payment methods",
      "The card Cloudflare charges for Workers Paid, domains and AI Gateway credit.",
      `<div class="panel"><h2>Payment methods</h2>${
        a.card
          ? `<div class="row"><div class="what"><b>Visa ending 4242</b> <span class="pill on">Default</span><span class="muted">Expires 12/2030</span></div><div class="act">${off("Remove payment method")}</div></div>`
          : `<p>No payment method on file.</p>${PRETEND_CARD}${post(`<button class="btn">Add payment method</button>`)}`
      }</div>`,
    ];
  if (page === "workers/plans")
    return [
      "Workers & Pages",
      "Workers plans",
      "iterate needs the Paid plan: its sandboxes run in Containers, which the Free plan doesn't have.",
      `<div class="plans">
        <div class="panel plan${a.paid ? "" : " cur"}"><h2>Workers Free</h2><div class="price">$0</div><p class="muted">100,000 requests a day. No Containers.</p>${a.paid ? "" : `<span class="pill on">Current plan</span>`}</div>
        <div class="panel plan${a.paid ? " cur" : ""}"><h2>Workers Paid</h2><div class="price">$5 <span class="muted small">a month</span></div><p class="muted">10 million requests a month, Containers, Durable Objects.</p>
          ${a.paid ? `<p><span class="pill on">Current plan</span></p>${off("Cancel Workers Paid")}` : `${a.card ? `<p class="small muted">Charged to Visa ending 4242.</p>` : PRETEND_CARD}${post(`<button class="btn">Subscribe to Workers Paid</button>`)}`}</div>
      </div>`,
    ];
  if (page === "r2/overview")
    return [
      "R2 object storage",
      "Overview",
      "Object storage. iterate keeps your minds' files in it.",
      a.r2
        ? `<div class="panel"><div class="row"><div class="what"><b>R2 is on</b><span class="muted">${(ex.r2 || []).length} bucket${(ex.r2 || []).length === 1 ? "" : "s"}</span></div><div class="act">${off("Disable R2")}</div></div>${(ex.r2 || []).map((n) => `<div class="row"><div class="what mono">${esc(n)}</div></div>`).join("")}</div>`
        : `<div class="panel"><h2>Get started with R2</h2><p class="muted">10 GB a month free. You agree to pay for what you use beyond that.</p>${post(`<button class="btn">Enable R2</button>`)}</div>`,
    ];
  if (page === "workers/onboarding")
    return [
      "Workers & Pages",
      "Overview",
      "Each account has one workers.dev address. Its Workers answer at name.address.workers.dev.",
      `<div class="panel"><h2>Your workers.dev address</h2>${
        a.subdomain
          ? `<div class="row"><div class="what"><b class="mono">${esc(a.subdomain)}.workers.dev</b></div><div class="act">${off("Remove")}</div></div>`
          : `<p class="muted">Pick a name. <code>ada</code>, <code>iterate</code> and names that start with <code>taken</code> belong to someone else.</p>
           <form method="post" class="login"><input type="text" name="name" aria-label="workers.dev name" placeholder="your-name" autocapitalize="none" autocomplete="off" spellcheck="false" required><span class="muted" style="align-self:center">.workers.dev</span><button class="btn">Set up</button></form>`
      }</div>
       <div class="panel"><h2>Workers</h2>${
         (ex.workers || []).length
           ? (ex.workers || [])
               .map(
                 (n) =>
                   `<div class="row"><div class="what"><b class="mono">${esc(n)}</b></div>${a.subdomain ? `<div class="act"><a href="/site/${esc(n)}.${esc(a.subdomain)}.workers.dev">Visit</a></div>` : ""}</div>`,
               )
               .join("")
           : `<p class="muted">No Workers yet. A deploy from the wizard puts iterate's here.</p>`
       }</div>`,
    ];
  if (page === "ai/ai-gateway")
    return [
      "AI",
      "AI Gateway",
      "Credit pays for the model calls your agents make through AI Gateway.",
      `<div class="panel"><div class="row"><div class="what"><b>Credit balance: ${money(a.credit)}</b><span class="muted">${a.card ? "Top-ups charge Visa ending 4242." : "No payment method on file: adding credit here adds the pretend card too."}</span></div>
        <div class="act">${a.credit ? off("Clear credit") : ""}${post(`<button class="btn">Add $10 credit</button>`)}</div></div></div>`,
    ];
  if (page === "domains/registrations") {
    const failed = Object.entries(w.registrations)
      .filter(([k, r]) => k.startsWith(`${a.id}:`) && r.failed)
      .map(([k]) => k.split(":")[1]);
    const bought = (name) => !!w.registrations[`${a.id}:${name}`];
    return [
      "Domains",
      "Domains",
      "Domains registered here, and domains from another registrar that point at Cloudflare.",
      `<div class="panel">${
        zones.length || failed.length
          ? `<div class="tablewrap"><table class="stack"><thead><tr><th>Domain</th><th>From</th><th>Status</th><th></th></tr></thead><tbody>
        ${zones
          .map((z) => {
            const active = z.status === "active";
            return `<tr><td><b>${esc(z.name)}</b>${active ? "" : `<div class="small muted">Nameservers: <span class="mono">${z.nameServers.map(esc).join('</span>, <span class="mono">')}</span></div>`}</td><td>${bought(z.name) ? "Cloudflare Registrar" : "Another registrar"}</td>
          <td>${active ? `<span class="pill on">Active</span>` : `<span class="pill wait">Waiting for nameservers</span>`}</td>
          <td>${active ? "" : post(`<button class="btn small">Nameservers point here now</button>`, `<input type="hidden" name="zone" value="${z.id}">`)}</td></tr>`;
          })
          .join("")}
        ${failed.map((n) => `<tr><td><b>${esc(n)}</b></td><td>Cloudflare Registrar</td><td><span class="pill bad">Registration failed</span></td><td></td></tr>`).join("")}
        </tbody></table></div>`
          : `<p class="muted">No domains in this account. Buy one or add one in the wizard.</p>`
      }</div>
       <p class="muted small">A domain from another registrar turns active about 20 seconds after you add it (a name with <code>stuck</code> waits for the button).</p>`,
    ];
  }
  if (page === "manage/configurations")
    return [
      "Manage account",
      "Configurations",
      "The account's name and ID, and how to delete it.",
      `<div class="panel"><div class="row"><div class="what"><span class="muted">Account name</span><b>${esc(a.name)}</b></div></div><div class="row"><div class="what"><span class="muted">Account ID</span><span class="mono">${a.id}</span></div></div></div>
       <div class="panel"><h2>Delete account</h2><p class="muted">Deletes the account and its domains from this pretend world. iterate's wizard then can't reach it.</p>${post(`<button class="btn danger" name="do" value="delete">Delete this account</button>`)}</div>`,
    ];
  if (page === "") {
    const rows = [
      ["Payment method", a.card, "Visa ending 4242", "None", "billing/subscriptions", "Billing"],
      ["Workers plan", a.paid, "Paid", "Free", "workers/plans", "Plans"],
      ["R2", a.r2, "On", "Off", "r2/overview", "R2"],
      [
        "workers.dev address",
        !!a.subdomain,
        `${esc(a.subdomain)}.workers.dev`,
        "Not set",
        "workers/onboarding",
        "Workers & Pages",
      ],
      ["AI Gateway credit", a.credit > 0, money(a.credit), "$0.00", "ai/ai-gateway", "AI Gateway"],
    ];
    return [
      "",
      "Account home",
      "What iterate needs from this account, and what is in it.",
      `<div class="panel"><h2>What iterate needs</h2>${rows.map(([what, on, yes, no, href, link]) => `<div class="row"><div class="what"><b>${what}</b></div><div class="act">${pill(on, yes, no)}<a href="${base}/${href}">${link}</a></div></div>`).join("")}</div>
       <div class="panel"><div class="row"><div class="what"><b>Domains</b><span class="muted">${zones.length ? zones.map((z) => esc(z.name)).join(", ") : "None"}</span></div><div class="act"><a href="${base}/domains/registrations">Domains</a></div></div>
       <div class="row"><div class="what"><b>Workers</b><span class="muted">${(ex.workers || []).length ? (ex.workers || []).map(esc).join(", ") : "None"}</span></div><div class="act"><a href="${base}/workers/onboarding">Workers & Pages</a></div></div></div>`,
    ];
  }
  return [
    "",
    "Not in the pretend Cloudflare",
    "",
    `<div class="panel"><p>The real dashboard has a page at <code>${esc(page)}</code>. This pretend one has only the pages in the menu.</p></div>`,
  ];
}

export function dashboard(view, a, page, saved) {
  const [section, title, lead, body] = dashPage(view, a, page);
  const flash =
    saved === "1"
      ? `<div class="flash ok" role="status">✓ Saved for ${esc(a.name)}. Go back to the iterate tab: it sees the change by itself. You can close this tab.</div>`
      : saved === "taken"
        ? `<div class="flash err" role="alert">That workers.dev name is taken. Try another.</div>`
        : saved === "bad-name"
          ? `<div class="flash err" role="alert">Use lowercase letters, digits and hyphens, two characters or more.</div>`
          : "";
  return shell(
    view,
    `${title} · ${a.name}`,
    `<div class="shell">
    <nav class="nav" aria-label="Account"><div class="acct"><span class="muted small">Account</span><b>${esc(a.name)}</b></div>
      <div class="items">${NAV.map(([href, label]) => `<a class="item" href="/dash/${a.id}${href ? `/${href}` : ""}"${href === page ? ` aria-current="page"` : ""}>${esc(label)}</a>`).join("")}</div>
      ${view.wizard ? `<div class="back">${backLink(view, "← Back to the iterate wizard")}</div>` : ""}</nav>
    <main class="main">${section ? `<div class="crumb">${esc(a.name)} / ${esc(section)}</div>` : `<div class="crumb">${esc(a.name)}</div>`}<h1>${esc(title)}</h1>${lead ? `<p class="lead">${esc(lead)}</p>` : ""}${flash}${body}</main>
  </div>`,
  );
}

export const missing = (view, title, text) =>
  shell(
    view,
    title,
    `<div class="center"><div class="card"><h1>${esc(title)}</h1><p class="muted">${esc(text)}</p><p><a href="/">Scenarios and controls</a>${view.wizard ? ` · ${backLink(view)}` : ""}</p></div></div>`,
  );

// ── home: what this is, the scenarios, and your world's controls ────────────────────────────────

const PRESETS = [
  [
    "you+new@example.com",
    "A new Cloudflare user",
    "One free account, nothing set up. The longest path.",
  ],
  ["you+card@example.com", "Has a card", "Workers Paid, R2 and workers.dev are still to do."],
  ["you+ready@example.com", "Everything ready", "Straight to the domain."],
  [
    "you+ready+domains@example.com",
    "Ready, with domains",
    "One domain registered here, one that waits for its nameservers.",
  ],
  ["you+ready+many@example.com", "Several accounts", "Four accounts, each in a different state."],
];

function loginForm(next, value = "") {
  return `<form method="post" action="/login" class="login"><input type="hidden" name="next" value="${esc(next)}">
    <input type="email" name="email" aria-label="Email" placeholder="you+ready@example.com" value="${esc(value)}" autocapitalize="none" autocomplete="off" spellcheck="false" required><button class="btn">Continue</button></form>
    <p class="small muted" style="margin-top:8px">An email is all there is: no password, and none is checked. This is not Cloudflare, so don't type a real password anywhere here. The email doesn't have to exist.</p>`;
}
const presets = (next) =>
  `<div class="grid">${PRESETS.map(([email, title, text]) => `<form method="post" action="/login"><input type="hidden" name="next" value="${esc(next)}"><input type="hidden" name="email" value="${email}"><button class="preset"><b>${email}</b><span>${title}. <span class="muted">${text}</span></span></button></form>`).join("")}</div>`;

const scenarioTables = () => `<div class="panel"><h2>Scenarios by email</h2>
  <p class="muted">The words after <code>+</code> set what the person's Cloudflare starts with. Join as many as you like: <code>ada+card+domains@example.com</code>. Each email is its own world and keeps its state, so a new name (<code>ada2+…</code>) starts clean.</p>
  <div class="tablewrap"><table><thead><tr><th>Tag</th><th>The first account starts with</th></tr></thead><tbody>${TAGS.map(([tag, text]) => `<tr><td><code>+${tag}</code></td><td>${esc(text)}</td></tr>`).join("")}</tbody></table></div></div>
  <div class="panel"><h2>Scenarios by what you type in the wizard</h2>
  <div class="tablewrap"><table><thead><tr><th>Where</th><th>The name</th><th>What happens</th></tr></thead><tbody>${TRIGGERS.map(([where, name, text]) => `<tr><td>${esc(where)}</td><td>${esc(name)}</td><td>${esc(text)}</td></tr>`).join("")}</tbody></table></div>
  <p class="muted small" style="margin-top:10px">A purchase without a card on file is refused, as on the real Cloudflare. A deploy is acted out: no container runs, and the result opens on this site.</p></div>`;

function control(view) {
  const w = view.world;
  const toggle = (a, act, label, on, yes, no) =>
    `<div class="row"><div class="what"><b>${label}</b></div><div class="act">${pill(on, yes, no)}<form method="post" action="/control"><input type="hidden" name="account" value="${a.id}"><button class="btn quiet small" name="do" value="${act}">${on ? "Turn off" : "Turn on"}</button></form></div></div>`;
  const act = (name, label, text, cls = "quiet") =>
    `<div class="row"><div class="what"><b>${label}</b><span class="muted">${text}</span></div><div class="act"><form method="post" action="/control"><button class="btn ${cls} small" name="do" value="${name}">${label}</button></form></div></div>`;
  const waiting = w.zones.filter((z) => z.status !== "active" && !view.pointed(z));
  return `<h2 id="world" style="margin-top:28px">Your pretend Cloudflare: ${esc(w.user.email)}</h2>
  <p class="muted">Change it here or in its dashboard, then look at the wizard: it reads the state again when you come back to its tab. When its checklist is already complete it stops looking: reload the wizard then.</p>
  ${
    w.accounts
      .map(
        (
          a,
        ) => `<div class="panel"><div class="row"><div class="what"><h3>${esc(a.name)}</h3><span class="muted mono">${a.id}</span></div><div class="act"><a class="btn ghost small" href="/dash/${a.id}">Open dashboard</a></div></div>
    ${toggle(a, "card", "Payment method", a.card, "Visa ending 4242", "None")}${toggle(a, "paid", "Workers Paid", a.paid, "On", "Off")}${toggle(a, "r2", "R2", a.r2, "On", "Off")}
    ${toggle(a, "workersdev", "workers.dev address", !!a.subdomain, `${esc(a.subdomain)}.workers.dev`, "Not set")}${toggle(a, "credit", "AI Gateway credit", a.credit > 0, money(a.credit), "$0.00")}
    ${w.zones
      .filter((z) => z.account === a.id)
      .map(
        (z) =>
          `<div class="row"><div class="what"><b>${esc(z.name)}</b></div><div class="act">${z.status === "active" || view.pointed(z) ? `<span class="pill on">Active</span>` : `<span class="pill wait">Waiting for nameservers</span><form method="post" action="/control"><input type="hidden" name="zone" value="${z.id}"><button class="btn quiet small" name="do" value="point">Nameservers point here</button></form>`}</div></div>`,
      )
      .join("")}
  </div>`,
      )
      .join("") ||
    `<div class="panel"><p class="muted">No accounts left. Reset this world to get the first one back.</p></div>`
  }
  <div class="panel"><h2>The wizard's connection</h2>
    ${act("expire", "End iterate's access", "As after an hour, or as if you removed iterate in Cloudflare. The wizard keeps its place and asks you to connect again.")}
    ${act("reset", "Reset this world", `Back to what ${esc(w.user.email)} starts with. Also ends iterate's access.`, "danger")}
  </div>
  ${waiting.length ? "" : ""}
  <div class="panel"><h2>The newest API calls from the wizard</h2>${
    (w.requests || []).length
      ? `<div class="tablewrap"><table><tbody>${w.requests
          .slice(0, 25)
          .map(
            (r) =>
              `<tr><td class="mono muted" style="white-space:nowrap">${new Date(r.at).toISOString().slice(11, 19)}</td><td class="mono">${esc(r.method)}</td><td class="mono" style="overflow-wrap:anywhere">${esc(r.path)}</td><td>${r.ok ? "" : `<span class="pill bad">401</span>`}</td></tr>`,
          )
          .join("")}</tbody></table></div>`
      : `<p class="muted">None yet.</p>`
  }</div>`;
}

export function home(view, q) {
  const w = view.world;
  const did = {
    card: "Payment method changed.",
    paid: "Workers Paid changed.",
    r2: "R2 changed.",
    credit: "AI Gateway credit changed.",
    workersdev: "workers.dev address changed.",
    point: "The domain's nameservers now point at Cloudflare.",
    expire: "iterate's access ended.",
    reset: "This world is new again.",
  }[q?.get("did")];
  const flash = did
    ? `<div class="flash ok" role="status">✓ ${did}</div>`
    : q?.get("deleted")
      ? `<div class="flash ok" role="status">✓ Deleted ${esc(q.get("deleted"))}. Go back to the iterate tab.</div>`
      : "";
  return shell(
    view,
    "Home",
    `<div class="wide">
    <h1>A pretend Cloudflare for the iterate wizard</h1>
    <p class="lead">It answers the wizard the way Cloudflare does: sign-in and consent, accounts, billing, R2, domains, deploys. Nothing is real, so you can buy domains and break things. Pick who you are here, and names you type in the wizard set off the awkward cases.</p>
    ${flash}
    ${view.wizard ? `<p><a class="btn" href="${esc(view.wizard)}" ${w ? "" : ""}>Open the wizard</a>${w ? "" : ` <span class="muted" style="margin-left:8px">It sends you here to sign in.</span>`}</p>` : ""}
    ${view.deployed ? `<div class="panel"><h2>${w ? "Be someone else" : "Who are you?"}</h2>${w ? `<p class="muted">You are <b>${esc(w.user.email)}</b>. The wizard keeps its own sign-in: use its “Sign out” too, or it stays connected as this person.</p>` : ""}${presets("/")}<div style="margin-top:14px">${loginForm("/")}</div></div>` : ""}
    ${w ? control(view) : ""}
    <h2 style="margin-top:28px">Scenarios</h2>
    ${scenarioTables()}
  </div>`,
  );
}

/** The sign-in page: an email, nothing else. `next` is where the person was going (the consent page). */
export function login(view, next, error) {
  const toConsent = next.startsWith("/oauth2/");
  return shell(
    view,
    "Sign in",
    `<div class="center"><div class="card">
    <div class="logo">${CLOUD}<span>CLOUDFLARE</span><span class="pill red">PRETEND</span></div>
    <h1>${toConsent ? "Who is signing in to Cloudflare?" : "Sign in"}</h1>
    <p class="muted">${toConsent ? "The wizard sent you to Cloudflare. On the real one you would log in now. Here you pick who you are; the email decides what your Cloudflare has in it." : "Pick who you are. The email decides what your Cloudflare has in it."}</p>
    ${error ? `<div class="flash err" role="alert">${esc(error)}</div>` : ""}
    ${loginForm(next)}
    <div class="sect"><h2>Or one of these</h2>${presets(next)}</div>
    <p class="small muted" style="margin-top:16px"><a href="/">All scenarios</a></p>
  </div></div>`,
  );
}

/** What a real deployment serves at an address on its domain. */
function served(host, domain, path) {
  if (host === `dash.${domain}`)
    return "this is the Dash: a home to start an agent from, every agent and a chat with each, and your main conversation (/agents/agents/main), with an agent that tests your mail with you and connects your tools. Your passkey signs you in.";
  if (host !== `iterate.${domain}`)
    return host === domain
      ? "the wizard's links go to the mind's own apps. Its Dash, on dash." +
          domain +
          ", sends you to iterate." +
          domain +
          " to sign in with a six-digit code, mailed to the owner's address, and back."
      : "the mind answers here: its own pages and its apps.";
  if (path === "/")
    return `this address has no page: it sends you to the mind's Dash, at dash.${domain}.`;
  if (path.startsWith("/keys/first"))
    return "this is where you add your first passkey, straight from the wizard: its link works once and for a few minutes, and you wait for no mailed code.";
  if (path.startsWith("/keys"))
    return "this is where you add a passkey or a security key, after you sign in with a mailed code.";
  if (path.startsWith("/members")) return "this is where the owner adds people to the mind.";
  if (path.startsWith("/mcp")) return "this is the MCP server that Claude Code connects to.";
  return "this is the mind's sign-in: a six-digit code, mailed to the owner's address.";
}

/** Where a deployed iterate would answer. */
export function site(view, host, domain, found, path) {
  const a = found && view.world.accounts.find((x) => x.id === found.account);
  return shell(
    view,
    host,
    `<div class="site"><div class="card">
    ${
      found
        ? `<p><span class="pill on">Deployed</span></p><h1 style="overflow-wrap:anywhere">${esc(host)}${path !== "/" ? esc(path.replace(/\?.*$/, "")) : ""}</h1>
         <p>On the real Cloudflare, ${esc(served(host, domain, path))}</p>
         <p class="muted">This is its stand-in: deployment <b>${esc(found.name)}</b> on <b>${esc(domain)}</b>${a ? `, in account <b>${esc(a.name)}</b>` : ""}.</p>`
        : `<p><span class="pill off">Nothing here</span></p><h1 style="overflow-wrap:anywhere">${esc(host)}</h1><p class="muted">No pretend deployment answers at this address in ${esc(view.world.user.email)}'s world.</p>`
    }
    <p>${backLink(view)}</p>
  </div></div>`,
    200,
  );
}