import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Fullwidth sentence terminators preserve the RTL sentence majority", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("direction-demo");
  const samples = [
    { label: "fullwidth-question", text: "שלום! This is English？ مرحبا" },
    { label: "ascii-control", text: "שלום! This is English? مرحبا" },
    { label: "fullwidth-exclamation", text: "שלום! This is English！ مرحبا" },
    { label: "fullwidth-period", text: "שלום! This is English． مرحبا" },
  ];
  const directions: string[] = [];
  for (const sample of samples) {
    let thread;
    for (let attempt = 0; attempt < 5; attempt++) {
      try {
        thread = await t3.thread({ project, title: sample.label, messages: ["Start"], model: "multi-turn" });
        break;
      } catch (error) {
        if (!String(error).includes("Advertised models: default") || attempt === 4) throw error;
      }
    }
    if (!thread) throw new Error("Replay discovery did not complete");
    await t3.open(thread);
    await screen.getByTestId("composer-editor").fill(sample.text);
    await screen.getByRole("button", "Submit message", { exact: true }).tap();
    await screen.getByText(sample.text, { exact: true }).waitFor();
    await screen.getByText("second fixture turn complete", { exact: true }).waitFor();
    const direction = await browser.evaluate(({ text, label }) => {
      const textNode = [...document.querySelectorAll('[data-thread-find-text]')].find(node => node.textContent === text);
      const wrapper = textNode?.closest('div[dir]');
      if (!wrapper) throw new Error("User message direction wrapper missing");
      const dir = wrapper.getAttribute('dir')!;
      const annotation = document.createElement('div');
      annotation.textContent = `${label}: [dir=${dir}]`;
      annotation.style.cssText = 'color:#ef4444;font: bold 16px monospace;direction:ltr;text-align:left;padding:8px 0';
      wrapper.after(annotation);
      wrapper.scrollIntoView({block:'center'});
      return dir;
    }, sample);
    directions.push(direction);
    await app.screenshot(sample.label);
  }
  await expect(directions).toEqual(["rtl", "rtl", "rtl", "rtl"]);
});
