/* A3 Studio (chat) — retail purchase · conversation, plan & context data. */

const CHAT_PROJECT = { title: 'buy-product', site: 'johnlewis.com', dataset: 'okonkwo-home' };

/* Selectable input datasets for the workflow run. */
const CHAT_DATASETS = [
    { id: 'okonkwo-home', label: 'okonkwo-home', hint: 'Sonos speaker · 1 item' },
    { id: 'gift-list', label: 'gift-list', hint: '3 items · gift wrap' },
    { id: 'office-kit', label: 'office-kit', hint: '8 items · business' },
    { id: 'qa-fixtures', label: 'qa-fixtures', hint: 'synthetic · 12 rows' },
];

const CHAT_SCOPE = {
    inputs: [
        { key: 'query', preview: '"speaker"' },
        { key: 'sku', preview: '"sonos-era-100"' },
        { key: 'qty', preview: '1' },
        { key: 'customer', preview: '{ firstName: "Amara", … }' },
        { key: 'address', preview: '{ city: "Bristol", … }' },
    ],
    outputs: [
        { key: 'ordered', preview: 'true' },
        { key: 'order', preview: '{ ref: "JL-8842", … }' },
    ],
    context: [
        { key: 'browser.url', preview: '"…/checkout/delivery"' },
        { key: 'stage.current', preview: '"enter-address"' },
        { key: 'session.exitCode', preview: 'null' },
    ],
};

/* Full JSON values for the data panel's tree viewer. */
const CHAT_SCOPE_DATA = {
    inputs: {
        query: 'speaker',
        sku: 'sonos-era-100',
        qty: 1,
        customer: { firstName: 'Amara', lastName: 'Okonkwo', title: 'Ms', email: 'amara@example.com' },
        address: { line1: '14 Elm Road', city: 'Bristol', postcode: 'BS1 4DJ' },
        options: { colour: 'Black' },
    },
    outputs: {
        ordered: true,
        order: { ref: 'JL-8842', item: 'Sonos Era 100 Smart Speaker', qty: 1, total: { currency: 'GBP', amount: 249 } },
        warnings: [],
    },
    context: {
        browser: { url: 'https://johnlewis.com/checkout/delivery', title: 'Delivery details', viewport: { width: 1280, height: 800 } },
        stage: { current: 'enter-address', index: 4, total: 6 },
        session: { id: 'sess_b41d7e', runner: 'chrome', exitCode: null, startedAt: '2026-06-18T09:21:04Z' },
    },
};

const CHAT_PLAN = [
    { name: 'open-site', status: 'pending' },
    { name: 'search', status: 'pending' },
    { name: 'choose-options', status: 'pending' },
    { name: 'view-basket', status: 'pending' },
    { name: 'enter-address', status: 'pending' },
    { name: 'place-order', status: 'pending' },
];

/* Learning mode — learn ALL workflows at once by chaining them. The rail
   shows every workflow's stages in sequence; the agent walks the chain,
   learning each stage and carrying outputs forward. */
const ORCHESTRATOR_PLAN = [
    { workflow: 'find-product', site: 'johnlewis.com', stages: [
        { name: 'open-site', status: 'pending' },
        { name: 'search', status: 'pending' },
    ] },
    { workflow: 'select-options', site: 'johnlewis.com', stages: [
        { name: 'open-product', status: 'pending' },
        { name: 'choose-options', status: 'pending' },
    ] },
    { workflow: 'add-to-basket', site: 'johnlewis.com', stages: [
        { name: 'add', status: 'pending' },
        { name: 'view-basket', status: 'pending' },
    ] },
    { workflow: 'delivery-details', site: 'johnlewis.com', stages: [
        { name: 'enter-address', status: 'pending' },
    ] },
    { workflow: 'payment', site: 'johnlewis.com', stages: [
        { name: 'enter-card', status: 'pending' },
        { name: 'authorize', status: 'pending' },
    ] },
    { workflow: 'confirm-order', site: 'johnlewis.com', stages: [
        { name: 'place-order', status: 'pending' },
    ] },
];

