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

const CHAT_PROJECT = { title: 'book-flight', site: 'emirates.com', dataset: 'al-rashid' };

/* Selectable input datasets for the workflow run. */
const CHAT_DATASETS = [
    { id: 'al-rashid', label: 'al-rashid', hint: 'DXB → LHR · 2 passengers' },
    { id: 'solo-business', label: 'solo-business', hint: 'DXB → JFK · 1 passenger' },
    { id: 'family-four', label: 'family-four', hint: 'LHR → DXB · 4 passengers' },
    { id: 'qa-fixtures', label: 'qa-fixtures', hint: 'synthetic · 12 rows' },
];

const CHAT_SCOPE = {
    inputs: [
        { key: 'origin', preview: '"DXB"' },
        { key: 'destination', preview: '"LHR"' },
        { key: 'departDate', preview: '"2026-08-22"' },
        { key: 'passengers', preview: '{ adults: 2, cabin: "business" }' },
    ],
    outputs: [
        { key: 'booked', preview: 'true' },
        { key: 'booking', preview: '{ ref: "EK-5530", … }' },
    ],
    context: [
        { key: 'browser.url', preview: '"…/book/passengers"' },
        { key: 'stage.current', preview: '"passenger-details"' },
        { key: 'session.exitCode', preview: 'null' },
    ],
};

/* Full JSON values for the data panel's tree viewer. */
const CHAT_SCOPE_DATA = {
    inputs: {
        origin: 'DXB',
        destination: 'LHR',
        departDate: '2026-08-22',
        passengers: { adults: 2, children: 0, cabin: 'business' },
        budget: { currency: 'GBP', maxFare: 1200 },
        passenger: { firstName: 'Layla', lastName: 'Al-Rashid', title: 'Ms', dateOfBirth: '1990-03-12', skywards: '4471 9920 1183' },
        preferences: { fare: 'Flex', seat: 'window', meal: 'standard' },
    },
    outputs: {
        booked: true,
        booking: { ref: 'EK-5530', flight: 'EK0007', seat: '23A', cabin: 'Business', departDate: '2026-08-22', total: { currency: 'GBP', amount: 842 } },
        warnings: [],
    },
    context: {
        browser: { url: 'https://emirates.com/book/passengers', title: 'Passenger details', viewport: { width: 1280, height: 800 } },
        stage: { current: 'passenger-details', index: 3, total: 5 },
        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: 'passenger-details', status: 'pending' },
    { name: 'seat-selection', status: 'pending' },
    { name: 'confirm', 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: 'search-flights', site: 'emirates.com', stages: [
        { name: 'open-site', status: 'pending' },
        { name: 'search', status: 'pending' },
    ] },
    { workflow: 'select-fare', site: 'emirates.com', stages: [
        { name: 'compare-fares', status: 'pending' },
        { name: 'choose-fare', status: 'pending' },
    ] },
    { workflow: 'passenger-details', site: 'emirates.com', stages: [
        { name: 'enter-passengers', status: 'pending' },
    ] },
    { workflow: 'seat-selection', site: 'emirates.com', stages: [
        { name: 'open-seatmap', status: 'pending' },
        { name: 'pick-seats', status: 'pending' },
    ] },
    { workflow: 'add-baggage', site: 'emirates.com', stages: [
        { name: 'choose-baggage', status: 'pending' },
    ] },
    { workflow: 'payment', site: 'emirates.com', stages: [
        { name: 'enter-card', status: 'pending' },
        { name: '3ds-challenge', status: 'pending' },
        { name: 'authorize', status: 'pending' },
    ] },
    { workflow: 'confirm-booking', site: 'emirates.com', stages: [
        { name: 'issue-ticket', status: 'pending' },
    ] },
];

