#!/usr/bin/env node
"use strict";

const assert = require("node:assert");
const fs = require("node:fs");
const { chromium } = require("playwright");
const { fetchWithTimeout } = require("./task114-rust-web-gateway-entry-smoke.js");

const BASE_URL = (process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const SCREENSHOT_DIR = process.env.MNOTE_PHASE_E_SCREENSHOT_DIR || "/mnt/Data1T/mnote/tmp/wolai-editor-parity/task151-e23-table-local-smoke";

const TABLE_EXTENSION_SOURCE = "/mnt/Data1T/mnote/design/05-editor-mainline/reference-code/leptos-tiptap/tiptap/src/extensions/tiptap_table.ts";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";

function assertOfficialTableSelectionBridge() {
  const source = fs.readFileSync(TABLE_EXTENSION_SOURCE, "utf8");
  assert(
    source.includes("CellSelection.rowSelection") && source.includes("CellSelection.colSelection"),
    "E23 表格行/列选择必须复用 @tiptap/pm/tables 的 CellSelection.rowSelection/colSelection",
  );
  assert(
    !source.includes("setCellSelection"),
    "E23 表格行/列选择不能绕过官方 CellSelection 静态选择逻辑",
  );
}

function assertOfficialTableInsertBridge() {
  const source = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
  assert(
    source.includes("editor.insert_table(4, 3, false)"),
    "E23 简单表格必须通过 bridge 调用 Tiptap 官方 insertTable(rows=4, cols=3, withHeaderRow=false)",
  );
  assert(
    !source.includes(`insert_content(
                TiptapContent::json(simple_table_node())`),
    "E23 简单表格不能再通过手写 JSON simple_table_node() 走 insert_content",
  );
}

async function readJsonResponse(response, label) {
  const text = await response.text();
  let payload = null;
  try {
    payload = text ? JSON.parse(text) : null;
  } catch {
    throw new Error(`${label} 返回了非 JSON 内容: ${text.slice(0, 1200)}`);
  }
  assert(response.ok, `${label} 请求失败: ${response.status}; body: ${text.slice(0, 1200)}`);
  return payload;
}

async function postTreeCommand(body, label) {
  const response = await fetchWithTimeout(`${BASE_URL}/api/tree/commands`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  const payload = await readJsonResponse(response, label);
  assert(payload?.result, `${label} 缺少 result`);
  return payload.result;
}

async function createTempDocument() {
  const title = `task151-e23-table-${Date.now().toString(36)}`;
  const result = await postTreeCommand({ action: "create", title }, "创建 E23 临时文档");
  assert(result.documentId, "创建 E23 临时文档缺少 documentId");
  assert(result.workspaceId, "创建 E23 临时文档缺少 workspaceId");
  return { documentId: result.documentId, workspaceId: result.workspaceId, title };
}

async function purgeTempDocument(target) {
  if (!target?.documentId || !target?.workspaceId) return;
  await postTreeCommand({ action: "purge", workspaceId: target.workspaceId, documentId: target.documentId }, "清理 E23 临时文档");
}

async function loadDocumentContent(target, label) {
  const url = `${BASE_URL}/api/documents/content?documentId=${encodeURIComponent(target.documentId)}&workspaceId=${encodeURIComponent(target.workspaceId)}`;
  const response = await fetchWithTimeout(url, { method: "GET" });
  return readJsonResponse(response, label);
}

async function waitForRuntimeIsland(page) {
  const root = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first();
  await root.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  const editor = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]').first();
  await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await page.waitForFunction(() => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const editorNode = host?.querySelector('.editor-surface .ProseMirror[contenteditable="true"]');
    return host?.getAttribute("data-runtime-editor-status") !== "error" && editorNode instanceof HTMLElement && editorNode.isContentEditable;
  }, null, { timeout: UI_TIMEOUT_MS });
  return editor;
}

async function waitForSavedTable(page, minRows = 2, minCells = 4) {
  await page.waitForFunction(({ minRows, minCells }) => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const table = host?.querySelector('.editor-surface .ProseMirror table');
    return host?.getAttribute("data-runtime-editor-status") === "saved"
      && table instanceof HTMLTableElement
      && table.querySelectorAll('tr').length >= minRows
      && table.querySelectorAll('td,th').length >= minCells;
  }, { minRows, minCells }, { timeout: UI_TIMEOUT_MS });
}