const ORCHESTRATOR_THREAD = [
    { role: 'user', text: 'learn johnlewis.com' },
    { role: 'agent', text: "I'll learn them as one chain: **find-product → select-options → add-to-basket → delivery-details → payment → confirm-order**, carrying each workflow's outputs into the next. Let me read the missions first." },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/find-product.mission.md', result: '12 lines · 2 stages', status: 'ok' },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/select-options.mission.md', result: '11 lines · 2 stages', status: 'ok' },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/add-to-basket.mission.md', result: '12 lines · 2 stages', status: 'ok' },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/delivery-details.mission.md', result: '11 lines · 1 stage', status: 'ok' },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/payment.mission.md', result: '12 lines · 2 stages', status: 'ok' },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/confirm-order.mission.md', result: '10 lines · 1 stage', status: 'ok' },
    { role: 'agent', text: "Starting with **find-product**. I'll author each stage and run it against johnlewis.com." },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'find-product / open-site', result: 'passed · johnlewis.com loaded', status: 'ok', ostages: { 'find-product/open-site': 'executed' }, screen: 'listing' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'find-product / search', result: 'passed · 48 results for "speaker"', status: 'ok', ostages: { 'find-product/search': 'executed' }, screen: 'listing' },
    { role: 'agent', text: "**find-product** is learned. Chaining the selected `sku` into **select-options**." },
    { role: 'tool', icon: 'far fa-link', name: 'chain', args: 'find-product.output → select-options.input', result: 'sku mapped', status: 'ok' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'select-options / open-product', result: 'passed · Sonos Era 100 · £249', status: 'ok', ostages: { 'select-options/open-product': 'executed' }, screen: 'product' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'select-options / choose-options', result: 'passed · colour=Black, qty=1', status: 'ok', ostages: { 'select-options/choose-options': 'executed' }, screen: 'product' },
    { role: 'agent', text: "**select-options** learned. Now **add-to-basket** — the add-to-basket click opens a confirmation modal that overlays the page, and the next assertion fires before it settles. Scoping the wait to the modal.", ostages: { 'add-to-basket/add': 'executing' } },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'add-to-basket / add', result: 'Error: waitFor(".basket-count") — overlay still animating', status: 'error', ostages: { 'add-to-basket/add': 'failed' }, screen: 'product' },
    { role: 'diff', file: 'add-to-basket/add.stage.ts', added: 1, removed: 1, hunks: [
        { type: 'ctx', text: "    await this.click('button.add-to-basket');" },
        { type: 'del', text: "    await this.waitFor('.basket-count');" },
        { type: 'add', text: "    await this.modal('#basket-added').waitFor('.basket-count');" },
    ] },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'add-to-basket / add → view-basket', result: 'passed · 1 item · £249', status: 'ok', ostages: { 'add-to-basket/add': 'executed', 'add-to-basket/view-basket': 'executed' }, screen: 'basket' },
    { role: 'agent', text: "**add-to-basket** learned. Now **delivery-details** — chaining the basket contents into the order." },
    { role: 'tool', icon: 'far fa-link', name: 'chain', args: 'add-to-basket.output → delivery-details.input', result: 'basketId mapped', status: 'ok' },
    { role: 'agent', text: "Learning `enter-address` — the title field is a custom combobox, so I'll drive it by keyboard.", ostages: { 'delivery-details/enter-address': 'executing' } },
    { role: 'diff', file: 'delivery-details/enter-address.stage.ts', added: 3, removed: 1, hunks: [
        { type: 'ctx', text: "    await this.type('#lastName', c.lastName);" },
        { type: 'del', text: "    await this.select('#title', c.title);" },
        { type: 'add', text: "    await this.click('#title');" },
        { type: 'add', text: "    await this.keyboard.type(c.title);" },
        { type: 'add', text: "    await this.keyboard.press('Enter');" },
    ] },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'delivery-details / enter-address', result: 'passed · delivery filled', status: 'ok', ostages: { 'delivery-details/enter-address': 'executed' }, screen: 'checkout' },
    { role: 'agent', text: "**delivery-details** learned. Now **payment** — entering the card and clearing the authorisation step." },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'payment / enter-card → authorize', result: 'passed · card authorised', status: 'ok', ostages: { 'payment/enter-card': 'executed', 'payment/authorize': 'executed' }, screen: 'checkout' },
    { role: 'agent', text: "**payment** learned. Finally **confirm-order** — placing the order and capturing the reference." },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'confirm-order / place-order', result: 'passed · ref JL-8842 · £249', status: 'ok', ostages: { 'confirm-order/place-order': 'executed' }, screen: 'confirmation' },
    { role: 'agent', text: "All six workflows are learned and chained: a search feeds the options, the options feed the basket, and the basket flows through delivery, payment and a placed order. **10/10 stages** passing end to end." },
    { role: 'cta', to: 'run', text: "All six workflows are learned and chained. You can now talk to them all at once as MCP tools.", link: 'Open Chat to MCP →' },
];

