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

test("Invalid When drafts survive pointer, header and keyboard visual edits, then recover", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("keybinding-demo");
  await t3.open("/settings/keybindings");
  await screen.getByLabel("Search keybindings").fill("Terminal: Close");
  await screen.getByRole("button", "Edit when clause for Terminal: Close", {exact:true}).tap();
  const expression = screen.getByRole("textbox", "When expression", {exact:true});
  const invalid = "terminalFocus &&";
  const read = () => browser.evaluate(() => (document.querySelector('[aria-label="When expression"]') as HTMLInputElement).value);
  const pointClick = async (selector: string) => {
    const p = await browser.evaluate((s) => { const r = document.querySelector(s)!.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; }, selector);
    await browser.mouse.move(p.x,p.y); await browser.mouse.down(); await browser.mouse.up();
  };
  await expression.fill("terminalFocus");
  await expression.fill(invalid);
  await app.screenshot("invalid-draft-locked");
  const disabled = await browser.evaluate(() => Array.from(document.querySelectorAll('button')).filter(b => b.textContent?.trim() === 'Condition' || b.textContent?.trim() === 'Group').every(b => b.disabled));
  await pointClick('[aria-label="Negate terminalFocus"]');
  const pointer = await read();
  await app.screenshot("after-click-through-overlay");
  await expression.fill("terminalFocus");
  await expression.fill(invalid);
  const header = await browser.evaluate(() => { const b = Array.from(document.querySelectorAll('button')).find(b => b.textContent?.trim() === 'Condition')!; const r=b.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; });
  await browser.mouse.move(header.x,header.y); await browser.mouse.down(); await browser.mouse.up();
  const condition = await read();
  await app.screenshot("after-header-condition-click");
  await expression.fill("terminalFocus");
  await screen.getByRole("button", "Negate terminalFocus", {exact:true}).tap();
  const recovered = await read();
  await app.screenshot("corrected-expression-visual-edit-restored");
  await expression.fill("terminalFocus");
  await expression.fill(invalid);
  await expression.focus();
  await app.screenshot("keyboard-start-invalid-draft");
  await browser.keyboard.press("Tab");
  const focusedBuilder = await browser.evaluate(() => document.activeElement?.getAttribute('aria-label') === 'Negate terminalFocus');
  if (focusedBuilder) await browser.keyboard.press("Space");
  const keyboard = await read();
  expect({disabled,pointer,condition,focusedBuilder,keyboard,recovered}).toEqual({disabled:true,pointer:invalid,condition:invalid,focusedBuilder:false,keyboard:invalid,recovered:"!terminalFocus"});
});
