/// <reference lib="dom" />
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { test, WEB } from './t3.ts';

test('Saving an edit after another client deletes the action refuses the save', WEB, async ({t3, app, browser, screen}) => {
  const capture = async (label: string) => {
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 800)));
    await app.screenshot(label);
    // Hold each evidence milestone in the video so a person can read it.
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 1500)));
  };
  const project = await t3.project('demo');
  await browser.setViewport({width:1440,height:1000});
  await browser.addInitScript(() => {
    const install = () => {
      const style=document.createElement('style'); style.textContent='*{backdrop-filter:none!important}'; document.head.append(style);
      const redact = () => {
        const walk=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);
        while(walk.nextNode()) { const n=walk.currentNode; if(n.textContent?.includes('/home/user/')) n.textContent=n.textContent.replace(/\/home\/user\/[^\s"<>]+/g,'[synthetic workspace path]'); }
      };
      new MutationObserver(redact).observe(document.body,{subtree:true,childList:true,characterData:true}); redact();
    };
    document.addEventListener('DOMContentLoaded',install,{once:true});
  });
  await t3.open('/settings/projects');
  await screen.getByRole('button', /^Project scope:/).tap();
  await screen.getByRole('menuitemradio', 'demo', {exact:true}).tap();
  await screen.getByRole('button','Add action',{exact:true}).tap();
  await browser.locator('#script-name').fill('Lint');
  await browser.locator('#script-command').fill('echo lint');
  await screen.getByRole('button','Save action',{exact:true}).tap();
  await screen.getByRole('button','Edit Lint',{exact:true}).waitFor();
  const settingsUrl = await browser.url();
  await browser.evaluate((url) => {
    const frame = document.createElement('iframe'); frame.id='client-b'; frame.src=url;
    frame.style.cssText='position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647';
    document.body.append(frame);
  }, settingsUrl);
  const b=browser.frameLocator('#client-b');
  await b.getByRole('button','Edit Lint',{exact:true}).waitFor();
  await browser.evaluate(()=>{document.querySelector<HTMLIFrameElement>('#client-b')!.style.display='none';});
  await screen.getByRole('button','Edit Lint',{exact:true}).tap();
  await browser.locator('#script-keybinding').press('Control+Shift+K');
  await capture('client-a-stale-edit-ready');
  await browser.evaluate(()=>{document.querySelector<HTMLIFrameElement>('#client-b')!.style.display='';});
  await b.getByRole('button','Edit Lint',{exact:true}).tap();
  await b.getByRole('button','Delete',{exact:true}).tap();
  await capture('client-b-delete-confirmation');
  await b.getByRole('button','Delete action',{exact:true}).tap();
  await b.getByText('No actions configured.',{exact:true}).waitFor();
  await capture('client-b-action-deleted');
  const read = async () => ({settings:await readFile(`${T3_HOME}/userdata/settings.json`,'utf8'), keybindings:await readFile(`${T3_HOME}/userdata/keybindings.json`,'utf8')});
  const before=await read();
  await browser.evaluate(()=>{document.querySelector<HTMLIFrameElement>('#client-b')!.style.display='none';});
  await screen.getByText('No actions configured.',{exact:true}).waitFor({state:'attached'});
  await screen.getByRole('button','Save changes',{exact:true}).tap();
  // Both outcomes are settled when the editor is closed or displays its validation error.
  await browser.locator('body').getByText(/Script not found\.|No actions configured\./).first().waitFor({state:'attached'});
  let refused=false;
  try { await screen.getByText('Script not found.',{exact:true}).first().waitFor(); refused=true; } catch {}
  await capture('save-result');
  const after=await read();
  const dir=`${process.env.EVIDENCE_DIR}/raw-${Date.now()}`;
  await mkdir(dir,{recursive:true});
  for(const [phase,value] of Object.entries({before,after})) for(const [name,contents] of Object.entries(value)) await writeFile(`${dir}/${phase}-${name}.json`,contents);
  // Render verbatim file bytes as evidence, without exposing the synthetic workspace's internal path.
  await browser.evaluate((data)=>{
    const panel=document.createElement('div'); panel.id='raw-evidence';
    panel.style.cssText='position:fixed;inset:0;z-index:2147483647;background:#101218;color:#eee;padding:24px;display:grid;grid-template-columns:1fr 1fr;gap:24px;font:16px/1.3 monospace';
    for (const [phase, files] of Object.entries(data)) {
      const column=document.createElement('pre'); column.style.cssText='white-space:pre-wrap;margin:0';
      const overrides=files.settings.match(/  "projectSettingsOverrides": \{[\s\S]*?\n  \}/)?.[0] ?? 'No project overrides';
      column.textContent=`${phase.toUpperCase()} Save changes\n\nsettings.json — verbatim override excerpt\n${overrides}\n\nkeybindings.json — verbatim last 26 lines\n${files.keybindings.split("\n").slice(-26).join("\n")}`;
      panel.append(column);
    }
    document.body.append(panel);
  },{before,after});
  await capture('raw-persisted-files');
  expect(refused,'The stale edit reports Script not found.').toBe(true);
  expect(after.settings,'Refusing the edit leaves settings bytes unchanged').toBe(before.settings);
  expect(after.keybindings,'Refusing the edit leaves keybindings bytes unchanged').toBe(before.keybindings);
});