/* The agent conversation — fixing a failing stage (learn-mode shape, kept
   for parity; reachable via the orchestrator's per-stage editing). */
const CHAT_THREAD = [
    { role: 'user', text: 'The enter-address stage keeps failing on the title dropdown. Can you take a look and fix it?' },
    { role: 'agent', text: "Let me reproduce it first — I'll read the stage and run it against the live site." },
    { role: 'tool', icon: 'far fa-file-code', name: 'read', args: 'stages/enter-address.stage.ts', result: '13 lines', status: 'ok' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'enter-address', result: "Error: select('#title') — element is not a <select>", status: 'error', stages: { 'open-site': 'executed', 'search': 'executed', 'choose-options': 'executed', 'view-basket': 'executed', 'enter-address': 'failed' }, screen: 'checkout' },
    { role: 'agent', text: "Found it. `#title` isn't a native `<select>` — it's a custom combobox, so `this.select()` can't drive it. I'll open it with a click and pick the option with the keyboard instead." },
    { role: 'diff', file: 'stages/enter-address.stage.ts', added: 3, removed: 1, hunks: [
        { type: 'ctx', text: "    await this.type('#lastName', c.lastName);" },
        { type: 'del', text: "    await this.select('#title', c.title);" },
        { type: 'add', text: "    await this.click('#title');" },
        { type: 'add', text: "    await this.keyboard.type(c.title);" },
        { type: 'add', text: "    await this.keyboard.press('Enter');" },
        { type: 'ctx', text: "    await this.click('button.continue');" },
    ] },
    { role: 'tool', icon: 'far fa-pen', name: 'edit', args: 'stages/enter-address.stage.ts', result: '+3 −1', status: 'ok' },
    { role: 'agent', text: "Re-running the stage against the live page to confirm the fix." },
    { role: 'tool', icon: 'far fa-location-dot', name: 'match stage', args: 'enter-address', result: 'matched', status: 'ok', stages: { 'enter-address': 'executing' }, screen: 'checkout' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'enter-address', result: 'passed · title=Ms, delivery filled', status: 'ok', stages: { 'enter-address': 'executed' }, screen: 'confirmation' },
    { role: 'agent', text: "Fixed. **enter-address** now matches — the title is selected via keyboard and the delivery details fill cleanly. Next up: `payment` and `confirm-order`. Want me to continue the run?" },
];

/* The workflows in this project — in Chat-to-MCP mode each is exposed to
   the agent as a single MCP tool (you talk to all of them at once). */
const CHAT_WORKFLOWS = [
    { name: 'find-product', site: 'johnlewis.com', desc: 'Open the site & search for a product' },
    { name: 'select-options', site: 'johnlewis.com', desc: 'Open the product & choose options' },
    { name: 'add-to-basket', site: 'johnlewis.com', desc: 'Add to basket & view the basket' },
    { name: 'delivery-details', site: 'johnlewis.com', desc: 'Enter the delivery address' },
    { name: 'payment', site: 'johnlewis.com', desc: 'Enter card & authorize payment' },
    { name: 'confirm-order', site: 'johnlewis.com', desc: 'Place the order & capture the reference' },
];

/* Chat-to-MCP mode — every WORKFLOW is exposed to the agent as a tool.
   You talk to all workflows at once; the agent invokes whole workflows. */
