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

const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { chromium } = require("playwright");

const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task511-slash-menu-position-dismiss-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const TEST_PASSWORD = process.env.MNOTE_E2E_PASSWORD || ["Mnote", "E2E", "123!"].join("");
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

function fileUrl(localPath) {
  return `file://${localPath.split(path.sep).map((part, index) => (
    index === 0 ? "" : encodeURIComponent(part)
  )).join("/")}`;
}

function localMdDocumentId(relativePath) {
  return `local-md:${Buffer.from(relativePath, "utf8")
    .toString("hex")
    .replace(/../g, (hex) => {
      const code = Number.parseInt(hex, 16);
      const ch = String.fromCharCode(code);
      return /[A-Za-z0-9._-]/.test(ch) ? ch : `~${hex.toUpperCase()}`;
    })}`;
}

function documentUrl(root, relativePath) {
  const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", fileUrl(root));
  url.searchParams.set("treeView", "filetree");
  return url.toString();
}

function writeWorkspaceManifest(root, ownerId) {
  const metadataDir = path.join(root, ".mnote");
  fs.mkdirSync(metadataDir, { recursive: true });
  fs.writeFileSync(
    path.join(metadataDir, "workspace.json"),
    `${JSON.stringify({
      workspaceId: `local-ws:${ownerId}:task511`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit"],
    }, null, 2)}\n`,
    "utf8",
  );
}

async function ensureTestUser(context) {
  const payload = (flow) => ({
    action: "auth:signIn",
    args: {
      provider: "password",
      params: {
        email: "mnote.e2e@example.com",
        username: "mnote-e2e",
        name: "mnote-e2e",
        password: TEST_PASSWORD,
        flow,
      },
    },
  });
  const signIn = await context.request.fetch(`${BASE_URL}/api/auth`, {
    method: "POST",
    data: payload("signIn"),
  });
  if (signIn.ok()) return;
  const signUp = await context.request.fetch(`${BASE_URL}/api/auth`, {
    method: "POST",
    data: payload("signUp"),
  });
  assert(signUp.ok(), `测试用户创建失败: ${signUp.status()} ${await signUp.text()}`);
}

async function quickLogin(page) {
  await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
  const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
  if (await quickLoginButton.count()) {
    await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
    await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS }).catch(() => undefined);
  }
}

async function waitForEditor(page) {
  await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
    state: "visible",
    timeout: UI_TIMEOUT_MS,
  });
  const editor = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror[contenteditable="true"]').first();
  await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
  return editor;
}

async function slashMenuBox(page) {
  return await page.evaluate(() => {
    const menu = document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]');
    if (!(menu instanceof HTMLElement)) return null;
    const rect = menu.getBoundingClientRect();
    const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
    const editorRect = editor instanceof HTMLElement ? editor.getBoundingClientRect() : null;
    return {
      x: rect.x,
      y: rect.y,
      width: rect.width,
      height: rect.height,
      viewportWidth: window.innerWidth,
      viewportHeight: window.innerHeight,
      editorX: editorRect ? editorRect.x : null,
      editorY: editorRect ? editorRect.y : null,
      editorWidth: editorRect ? editorRect.width : null,
    };
  });
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task511-slash-"));
  const relativePath = "SlashPosition.md";
  writeWorkspaceManifest(root, "mnote-e2e");
  fs.writeFileSync(path.join(root, relativePath), "# Slash Position\n\n第一行\n\n第二行\n", "utf8");

  const browser = await chromium.launch({
    headless: process.env.HEADFUL !== "1",
    executablePath: CHROMIUM_EXECUTABLE_PATH,
  });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 900 },
    locale: "zh-CN",
    extraHTTPHeaders: {
      "x-mnote-actor-id": "mnote-e2e",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();
  const result = { root, relativePath, states: [], console: [], pageErrors: [] };
  page.on("console", (message) => result.console.push({ type: message.type(), text: message.text() }));
  page.on("pageerror", (error) => result.pageErrors.push(String(error && error.stack || error)));

  try {
    await ensureTestUser(context);
    await quickLogin(page);
    await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    const editor = await waitForEditor(page);
    await editor.click({ timeout: UI_TIMEOUT_MS });
    await page.keyboard.press("End").catch(() => undefined);
    await page.keyboard.type("/");
    await page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    const openedBox = await slashMenuBox(page);
    assert(openedBox, "slash 菜单应打开");
    assert(openedBox.x < openedBox.viewportWidth - openedBox.width - 32, `slash 菜单不应贴到右下角: ${JSON.stringify(openedBox)}`);
    assert(openedBox.x >= Math.max(0, (openedBox.editorX || 0) - 24), `slash 菜单不应跑到编辑器左侧外: ${JSON.stringify(openedBox)}`);
    assert(openedBox.y < openedBox.viewportHeight - 96, `slash 菜单不应贴到视口底部: ${JSON.stringify(openedBox)}`);
    result.states.push({ step: "opened", box: openedBox });
    await page.screenshot({ path: path.join(OUTPUT_DIR, "01-opened.png"), fullPage: false });

    await page.mouse.click(1320, 820);
    await page.waitForFunction(
      () => !document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]'),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    result.states.push({ step: "outside-click-closed" });
    await page.screenshot({ path: path.join(OUTPUT_DIR, "02-outside-click-closed.png"), fullPage: false });

    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,
    });
    const reopenedBox = await slashMenuBox(page);
    assert(reopenedBox, "slash 菜单应能再次打开");
    result.states.push({ step: "reopened", box: reopenedBox });

    await page.mouse.click(Math.round((openedBox.editorX || 487) + 40), Math.round((openedBox.editorY || 242) + 40));
    await page.waitForFunction(
      () => !document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]'),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    result.states.push({ step: "editor-click-closed" });
    await page.screenshot({ path: path.join(OUTPUT_DIR, "03-editor-click-closed.png"), fullPage: false });
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, ...result }, null, 2)}\n`, "utf8");
    console.log(JSON.stringify({ ok: true, resultPath: RESULT_PATH, screenshotDir: OUTPUT_DIR }, null, 2));
  } catch (error) {
    const diagnostics = await page.evaluate(() => ({
      url: location.href,
      slashBox: (() => {
        const menu = document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]');
        if (!(menu instanceof HTMLElement)) return null;
        const rect = menu.getBoundingClientRect();
        return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
      })(),
    })).catch((err) => ({ diagnosticsError: String(err) }));
    await page.screenshot({ path: path.join(OUTPUT_DIR, "failure.png"), fullPage: true }).catch(() => undefined);
    fs.writeFileSync(
      RESULT_PATH,
      `${JSON.stringify({ ok: false, ...result, diagnostics, error: String(error && error.stack || error) }, null, 2)}\n`,
      "utf8",
    );
    console.error(JSON.stringify({ ok: false, resultPath: RESULT_PATH, diagnostics, error: String(error && error.stack || error) }, null, 2));
    process.exitCode = 1;
  } finally {
    fs.rmSync(root, { recursive: true, force: true });
    await page.close().catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

main().catch((error) => {
  console.error(error && error.stack ? error.stack : error);
  process.exit(1);
});
