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

test("An inline thread project icon stays small while a thread opens", WEB, async ({ t3, app, browser, screen }) => {
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="140" height="140" viewBox="0 0 140 140"><rect width="140" height="140" rx="24" fill="#2563eb"/><path d="M35 40h70v15H78v50H62V55H35z" fill="white"/><!--${"project icon ".repeat(3500)}--></svg>`;
  const project = await t3.project("Icon demo", { "favicon.svg": svg });
  const linked = await t3.thread({ project, title: "Linked target", messages: ["Ready"] });
  const a = await t3.thread({ project, title: "Thread A", messages: ["Start"] });
  const b = await t3.thread({ project, title: "Thread B", messages: ["Waiting"] });
  await browser.setViewport({ width: 1280, height: 900 });
  await t3.open(a);
  await screen.getByRole("textbox").tap();
  await browser.evaluate((text) => {
    const clipboardData = new DataTransfer();
    clipboardData.setData("text/plain", text);
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    return null;
  }, `Orchestrator: I sent "#01 ready for review" to [Linked target](t3-thread://v1/${linked.threadId}) for review.`);
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await browser.locator('.chat-markdown').getByText('Linked target', { exact: true }).waitFor();
  await screen.getByRole("button", /^Thread B,/).press("Enter");
  await screen.getByText("Waiting", { exact: true }).waitFor();
  await browser.evaluate(() => {
    const state = { maxHeight: 0, samples: 0 };
    (window as any).__iconProof = state;
    const sample = () => {
      for (const img of document.querySelectorAll('.chat-markdown img')) {
        state.maxHeight = Math.max(state.maxHeight, img.getBoundingClientRect().height);
        state.samples++;
      }
      requestAnimationFrame(sample);
    };
    requestAnimationFrame(sample);
    return null;
  });
  await screen.getByRole("button", /^Thread A,/).press("Enter");
  await browser.locator('.chat-markdown').getByText('Linked target', { exact: true }).waitFor();
  await app.screenshot("thread-opening");
  const result = await browser.evaluate(async () => {
    await new Promise<void>(resolve => {
      let frames = 0;
      const next = () => ++frames >= 60 ? resolve() : requestAnimationFrame(next);
      requestAnimationFrame(next);
    });
    return (window as any).__iconProof;
  });
  await app.screenshot("thread-loaded");
  expect(result.maxHeight).toBeLessThanOrEqual(18);
});
