/// <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("An unrelated preview-annotation upload stays in the gallery", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  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:"Sidebar review", messages:["Start"]});
  await browser.addInitScript(() => {
    navigator.clipboard.write = async (items) => {
      const data: Record<string,string> = {};
      for (const type of items[0].types) data[type] = await (await items[0].getType(type)).text();
      Object.assign(window, {copiedMessage:data});
    };
  });
  await t3.open(thread);
  const editor = screen.getByRole("textbox");
  await editor.tap();
  await browser.evaluate(() => {
    const record = {version:1,kind:"preview-annotation",contextId:"preview-annotation_sidebar",label:"Sidebar annotation",annotationId:"sidebar",pageUrl:"https://example.com",pageTitle:"Sidebar",comment:"Leave more space by the sidebar",targetSummary:"Sidebar",styleChanges:[]};
    const fragment = JSON.stringify({version:1,source:{environmentId:location.pathname.split("/")[1]},records:[record]});
    const data = new DataTransfer();
    data.setData("text/plain", "Review this sidebar [Sidebar annotation](t3-context://v1/preview-annotation/preview-annotation_sidebar)");
    data.setData("web application/x-t3-context-fragment+json",fragment);
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:data,bubbles:true,cancelable:true}));
    return null;
  });
  await editor.press("Enter");
  await screen.getByText("second fixture turn complete").waitFor();
  const first = browser.locator('[data-message-role="user"]').filter({hasText:"Review this sidebar"});
  await first.getByRole("button","Leave more space by the sidebar",{exact:false}).tap();
  await screen.getByText("Screenshot unavailable",{exact:true}).waitFor();
  await browser.keyboard.press("Escape");
  await first.hover();
  await first.getByRole("button","Copy message").tap();
  await editor.tap();
  await browser.evaluate(() => {
    const data = new DataTransfer();
    for (const [type,value] of Object.entries((window as unknown as {copiedMessage:Record<string,string>}).copiedMessage)) data.setData(type,value);
    document.activeElement!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:data,bubbles:true,cancelable:true}));
    const canvas = document.createElement("canvas"); canvas.width=600; canvas.height=200;
    const ctx=canvas.getContext("2d")!; ctx.fillStyle="#ff9500"; ctx.fillRect(0,0,600,200); ctx.fillStyle="#111"; ctx.font="bold 24px sans-serif"; ctx.fillText("UNRELATED MOCKUP",30,80);ctx.fillText("uploaded by user",30,125);
    const bytes=Uint8Array.from(atob(canvas.toDataURL("image/png").split(",")[1]),c=>c.charCodeAt(0));
    const files=new DataTransfer();files.items.add(new File([bytes],"preview-annotation-mockup.png",{type:"image/png"}));
    const picker=document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
    picker.files=files.files;picker.dispatchEvent(new Event("change",{bubbles:true}));return null;
  });
  await browser.locator('button[aria-label="Preview preview-annotation-mockup.png"]:enabled').waitFor();
  await screen.getByRole("button","Submit message",{exact:true}).tap();
  await browser.locator('[data-message-role="user"]').filter({hasText:"Review this sidebar"}).nth(1).waitFor();
  const sent = browser.locator('[data-message-role="user"]').filter({hasText:"Review this sidebar"}).nth(1);
  await screen.getByText("first fixture turn complete",{exact:true}).nth(1).waitFor();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return null; });
  await app.screenshot("message-gallery");
  await sent.getByRole("button","Leave more space by the sidebar",{exact:false}).tap();
  await browser.locator("[data-slot=popover-popup]").waitFor();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return null; });
  await app.screenshot("annotation-details");
  await expect(screen.getByText("Screenshot unavailable",{exact:true})).toBeVisible();
  await expect(sent.getByRole("button","Preview preview-annotation-mockup.png",{exact:true})).toBeVisible();
});
