/// <reference lib="dom" />
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Long Markdown preserves price notes and respects math boundaries", WEB, async ({ t3, app, browser, screen }) => {
  const capture = async (label: string) => {
    let previous = await app.screenshot(`${label}-stability-check`);
    for (let attempt = 0; attempt < 5; attempt++) {
      await new Promise(done => setTimeout(done, 500));
      const current = await app.screenshot(label);
      const [a, b] = await Promise.all([readFile(resolve(previous)), readFile(resolve(current))]);
      if (a.equals(b)) return;
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  const padding = Array.from({length: 16}, (_, i) => `Background ${i + 1}. ${"Synthetic ticket documentation. ".repeat(12)}`).join("\n\n");
  const cases = [
    { file: "prices.md", title: "Ticket prices", body: "Tickets cost $5[^1]-$10.\n\n| Ticket | Price |\n| --- | --- |\n| Admission | $5[^2]-$10 |\n\nGenuine math: $x[^3]+y$.", notes: ["Ticket pricing details.", "Table pricing details.", "Hidden inline math note."], refs: 2 },
    { file: "boundaries.md", title: "Math boundaries", body: "Multiline math: a $$x[^1]\ny$$ visible note[^2] $$\n\nComma closer: $x[^3],$\nmore\n\nCRLF comma closer: $x[^4],$\r\nmore", notes: ["Hidden multiline math note.", "Visible after multiline math.", "Hidden comma math note.", "Hidden CRLF math note."], refs: 1 },
    { file: "paragraphs.md", title: "Paragraph boundaries", body: "> a $$x[^1]\n>\n> y$$ z\n\nDouble dollars before newline: a $$\n[^2]\ny$$ z\n\nDollars around code: a $$ `x` [^3] $$\n\nRun echo $HOME[^4] and see `$PATH`", notes: ["Quoted blank line note.", "Dollar newline note.", "Code span note.", "Shell variable note."], refs: 4 },
    { file: "math-off.md", title: "Render math OFF", body: "Text dollars: Tickets cost $5[^1]-$10 and $x[^2]+y$.\n\n| Literal TeX | Literal dollars |\n| --- | --- |\n| \\([^3]\\) | $[^4]$ |\n\n| First | Second |\n| --- | --- |\n| $x|y|[^5]z$ |", notes: ["Literal price note.", "Literal dollar note.", "Literal TeX note.", "Literal table dollar note.", "Outside truncated table cells."], refs: 4 },
  ];
  cases.push({...cases[3]!, file: "large-math-off.md", title: "Large file Render math OFF"});
  const files = Object.fromEntries(cases.map(c => [c.file, `${padding}\n\n## ${c.title}\n\n${c.body}\n\n${c.file === "large-math-off.md" ? (padding + "\n\n").repeat(180) : padding}\n\n${c.notes.map((note,i) => `[^${i+1}]: ${note}`).join("\n")}\n`]));
  const project = await t3.project("ticket-documentation", files);
  const thread = await t3.thread({project, title: "Markdown ticket guide", messages: [cases.map(c => `:codex-file-citation{path="${c.file}"}`).join(" ")]});
  await t3.open("/settings/appearance");
  const math = screen.getByRole("switch", "Render math", {exact:true});
  // Set the initial mode through the app's actual appearance control.
  await math.waitFor();
  const enabled = await math.getAttribute("aria-checked");
  if (enabled !== "true") await math.tap();
  await capture("render-math-on-setting");
  const results: Array<{file:string; refs:number; notes:string}> = [];
  for (const c of cases) {
    if (c.file === "math-off.md") {
      await t3.open("/settings/appearance");
      await screen.getByRole("switch", "Render math", {exact:true}).tap();
      await capture("render-math-off-setting");
    }
    await t3.open(thread);
    const prompt = screen.getByRole("button", /^Agent /);
    await prompt.waitFor();
    if ((await prompt.getAttribute("aria-expanded")) !== "true") await prompt.tap();
    await screen.getByRole("link", new RegExp(`^${c.file.replace(".", "\\.")}`)).tap();
    const renderButton = screen.getByRole("button", /^Show (rendered markdown|markdown source)$/);
    await renderButton.waitFor();
    if ((await renderButton.getAttribute("aria-pressed")) !== "true") await renderButton.tap();
    const explorer = screen.getByRole("button", "Hide file explorer", {exact:true});
    const hasExplorer = await browser.evaluate(() => !!document.querySelector('[aria-label="Hide file explorer"]'));
    if (hasExplorer) await explorer.tap();
    await screen.getByRole("heading", c.title, {exact:true}).waitFor();
    await browser.evaluate((title) => {
      [...document.querySelectorAll("h2")].find(e => e.textContent === title)?.scrollIntoView({block:"start"});
      return null;
    }, c.title);
    await capture(`${c.file}-references`);
    const result = await browser.evaluate(() => ({
      refs: document.querySelectorAll("a[data-footnote-ref]").length,
      notes: [...document.querySelectorAll("section[data-footnotes]")].map(e => e.textContent).join("\n"),
    }));
    await browser.evaluate((title) => {
      const heading = [...document.querySelectorAll("h2")].find(e => e.textContent === title);
      let parent = heading?.parentElement;
      while (parent && parent.scrollHeight <= parent.clientHeight) parent = parent.parentElement;
      if(parent) parent.scrollTop = parent.scrollHeight;
      return null;
    }, c.title);
    await capture(`${c.file}-definitions`);
    const notes = await browser.evaluate(() => [...document.querySelectorAll("section[data-footnotes]")].map(e => e.textContent).join("\n"));
    results.push({file:c.file, refs: result.refs, notes});
  }
  for (const c of cases) {
    const result = results.find(r => r.file === c.file)!;
    expect(result.refs, c.file).toBe(c.refs);
    for (const note of c.notes) {
      const visible = c.file === "prices.md" ? !note.startsWith("Hidden") : c.file === "boundaries.md" ? note.startsWith("Visible") : c.file.endsWith("math-off.md") ? !note.startsWith("Outside") : true;
      if (visible) expect(result.notes, c.file).toContain(note);
      else expect(result.notes, c.file).not.toContain(note);
    }
  }
});
