import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Inline file tooltip opens at its anchor on first hover", WEB, async ({t3, app, screen, browser}) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  await writeFile(fixture, original.replace("The command printed one JSON line.", "See [package.json](package.json) for the scripts."));
  let thread;
  try {
    const project = await t3.project(`../../../../../../../../tmp/factory-issue-41187-evidence-1/run-${Date.now()}/tooltip-demo`, {"package.json": '{"name":"tooltip-demo","scripts":{"dev":"vite"}}'});
    await runPromise(makeState(T3_HOME).cli(["project", "rename", project, "tooltip-demo"]));
    thread = await t3.thread({project, title:"File tooltip", messages:["go"], model:"command-output"});
  } finally { await writeFile(fixture, original); }
  await t3.open(thread!);
  const chip = screen.getByText("package.json", {exact:true});
  await browser.mouse.move(1100,700);
  await browser.evaluate(() => {
    const state = {samples: [] as {x:number;y:number;t:number}[], done:false};
    (window as any).__tooltipProof = state;
    let start = 0;
    function sample() {
      const el = document.querySelector('[data-slot="tooltip-positioner"]');
      if (el) { const r = el.getBoundingClientRect(); if (r.width && r.height) state.samples.push({x:r.x,y:r.y,t:performance.now()-start}); }
      if (performance.now()-start < 1800) requestAnimationFrame(sample); else state.done = true;
    }
    document.addEventListener("pointerover", function onHover(event) {
      if (!(event.target instanceof Element) || !event.target.closest("a,button")?.textContent?.includes("package.json")) return;
      document.removeEventListener("pointerover", onHover);
      start = performance.now();
      requestAnimationFrame(sample);
    });
  });
  await chip.hover();
  await browser.evaluate(() => new Promise<void>(resolve => {
    function check(){ if((window as any).__tooltipProof.done) resolve(); else requestAnimationFrame(check); } check();
  }));
  await app.screenshot("first-hover-settled");
  const samples = await browser.evaluate(() => (window as any).__tooltipProof.samples as {x:number;y:number;t:number}[]);
  console.log("TOOLTIP_FRAME_SAMPLES", JSON.stringify(samples));
  if (samples.length === 0) throw new Error("Tooltip did not appear during first hover");
  const last = samples.at(-1)!;
  const maxTravel = Math.max(...samples.map(s => Math.hypot(s.x-last.x,s.y-last.y)));
  await expect(maxTravel).toBeLessThan(5);
});
