/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB, runPromise } from "./t3.ts";
import { run } from "./shell.ts";

const fixture = '\uFEFF```\n[^b] fake\n```\n\nhttps://github.com/user-attachments/assets/a.mp4\n\nFirst[^a] then[^b].\n\n[^a]: note a\n[^b]: note b';
test("Opening BOM fence does not seed footnote numbering", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1440, height: 1100 });
  const project = await t3.project("Footnote proof");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  const thread = await t3.thread({ project, title: "Footnote preview", messages: ["Start"] });
  await t3.open(thread);
  await t3.open("/issues?q=47867&status=open&who=all");
  await screen.getByText("#47867", { exact: true }).tap();
  await screen.getByRole("button", "Edit description", { exact: true }).tap();
  const preview = async (text: string) => {
    await screen.getByRole("textbox", "Description", { exact: true }).fill(text);
    await screen.getByRole("button", "Preview", { exact: true }).tap();
    await browser.locator('[role="alert"]').waitFor({ state: "attached" });
    await browser.locator('section.footnotes').waitFor({ state: 'attached' });
    await browser.evaluate(() => { document.querySelector('section.footnotes')?.scrollIntoView({ block: 'center' }); return null; });
  };
  const references = () => browser.evaluate(() => Array.from(document.querySelectorAll<HTMLAnchorElement>('a[href*="#user-content-fn-"]')).map(a => ({ text: a.textContent, href: new URL(a.href).hash, target: (document.getElementById('user-content-' + new URL(a.href).hash.slice(1)) ?? document.getElementById(new URL(a.href).hash.slice(1)))?.textContent?.trim().replace(/\s*↩.*$/, "") })));
  await preview(fixture);
  await app.screenshot("bom-fence-footnotes");
  const refs = await references();
  await browser.evaluate(() => { document.querySelector<HTMLAnchorElement>('a[href*="#user-content-fn-"]')?.click(); return null; });
  await app.screenshot("first-citation-destination");
  await screen.getByRole("button", "Write", { exact: true }).tap();
  await preview(fixture.slice(1));
  await app.screenshot("without-bom-control");
  const control = await references();
  await screen.getByRole("button", "Cancel", { exact: true }).tap();
  expect(refs.map(r => r.text)).toEqual(["1", "2"]);
  expect(refs.map(r => r.href)).toEqual(["#user-content-fn-1", "#user-content-fn-2"]);
  expect(refs.map(r => r.target)).toEqual(["note a", "note b"]);
  expect(control.map(r => r.text)).toEqual(["1", "2"]);
  expect(control.map(r => r.target)).toEqual(["note a", "note b"]);
});
