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

test("Side chat find shortcuts, Escape, retention and pane cleanup", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Side chat proof");
  const thread = await t3.thread({ project, title: "Main conversation", messages: ["Main conversation"], model: "multi-turn" });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill("/side quartzfinch side conversation");
  await browser.keyboard.press("Enter");
  const pane = browser.locator("[data-side-chat-pane]");
  await pane.waitFor();
  await pane.getByText("quartzfinch side conversation", { exact: false }).first().waitFor();
  await browser.evaluate(async () => {
    const deadline = Date.now() + 30000;
    while (document.querySelector('[data-side-chat-pane] [aria-label="Stop generation"]') && Date.now() < deadline) await new Promise(r => setTimeout(r, 100));
    document.documentElement.classList.add("dark");
    return true;
  });
  const isMac = await browser.evaluate(() => navigator.platform.includes('Mac'));
  const findShortcut = isMac ? 'Meta+f' : 'Control+f';
  const selectAll = isMac ? 'Meta+a' : 'Control+a';
  const observations: Record<string, boolean> = {};
  const state = () => browser.evaluate(() => {
    const pane = document.querySelector('[data-side-chat-pane]');
    const input = pane?.querySelector<HTMLInputElement>('input[type="search"]');
    return { pane: !!pane, find: !!input, query: input?.value ?? "", composer: !!document.activeElement?.closest('[data-side-chat-pane] [data-testid="composer-editor"]'), main: [...document.querySelectorAll('.messages-timeline-scroll')].some(e => !e.closest('[data-side-chat-pane]') && e.textContent?.includes('first fixture turn complete')) };
  });
  const capture = async (label: string) => {
    await browser.mouse.move(650, 795);
    // Wait for transitions and tooltips to settle, then compare the actual screenshots.
    await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 800)); return true; });
    await app.screenshot(label);
  };
  const closeFind = async () => {
    if ((await state()).find) await pane.getByRole("button", "Close find").tap();
  };
  const focus = async (target: string) => {
    if (target === 'composer') { await pane.getByRole('textbox').tap(); return; }
    await browser.evaluate((target) => {
      const pane = document.querySelector('[data-side-chat-pane]')!;
      const el = target === 'composer' ? pane.querySelector<HTMLElement>('[data-testid="composer-editor"]') : target === 'conversation' ? pane.querySelector<HTMLElement>('.messages-timeline-scroll') : [...pane.querySelectorAll('button')].find(e => /Add to chat|Bring back/.test(e.textContent ?? ''));
      if (!el) throw new Error('Missing focus target ' + target);
      if (target === 'conversation') el.tabIndex = 0;
      el.focus();
      return true;
    }, target);
    // A real keyboard event exposes :focus-visible on the header button.
    if (target === 'button') { await browser.keyboard.press('Tab'); await browser.keyboard.press('Shift+Tab'); await browser.keyboard.press('Escape'); }
  };
  for (const target of ['composer', 'conversation', 'button']) {
    await closeFind();
    await focus(target);
    await capture(`${target}-focused-before-find-shortcut`);
    await browser.keyboard.press(findShortcut);
    observations[`find-shortcut-${target}`] = (await state()).find;
    if ((await state()).find) await pane.getByRole('searchbox', 'Find in thread').fill('quartzfinch');
    await capture(`${target}-find-shortcut-result`);
  }
  // Establish the same real find state on both commits for the downstream comparisons.
  // Base cannot reach it with Ctrl+F. This is the app's action, not a replacement find UI.
  const establishFind = async () => {
    await browser.evaluate(async () => {
      const pane = document.querySelector<HTMLElement>('[data-side-chat-pane]')!;
      const store = await import('/src/components/chat/threadFindStore.ts');
      const env = location.pathname.split('/')[1];
      store.openThreadFind(`${env}:${pane.dataset.sideChatPane}`);
      return true;
    });
    await pane.getByRole('searchbox', 'Find in thread').fill('quartzfinch');
  };
  await establishFind();
  await capture('find-input-before-escape');
  await browser.keyboard.press('Escape');
  observations['escape-input'] = !(await state()).find && (await state()).composer;
  await browser.keyboard.type('Focus returned to composer');
  await capture('escape-input-composer-focus');
  await browser.keyboard.press(selectAll);
  await browser.keyboard.press('Backspace');
  await establishFind();
  await focus('conversation');
  await browser.keyboard.press('Escape');
  observations['escape-conversation'] = !(await state()).find && (await state()).composer;
  await browser.keyboard.type('Focus returned to composer');
  await capture('escape-conversation-composer-focus');
  await browser.keyboard.press(selectAll);
  await browser.keyboard.press('Backspace');
  await establishFind();
  // Open Settings through its actual gear, then return through the modal close control.
  await screen.getByRole('button', 'Settings', { exact: true }).tap();
  await capture('settings-with-find-suspended');
  await browser.keyboard.press('Escape');
  await pane.waitFor();
  await focus('composer');
  observations['settings-retains'] = (await state()).find && (await state()).query === 'quartzfinch';
  await capture('settings-return-retains-find');
  // Re-establish on both sides so resize and close are independent comparisons.
  await establishFind();
  await browser.setViewport({ width: 900, height: 800 });
  await pane.waitFor();
  observations['narrow-retains'] = (await state()).find && (await state()).query === 'quartzfinch';
  await capture('narrow-retains-find');
  await browser.setViewport({ width: 1280, height: 800 });
  await pane.waitFor();
  observations['wide-retains'] = (await state()).find && (await state()).query === 'quartzfinch';
  await focus('composer');
  await capture('wide-retains-find');
  await establishFind();
  const sideId = await browser.evaluate(() => document.querySelector<HTMLElement>('[data-side-chat-pane]')!.dataset.sideChatPane!);
  await pane.getByRole('button', 'Close side chat').tap();
  await capture('side-chat-tab-closed');
  // A closed saved side chat remains in the panel's tab list/history; reopen through the panel.
  await browser.evaluate(async (sideId) => {
    const store = await import('/src/rightPanelStore.ts');
    const [, environmentId, threadId] = location.pathname.split('/');
    store.useRightPanelStore.getState().openThread({ environmentId, threadId }, sideId);
    return true;
  }, sideId);
  await pane.waitFor();
  observations['close-clears'] = !(await state()).find;
  await capture('reopened-pane-find-cleared');
  await establishFind();
  await browser.setViewport({ width: 900, height: 800 });
  await pane.waitFor();
  await closeFind();
  await focus('composer');
  await browser.keyboard.press(findShortcut);
  await establishFind();
  await capture('narrow-before-escape');
  await browser.keyboard.press('Escape');
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 100)); return true; });
  observations['first-escape-keeps-sheet'] = (await state()).pane && !(await state()).find && (await state()).composer;
  // Blur only after observing focus, so sheet-restored gear tooltips cannot cover the evidence.
  await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); return true; });
  await capture('first-escape-closes-find');
  await browser.keyboard.press('Escape');
  observations['second-escape-closes-sheet'] = !(await state()).pane;
  // Move focus off the gear that a sheet can restore, without changing the conversation.
  await browser.evaluate(() => { const el = document.querySelector<HTMLElement>('[data-testid="composer-editor"]'); el?.focus(); return true; });
  await capture('second-escape-closes-sheet');
  observations['main-conversation-preserved'] = (await state()).main;
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 2000)); return true; });
  await capture('final-main-conversation-preserved');
  expect(observations).toEqual(Object.fromEntries(Object.keys(observations).map(k => [k, true])));
});
