/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const short = "PR נפתח עם תיקון חשוב.";
const long = "PR נפתח עם תיקון חשוב שמשפר את הביצועים של רשימת השרשורים בסרגל הצד.";

test("English-leading Hebrew prompt previews preserve reading order", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("demo");
  await t3.open();
  const modelPicker = browser.locator("[data-chat-provider-model-picker-label]").first();
  await modelPicker.tap();
  await screen.getByRole("option", "Multi turn", {exact:false}).waitFor();
  await browser.keyboard.press("Escape");
  const thread = await t3.thread({project, title: "Preview reading order", messages: ["Explain the plan"]});
  await t3.open(thread);
  await screen.getByRole("button", "New thread in demo", {exact:true}).first().tap();
  await screen.getByRole("textbox").fill(long);
  await t3.open(thread);
  await browser.locator('[data-testid="sidebar-draft-row"]').waitFor();
  const sidebar = await browser.evaluate((text) => {
    const el = [...document.querySelectorAll<HTMLElement>('[data-testid="sidebar-draft-row"] div')].find(e => e.textContent === text && e.classList.contains("truncate"));
    return el ? getComputedStyle(el).direction : "missing";
  }, long);
  await app.screenshot("sidebar-draft");

  const composer = screen.getByRole("textbox");
  await composer.fill(short);
  await composer.press("ControlOrMeta+s");
  await composer.fill(long);
  await composer.press("ControlOrMeta+s");
  await screen.getByRole("button", /Stashed prompts: 2/).tap();
  await browser.locator('[data-stash-restore]').first().waitFor();
  const stash = await browser.evaluate(() => [...document.querySelectorAll<HTMLElement>('[data-stash-restore]')].map(el => ({direction:getComputedStyle(el).direction, align:getComputedStyle(el).textAlign})));
  await app.screenshot("stash-prompts");
  await screen.getByRole("button", "Close stash").tap();
  await modelPicker.tap();
  await browser.keyboard.type("Long stream");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Escape");
  await composer.fill("Keep going");
  await composer.press("Enter");
  await screen.getByRole("button", "Stop generation").waitFor();
  await composer.fill(short);
  await composer.press("ControlOrMeta+Enter");
  await screen.getByRole("listitem", "Queued message 1 of 1, not sent").waitFor();
  const queued = await browser.evaluate((text) => {
    const el = [...document.querySelectorAll("p")].find(e => e.textContent === text);
    return el ? getComputedStyle(el).direction : "missing";
  }, short);
  await app.screenshot("queued-prompt");
  expect({sidebar, stash, queued}).toEqual({sidebar:"rtl", stash:[{direction:"rtl",align:"start"},{direction:"rtl",align:"start"}], queued:"rtl"});
});