const CHAT_THREAD_RUN = [
    { role: 'user', text: 'Buy a Sonos Era 100 and deliver it to the Bristol address.' },
    { role: 'agent', text: 'I have **6 workflows** available as MCP tools. I’ll run them against johnlewis.com with the `okonkwo-home` dataset.' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'find-product', args: '{ query: "speaker" }', result: 'ok · 48 results · top: Sonos Era 100', status: 'ok', screen: 'listing' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'select-options', args: '{ sku: "sonos-era-100", colour: "Black" }', result: 'ok · Sonos Era 100 · £249', status: 'ok', screen: 'product' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'add-to-basket', args: '{ qty: 1 }', result: 'ok · 1 item · £249', status: 'ok', screen: 'basket' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'payment', args: '{ card: "default" }', result: 'ok · card authorised', status: 'ok', screen: 'checkout' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'confirm-order', args: '{ delivery: "standard" }', result: 'ok · ordered · ref JL-8842 · £249', status: 'ok', screen: 'confirmation' },
    { role: 'agent', text: "Done — the **Sonos Era 100 Smart Speaker** is ordered for **£249** and delivering to 14 Elm Road, Bristol (ref `JL-8842`). Want me to also add a 2-year guarantee?" },
];

/* Project-config mode — the left pane shows the project's source tree
   (missions, workflows, schemas, libraries, skills) and the agent helps
   you author them. */
const CONFIG_TREE = [
    { type: 'folder', name: 'missions', children: [
        { type: 'file', name: 'find-product.mission.md', path: 'find-product.mission.md' },
        { type: 'file', name: 'select-options.mission.md', path: 'select-options.mission.md' },
        { type: 'file', name: 'add-to-basket.mission.md', path: 'add-to-basket.mission.md' },
        { type: 'file', name: 'delivery-details.mission.md', path: 'delivery-details.mission.md' },
        { type: 'file', name: 'payment.mission.md', path: 'payment.mission.md' },
        { type: 'file', name: 'confirm-order.mission.md', path: 'confirm-order.mission.md' },
    ] },
    { type: 'folder', name: 'workflows', children: [
        { type: 'file', name: 'find-product.workflow.ts', path: 'find-product.workflow.ts' },
        { type: 'file', name: 'select-options.workflow.ts', path: 'select-options.workflow.ts' },
        { type: 'file', name: 'add-to-basket.workflow.ts', path: 'add-to-basket.workflow.ts' },
        { type: 'file', name: 'delivery-details.workflow.ts', path: 'delivery-details.workflow.ts' },
        { type: 'file', name: 'payment.workflow.ts', path: 'payment.workflow.ts' },
        { type: 'file', name: 'confirm-order.workflow.ts', path: 'confirm-order.workflow.ts' },
    ] },
    { type: 'folder', name: 'schemas', children: [
        { type: 'file', name: 'product.schema.ts', path: 'product.schema.ts' },
        { type: 'file', name: 'customer.schema.ts', path: 'customer.schema.ts' },
    ] },
    { type: 'folder', name: 'libraries', children: [
        { type: 'file', name: 'retail.lib.ts', path: 'retail.lib.ts' },
        { type: 'file', name: 'dates.lib.ts', path: 'dates.lib.ts' },
    ] },
    { type: 'folder', name: 'skills', children: [
        { type: 'file', name: 'cookie-messages.md', path: 'cookie-messages.md' },
        { type: 'file', name: 'captcha.md', path: 'captcha.md' },
        { type: 'file', name: 'two-factor.md', path: 'two-factor.md' },
    ] },
    { type: 'file', name: 'project.config.ts', path: 'project.config.ts' },
];