async function waitForSavedWithoutTable(page) {
  await page.waitForFunction(() => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    return host?.getAttribute("data-runtime-editor-status") === "saved"
      && !host.querySelector('.editor-surface .ProseMirror table');
  }, null, { timeout: UI_TIMEOUT_MS });
}

async function screenshot(page, name) {
  fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
  await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png`, fullPage: true });
}

async function clickTableCell(page, { row = 0, col = 0, text = null } = {}) {
  const point = await page.locator('.editor-surface .ProseMirror table').first().evaluate((table, options) => {
    const rows = Array.from(table.querySelectorAll('tr'));
    let cell = null;
    if (options.text) {
      cell = Array.from(table.querySelectorAll('td,th')).find((candidate) => (candidate.textContent || '').includes(options.text));
    } else {
      const rowIndex = options.row < 0 ? rows.length + options.row : options.row;
      const targetRow = rows[rowIndex];
      const cells = targetRow ? Array.from(targetRow.querySelectorAll('td,th')) : [];
      const colIndex = options.col < 0 ? cells.length + options.col : options.col;
      cell = cells[colIndex] || null;
    }
    if (!(cell instanceof HTMLElement)) return null;
    const rect = cell.getBoundingClientRect();
    return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  }, { row, col, text });
  assert(point, `找不到可点击的表格单元格: ${JSON.stringify({ row, col, text })}`);
  await page.mouse.click(point.x, point.y);
}

function findTable(value) {
  if (!value || typeof value !== "object") return null;
  if (Array.isArray(value)) return value.map(findTable).find(Boolean) || null;
  if (value.type === "table" || value.blockType === "table") return value;
  return findTable(value.content) || findTable(value.children) || findTable(value.props?.tiptapTable);
}

function tableText(value) {
  if (!value || typeof value !== "object") return "";
  if (Array.isArray(value)) return value.map(tableText).join("");
  if (typeof value.text === "string") return value.text;
  if (typeof value.content === "string") return value.content;
  return `${tableText(value.content)}${tableText(value.children)}${tableText(value.props?.tiptapTable)}`;
}

function countNodeType(value, type) {
  if (!value || typeof value !== "object") return 0;
  if (Array.isArray(value)) return value.reduce((sum, item) => sum + countNodeType(item, type), 0);
  const own = value.type === type || value.blockType === type ? 1 : 0;
  return own + countNodeType(value.content, type) + countNodeType(value.children, type) + countNodeType(value.props?.tiptapTable, type);
}

function findColwidth(value) {
  if (!value || typeof value !== "object") return null;
  if (Array.isArray(value)) return value.map(findColwidth).find(Boolean) || null;
  const colwidth = value.attrs?.colwidth;
  if (Array.isArray(colwidth) && colwidth.some((width) => typeof width === "number" && width > 0)) {
    return colwidth;
  }
  return findColwidth(value.content) || findColwidth(value.children) || findColwidth(value.props?.tiptapTable);
}

async function main() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();
  const saveRequests = [];
  page.on("request", (request) => {
    if (!request.url().includes("/api/documents/save")) return;
    const body = request.postData();
    if (!body) return;
    try {
      saveRequests.push(JSON.parse(body));
    } catch {
      saveRequests.push({ raw: body });
    }
  });

  assertOfficialTableSelectionBridge();
  assertOfficialTableInsertBridge();

  let target = null;
  try {
    target = await createTempDocument();
    const url = `${BASE_URL}/documents/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`;
    const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    assert(response, "文档页没有返回响应");
    assert.equal(response.status(), 200, `文档页状态码异常: ${response.status()}`);

    const editor = await waitForRuntimeIsland(page);
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("/");
    const slash = page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first();
    await slash.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const slashText = await slash.innerText();
    assert(slashText.includes("进阶块列表"), `slash 菜单缺少进阶块列表: ${slashText}`);
    assert(slashText.includes("简单表格"), `slash 菜单缺少简单表格: ${slashText}`);
    assert(slashText.includes("/jdbg"), `slash 菜单缺少简单表格快捷码 /jdbg: ${slashText}`);

    const simpleTableItem = page.locator('[data-testid="slash-item-simple-table"]').first();
    await simpleTableItem.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
    await screenshot(page, "01-slash-simple-table-entry");
    await simpleTableItem.click({ timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 4, 12);
    await screenshot(page, "02-after-simple-table-insert");

    const tableShape = await page.locator('.editor-surface .ProseMirror table').first().evaluate((table) => ({
      rows: table.querySelectorAll('tr').length,
      cells: table.querySelectorAll('td,th').length,
      text: table.textContent || "",
    }));
    assert.equal(tableShape.rows, 4, `简单表格应按 Wolai 基线插入 4 行: ${JSON.stringify(tableShape)}`);
    assert.equal(tableShape.cells, 12, `简单表格应按 Wolai 基线插入 3 列共 12 个单元格: ${JSON.stringify(tableShape)}`);

    const firstCell = page.locator('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th').first();
    await firstCell.click({ timeout: UI_TIMEOUT_MS });
    const tableToolbar = page.locator('[data-testid="mnote-leptos-tiptap-table-toolbar"]').first();
    await tableToolbar.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const tableControls = page.locator('[data-testid="mnote-leptos-tiptap-table-controls"]').first();
    await tableControls.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert(await page.locator('[data-testid="table-row-aux-0"]').first().isVisible(), "表格应显示首行左侧 aux 选择手柄");
    assert(await page.locator('[data-testid="table-col-aux-0"]').first().isVisible(), "表格应显示首列顶部 aux 选择手柄");
    await page.locator('[data-testid="table-row-aux-0"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const selection = document.querySelector('[data-testid="table-selection-overlay"]');
      const table = document.querySelector('.editor-surface .ProseMirror table');
      return selection?.getAttribute('data-selection-kind') === 'row'
        && selection?.getAttribute('data-selection-index') === '0'
        && table?.querySelectorAll('tr').length === 5
        && table?.querySelectorAll('td,th').length === 15;
    }, null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 5, 15);
    await page.waitForFunction(() => {
      const table = document.querySelector('.editor-surface .ProseMirror table');
      if (!(table instanceof HTMLTableElement)) return false;
      const rows = Array.from(table.querySelectorAll('tr'));
      const targetRow = rows[0];
      const selectedCells = Array.from(table.querySelectorAll('.selectedCell'));
      const targetCells = targetRow ? Array.from(targetRow.querySelectorAll('td,th')) : [];
      return targetCells.length > 0
        && selectedCells.length === targetCells.length
        && selectedCells.every((cell) => targetCells.includes(cell));
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "03a-table-row-aux-insert");
    await page.locator('[data-testid="table-col-aux-0"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const selection = document.querySelector('[data-testid="table-selection-overlay"]');
      const table = document.querySelector('.editor-surface .ProseMirror table');
      return selection?.getAttribute('data-selection-kind') === 'column'
        && selection?.getAttribute('data-selection-index') === '0'
        && table?.querySelectorAll('tr').length === 5
        && table?.querySelectorAll('td,th').length === 20;
    }, null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 5, 20);
    await page.waitForFunction(() => {
      const table = document.querySelector('.editor-surface .ProseMirror table');
      if (!(table instanceof HTMLTableElement)) return false;
      const rows = Array.from(table.querySelectorAll('tr'));
      const selectedCells = Array.from(table.querySelectorAll('.selectedCell'));
      const firstColumnCells = rows
        .map((row) => row.querySelector('td,th'))
        .filter((cell) => cell instanceof HTMLTableCellElement);
      return firstColumnCells.length === rows.length
        && selectedCells.length === firstColumnCells.length
        && selectedCells.every((cell) => firstColumnCells.includes(cell));
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "03b-table-column-aux-insert");
    await clickTableCell(page, { row: -1, col: 0 });
    for (const testid of [
      "table-toolbar-add-row-after",
      "table-toolbar-add-column-after",
      "table-toolbar-clear-cell",
      "table-toolbar-delete-row",
      "table-toolbar-delete-column",
      "table-toolbar-delete-table",
      "table-toolbar-options",
    ]) {
      assert(await page.locator(`[data-testid="${testid}"]`).first().isVisible(), `表格 toolbar 缺少 ${testid}`);
    }
    await screenshot(page, "03-table-toolbar-visible");

    const initialColumnMetrics = await page.locator('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th').first().evaluate((cell) => {
      const rect = cell.getBoundingClientRect();
      return { left: rect.left, right: rect.right, top: rect.top, height: rect.height, width: rect.width };
    });
    await page.mouse.move(initialColumnMetrics.right - 2, initialColumnMetrics.top + initialColumnMetrics.height / 2);
    await page.waitForFunction(() => {
      const editor = document.querySelector('.editor-surface .ProseMirror');
      return editor?.classList.contains('resize-cursor')
        || document.querySelectorAll('.editor-surface .ProseMirror .column-resize-handle').length > 0;
    }, null, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "03c-table-column-resize-handle");
    await page.mouse.down();
    await page.mouse.move(initialColumnMetrics.right + 86, initialColumnMetrics.top + initialColumnMetrics.height / 2, { steps: 8 });
    await page.mouse.up();
    await page.waitForFunction((initialWidth) => {
      const firstCell = document.querySelector('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th');
      const firstCol = document.querySelector('.editor-surface .ProseMirror table col');
      const domWidth = firstCell instanceof HTMLElement ? firstCell.getBoundingClientRect().width : 0;
      const styleWidth = firstCol instanceof HTMLTableColElement ? parseFloat(firstCol.style.width || '0') : 0;
      const attrWidth = firstCell instanceof HTMLElement ? Number((firstCell.getAttribute('data-colwidth') || '').split(',')[0]) : 0;
      return domWidth >= initialWidth + 40 || styleWidth >= initialWidth + 40 || attrWidth >= initialWidth + 40;
    }, initialColumnMetrics.width, { timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 5, 20);
    await screenshot(page, "03d-after-column-resize");

    await page.keyboard.type("A1");
    await page.locator('[data-testid="table-toolbar-add-row-after"]').first().click({ timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 6, 24);
    await page.locator('[data-testid="table-toolbar-add-column-after"]').first().click({ timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 6, 30);
    await screenshot(page, "04-after-row-column-ops");

    await clickTableCell(page, { text: "A1" });
    await page.locator('[data-testid="table-toolbar-clear-cell"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => !(document.querySelector('.editor-surface .ProseMirror table')?.textContent || '').includes('A1'), null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 6, 30);
    await screenshot(page, "05-after-clear-cell");

    await page.locator('[data-testid="table-toolbar-options"]').first().click({ timeout: UI_TIMEOUT_MS });
    const optionsMenu = page.locator('[data-testid="table-toolbar-options-menu"]').first();
    await optionsMenu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    for (const testid of [
      "table-option-toggle-header-row",
      "table-option-toggle-header-column",
      "table-option-toggle-hidden-borders",
    ]) {
      const option = page.locator(`[data-testid="${testid}"]`).first();
      assert(await option.isVisible(), `表格选项菜单缺少 ${testid}`);
      assert.equal(await option.getAttribute("role"), "switch", `${testid} 应使用 switch 语义`);
      assert.equal(await option.getAttribute("aria-checked"), "false", `${testid} 初始应为关闭态`);
    }
    await screenshot(page, "06-table-options-menu");

    await page.locator('[data-testid="table-option-toggle-header-row"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => document.querySelector('[data-testid="table-option-toggle-header-row"]')?.getAttribute('aria-checked') === 'true', null, { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const table = document.querySelector('.editor-surface .ProseMirror table');
      const firstRowCells = [...(table?.querySelectorAll('tr:first-child > td, tr:first-child > th') || [])];
      return firstRowCells.length >= 4 && firstRowCells.every((cell) => cell.tagName === 'TH');
    }, null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 5, 20);

    await page.locator('[data-testid="table-option-toggle-header-column"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => document.querySelector('[data-testid="table-option-toggle-header-column"]')?.getAttribute('aria-checked') === 'true', null, { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const rows = [...document.querySelectorAll('.editor-surface .ProseMirror table tr')];
      return rows.length >= 5 && rows.every((row) => row.firstElementChild?.tagName === 'TH');
    }, null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 5, 20);

    await page.locator('[data-testid="table-option-toggle-hidden-borders"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => document.querySelector('[data-testid="table-option-toggle-hidden-borders"]')?.getAttribute('aria-checked') === 'true', null, { timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(() => {
      const table = document.querySelector('.editor-surface .ProseMirror table');
      const firstCell = table?.querySelector('td,th');
      return table?.getAttribute('data-hidden-borders') === 'true'
        && firstCell instanceof HTMLElement
        && getComputedStyle(firstCell).borderTopWidth === '0px';
    }, null, { timeout: UI_TIMEOUT_MS });
    await waitForSavedTable(page, 5, 20);
    await screenshot(page, "07-after-table-options");

    const lastSave = saveRequests.at(-1);
    assert(lastSave?.tiptapDocument, `表格操作后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
    const savedTable = findTable(lastSave.tiptapDocument);
    assert(savedTable, `保存请求 Tiptap JSON 必须包含 table: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
    assert(!tableText(savedTable).includes("A1"), `清空单元格后保存请求不应保留 A1: ${JSON.stringify(savedTable).slice(0, 1600)}`);
    assert.equal(savedTable.attrs?.hiddenBorders, true, `隐藏边框应写入 table attrs.hiddenBorders: ${JSON.stringify(savedTable).slice(0, 1600)}`);
    assert(countNodeType(savedTable, "tableHeader") >= 8, `标题行/标题列应写入 tableHeader 节点: ${JSON.stringify(savedTable).slice(0, 1600)}`);
    const savedColwidth = findColwidth(savedTable);
    assert(savedColwidth?.some((width) => width >= initialColumnMetrics.width + 40), `列宽拖拽应写入保存请求 attrs.colwidth: ${JSON.stringify(savedTable).slice(0, 1600)}`);

    const contentAfterTable = await loadDocumentContent(target, "读取表格保存后的正文");
    const savedContent = contentAfterTable?.result?.content;
    const contentTable = findTable(savedContent);
    const contentTiptapTable = findTable(contentTable?.props?.tiptapTable) || contentTable;
    assert(contentTable, `/api/documents/content 必须保留 table 语义: ${JSON.stringify(savedContent).slice(0, 1600)}`);
    assert(!tableText(contentTiptapTable).includes("A1"), `/api/documents/content 清空单元格后不应保留 A1: ${JSON.stringify(savedContent).slice(0, 1600)}`);
    assert.equal(contentTiptapTable.attrs?.hiddenBorders, true, `/api/documents/content 应保留隐藏边框属性: ${JSON.stringify(savedContent).slice(0, 1600)}`);
    assert(countNodeType(contentTiptapTable, "tableHeader") >= 8, `/api/documents/content 应保留标题行/列语义: ${JSON.stringify(savedContent).slice(0, 1600)}`);
    const contentColwidth = findColwidth(contentTiptapTable);
    assert(contentColwidth?.some((width) => width >= initialColumnMetrics.width + 40), `/api/documents/content 应保留列宽 attrs.colwidth: ${JSON.stringify(savedContent).slice(0, 1600)}`);

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await waitForRuntimeIsland(page);
    await page.waitForFunction((initialWidth) => {
      const table = document.querySelector('.editor-surface .ProseMirror table');
      return table instanceof HTMLTableElement
        && table.querySelectorAll('tr').length >= 5
        && table.querySelectorAll('td,th').length >= 20
        && table.getAttribute('data-hidden-borders') === 'true'
        && [...table.querySelectorAll('tr:first-child > td, tr:first-child > th')].every((cell) => cell.tagName === 'TH')
        && [...table.querySelectorAll('tr')].every((row) => row.firstElementChild?.tagName === 'TH')
        && (() => {
          const firstCell = table.querySelector('td,th');
          const firstCol = table.querySelector('col');
          const domWidth = firstCell instanceof HTMLElement ? firstCell.getBoundingClientRect().width : 0;
          const styleWidth = firstCol instanceof HTMLTableColElement ? parseFloat(firstCol.style.width || firstCol.style.minWidth || '0') : 0;
          const attrWidth = firstCell instanceof HTMLElement ? Number((firstCell.getAttribute('data-colwidth') || '').split(',')[0]) : 0;
          return domWidth >= initialWidth + 40 || styleWidth >= initialWidth + 40 || attrWidth >= initialWidth + 40;
        })()
        && !(table.textContent || '').includes('A1');
    }, initialColumnMetrics.width, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "08-after-reload-table-ops");

    await page.locator('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th').first().click({ timeout: UI_TIMEOUT_MS });
    await tableToolbar.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="table-toolbar-delete-table"]').first().click({ timeout: UI_TIMEOUT_MS });
    await waitForSavedWithoutTable(page);
    const contentAfterDelete = await loadDocumentContent(target, "读取删除表格后的正文");
    assert(!findTable(contentAfterDelete?.result?.content), `删除表格后 content API 不应保留 table: ${JSON.stringify(contentAfterDelete).slice(0, 1600)}`);
    await screenshot(page, "09-after-delete-table");

    console.log(JSON.stringify({ ok: true, baseUrl: BASE_URL, documentId: target.documentId, screenshotDir: SCREENSHOT_DIR }, null, 2));
  } finally {
    if (target) await purgeTempDocument(target).catch(() => undefined);
    await page.close().catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

if (require.main === module) {
  main().catch((error) => {
    console.error(error instanceof Error ? error.stack || error.message : String(error));
    process.exit(1);
  });
}