const ORCHESTRATOR_THREAD = [
    { role: 'user', text: 'learn emirates.com' },
    { role: 'agent', text: "I'll learn the funnel as one chain of **7 workflows**: **search-flights → select-fare → passenger-details → seat-selection → add-baggage → payment → confirm-booking**, 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/search-flights.mission.md · select-fare.mission.md · passenger-details.mission.md', result: '3 missions · 5 stages', status: 'ok' },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/seat-selection.mission.md · add-baggage.mission.md', result: '2 missions · 3 stages', status: 'ok' },
    { role: 'tool', icon: 'far fa-file-lines', name: 'read', args: 'missions/payment.mission.md · confirm-booking.mission.md', result: '2 missions · 4 stages', status: 'ok' },
    { role: 'agent', text: "Starting with **search-flights**. I'll author each stage and run it against emirates.com." },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'search-flights / open-site', result: 'passed · emirates.com loaded', status: 'ok', ostages: { 'search-flights/open-site': 'executed' }, screen: 'search' },
    { role: 'agent', text: "The date picker is a custom calendar widget, not native inputs. Writing the `search` stage to open it and click the day cells.", ostages: { 'search-flights/search': 'executing' } },
    { role: 'diff', file: 'search-flights/search.stage.ts', added: 3, removed: 1, hunks: [
        { type: 'ctx', text: "    await this.type('#origin', ctx.inputs.origin);" },
        { type: 'del', text: "    await this.type('#depart', ctx.inputs.departDate);" },
        { type: 'add', text: "    await this.click('[data-testid=depart-date-field]');" },
        { type: 'add', text: "    await this.click(`[data-date=\"${ctx.inputs.departDate}\"]`);" },
        { type: 'add', text: "    await this.click('button.search-flights');" },
    ] },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'search-flights / search', result: 'passed · 18 flights found', status: 'ok', ostages: { 'search-flights/search': 'executed' }, screen: 'results' },
    { role: 'agent', text: "**search-flights** is fully learned. Chaining the top result's `flightId` into **select-fare**." },
    { role: 'tool', icon: 'far fa-link', name: 'chain', args: 'search-flights.output → select-fare.input', result: 'flightId, date mapped', status: 'ok' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'select-fare / compare-fares', result: 'passed · 3 fare families shown', status: 'ok', ostages: { 'select-fare/compare-fares': 'executed' }, screen: 'results' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'select-fare / choose-fare', result: 'passed · Business Flex selected', status: 'ok', ostages: { 'select-fare/choose-fare': 'executed' }, screen: 'results' },
    { role: 'agent', text: "**select-fare** learned. Chaining the chosen `fareId` into **passenger-details**." },
    { role: 'tool', icon: 'far fa-link', name: 'chain', args: 'select-fare.output → passenger-details.input', result: 'fareId, cabin mapped', status: 'ok' },
    { role: 'agent', text: "Learning `enter-passengers` — the title field is a custom combobox, so I'll drive it by keyboard.", ostages: { 'passenger-details/enter-passengers': 'executing' } },
    { role: 'diff', file: 'passenger-details/enter-passengers.stage.ts', added: 3, removed: 1, hunks: [
        { type: 'ctx', text: "    await this.type('#lastName', p.lastName);" },
        { type: 'del', text: "    await this.select('#title', p.title);" },
        { type: 'add', text: "    await this.click('#title');" },
        { type: 'add', text: "    await this.keyboard.type(p.title);" },
        { type: 'add', text: "    await this.keyboard.press('Enter');" },
    ] },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'passenger-details / enter-passengers', result: 'passed · passenger filled', status: 'ok', ostages: { 'passenger-details/enter-passengers': 'executed' }, screen: 'passenger-details' },
    { role: 'agent', text: "**passenger-details** learned. Chaining the `passengerId` into **seat-selection**." },
    { role: 'tool', icon: 'far fa-link', name: 'chain', args: 'passenger-details.output → seat-selection.input', result: 'passengerId mapped', status: 'ok' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'seat-selection / open-seatmap', result: 'passed · seat map iframe loaded', status: 'ok', ostages: { 'seat-selection/open-seatmap': 'executed' }, screen: 'seat-map' },
    { role: 'agent', text: "The seat map lazy-loads inside an iframe. Scoping the wait to the frame before clicking the window seat.", ostages: { 'seat-selection/pick-seats': 'executing' } },
    { role: 'diff', file: 'seat-selection/pick-seats.stage.ts', added: 2, removed: 1, hunks: [
        { type: 'del', text: "    await this.click('[data-seat=\"23A\"]');" },
        { type: 'add', text: "    await this.frame('#seatmap').waitFor('[data-seat]');" },
        { type: 'add', text: "    await this.frame('#seatmap').click('[data-seat=\"23A\"]');" },
    ] },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'seat-selection / pick-seats', result: 'passed · seat 23A selected', status: 'ok', ostages: { 'seat-selection/pick-seats': 'executed' }, screen: 'seat-map' },
    { role: 'agent', text: "**seat-selection** learned. The extras panel shares the seat-map screen — learning **add-baggage** next." },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'add-baggage / choose-baggage', result: 'passed · +1 extra bag (23kg)', status: 'ok', ostages: { 'add-baggage/choose-baggage': 'executed' }, screen: 'seat-map' },
    { role: 'agent', text: "**add-baggage** learned. Chaining the running cart total into **payment**." },
    { role: 'tool', icon: 'far fa-link', name: 'chain', args: 'add-baggage.output → payment.input', result: 'cartTotal mapped', status: 'ok' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'payment / enter-card', result: 'passed · card accepted', status: 'ok', ostages: { 'payment/enter-card': 'executed' }, screen: 'payment' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'payment / 3ds-challenge', result: 'Error: 3-D Secure iframe timed out', status: 'error', ostages: { 'payment/3ds-challenge': 'failed' }, screen: 'payment' },
    { role: 'agent', text: "Payment bounced to a 3-D Secure challenge in an iframe. Scoping the wait to the frame and resuming.", ostages: { 'payment/3ds-challenge': 'executing' } },
    { role: 'diff', file: 'payment/3ds-challenge.stage.ts', added: 1, removed: 1, hunks: [
        { type: 'del', text: "    await this.waitFor('input[name=otp]');" },
        { type: 'add', text: "    await this.frame('#3ds').waitFor('input[name=otp]');" },
    ] },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'payment / 3ds-challenge → authorize', result: 'passed · authorized · £842', status: 'ok', ostages: { 'payment/3ds-challenge': 'executed', 'payment/authorize': 'executed' }, screen: 'payment' },
    { role: 'agent', text: "**payment** learned. Chaining the `paymentRef` into **confirm-booking** to issue the ticket." },
    { role: 'tool', icon: 'far fa-link', name: 'chain', args: 'payment.output → confirm-booking.input', result: 'paymentRef mapped', status: 'ok' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'confirm-booking / issue-ticket', result: 'passed · ref EK-5530 · ticket issued', status: 'ok', ostages: { 'confirm-booking/issue-ticket': 'executed' }, screen: 'confirmation' },
    { role: 'agent', text: "All **7 workflows** learned and chained · 12/12 stages passing end to end: a search feeds the fare, the fare carries into passengers, then seats, bags, payment and the issued ticket." },
    { role: 'cta', to: 'run', text: "All 7 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 passenger-details 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-passengers.stage.ts', result: '13 lines', status: 'ok' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'passenger-details', result: "Error: select('#title') — element is not a <select>", status: 'error', stages: { 'open-site': 'executed', 'search': 'executed', 'passenger-details': 'failed' }, screen: 'passenger-details' },
    { 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-passengers.stage.ts', added: 3, removed: 1, hunks: [
        { type: 'ctx', text: "    await this.type('#lastName', p.lastName);" },
        { type: 'del', text: "    await this.select('#title', p.title);" },
        { type: 'add', text: "    await this.click('#title');" },
        { type: 'add', text: "    await this.keyboard.type(p.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-passengers.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: 'passenger-details', result: 'matched', status: 'ok', stages: { 'passenger-details': 'executing' }, screen: 'passenger-details' },
    { role: 'tool', icon: 'far fa-play', name: 'run stage', args: 'passenger-details', result: 'passed · title=Ms, passenger filled', status: 'ok', stages: { 'passenger-details': 'executed' }, screen: 'confirmation' },
    { role: 'agent', text: "Fixed. **passenger-details** now matches — the title is selected via keyboard and the passenger details fill cleanly. Want me to continue the run through seats and payment?" },
];

/* 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: 'search-flights', site: 'emirates.com', desc: 'Search available flights' },
    { name: 'select-fare', site: 'emirates.com', desc: 'Compare & choose a cabin and fare' },
    { name: 'passenger-details', site: 'emirates.com', desc: 'Enter the passenger details' },
    { name: 'seat-selection', site: 'emirates.com', desc: 'Open the seat map & pick seats' },
    { name: 'add-baggage', site: 'emirates.com', desc: 'Add extra checked baggage' },
    { name: 'payment', site: 'emirates.com', desc: 'Pay & clear the 3-D Secure check' },
    { name: 'confirm-booking', site: 'emirates.com', desc: 'Issue the ticket & capture the ref' },
];

/* 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: 'Book the Al-Rashid party DXB→LHR on 22 Aug in Business with extra bags and window seats.' },
    { role: 'agent', text: 'I have **7 workflows** available as MCP tools. I’ll run them against emirates.com with the `al-rashid` dataset.' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'search-flights', args: '{ from: "DXB", to: "LHR" }', result: 'ok · 6 nonstop · top: EK0007 07:45', status: 'ok', screen: 'results' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'select-fare', args: '{ cabin: "business", fare: "Flex" }', result: 'ok · Business Flex · £842', status: 'ok', screen: 'results' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'seat-selection', args: '{ seat: "window" }', result: 'ok · seat 23A selected', status: 'ok', screen: 'seat-map' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'add-baggage', args: '{ extraBags: 1 }', result: 'ok · +1 bag (23kg) · +£60', status: 'ok', screen: 'seat-map' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'payment', args: '{ card: "•••• 1183" }', result: 'ok · authorized · 3-D Secure cleared', status: 'ok', screen: 'payment' },
    { role: 'tool', kind: 'workflow', icon: 'far fa-diagram-project', name: 'confirm-booking', args: '{}', result: 'ok · booked · ref EK-5530 · ticket issued', status: 'ok', screen: 'confirmation' },
    { role: 'agent', text: "Done — the Al-Rashid party is booked on **EK0007** (DXB→LHR, 22 Aug, Business Flex) for **£842** plus an extra bag, with window seat 23A (ref `EK-5530`). Anything else to add to the booking?" },
];

/* 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: 'search-flights.mission.md', path: 'search-flights.mission.md' },
        { type: 'file', name: 'select-fare.mission.md', path: 'select-fare.mission.md' },
        { type: 'file', name: 'passenger-details.mission.md', path: 'passenger-details.mission.md' },
        { type: 'file', name: 'seat-selection.mission.md', path: 'seat-selection.mission.md' },
        { type: 'file', name: 'add-baggage.mission.md', path: 'add-baggage.mission.md' },
        { type: 'file', name: 'payment.mission.md', path: 'payment.mission.md' },
        { type: 'file', name: 'confirm-booking.mission.md', path: 'confirm-booking.mission.md' },
    ] },
    { type: 'folder', name: 'workflows', children: [
        { type: 'file', name: 'search-flights.workflow.ts', path: 'search-flights.workflow.ts' },
        { type: 'file', name: 'select-fare.workflow.ts', path: 'select-fare.workflow.ts' },
        { type: 'file', name: 'passenger-details.workflow.ts', path: 'passenger-details.workflow.ts' },
        { type: 'file', name: 'seat-selection.workflow.ts', path: 'seat-selection.workflow.ts' },
        { type: 'file', name: 'add-baggage.workflow.ts', path: 'add-baggage.workflow.ts' },
        { type: 'file', name: 'payment.workflow.ts', path: 'payment.workflow.ts' },
        { type: 'file', name: 'confirm-booking.workflow.ts', path: 'confirm-booking.workflow.ts' },
    ] },
    { type: 'folder', name: 'schemas', children: [
        { type: 'file', name: 'passenger.schema.ts', path: 'passenger.schema.ts' },
        { type: 'file', name: 'journey.schema.ts', path: 'journey.schema.ts' },
    ] },
    { type: 'folder', name: 'libraries', children: [
        { type: 'file', name: 'flights.lib.ts', path: 'flights.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 = {
    'search-flights.mission.md': [
        "# Search flights mission",
        "",
        "Search available flights on **emirates.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** — enter `origin` / `destination`, open the calendar",
        "   and pick `departDate`, then set the passenger count.",
        "",
        "## Inputs",
        "- `origin`, `destination`, `departDate` — see `schemas/journey.schema.ts`",
        "- `passengers`, `budget`",
        "",
        "## Output",
        "- `results: { flightId, number, fareFrom }[]`",
    ],
    'select-fare.mission.md': [
        "# Select fare mission",
        "",
        "Compare and choose a cabin and fare family on **emirates.com**.",
        "",
        "## Stages to build",
        "1. **compare-fares** — open the chosen flight's fare matrix.",
        "2. **choose-fare** — pick the cabin + fare (Saver, Flex, …).",
        "",
        "## Inputs",
        "- `flightId`, `cabin`, `fare`",
        "",
        "## Output",
        "- `fareId`, `total: number`",
    ],
    'passenger-details.mission.md': [
        "# Passenger details mission",
        "",
        "Enter the lead passenger's details on **emirates.com**.",
        "",
        "## Stages to build",
        "1. **enter-passengers** — fill the lead passenger. The title field",
        "   is a custom combobox: click it, then keyboard-select the value.",
        "",
        "## Inputs",
        "- `passenger` — see `schemas/passenger.schema.ts`",
        "- `fareId`",
        "",
        "## Output",
        "- `passengerId: string`",
    ],
    'seat-selection.mission.md': [
        "# Seat selection mission",
        "",
        "Open the seat map and pick seats on **emirates.com**.",
        "",
        "## Stages to build",
        "1. **open-seatmap** — open the seat map; it lazy-loads in an iframe.",
        "2. **pick-seats** — scope to the frame and click the preferred seat.",
        "",
        "## Inputs",
        "- `passengerId`, `seat` (e.g. window/aisle)",
        "",
        "## Output",
        "- `seats: string[]`",
    ],
    'add-baggage.mission.md': [
        "# Add baggage mission",
        "",
        "Add extra checked baggage to the booking on **emirates.com**.",
        "",
        "## Stages to build",
        "1. **choose-baggage** — open the extras panel and add the bags.",
        "",
        "## Inputs",
        "- `extraBags: number`",
        "",
        "## Output",
        "- `cartTotal: number`",
    ],
    'payment.mission.md': [
        "# Payment mission",
        "",
        "Pay for the booking on **emirates.com**.",
        "",
        "## Stages to build",
        "1. **enter-card** — fill the card details.",
        "2. **3ds-challenge** — handle the 3-D Secure iframe (OTP).",
        "3. **authorize** — submit and wait for authorization.",
        "",
        "## Inputs",
        "- `card`, `cartTotal`",
        "",
        "## Output",
        "- `paymentRef: string`, `total: number`",
    ],
    'confirm-booking.mission.md': [
        "# Confirm booking mission",
        "",
        "Issue the ticket and capture the reference on **emirates.com**.",
        "",
        "## Stages to build",
        "1. **issue-ticket** — submit and capture the booking reference.",
        "",
        "## Inputs",
        "- `paymentRef`",
        "",
        "## Output",
        "- `booked: boolean`",
        "- `booking: { ref, flight, seat, total }`",
    ],
    'search-flights.workflow.ts': [
        "// search-flights.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'search-flights',",
        "    site: 'emirates.com',",
        "    mission: 'search-flights.mission.md',",
        "    stages: ['open-site', 'search'],",
        "    output: { results: 'array' },",
        "});",
    ],
    'select-fare.workflow.ts': [
        "// select-fare.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'select-fare',",
        "    site: 'emirates.com',",
        "    mission: 'select-fare.mission.md',",
        "    stages: ['compare-fares', 'choose-fare'],",
        "    output: { fareId: 'string', total: 'number' },",
        "});",
    ],
    'passenger-details.workflow.ts': [
        "// passenger-details.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'passenger-details',",
        "    site: 'emirates.com',",
        "    mission: 'passenger-details.mission.md',",
        "    stages: ['enter-passengers'],",
        "    output: { passengerId: 'string' },",
        "});",
    ],
    'seat-selection.workflow.ts': [
        "// seat-selection.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'seat-selection',",
        "    site: 'emirates.com',",
        "    mission: 'seat-selection.mission.md',",
        "    stages: ['open-seatmap', 'pick-seats'],",
        "    output: { seats: 'array' },",
        "});",
    ],
    'add-baggage.workflow.ts': [
        "// add-baggage.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'add-baggage',",
        "    site: 'emirates.com',",
        "    mission: 'add-baggage.mission.md',",
        "    stages: ['choose-baggage'],",
        "    output: { cartTotal: 'number' },",
        "});",
    ],
    'payment.workflow.ts': [
        "// payment.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'payment',",
        "    site: 'emirates.com',",
        "    mission: 'payment.mission.md',",
        "    stages: ['enter-card', '3ds-challenge', 'authorize'],",
        "    output: { paymentRef: 'string', total: 'number' },",
        "});",
    ],
    'confirm-booking.workflow.ts': [
        "// confirm-booking.workflow.ts",
        "import { Workflow } from '@athree/core';",
        "",
        "export default new Workflow({",
        "    name: 'confirm-booking',",
        "    site: 'emirates.com',",
        "    mission: 'confirm-booking.mission.md',",
        "    stages: ['issue-ticket'],",
        "    output: { booked: 'boolean', booking: 'object' },",
        "});",
    ],
    'passenger.schema.ts': [
        "// passenger.schema.ts",
        "import { z } from 'zod';",
        "",
        "export const passenger = z.object({",
        "    firstName: z.string().min(1),",
        "    lastName: z.string().min(1),",
        "    title: z.enum(['Mr', 'Ms', 'Mx', 'Dr']),",
        "    dateOfBirth: z.coerce.date(),",
        "    skywards: z.string().optional(),",
        "});",
        "",
        "export type Passenger = z.infer<typeof passenger>;",
    ],
    'journey.schema.ts': [
        "// journey.schema.ts",
        "import { z } from 'zod';",
        "",
        "export const journey = z.object({",
        "    origin: z.string().length(3),",
        "    destination: z.string().length(3),",
        "    departDate: z.coerce.date(),",
        "    cabin: z.enum(['economy', 'premium', 'business', 'first']),",
        "    passengers: z.number().int().min(1),",
        "});",
        "",
        "export type Journey = z.infer<typeof journey>;",
    ],
    'flights.lib.ts': [
        "// flights.lib.ts",
        "export const airlines = {",
        "    emirates: { name: 'Emirates', code: 'EK', site: 'emirates.com' },",
        "    qatar: { name: 'Qatar Airways', code: 'QR', site: 'qatarairways.com' },",
        "};",
        "",
        "export const flightNo = (code, n) =>",
        "    `${code}${String(n).padStart(4, '0')}`;",
    ],
    '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: 'flight-booking',",
        "    runner: 'chrome',",
        "    dataset: 'al-rashid',",
        "};",
    ],
};

const CHAT_THREAD_CONFIG = [
    { role: 'agent', text: "Let's set up your **flight-booking** 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: 'Emirates.com — the whole booking funnel: search, fare, passengers, seats, bags, payment and the ticket.' },
    { role: 'agent', text: "Got it — seven workflows mapping the booking funnel on one site. 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** (airline metadata, 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/flights.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**. Every workflow touches a **journey** (origin, destination, date, cabin, passengers) and a lead **passenger** (title, names, date of birth, Skywards). The booking steps reuse the same passenger. So two shared schemas cover all seven 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/passenger.schema.ts', cfile: 'schemas/passenger.schema.ts', result: '+11 lines', status: 'ok' },
    { role: 'tool', kind: 'config', icon: 'far fa-file-pen', name: 'write', args: 'schemas/journey.schema.ts', cfile: 'schemas/journey.schema.ts', result: '+12 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 author all seven funnel steps in one pass." },
    { role: 'tool', kind: 'config', icon: 'far fa-file-pen', name: 'scaffold', args: 'missions/ · 7 funnel steps', cfiles: ['missions/search-flights.mission.md', 'missions/select-fare.mission.md', 'missions/passenger-details.mission.md', 'missions/seat-selection.mission.md', 'missions/add-baggage.mission.md', 'missions/payment.mission.md', 'missions/confirm-booking.mission.md'], result: '7 missions written', 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." },
    { role: 'tool', kind: 'config', icon: 'far fa-file-pen', name: 'scaffold', args: 'workflows/ · 7 funnel steps', cfiles: ['workflows/search-flights.workflow.ts', 'workflows/select-fare.workflow.ts', 'workflows/passenger-details.workflow.ts', 'workflows/seat-selection.workflow.ts', 'workflows/add-baggage.workflow.ts', 'workflows/payment.workflow.ts', 'workflows/confirm-booking.workflow.ts'], result: '7 workflows written', status: 'ok' },
    { role: 'agent', text: "Project scaffolded — **24 files**: 2 libraries, 3 skills, 2 Zod schemas, 7 missions and 7 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://emirates.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('#origin', ctx.inputs.origin);",
        "        await this.type('#destination', ctx.inputs.destination);",
        "        await this.click('[data-testid=depart-date-field]');",
        "        await this.click(`[data-date=\"${ctx.inputs.departDate}\"]`);",
        "        await this.click('button.search-flights');",
        "        return { matched: true };",
        "    }",
        "}",
    ],
    'enter-passengers': [
        "// enter-passengers.stage.ts",
        "",
        "import { Stage } from '@athree/runner';",
        "",
        "export default class EnterPassengers extends Stage {",
        "    async run(ctx) {",
        "        const p = ctx.inputs.passenger;",
        "        await this.type('#firstName', p.firstName);",
        "        await this.type('#lastName', p.lastName);",
        "        await this.click('#title');",
        "        await this.keyboard.type(p.title);",
        "        await this.keyboard.press('Enter');",
        "        await this.click('button.continue');",
        "        return { matched: true };",
        "    }",
        "}",
    ],
    'pick-seats': [
        "// pick-seats.stage.ts",
        "",
        "import { Stage } from '@athree/runner';",
        "",
        "export default class PickSeats extends Stage {",
        "    async run(ctx) {",
        "        await this.frame('#seatmap').waitFor('[data-seat]');",
        "        await this.frame('#seatmap').click(`[data-seat=\"${ctx.inputs.seat}\"]`);",
        "        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) {",
        "        const c = ctx.inputs.card;",
        "        await this.type('#card-number', c.number);",
        "        await this.type('#card-expiry', c.expiry);",
        "        await this.type('#card-cvc', c.cvc);",
        "        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 emirates.com', prompt: 'learn emirates.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-plane', label: 'Book DXB→LHR in Business', prompt: 'Book the Al-Rashid party DXB→LHR on 22 Aug in Business with extra bags and window seats.' },
            { icon: 'far fa-pen-to-square', label: 'Add baggage to a booking', prompt: 'Add extra baggage to booking EK-5530.' },
        ],
    },
    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: 'Book flights', desc: 'Set up an agent to book flights for me. It should search for flights between two cities on my dates, compare and select a fare, enter the passenger details, choose seats, add baggage, and then take payment to issue the ticket.', prompt: 'Set up an agent to book flights for me. It should search for flights between two cities on my dates, compare and select a fare, enter the passenger details, choose seats, add baggage, and then take payment to issue the ticket.' },
        ],
    },
};

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 };
