#!/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/task158-e30-menu-state-local-smoke";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";
const IMAGE_SRC = "/api/editor/image-placeholder.svg";
const TARGET_BLOCK_ID = "e30-menu-state-target";

function assertMenuStateSourceBoundary() {
  const source = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
  assert(
    source.includes("close_editor_floating_overlays"),
    "E30 必须把菜单/浮层关闭逻辑收口到 close_editor_floating_overlays，而不是每个菜单散写 set(false)",
  );
  assert(
    source.includes("close_editor_floating_overlays_if_escape"),
    "E30 Escape 必须通过统一函数关闭 slash/block/toolbar/image/table 浮层",
  );
  assert(
    source.includes("open_slash_menu_overlay"),
    "E30 slash 打开必须走统一互斥入口，避免和其他浮层叠开",
  );
  assert(
    source.includes("open_image_toolbar_overlay"),
    "E30 image toolbar 打开必须走统一互斥入口",
  );
  assert(
    source.includes("open_block_menu_overlay"),
    "E30 block menu 打开必须走统一互斥入口",
  );
}

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 = `task158-e30-menu-state-${Date.now().toString(36)}`;
  const result = await postTreeCommand({ action: "create", title }, "创建 E30 临时文档");
  assert(result.documentId, "创建 E30 临时文档缺少 documentId");
  assert(result.workspaceId, "创建 E30 临时文档缺少 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 }, "清理 E30 临时文档");
}

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 screenshot(page, name) {
  fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
  await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png`, fullPage: true });
}

async function setMenuStateFixture(page) {
  await page.evaluate(({ targetBlockId, imageSrc }) => {
    const editor = document.querySelector('.editor-surface .ProseMirror')?.editor;
    if (!editor) throw new Error('找不到 Tiptap editor');
    editor.commands.setContent({
      type: 'doc',
      content: [
        {
          type: 'paragraph',
          attrs: { blockId: targetBlockId },
          content: [{ type: 'text', text: 'E30 menu state target paragraph' }],
        },
        {
          type: 'paragraph',
          attrs: { blockId: 'e30-selection-target' },
          content: [{ type: 'text', text: 'E30 selection toolbar target text' }],
        },
        {
          type: 'image',
          attrs: { src: imageSrc, alt: 'E30 图片占位', title: 'E30 图片', 'data-align': 'left' },
        },
        {
          type: 'table',
          content: [
            {
              type: 'tableRow',
              content: [
                { type: 'tableCell', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'A1' }] }] },
                { type: 'tableCell', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'B1' }] }] },
              ],
            },
            {
              type: 'tableRow',
              content: [
                { type: 'tableCell', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'A2' }] }] },
                { type: 'tableCell', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'B2' }] }] },
              ],
            },
          ],
        },
      ],
    }, true);
    editor.commands.focus('start');
  }, { targetBlockId: TARGET_BLOCK_ID, imageSrc: IMAGE_SRC });
  await page.waitForFunction(({ targetBlockId, imageSrc }) => {
    return document.querySelector(`[data-block-id="${targetBlockId}"]`) instanceof HTMLElement
      && document.querySelector(`.editor-surface .ProseMirror img[src="${imageSrc}"]`) instanceof HTMLImageElement
      && document.querySelector('.editor-surface .ProseMirror table') instanceof HTMLTableElement;
  }, { targetBlockId: TARGET_BLOCK_ID, imageSrc: IMAGE_SRC }, { timeout: UI_TIMEOUT_MS });
}

async function openBlockMenuForTarget(page) {
  const target = page.locator(`[data-block-id="${TARGET_BLOCK_ID}"]`).first();
  await target.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
  const targetBox = await target.boundingBox();
  assert(targetBox, "E30 目标块缺少可 hover 区域");
  await page.mouse.move(targetBox.x + 8, targetBox.y + Math.min(10, Math.max(4, targetBox.height / 2)));
  const handle = page.locator('[data-testid="block-drag-handle-trigger"]').first();
  await handle.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  await handle.click({ timeout: UI_TIMEOUT_MS });
  const menu = page.locator('[data-testid="block-drag-menu"]').first();
  await menu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  return menu;
}

async function openSelectionToolbar(page) {
  await page.evaluate(() => {
    const textNode = Array.from(document.querySelectorAll('.editor-surface .ProseMirror p'))
      .find((node) => (node.textContent || '').includes('E30 selection toolbar target text'))
      ?.firstChild;
    if (!textNode) throw new Error('找不到 E30 选区文本节点');
    const range = document.createRange();
    range.setStart(textNode, 0);
    range.setEnd(textNode, Math.min(12, textNode.textContent.length));
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  });
  await page.mouse.up();
  const toolbar = page.locator('[data-testid="mnote-leptos-tiptap-toolbar"]').first();
  await toolbar.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  return toolbar;
}

async function assertNoFloatingOverlay(page, label) {
  const state = await page.evaluate(() => ({
    slash: Boolean(document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]')),
    block: Boolean(document.querySelector('[data-testid="block-drag-menu"]')),
    toolbar: Boolean(document.querySelector('[data-testid="mnote-leptos-tiptap-toolbar"]')),
    turnInto: Boolean(document.querySelector('[data-testid="turn-into-panel"]')) && getComputedStyle(document.querySelector('[data-testid="turn-into-panel"]')).display !== 'none',
    color: Boolean(document.querySelector('[data-testid="toolbar-color-panel"]')) && getComputedStyle(document.querySelector('[data-testid="toolbar-color-panel"]')).display !== 'none',
    more: Boolean(document.querySelector('[data-testid="toolbar-more-panel"]')) && getComputedStyle(document.querySelector('[data-testid="toolbar-more-panel"]')).display !== 'none',
    image: Boolean(document.querySelector('[data-testid="image-floating-toolbar"]')),
    tableToolbar: Boolean(document.querySelector('[data-testid="mnote-leptos-tiptap-table-toolbar"]')),
    tableOptions: Boolean(document.querySelector('[data-testid="table-toolbar-options-menu"]')),
  }));
  assert.deepEqual(state, {
    slash: false,
    block: false,
    toolbar: false,
    turnInto: false,
    color: false,
    more: false,
    image: false,
    tableToolbar: false,
    tableOptions: false,
  }, `${label} 后仍有浮层残留: ${JSON.stringify(state)}`);
}

async function main() {
  assertMenuStateSourceBoundary();

  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();

  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 setMenuStateFixture(page);

    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("/");
    await page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.keyboard.press("ArrowDown");
    const selectedAfterArrow = await page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"] .slash-item[data-active="true"]').first().innerText();
    assert(selectedAfterArrow.trim().length > 0, "slash menu 方向键后必须有 active 项");
    await screenshot(page, "01-slash-arrow-active");
    await page.keyboard.press("Escape");
    await assertNoFloatingOverlay(page, "Slash Escape");

    await openBlockMenuForTarget(page);
    await page.locator('[data-testid="block-drag-menu-item-turn-into"]').first().hover({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="block-turn-into-menu"], [data-e30-testid="block-turn-into-menu"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await screenshot(page, "02-block-submenu-open");
    await page.keyboard.press("Escape");
    await assertNoFloatingOverlay(page, "Block menu Escape");

    const toolbar = await openSelectionToolbar(page);
    await toolbar.locator('[data-testid="toolbar-color"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="toolbar-color-panel"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await screenshot(page, "03-color-panel-open");
    await page.keyboard.press("Escape");
    await assertNoFloatingOverlay(page, "Selection color Escape");

    const image = page.locator('.editor-surface .ProseMirror img[src]').first();
    await image.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="image-floating-toolbar"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await screenshot(page, "04-image-toolbar-open");
    await page.keyboard.press("Escape");
    await assertNoFloatingOverlay(page, "Image toolbar Escape");

    await page.locator('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th').first().click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="mnote-leptos-tiptap-table-toolbar"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="table-toolbar-options"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="table-toolbar-options-menu"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await screenshot(page, "05-table-options-open");
    await page.keyboard.press("Escape");
    await assertNoFloatingOverlay(page, "Table options Escape");

    await openSelectionToolbar(page);
    await page.locator('[data-testid="mnote-leptos-tiptap-toolbar"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.type("/");
    await page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert.equal(await page.locator('[data-testid="mnote-leptos-tiptap-toolbar"]').count(), 0, "打开 slash 时 selection toolbar 必须关闭");
    await page.keyboard.press("Escape");

    await image.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="image-floating-toolbar"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await openBlockMenuForTarget(page);
    assert.equal(await page.locator('[data-testid="image-floating-toolbar"]').count(), 0, "打开块菜单时 image toolbar 必须关闭");
    await screenshot(page, "06-block-menu-after-image-mutual-exclusion");

    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);
  });
}
