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

async function workbook(hideA = false) {
  const zip = new JSZip();
  const rel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
  zip.file("xl/workbook.xml", `<workbook xmlns:r="${rel}"><sheets><sheet name="${hideA ? "Hidden A control" : "Sheet1"}" sheetId="1" r:id="sheet1"/></sheets></workbook>`);
  zip.file("xl/_rels/workbook.xml.rels", `<Relationships><Relationship Id="sheet1" Type="${rel}/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`);
  zip.file("xl/worksheets/sheet1.xml", `<worksheet><cols>${hideA ? '<col min="1" max="1" hidden="1"/>' : ''}<col min="3" max="3" hidden="1"/></cols><sheetData><row r="1"><c r="A1"><v>42</v></c><c r="D1"><v>99</v></c></row></sheetData><mergeCells count="1"><mergeCell ref="A1:B1"/></mergeCells></worksheet>`);
  return zip.generateAsync({ type: "uint8array" });
}

test("ArrowLeft across hidden C focuses the visible merged anchor", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("spreadsheet-demo", {
    "hidden-c.xlsx": await workbook(),
    "hidden-a-c.xlsx": await workbook(true),
  });
  const thread = await t3.thread({ project, title: "Merged cell navigation", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  const open = async (name: string) => {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(name);
    await screen.getByRole("option", name, { exact: false }).tap();
    await browser.locator('[data-active-tab="true"]').getByText(name, { exact: true }).waitFor();
    await screen.getByRole("grid", name === "hidden-a-c.xlsx" ? "Hidden A control" : "Sheet1", { exact: true }).waitFor({ timeout: 120_000 });
    await screen.getByRole("gridcell", "D1", { exact: true }).waitFor();
    // The worker publishes accessible cells before its first canvas frame is ready for hit testing.
    await browser.evaluate(async (sheet) => {
      document.documentElement.dataset.proofSheet = sheet;
      await new Promise<void>((resolve) => {
        const painted = () => {
          const canvas = document.querySelector<HTMLCanvasElement>(`[role="grid"][aria-label="${sheet}"] canvas`);
          const pixel = canvas?.getContext("2d")?.getImageData(50, 5, 1, 1).data;
          if (pixel && pixel[3] > 0 && (pixel[0] < 250 || pixel[1] < 250 || pixel[2] < 250)) resolve();
          else requestAnimationFrame(painted);
        };
        painted();
      });
    }, name === "hidden-a-c.xlsx" ? "Hidden A control" : "Sheet1");
  };
  await open("hidden-c.xlsx");
  await screen.getByRole("button", /^Maximize panel/).tap();
  // This read-only evidence panel exposes the grid's actual accessibility state beside the canvas.
  await browser.evaluate(() => {
    const panel = document.createElement("pre");
    panel.id = "proof-accessibility";
    panel.style.cssText = "position:fixed;right:24px;bottom:90px;padding:18px;background:#172033;color:white;border:2px solid #789;z-index:99999;font:16px/1.6 monospace;pointer-events:none";
    document.body.append(panel);
    const update = () => {
      const grid = document.querySelector<HTMLElement>(`[role="grid"][aria-label="${document.documentElement.dataset.proofSheet}"]`);
      const id = grid?.getAttribute("aria-activedescendant") ?? "none";
      const cell = grid?.querySelector(`[id="${id}"]`);
      const text = 'Accessibility observation (read-only)\naria-activedescendant: ' + id + '\nCell: ' + (cell?.getAttribute("aria-label") ?? "none") + '\nCell text: ' + JSON.stringify(cell?.textContent ?? null);
      if (panel.textContent !== text) panel.textContent = text;
    };
    new MutationObserver(update).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["aria-activedescendant", "data-proof-sheet"] });
    update();
  });
  const clickCell = async (x: number) => {
    const point = await browser.evaluate((offset) => {
      const rect = document.querySelector<HTMLElement>(`[role="grid"][aria-label="${document.documentElement.dataset.proofSheet}"]`)!.getBoundingClientRect();
      return { x: rect.x + offset, y: rect.y + 30 };
    }, x);
    await browser.mouse.move(point.x, point.y);
    await browser.mouse.down();
    await browser.mouse.up();
  };
  const state = () => browser.evaluate(() => {
    const grid = document.querySelector<HTMLElement>(`[role="grid"][aria-label="${document.documentElement.dataset.proofSheet}"]`);
    const id = grid?.getAttribute("aria-activedescendant");
    return { id, text: id ? grid?.querySelector(`[id="${id}"]`)?.textContent : null };
  });
  await clickCell(204);
  await app.screenshot("clicked-D1");
  const start = await state();
  await browser.keyboard.press("ArrowLeft");
  await app.screenshot("arrow-left-over-hidden-C");
  const left = await state();
  await browser.keyboard.press("ArrowRight");
  await app.screenshot("arrow-right-returns-D1");
  const right = await state();
  await clickCell(75);
  await app.screenshot("direct-click-merged-cell-control");
  const direct = await state();
  await open("hidden-a-c.xlsx");
  await clickCell(140);
  await app.screenshot("hidden-A-clicked-D1");
  const hiddenAStart = await state();
  await browser.keyboard.press("ArrowLeft");
  await app.screenshot("hidden-A-remains-visible-B1");
  const hiddenA = await state();
  expect({ start, left, right, direct, hiddenAStart, hiddenA }).toEqual({
    start: { id: "office-cell-0-3", text: "99" },
    left: { id: "office-cell-0-0", text: "42" },
    right: { id: "office-cell-0-3", text: "99" },
    direct: { id: "office-cell-0-0", text: "42" },
    hiddenAStart: { id: "office-cell-0-3", text: "99" },
    hiddenA: { id: "office-cell-0-1", text: "" },
  });
});
