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

test("Arabic chat folds retain detected direction and English stays LTR", WEB, async ({ t3, app, screen, browser }) => {
  const reply = "<details><summary>تفاصيل التثبيت</summary>\n\nشغّل الأمر ثم أعد التشغيل.\n\n</details>\n\n<details><summary>Install details</summary>\n\nRun the command, then restart.\n\n</details>";
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { 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" } } },
  ];
  await writeFile(join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson"), frames.map(x => JSON.stringify(x)).join("\n") + "\n");
  const project = await t3.project("Fold direction");
  const thread = await t3.thread({ project, title: "Arabic and English folds", messages: ["Show the installation details in Arabic and English."], model: "command-output" });
  await t3.open(thread);
  const arabic = screen.getByRole("button", "تفاصيل التثبيت");
  const english = screen.getByRole("button", "Install details");
  await arabic.waitFor({ state: "visible" });
  await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("closed-folds");
  const closed = await browser.evaluate(() => Array.from(document.querySelectorAll("[data-markdown-details-summary]")).map(el => ({ direction: getComputedStyle(el).direction, chevron: getComputedStyle(el.querySelector("svg")!).rotate })));
  await arabic.tap();
  await english.tap();
  await screen.getByText("شغّل الأمر ثم أعد التشغيل.", { exact: true }).waitFor({ state: "visible" });
  await screen.getByText("Run the command, then restart.", { exact: true }).waitFor({ state: "visible" });
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return true; });
  await app.screenshot("expanded-folds");
  const bodies = await browser.evaluate(() => Array.from(document.querySelectorAll("[data-markdown-details-content] p")).map(el => getComputedStyle(el).direction));
  await expect(closed.map(x => x.direction)).toEqual(["rtl", "ltr"]);
  await expect(closed[0].chevron).toEqual("180deg");
  await expect(bodies).toEqual(["rtl", "ltr"]);
});
