import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Side chat find follows pane focus and lifecycle", { ...WEB, video: "off" }, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Search demo");
  const thread = await t3.thread({ project, title: "Main conversation", messages: ["Main conversation"] });
  await t3.open(thread);
  await screen.getByRole("textbox").pressSequentially("/side quasarneedle side conversation");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "Bring back", { exact: true }).waitFor({ state: "visible" });
  await browser.locator('[data-side-chat-pane] [data-timeline-row-kind="message"]').last().waitFor({ state: "visible" });
  await browser.mouse.move(450, 400);
  // The recording ends before the t3 fixture removes its synthetic project.
  await app.startRecording({ name: "side-chat-find" });
  const results: Record<string, boolean> = {};
  const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
  const capture = async (label: string) => {
    await browser.mouse.move(450, 400);
    for (let attempt = 0; attempt < 5; attempt++) {
      const a = await app.screenshot(`${label}-stability`);
      await pause(500);
      const b = await app.screenshot(label);
      if ((await readFile(a)).equals(await readFile(b))) return;
    }
    throw new Error(`Unstable capture: ${label}`);
  };
  const sideComposer = () => browser.locator('[data-side-chat-pane] [role="textbox"]');
  const find = () => browser.locator('[data-side-chat-pane] input[placeholder="Find in thread"]');
  const hasFind = () => browser.evaluate(() => !!document.querySelector('[data-side-chat-pane] input[placeholder="Find in thread"]'));
  const focusConversation = async () => {
    await browser.evaluate(() => (document.querySelector('[data-side-chat-pane] .messages-timeline-scroll') as HTMLElement).focus());
  };
  const openFind = async () => {
    await sideComposer().tap();
    await browser.keyboard.press("Control+f");
    await pause(250);
  };
  const queryIfOpen = async () => {
    if (await hasFind()) { await find().fill("quasarneedle"); await pause(750); }
  };
  const composerFocused = () => browser.evaluate(() => !!document.activeElement?.matches('[data-side-chat-pane] [role="textbox"]'));

  // Supplemental lifecycle setup uses the app's exported find action on BOTH commits.
  // Base cannot reach find through Ctrl+F; this makes Escape and retention comparable.
  const seedFind = async () => {
    await browser.evaluate(`async () => {
      const { openThreadFindOnQuery } = await import('/src/components/chat/threadFindStore.ts');
      const environmentId = location.pathname.split('/')[1];
      const threadId = document.querySelector('[data-side-chat-pane]').getAttribute('data-side-chat-pane');
      openThreadFindOnQuery(environmentId + ':' + threadId, { query: 'quasarneedle' });
    }`);
    await find().waitFor({ state: "visible" });
    await pause(750);
  };
  const dismissWithButton = async () => {
    if (await hasFind()) await browser.locator('[data-side-chat-pane] button[aria-label="Close find"]').tap();
  };
  const reopen = async () => {
    if (!await browser.evaluate(() => !!document.querySelector('[data-thread-side-chats-panel]'))) {
      await screen.getByRole("button", "Toggle thread details panel", { exact: true }).tap();
    }
    await browser.locator('[data-thread-side-chats-panel] button').first().tap();
    await sideComposer().waitFor({ state: "visible" });
    await sideComposer().tap();
    await browser.mouse.move(450,400);
  };

  await openFind();
  results.composerShortcut = await hasFind();
  await queryIfOpen();
  await capture("01-composer-ctrl-f");
  await seedFind();
  await capture("01b-input-escape-start");
  await browser.keyboard.press("Escape");
  results.inputEscape = !(await hasFind()) && await composerFocused();
  await browser.keyboard.type("composer focus returned");
  await capture("02-input-escape-composer-focus");
  await dismissWithButton();
  await sideComposer().fill("");

  await focusConversation();
  await browser.keyboard.press("Control+f");
  await pause(250);
  results.conversationShortcut = await hasFind();
  await queryIfOpen();
  await capture("03-conversation-ctrl-f");
  await seedFind();
  await focusConversation();
  await browser.keyboard.press("Escape");
  results.conversationEscape = !(await hasFind()) && await composerFocused();
  await browser.keyboard.type("conversation escape returned focus");
  await capture("04-conversation-escape-composer-focus");
  await dismissWithButton();
  await sideComposer().fill("");

  await browser.evaluate(() => (Array.from(document.querySelectorAll('[data-side-chat-pane] button')).find(b => b.textContent === "Bring back") as HTMLElement).focus());
  await browser.keyboard.press("Tab");
  await browser.keyboard.press("Shift+Tab");
  await browser.keyboard.press("Escape");
  await capture("05-bring-back-keyboard-focus");
  await browser.keyboard.press("Control+f");
  await pause(250);
  results.bringBackShortcut = await hasFind();
  await queryIfOpen();
  await capture("06-bring-back-ctrl-f");

  await seedFind();
  await capture("06b-before-settings");
  await screen.getByRole("button", "Settings", { exact: true }).tap();
  await browser.mouse.move(450,400);
  await screen.getByRole("button", "Close", { exact: true }).tap();
  await sideComposer().tap();
  await pause(500);
  results.settingsRetention = await hasFind() && await browser.evaluate(() => (document.querySelector('[data-side-chat-pane] input[placeholder="Find in thread"]') as HTMLInputElement)?.value === "quasarneedle");
  await capture("07-settings-return-retains-find");

  await seedFind();
  await browser.setViewport({ width: 900, height: 800 });
  await pause(500);
  results.narrowRetention = await hasFind();
  await capture("08-narrow-retains-find");
  await browser.setViewport({ width: 1280, height: 800 });
  await pause(500);
  await sideComposer().tap();
  results.wideRetention = await hasFind();
  await capture("09-wide-retains-find");

  await seedFind();
  await screen.getByRole("button", "Close side chat", { exact: true }).tap();
  await pause(500);
  await capture("10-closed-pane");
  await reopen();
  results.closeClearsFind = !(await hasFind());
  await capture("11-reopened-pane-clears-find");
  await dismissWithButton();
  await browser.setViewport({ width: 900, height: 800 });
  await pause(500);
  await seedFind();
  await capture("12-narrow-before-escape");
  await browser.keyboard.press("Escape");
  await pause(500);
  results.firstEscapeKeepsSheet = !(await hasFind()) && await browser.evaluate(() => !!document.querySelector('[data-side-chat-pane]'));
  if (await browser.evaluate(() => !!document.querySelector('[data-side-chat-pane]'))) {
    await browser.keyboard.type("first Escape kept composer");
  } else {
    await browser.locator('[role="textbox"]').first().tap();
  }
  await capture("13-first-escape-closes-find");
  await browser.keyboard.press("Escape");
  await pause(500);
  results.secondEscapeClosesSheet = !await browser.evaluate(() => !!document.querySelector('[data-side-chat-pane]'));
  // Move focus to the main composer before capturing; sheet finalFocus may choose a launcher.
  await browser.locator('[role="textbox"]').first().tap();
  await capture("14-second-escape-closes-sheet");
  await pause(2500);
  results.mainConversationRetained = await browser.evaluate(() => document.body.textContent?.includes('first fixture turn complete') === true && !document.body.textContent?.includes('Send a message to start the conversation.'));
  await capture("15-main-conversation-remains");
  await app.stopRecording();
  console.log("OBSERVED", JSON.stringify(results));
  expect(Object.values(results).every(Boolean)).toBe(true);
});
