#!/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/task150-e22-folding-blocks-local-smoke";

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

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 waitForSavedText(page, text) {
  await page.waitForFunction((expected) => {
    const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
    const editor = host?.querySelector('.editor-surface .ProseMirror');
    return host?.getAttribute("data-runtime-editor-status") === "saved" && (editor?.textContent || "").includes(expected);
  }, text, { 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 });
}

function findCollapsedHeading(value) {
  if (!value || typeof value !== "object") return null;
  if (Array.isArray(value)) return value.map(findCollapsedHeading).find(Boolean) || null;
  const isHeading = value.type === "heading" || value.blockType === "heading";
  const attrs = value.attrs || value.props || {};
  if (isHeading && (attrs.collapsed === true || value.collapsed === true)) return value;
  return findCollapsedHeading(value.content) || findCollapsedHeading(value.children) || null;
}

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

  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 });
    const text = `E22 folded heading ${Date.now().toString(36)}`;
    await page.keyboard.type(text);
    await waitForSavedText(page, text);
    await screenshot(page, "01-before-folded-title");

    const firstBlock = page.locator('.editor-surface .ProseMirror > *').filter({ hasText: text }).first();
    await firstBlock.hover({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="mnote-leptos-tiptap-handle"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="block-drag-handle-trigger"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="block-drag-menu"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="block-drag-menu-item-turn-into"]').first().hover({ timeout: UI_TIMEOUT_MS });
    const transformMenu = page.locator('[data-testid="block-transform-submenu"]').first();
    await transformMenu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await screenshot(page, "02-transform-submenu-before-e22");

    const foldedTitle = page.locator('[data-testid="block-transform-item-folded-title"]').first();
    assert.equal(await foldedTitle.isDisabled(), false, "折叠标题不能是 disabled 静态文案");
    await foldedTitle.hover({ timeout: UI_TIMEOUT_MS });
    const foldedTitleSubmenu = page.locator('[data-testid="block-transform-folded-title-submenu"]').first();
    await foldedTitleSubmenu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const labels = await foldedTitleSubmenu.locator('[data-testid^="block-transform-folded-heading-"]').evaluateAll((nodes) => nodes.map((node) => (node.textContent || "").trim()));
    for (const expected of ["折叠主标题", "折叠大标题", "折叠中标题", "折叠小标题"]) {
      assert(labels.some((label) => label.includes(expected)), `折叠标题三级菜单缺少 ${expected}: ${labels.join(" | ")}`);
    }
    await screenshot(page, "03-folded-title-tertiary-submenu");

    await page.locator('[data-testid="block-transform-folded-heading-1"]').first().click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction((expected) => {
      const heading = Array.from(document.querySelectorAll('.editor-surface .ProseMirror h1')).find((node) => (node.textContent || '').includes(expected));
      return heading instanceof HTMLElement && heading.getAttribute('data-collapsed') === 'true';
    }, text, { timeout: UI_TIMEOUT_MS });
    await waitForSavedText(page, text);
    await screenshot(page, "04-after-folded-heading-click");

    const lastSave = saveRequests.at(-1);
    assert(lastSave?.tiptapDocument, `折叠标题后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
    assert(findCollapsedHeading(lastSave.tiptapDocument), `保存请求 Tiptap JSON 必须包含 heading attrs.collapsed=true: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);

    const contentAfterFold = await loadDocumentContent(target, "读取折叠标题保存后的正文");
    const savedContent = contentAfterFold?.result?.content;
    assert(findCollapsedHeading(savedContent), `/api/documents/content 必须保留折叠标题语义: ${JSON.stringify(savedContent).slice(0, 1600)}`);

    await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await waitForRuntimeIsland(page);
    await page.waitForFunction((expected) => {
      const heading = Array.from(document.querySelectorAll('.editor-surface .ProseMirror h1')).find((node) => (node.textContent || '').includes(expected));
      return heading instanceof HTMLElement && heading.getAttribute('data-collapsed') === 'true';
    }, text, { timeout: UI_TIMEOUT_MS });
    await screenshot(page, "05-after-reload-folded-heading");

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