const CONFIG_FILES = {
    'find-product.mission.md': [
        "# Find product mission",
        "",
        "Open the site and search for a product on **johnlewis.com**.",
        "Follow these steps to author the stage files under `stages/`.",
        "",
        "## Stages to build",
        "1. **open-site** — navigate to the homepage and wait for search.",
        "2. **search** — type the `query` into the search box and submit.",
        "",
        "## Inputs",
        "- `query` — see `schemas/product.schema.ts`",
        "",
        "## Output",
        "- `results: { sku, name, price }[]`",
    ],
    'select-options.mission.md': [
        "# Select options mission",
        "",
        "Open a product and choose its options on **johnlewis.com**.",
        "",
        "## Stages to build",
        "1. **open-product** — open the matching result by `sku`.",
        "2. **choose-options** — set the colour and `qty` options.",
        "",
        "## Inputs",
        "- `sku`, `qty`, `options` — see `schemas/product.schema.ts`",
        "",
        "## Output",
        "- `product: { sku, name, price, options }`",
    ],
    'add-to-basket.mission.md': [
        "# Add to basket mission",
        "",
        "Add the configured product to the basket on **johnlewis.com**.",
        "",
        "## Stages to build",
        "1. **add** — click add-to-basket; wait for the modal overlay to",
        "   settle before asserting the basket count.",
        "2. **view-basket** — open the basket and read the line items.",
        "",
        "## Inputs",
        "- `sku`, `qty` — see `schemas/product.schema.ts`",
        "",
        "## Output",
        "- `basket: { items, subtotal }`",
    ],
    'delivery-details.mission.md': [
        "# Delivery details mission",
        "",
        "Enter the delivery address on **johnlewis.com**.",
        "",
        "## Stages to build",
        "1. **enter-address** — fill the delivery form. The title field is",
        "   a custom combobox: click it, then keyboard-select the value.",
        "",
        "## Inputs",
        "- `customer`, `address` — see `schemas/customer.schema.ts`",
        "",
        "## Output",
        "- `delivery: { address, slot }`",
    ],
    'payment.mission.md': [
        "# Payment mission",
        "",
        "Enter card details and authorize payment on **johnlewis.com**.",
        "",
        "## Stages to build",
        "1. **enter-card** — fill the card number, expiry and CVV.",
        "2. **authorize** — clear the 3-D Secure authorisation step.",
        "",
        "## Inputs",
        "- `customer` — see `schemas/customer.schema.ts`",
        "",
        "## Output",
        "- `authorized: boolean`",
    ],
    'confirm-order.mission.md': [
        "# Confirm order mission",
        "",
        "Place the order on **johnlewis.com**.",
        "",
        "## Stages to build",
        "1. **place-order** — submit and capture the order reference.",
        "",
        "## Output",
        "- `ordered: boolean`",
        "- `order: { ref, item, total }`",
    ],
    'find-product.workflow.ts': [
        "// find-product.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'find-product',",
        "    site: 'johnlewis.com',",
        "    mission: 'find-product.mission.md',",
        "    stages: ['open-site', 'search'],",
        "    output: { results: 'array' },",
        "});",
    ],
    'select-options.workflow.ts': [
        "// select-options.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'select-options',",
        "    site: 'johnlewis.com',",
        "    mission: 'select-options.mission.md',",
        "    stages: ['open-product', 'choose-options'],",
        "    output: { product: 'object' },",
        "});",
    ],
    'add-to-basket.workflow.ts': [
        "// add-to-basket.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'add-to-basket',",
        "    site: 'johnlewis.com',",
        "    mission: 'add-to-basket.mission.md',",
        "    stages: ['add', 'view-basket'],",
        "    output: { basket: 'object' },",
        "});",
    ],
    'delivery-details.workflow.ts': [
        "// delivery-details.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'delivery-details',",
        "    site: 'johnlewis.com',",
        "    mission: 'delivery-details.mission.md',",
        "    stages: ['enter-address'],",
        "    output: { delivery: 'object' },",
        "});",
    ],
    'payment.workflow.ts': [
        "// payment.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'payment',",
        "    site: 'johnlewis.com',",
        "    mission: 'payment.mission.md',",
        "    stages: ['enter-card', 'authorize'],",
        "    output: { authorized: 'boolean' },",
        "});",
    ],
    'confirm-order.workflow.ts': [
        "// confirm-order.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'confirm-order',",
        "    site: 'johnlewis.com',",
        "    mission: 'confirm-order.mission.md',",
        "    stages: ['place-order'],",
        "    output: { ordered: 'boolean', order: 'object' },",
        "});",
    ],
    'product.schema.ts': [
        "// product.schema.ts",
        "import { z } from 'zod';",
        "",
        "export const product = z.object({",
        "    sku: z.string().min(1),",
        "    name: z.string().min(1),",
        "    price: z.number(),",
        "    qty: z.number().int().min(1),",
        "    options: z.record(z.string()).optional(),",
        "});",
        "",
        "export type Product = z.infer<typeof product>;",
    ],
    'customer.schema.ts': [
        "// customer.schema.ts",
        "import { z } from 'zod';",
        "",
        "export const customer = z.object({",
        "    firstName: z.string().min(1),",
        "    lastName: z.string().min(1),",
        "    title: z.enum(['Mr', 'Ms', 'Mx', 'Dr']),",
        "    email: z.string().email(),",
        "    address: z.object({",
        "        line1: z.string().min(1),",
        "        city: z.string().min(1),",
        "        postcode: z.string().min(5),",
        "    }),",
        "});",
        "",
        "export type Customer = z.infer<typeof customer>;",
    ],
    'retail.lib.ts': [
        "// retail.lib.ts",
        "export const retailers = {",
        "    johnlewis: { name: 'John Lewis & Partners', site: 'johnlewis.com' },",
        "    next: { name: 'Next', site: 'next.co.uk' },",
        "};",
        "",
        "export const money = (amount, currency = 'GBP') =>",
        "    new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(amount);",
    ],
    'dates.lib.ts': [
        "// dates.lib.ts",
        "export const fmtDate = (d) => new Date(d).toISOString().slice(0, 10);",
    ],
    'cookie-messages.md': [
        "# Skill: dismiss cookie messages",
        "",
        "A reusable skill any stage can apply before interacting with a page.",
        "Most sites show a consent banner that blocks clicks until dismissed.",
        "",
        "## When to use",
        "- Right after `open-site`, before the first interaction.",
        "- Whenever a click is intercepted by an overlay.",
        "",
        "## Steps",
        "1. Wait up to 3s for a consent dialog (`[id*=cookie]`, `[class*=consent]`).",
        "2. Prefer the **reject-all** control; fall back to **accept-all**.",
        "3. Confirm the overlay is gone before continuing.",
        "",
        "## Selectors to try",
        "- `button:has-text(\"Reject all\")`, `button:has-text(\"Accept all\")`",
        "- `#onetrust-reject-all-handler`, `.cookie-banner button`",
        "",
        "> If no banner appears within the timeout, continue silently.",
    ],
    'captcha.md': [
        "# Skill: handle captcha",
        "",
        "Detect and route around CAPTCHA challenges.",
        "",
        "## Steps",
        "1. Detect a challenge (`iframe[src*=recaptcha]`, `[class*=captcha]`).",
        "2. Pause the run and request a solve via the configured provider.",
        "3. Resume once the token is injected; retry the blocked action.",
        "",
        "> If unsolvable, fail the stage with `reason: 'captcha'`.",
    ],
    'two-factor.md': [
        "# Skill: two-factor / OTP",
        "",
        "Complete a one-time-password challenge during login or payment.",
        "",
        "## Steps",
        "1. Detect the OTP field (`input[autocomplete=one-time-code]`).",
        "2. Fetch the code from the dataset or the connected inbox/SMS hook.",
        "3. Type the code and submit; wait for navigation.",
    ],
    'project.config.ts': [
        "// project.config.ts",
        "export default {",
        "    project: 'retail-purchase',",
        "    runner: 'chrome',",
        "    dataset: 'okonkwo-home',",
        "};",
    ],
};

