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

test("Mobile sidebar hides underlying thread and pull request controls", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Demo", {
    "src/navigation.ts": "export const navigation = 'ready';\n",
    ".git/config": '[remote "origin"]\n url = https://github.com/scenario/navigation.git\n fetch = +refs/heads/*:refs/remotes/origin/*\n',
  });
  await t3.thread({ project, title: "Navigation", messages: ["Inspect navigation"] });
  await t3.open();
  await screen.getByRole("button", "Navigation, Done, Demo").tap();
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor({ state: "visible" });
  let viewport = { width: 1280, height: 800 };
  const resize = async (width: number, height: number) => {
    viewport = { width, height };
    await browser.setViewport(viewport);
  };
  const capture = async (label: string) => {
    await browser.mouse.move(2, viewport.height - 2);
    await browser.evaluate(() => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); return null; });
    await delay(300);
    await screen.getByRole("tooltip").waitFor({ state: "hidden" });
    let previous = await app.screenshot(`${label}-probe`);
    for (let attempt = 0; attempt < 8; attempt++) {
      await delay(500);
      const current = await app.screenshot(`${label}-settling-${attempt}`);
      if ((await readFile(previous)).equals(await readFile(current))) { await app.screenshot(`${label}-stable`); return; }
      previous = current;
    }
    throw new Error(`The frame did not settle: ${label}`);
  };
  const controls = () => browser.locator("[data-workspace-titlebar-controls]");
  const checkControls = async (hidden: boolean) => {
    for (const control of await controls().all()) {
      if (hidden) await expect.soft(control).toBeHidden({ timeout: 500 });
      else await expect.soft(control).toBeVisible({ timeout: 1000 });
    }
  };
  const sidebarCycle = async (label: string) => {
    await capture(`${label}-closed`);
    await screen.getByRole("button", "Toggle main sidebar", { exact: true }).tap();
    await browser.locator('[data-mobile="true"]').waitFor({ state: "visible" });
    await capture(`${label}-sidebar-open`);
    await checkControls(true);
    await browser.keyboard.press("Escape");
    await browser.locator('[data-mobile="true"]').waitFor({ state: "detached" });
    await capture(`${label}-restored`);
    await checkControls(false);
  };

  await resize(375, 667);
  await sidebarCycle("thread-375");
  await resize(430, 932);
  await sidebarCycle("thread-430");

  await resize(1280, 800);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).waitFor({ state: "visible" });
  await screen.getByRole("button", "Files F", { exact: true }).tap();
  await screen.getByRole("treeitem", "src", { exact: true }).tap();
  await screen.getByRole("treeitem", "navigation.ts", { exact: true }).waitFor({ state: "visible" });
  await capture("thread-desktop-inline-panel");
  await checkControls(false);
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await resize(430, 932);
  await sidebarCycle("thread-430-maximized-panel");
  await resize(1280, 800);
  await screen.getByRole("button", "Restore panel size", { exact: true }).tap();
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();

  await app.open("/pull-requests");
  await screen.getByText("Improve mobile navigation", { exact: true }).first().waitFor({ state: "visible", timeout: 60000 });
  await screen.getByText("Improve mobile navigation", { exact: true }).first().tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).waitFor({ state: "visible" });
  await screen.getByText("Synthetic pull request for sidebar verification.", { exact: false }).waitFor({ state: "visible", timeout: 60000 });
  await capture("pull-requests-desktop-open-panel");
  await checkControls(false);
  await resize(375, 667);
  await sidebarCycle("pull-requests-375-open-panel");
  await resize(430, 932);
  await sidebarCycle("pull-requests-430-open-panel");
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await sidebarCycle("pull-requests-430-maximized-panel");
  await resize(1280, 800);
  await capture("pull-requests-desktop-maximized-panel");
  await checkControls(false);
  await screen.getByRole("button", "Restore panel size", { exact: true }).tap();
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await resize(430, 932);
  await sidebarCycle("pull-requests-430-closed-panel");
});
