import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Closing the left split focuses the adjacent middle terminal", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Split terminal neighbour", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", /^Terminal(?: T)?$/).tap();
  await browser.locator('.t3-ghostty-input[data-workspace-focus-default]').waitFor();
  await browser.keyboard.press("Control+d");
  await browser.locator('[data-terminal-owner="right-panel"] .grid > div:nth-child(2) .t3-ghostty-input[data-workspace-focus-default]').waitFor();
  await browser.keyboard.press("Control+d");
  await browser.locator('[data-terminal-owner="right-panel"] .grid > div:nth-child(3) .t3-ghostty-input[data-workspace-focus-default]').waitFor();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  for (const [index, name] of ["LEFT", "MIDDLE", "RIGHT"].entries()) {
    const input = browser.locator(`[data-terminal-owner="right-panel"] .grid > div:nth-child(${index + 1}) .t3-ghostty-input`);
    await browser.locator(`[data-terminal-owner="right-panel"] .grid > div:nth-child(${index + 1}) canvas`).tap();
    await browser.keyboard.type(`export PS1="\$ "; clear; echo I-AM-${name}`);
    await browser.keyboard.press("Enter");
  }
  await browser.evaluate(() => {
    const inputs = document.querySelectorAll('[data-terminal-owner="right-panel"] .t3-ghostty-input');
    inputs[1]!.setAttribute("data-proof-middle", "true");
  });
  await screen.getByRole("button", "Terminal 1", { exact: true }).tap();
  await browser.keyboard.press("Control+w");
  await screen.getByRole("button", "Confirm", { exact: true }).tap();
  await browser.keyboard.type("echo TYPED-AFTER-CLOSING-LEFT");
  await browser.keyboard.press("Enter");
  await app.screenshot("after-closing-left-terminal");
  await expect(browser.locator('.t3-ghostty-input:focus')).toHaveAttribute("data-proof-middle", "true");
});