const CHAT_THREAD_CONFIG = [
    { role: 'agent', text: "Let's set up your **retail-purchase** project. I'll work bottom-up: first scaffold the reusable **libraries** and **skills**, then reason about the data **schemas**, then write a **mission** per workflow, and finally the **workflow** definitions that tie it together. What site and tasks should it cover?" },
    { role: 'user', text: 'John Lewis — the whole shopping funnel: find a product, choose options, add to basket, enter delivery, pay, and place the order.' },
    { role: 'agent', text: "Got it — six workflows on one site, one per step of the funnel. Starting with the project config and the shared building blocks, since missions and workflows will depend on them." },
    { role: 'tool', kind: 'config', icon: 'far fa-file-pen', name: 'write', args: 'project.config.ts', cfile: 'project.config.ts', result: '+5 lines', status: 'ok' },
    { role: 'agent', text: "Scaffolding the **libraries** (retailer metadata, a money helper, date helpers) and the **skills** every stage can reuse — dismissing cookie banners, solving captchas, and OTP at payment. These are generic, so I can drop them in immediately." },
    { role: 'tool', kind: 'config', icon: 'far fa-folder-plus', name: 'scaffold', args: 'libraries/ + skills/', cfiles: ['libraries/retail.lib.ts', 'libraries/dates.lib.ts', 'skills/cookie-messages.md', 'skills/captcha.md', 'skills/two-factor.md'], result: '5 files · 2 libraries, 3 skills', status: 'ok' },
    { role: 'agent', text: "Now the **schemas**. Each workflow touches a **product** (sku, name, price, qty, options) and a **customer** (title, names, email, delivery address). Options, basket and checkout all reuse the same product. So two shared schemas cover all six workflows — I'll model them in Zod so inputs are validated everywhere." },
    { role: 'tool', kind: 'config', icon: 'far fa-file-pen', name: 'write', args: 'schemas/product.schema.ts', cfile: 'schemas/product.schema.ts', result: '+11 lines', status: 'ok' },
    { role: 'tool', kind: 'config', icon: 'far fa-file-pen', name: 'write', args: 'schemas/customer.schema.ts', cfile: 'schemas/customer.schema.ts', result: '+15 lines', status: 'ok' },
    { role: 'agent', text: "With the schemas in place I can write the **missions** — a Markdown brief per workflow that the agent follows to build the stage files. Each lists the stages, the inputs (referencing the schemas above), and the expected output. I'll batch all six." },
    { role: 'tool', kind: 'config', icon: 'far fa-folder-plus', name: 'scaffold', args: 'missions/', cfiles: ['missions/find-product.mission.md', 'missions/select-options.mission.md', 'missions/add-to-basket.mission.md', 'missions/delivery-details.mission.md', 'missions/payment.mission.md', 'missions/confirm-order.mission.md'], result: '6 files · one mission per workflow', status: 'ok' },
    { role: 'agent', text: "Finally the **workflow** definitions — each binds its mission to a site, declares the stage list, and types its output so the orchestrator can chain workflows together later. Batching all six." },
    { role: 'tool', kind: 'config', icon: 'far fa-folder-plus', name: 'scaffold', args: 'workflows/', cfiles: ['workflows/find-product.workflow.ts', 'workflows/select-options.workflow.ts', 'workflows/add-to-basket.workflow.ts', 'workflows/delivery-details.workflow.ts', 'workflows/payment.workflow.ts', 'workflows/confirm-order.workflow.ts'], result: '6 files · one workflow per funnel step', status: 'ok' },
    { role: 'agent', text: "Project scaffolded — **22 files**: 2 libraries, 3 skills, 2 Zod schemas, 6 missions and 6 workflows. Each mission lists the stages to build; open one on the left to review it, then learn the workflows in Learning mode." },
    { role: 'cta', to: 'orchestrate', text: "Your project is configured. Next, learn all the workflows at once by chaining them together.", link: 'Open Learning →' },
];

