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

test("Remapped sidebar shortcut permits bold at a collapsed composer cursor", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    await browser.evaluate(() => {
      const style = document.createElement("style");
      style.textContent = "* { caret-color: transparent !important; }";
      document.head.append(style);
    });
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt = 0; attempt < 8; attempt++) {
      await delay(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  const project = await t3.project("Formatting demo");
  await t3.thread({ project, title: "Composer shortcuts", messages: ["Start"] });
  await t3.open();
  await screen.getByTestId("sidebar-row-card").first().tap();
  await app.open("/settings/chat");
  const richText = screen.getByRole("switch", "Rich text composer");
  await richText.waitFor();
  if (await browser.evaluate(() => document.querySelector('[aria-label="Rich text composer"]')?.getAttribute("aria-checked") !== "true")) await richText.tap();
  await app.open("/settings/keybindings");
  await screen.getByRole("searchbox", "Search keybindings").fill("sidebar.toggle");
  await browser.locator('button[aria-label^="Edit shortcut for"]').tap();
  await browser.keyboard.press("Alt+b");
  await screen.getByRole("button", "Save", { exact: true }).tap();
  await screen.getByRole("button", "Dismiss notification").tap();
  await capture("sidebar-remapped-to-alt-b");
  await screen.getByRole("button", "Close", { exact: true }).tap();
  await screen.getByTestId("sidebar-row-card").first().tap();
  const composer = browser.locator('[contenteditable="true"][data-composer-rich-text="true"]');
  await composer.tap();
  await browser.keyboard.type("x");
  await browser.keyboard.press("Control+b");
  await browser.keyboard.type("y");
  await browser.keyboard.press("Control+b");
  await browser.keyboard.type("z");
  await capture("remapped-collapsed-xyz");
  const remapped = await browser.evaluate(() => ({
    text: document.querySelector('[contenteditable="true"][data-composer-rich-text="true"]')?.textContent,
    bold: Array.from(document.querySelectorAll('[contenteditable="true"] strong')).map(e => e.textContent),
    sidebar: document.querySelector('[data-slot="sidebar"][data-state]')?.getAttribute("data-state"),
  }));
  await browser.keyboard.press("Control+a");
  await browser.keyboard.press("Control+b");
  await capture("remapped-selected-bold");
  await app.open("/settings/keybindings");
  await screen.getByRole("searchbox", "Search keybindings").fill("sidebar.toggle");
  await browser.locator('button[aria-label^="Edit shortcut for"]').tap();
  await browser.keyboard.press("Control+b");
  await screen.getByRole("button", "Save", { exact: true }).tap();
  await screen.getByRole("button", "Dismiss notification").tap();
  await capture("sidebar-restored-to-control-b");
  await screen.getByRole("button", "Close", { exact: true }).tap();
  await screen.getByTestId("sidebar-row-card").first().tap();
  await composer.tap();
  await browser.keyboard.press("Control+a");
  await browser.keyboard.press("Backspace");
  await browser.keyboard.type("x");
  await browser.keyboard.press("Control+b");
  await browser.keyboard.type("y");
  await capture("default-sidebar-collapsed");
  await browser.keyboard.press("Control+b");
  await browser.keyboard.type("z");
  await capture("default-collapsed-plain");
  await browser.keyboard.press("Control+a");
  await browser.keyboard.press("Control+b");
  await capture("default-selected-bold");
  expect(remapped.text).toBe("xyz");
  expect(remapped.bold).toEqual(["y"]);
});
