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

test("Long conversation minimap keeps separate strips through navigation", { ...WEB, video: "off" }, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("minimap-proof");
  const thread = await t3.thread({ project, title: "220 message navigation", messages: Array.from({length: 220}, (_, i) => `Message ${String(i + 1).padStart(3, "0")}: Review checkpoint ${i + 1}`) });
  await t3.open(thread);
  await browser.locator("[data-minimap-strip]").first().waitFor({ timeout: 120_000 });
  await app.startRecording({ name: "minimap-loading-and-navigation" });
  const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
  const settled = async (label: string) => {
    await pause(1500);
    let previous = await app.screenshot(`${label}-settling`);
    for (let i = 0; i < 8; i++) {
      await pause(500);
      const current = await app.screenshot(`${label}-stable-${i}`);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error(`Screen did not settle: ${label}`);
  };
  await browser.mouse.move(1200, 60);
  await settled("first-page");
  for (let page = 0; page < 20; page++) {
    const hasEarlier = await browser.evaluate<boolean>(`Boolean(document.querySelector('button[aria-label="Load earlier turns"]'))`);
    if (!hasEarlier) break;
    await screen.getByRole("button", "Load earlier turns").tap();
    await pause(700);
  }
  await browser.mouse.move(1200, 60);
  await settled("all-220-loaded");
  const geometry = await browser.evaluate<{x:number;y:number;height:number}>(`(() => {
    const b = document.querySelector('[data-testid="timeline-minimap"] button[aria-label^="Jump to message"]');
    if (!b) throw new Error("Minimap missing");
    const r = b.getBoundingClientRect(); return { x:r.left + 4, y:r.top, height:r.height };
  })()`);
  for (const index of [109, 110]) {
    await browser.mouse.move(geometry.x, geometry.y + geometry.height * index / 219);
    await settled(`hover-message-${index + 1}`);
  }
  await browser.mouse.down();
  await browser.mouse.up();
  await browser.mouse.move(1200, 60);
  await settled("clicked-message-111-in-view");
  await browser.evaluate(`document.querySelector('[data-testid="timeline-minimap"] button[aria-label^="Jump to message"]').focus()`);
  await browser.keyboard.press("ArrowUp");
  await settled("keyboard-previous-preview");
  await browser.keyboard.press("Enter");
  await settled("keyboard-selected-previous");
  await browser.keyboard.press("ArrowDown");
  await settled("keyboard-next-preview");
  await browser.keyboard.press("Enter");
  await settled("keyboard-selected-next");
  await browser.keyboard.press("Home");
  await settled("keyboard-first-preview");
  await browser.keyboard.press("End");
  await settled("keyboard-last-preview");
  await browser.keyboard.press("Enter");
  await browser.mouse.move(1200, 60);
  await browser.keyboard.press("Tab");
  await settled("last-message-in-view");
  const spacing = await browser.evaluate<number>(`(() => {
    const marks = [...document.querySelectorAll('[data-minimap-strip]')].map(e => e.getBoundingClientRect().top).sort((a,b)=>a-b);
    return Math.min(...marks.slice(1).map((v,i)=>v-marks[i]));
  })()`);
  await app.stopRecording();
  expect(spacing).toBeGreaterThanOrEqual(4);
});
