/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
const pause = (ms:number) => new Promise(resolve => setTimeout(resolve,ms));
const TEXT = "When `enableFeatureFlag` is enabled, only release the buffer if `group`/`model` **cannot match any active capture rule** (and does not match user or media capture); otherwise keep retaining it across subsequent retries.\n\nQuestion: how do we know **cannot match any active capture rule** ahead of time?";
test("Dragging across inline Markdown keeps layout and selection stable", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:816,height:900});
  const project = await t3.project("Markdown demo");
  const thread = await t3.thread({project,title:"Inline Markdown selection",messages:["first"]});
  await t3.open(thread);
  await screen.getByRole("textbox").tap();
  await browser.evaluate(async () => {
    await document.fonts.ready;
    if (document.body.textContent?.includes("Syncing messages...")) await new Promise<void>(resolve => {
      const observer=new MutationObserver(() => {if(!document.body.textContent?.includes("Syncing messages...")){observer.disconnect();resolve();}}); observer.observe(document.body,{childList:true,subtree:true,characterData:true});
    });
    return null;
  });
  const reset = async () => {
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("Control+a");
    await browser.keyboard.press("Backspace");
    await browser.evaluate((text) => {
      const ed = document.querySelector('[data-testid="composer-editor"]')!;
      const dt = new DataTransfer(); dt.setData("text/plain",text);
      ed.dispatchEvent(new ClipboardEvent("paste",{clipboardData:dt,bubbles:true,cancelable:true}));
      return null;
    },TEXT);
    await browser.keyboard.press("Control+End");
  };
  const geometry = async (selector:string) => browser.evaluate((selector) => {
    const ed = document.querySelector('[data-testid="composer-editor"]')!;
    const p = ed.querySelector("p")!;
    const r = p.querySelector(selector)!.getClientRects()[0]!;
    const pr = p.getBoundingClientRect();
    return {x:r.left+4,y:r.top+r.height/2,startX:pr.left+60,startY:pr.bottom-6};
  },selector);
  const state = async () => browser.evaluate(() => {
    const ed=document.querySelector('[data-testid="composer-editor"]')!;
    const p=ed.querySelector("p")!; const r=p.getBoundingClientRect();
    return {top:Math.round(ed.getBoundingClientRect().top),lines:Math.round(r.height/parseFloat(getComputedStyle(p).lineHeight)),text:p.textContent!.length,selection:getSelection()!.toString(),sources:ed.querySelectorAll(".composer-markdown-source").length};
  });
  // Capture both caret paths before asserting, so base failure still includes them.
  for (const [selector,label] of [["strong","bold"],["code","inline-code"]]) {
    await reset(); const g=await geometry(selector!);
    await browser.mouse.move(g.x,g.y); await browser.mouse.down();
    await pause(500); await app.screenshot(`${label}-click-mousedown`);
    await browser.mouse.up(); await pause(500); await app.screenshot(`${label}-click-mouseup`);
  }
  await reset(); await app.screenshot("before-drag");
  const g=await geometry("strong"); const samples=[await state()];
  await browser.mouse.move(g.startX,g.startY); await browser.mouse.down();
  for(let i=1;i<=12;i++) {
    await browser.mouse.move(g.startX+(g.x-g.startX)*i/12,g.startY+(g.y-g.startY)*i/12);
    await pause(60); samples.push(await state());
  }
  for(const dx of [-12,12,-12,12,-20,20,-6,6]) {
    await browser.mouse.move(g.x+dx,g.y); await pause(60); samples.push(await state());
    if(dx===12) await app.screenshot("mid-drag");
  }
  const beforeUp=await state(); await browser.mouse.up(); const afterUp=await state();
  samples.push(afterUp); await pause(500); await app.screenshot("after-release");
  console.log(JSON.stringify({samples,beforeUp,afterUp}));
  expect(new Set(samples.map(s=>s.top)).size).toBe(1);
  expect(new Set(samples.map(s=>s.lines)).size).toBe(1);
  expect(afterUp.selection).toBe(beforeUp.selection);
  expect(afterUp.selection.length).toBeGreaterThan(30);
});
