import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Thread shortcuts navigate with the narrow sidebar closed", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Shortcut demo");
  for (const title of ["First thread", "Second thread", "Third thread"]) {
    await t3.thread({ project, title, messages: [`Conversation for ${title}`] });
  }
  await writeFile(join(T3_HOME, "userdata/keybindings.json"), JSON.stringify([
    { key: "ctrl+alt+2", command: "thread.jump.2" },
  ]));
  await t3.open();
  const paths: Record<string, string> = {};
  for (const title of ["First thread", "Second thread", "Third thread"]) {
    await screen.getByRole("button", `${title}, Done, Shortcut demo`).tap();
    paths[title] = new URL(await browser.url()).pathname;
  }
  await browser.setViewport({ width: 700, height: 800 });
  const checks = [
    { from: "Third thread", key: "Control+Alt+2", to: "Second thread", label: "numbered-closed" },
    { from: "Third thread", key: "Control+Shift+]", to: "Second thread", label: "next-closed" },
    { from: "Second thread", key: "Control+Shift+[", to: "Third thread", label: "previous-closed" },
  ];
  for (const check of checks) {
    await app.open(paths[check.from]!);
    await screen.getByText(`Conversation for ${check.from}`, { exact: true }).tap();
    await app.screenshot(`${check.label}-start`);
    await browser.keyboard.press(check.key);
    await expect.soft(browser).toHaveURL(paths[check.to]!);
    await app.screenshot(check.label);
  }
  await app.open(paths["Third thread"]!);
  await screen.getByText("Conversation for Third thread", { exact: true }).tap();
  await browser.keyboard.press("Control+b");
  await browser.keyboard.press("Control+Alt+2");
  await expect.soft(browser).toHaveURL(paths["Second thread"]!);
  await app.screenshot("numbered-sheet-open-workaround");
});