/* Per-stage source files — the post-fix (clean, diff-free) contents,
   shown in the right-pane editor when a stage is opened. */
const STAGE_FILES = {
    'open-site': [
        "// open-site.stage.ts",
        "",
        "import { Stage } from '@athree/runner';",
        "",
        "export default class OpenSite extends Stage {",
        "    async run(ctx) {",
        "        await this.goto('https://johnlewis.com');",
        "        await this.waitFor('form.search');",
        "        return { matched: true };",
        "    }",
        "}",
    ],
    'search': [
        "// search.stage.ts",
        "",
        "import { Stage } from '@athree/runner';",
        "",
        "export default class Search extends Stage {",
        "    async run(ctx) {",
        "        await this.type('#search', ctx.inputs.query);",
        "        await this.click('button.search-submit');",
        "        await this.waitFor('ul.product-results');",
        "        return { matched: true };",
        "    }",
        "}",
    ],
    'choose-options': [
        "// choose-options.stage.ts",
        "",
        "import { Stage } from '@athree/runner';",
        "",
        "export default class ChooseOptions extends Stage {",
        "    async run(ctx) {",
        "        await this.click(`[data-sku=\"${ctx.inputs.sku}\"]`);",
        "        await this.waitFor('main.product');",
        "        await this.click(`[data-colour=\"${ctx.inputs.options.colour}\"]`);",
        "        await this.select('#qty', String(ctx.inputs.qty));",
        "        return { matched: true };",
        "    }",
        "}",
    ],
    'enter-address': [
        "// enter-address.stage.ts",
        "",
        "import { Stage } from '@athree/runner';",
        "",
        "export default class EnterAddress extends Stage {",
        "    async run(ctx) {",
        "        const c = ctx.inputs.customer;",
        "        await this.type('#firstName', c.firstName);",
        "        await this.type('#lastName', c.lastName);",
        "        await this.click('#title');",
        "        await this.keyboard.type(c.title);",
        "        await this.keyboard.press('Enter');",
        "        await this.click('button.continue');",
        "        return { matched: true };",
        "    }",
        "}",
    ],
    'enter-card': [
        "// enter-card.stage.ts",
        "",
        "import { Stage } from '@athree/runner';",
        "",
        "export default class EnterCard extends Stage {",
        "    async run(ctx) {",
        "        await this.type('#cardNumber', ctx.inputs.card.number);",
        "        await this.type('#expiry', ctx.inputs.card.expiry);",
        "        await this.type('#cvv', ctx.inputs.card.cvv);",
        "        await this.click('button.pay');",
        "        return { matched: true };",
        "    }",
        "}",
    ],
};

