import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { APP_DIR } from "../e2e.config.ts";
import { test, IOS } from "./t3-mobile.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: <a href=https://example.com/hello\u00a0world>NBSP link</a>
`;

test("Only actual open attributes expand chat folds on iOS", IOS, async ({t3, app, screen}) => {
 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();
  await screen.getByText("HTML attribute controls", {exact:false}).first().tap();
  await screen.getByText("VisibleD", {exact:true}).waitFor();
  await app.screenshot("folds-on-load");
  await expect(screen.getByText("HiddenB", {exact:true})).not.toBeVisible();
  await expect(screen.getByText("HiddenA", {exact:true})).not.toBeVisible();
  await expect(screen.getByText("HiddenC", {exact:true})).not.toBeVisible();
 } finally { await writeFile(fixture, original); }
});
