import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const reply = `Attribute parsing: B contains U+00A0 (NBSP) between hello and open.

<details open-on-load>
<summary>A: open-on-load</summary>
HiddenA
</details>

<details data-label=hello\u00a0open>
<summary>B: data-label=hello[NBSP]open</summary>
HiddenB
</details>

<details data-url=https://example.com/?mode=open>
<summary>C: unquoted URL</summary>
HiddenC
</details>

<details open>
<summary>D: actual open</summary>
VisibleD
</details>

<details>
<summary>E: no attribute</summary>
HiddenE
</details>

<details OPEN="false">
<summary>F: OPEN="false" (boolean)</summary>
VisibleF
</details>

Other tag: <input type=checkbox data-label=hello\u00a0checked> NBSP inside data-label must not check this box.
`;

test("Only actual open attributes expand chat folds", WEB, async ({t3, app, screen, browser}) => {
 const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
 const original = await readFile(fixture, "utf8");
 const transcript = [
 {type:"expect_outbound", frame:{kind:"request",method:"session/prompt",params:{}}},
 {type:"emit_inbound", frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:reply}}}}},
 {type:"emit_inbound", frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}}
 ].map(entry => JSON.stringify(entry)).join("\n");
 await writeFile(fixture, transcript);
 try {
  const project = await t3.project("Fold attributes");
  const thread = await t3.thread({project, title:"HTML attribute controls", model:"showcase", messages:["Render the attribute samples."]});
  await t3.open(thread);
  await browser.reload();
  await screen.getByText("VisibleD", {exact:true}).waitFor();
  await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("folds-on-load");
  await expect(screen.getByText("HiddenB", {exact:true})).not.toBeVisible();
  await expect(screen.getByRole("checkbox")).not.toBeChecked();
 } finally { await writeFile(fixture, original); }
});