/* Empty-state suggested prompts, per mode. Each has a headline title and
   the prompt text that gets "typed" when clicked. */
const CHAT_SUGGESTIONS = {
    orchestrate: {
        title: 'Learn every workflow at once',
        blurb: 'A3 learns all workflows and chains each one’s output into the next.',
        items: [
            { icon: 'far fa-graduation-cap', label: 'Learn johnlewis.com', prompt: 'learn johnlewis.com' },
        ],
    },
    run: {
        title: 'Chat with your workflows',
        blurb: 'Every workflow is exposed to the agent as an MCP tool — just say what you need.',
        items: [
            { icon: 'far fa-cart-shopping', label: 'Buy & deliver a Sonos', prompt: 'Buy a Sonos Era 100 and deliver it to the Bristol address.' },
            { icon: 'far fa-pen-to-square', label: 'Add a guarantee to an order', prompt: 'Add a 2-year guarantee to order JL-8842.' },
        ],
    },
    config: {
        title: 'Describe your project',
        blurb: 'Tell A3 your objective in plain language — it scaffolds the missions, workflows and Zod schemas from scratch.',
        items: [
            { icon: 'far fa-wand-magic-sparkles', label: 'Buy a product', desc: 'Set up an agent to buy products from the retail site for me. It should find the product I want, choose its options, add it to the basket, enter my delivery address, and pay to place the order.', prompt: 'Set up an agent to buy products from the retail site for me. It should find the product I want, choose its options, add it to the basket, enter my delivery address, and pay to place the order.' },
        ],
    },
};

window.A3ChatData = { CHAT_PROJECT, CHAT_DATASETS, CHAT_SUGGESTIONS, CHAT_SCOPE, CHAT_SCOPE_DATA, CHAT_WORKFLOWS, CHAT_PLAN, ORCHESTRATOR_PLAN, ORCHESTRATOR_THREAD, CHAT_THREAD, CHAT_THREAD_RUN, CHAT_THREAD_CONFIG, CONFIG_TREE, CONFIG_FILES, STAGE_FILES };
