/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Switching large files does not inherit Copied", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("copy-demo", {
    "first.txt": "First file content\n".repeat(70000),
    "second.txt": "Second file content\n".repeat(70000),
  });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers
          : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(provider => provider.instanceId === "devReplay" &&
          provider.models.some(model => model.slug === "multi-turn"));
      }),
      Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Large file copy", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F", { exact: true }).tap();
  const openFile = async (name: string) => {
    await expect.poll(() => browser.evaluate((name) => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${name}"]`);
        if (row) { row.click(); return true; }
      }
      return false;
    }, name)).toBe(true);
    await screen.getByRole("button", "Copy contents", { exact: true }).waitFor();
  };
  await openFile("first.txt");
  await openFile("second.txt");
  const firstTab = await browser.evaluate(() => {
    const tab = Array.from(document.querySelectorAll("[data-right-panel-tab-list] [data-active-tab]")).find(el => el.textContent?.includes("first.txt"));
    if (!tab) throw new Error("Missing first.txt tab");
    const box = tab.getBoundingClientRect();
    return { x: box.left + box.width / 2, y: box.top + box.height / 2 };
  });
  await screen.getByRole("button", "Copy contents", { exact: true }).tap();
  await screen.getByRole("button", "Copied", { exact: true }).waitFor();
  await browser.mouse.move(firstTab.x, firstTab.y);
  await browser.mouse.down();
  await browser.mouse.up();
  const state = await browser.evaluate(async () => {
    await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
    return {
      active: document.querySelector('[data-right-panel-tab-list] [data-active-tab="true"]')?.textContent,
      copied: !!document.querySelector('button[aria-label="Copied"]'),
      copy: !!document.querySelector('button[aria-label="Copy contents"]'),
    };
  });
  await app.screenshot("first-file-after-copying-second");
  expect(state).toEqual({ active: "first.txt", copied: false, copy: true });
});
