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

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

const ROOT = path.resolve(__dirname, "..");
const BASE_URL = (process.env.MNOTE_UI_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 OUT_DIR = path.join(ROOT, "tmp", "task440-page-title-filetree-md-sync-smoke");

function cssString(value) {
  return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}

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

async function openFileTree(page) {
  await page.evaluate(() => {
    const tab = document.querySelector('[data-mnote-sidebar-tree-tab="filetree"], button[aria-label="文件"]');
    if (tab instanceof HTMLElement) tab.click();
  });
  await page.locator("#sidebar-file-tree-root").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
}

async function createPage(page) {
  const previousPathname = new URL(page.url()).pathname;
  await page.getByRole("button", { name: "新建页面" }).click({ timeout: UI_TIMEOUT_MS });
  await page.waitForURL((url) => url.pathname.startsWith("/documents/") && url.pathname !== previousPathname, { timeout: UI_TIMEOUT_MS });
  const documentId = new URL(page.url()).pathname.split("/").filter(Boolean).pop();
  assert(documentId, "新建后 URL 缺少 documentId");
  await page.waitForFunction(
    (id) => Boolean(document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`)),
    documentId,
    { timeout: UI_TIMEOUT_MS },
  );
  return documentId;
}

async function readState(page, documentId) {
  return page.evaluate((id) => {
    const fileRow = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
    const pageRow = document.querySelector(`#sidebar-tree-root .tree-row[data-node-id="${CSS.escape(id)}"]`);
    const titleInput = document.querySelector(`[data-page-title-input="true"][data-document-id="${CSS.escape(id)}"]`);
    return {
      documentTitle: document.title,
      topbarTitle: document.querySelector("[data-page-title-current='true']")?.textContent?.trim() || "",
      titleInputValue: titleInput instanceof HTMLTextAreaElement ? titleInput.value : "",
      fileTreeTitle: fileRow instanceof HTMLElement ? fileRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "",
      pageTreeTitle: pageRow instanceof HTMLElement ? pageRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "",
      titleLocalApplied: document.documentElement.getAttribute("data-mnote-title-local-applied") || "",
      fileRowExists: fileRow instanceof HTMLElement,
      indexRowExists: document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="index:${CSS.escape(id)}"]`) instanceof HTMLElement,
      titleHistory: Array.isArray(window.__mnoteTask440TitleHistory) ? window.__mnoteTask440TitleHistory.slice() : [],
    };
  }, documentId);
}

async function watchFileTreeTitle(page, documentId) {
  await page.evaluate((id) => {
    const row = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
    const title = row instanceof HTMLElement ? row.querySelector(".tree-link-title") : null;
    window.__mnoteTask440TitleHistory = [];
    const push = () => {
      const text = title instanceof HTMLElement ? title.textContent?.trim() || "" : "";
      if (!text) return;
      const history = window.__mnoteTask440TitleHistory;
      if (!Array.isArray(history)) return;
      if (history[history.length - 1] !== text) history.push(text);
    };
    push();
    if (title instanceof HTMLElement) {
      const observer = new MutationObserver(push);
      observer.observe(title, { childList: true, characterData: true, subtree: true });
      window.__mnoteTask440TitleObserver = observer;
    }
  }, documentId);
}

async function main() {
  await fs.mkdir(OUT_DIR, { recursive: true });
  const browser = await chromium.launch({ headless: process.env.HEADFUL !== "1" });
  const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  const page = await context.newPage();
  const requests = [];
  page.on("request", (request) => {
    if (request.url().includes("/api/documents/title")) {
      requests.push({ url: request.url(), postData: request.postData() || "" });
    }
  });

  const result = { ok: false, baseUrl: BASE_URL, documentId: null, targetTitle: null, before: null, after: null, requests };

  try {
    await quickLogin(page);
    await page.goto(BASE_URL, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await openFileTree(page);
    const documentId = await createPage(page);
    result.documentId = documentId;
    await openFileTree(page);
    result.before = await readState(page, documentId);
    assert.equal(result.before.fileRowExists, true, "File Tree 应出现页面 markdown row");
    assert.equal(result.before.indexRowExists, false, "File Tree 不应显示旧 index row");
    assert.match(result.before.fileTreeTitle, /\.md$/, "新建页面 File Tree 标题应是 .md 文件名");

    await watchFileTreeTitle(page, documentId);

    const targetTitle = `P3-Title-${Date.now().toString().slice(-6)}`;
    result.targetTitle = targetTitle;
    const titleInput = page.locator(`[data-page-title-input="true"][data-pane-role="primary"][data-document-id="${cssString(documentId)}"]`).first();
    await titleInput.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await titleInput.fill(targetTitle);
    const titleSaveResponse = page.waitForResponse(
      (response) =>
        response.url().includes("/api/documents/title") &&
        response.request().method() === "POST" &&
        response.status() === 200 &&
        (response.request().postData() || "").includes(targetTitle),
      { timeout: UI_TIMEOUT_MS },
    );
    await titleInput.evaluate((node) => node.blur());
    await titleSaveResponse;
    await page.waitForFunction(
      ({ id, expected }) => {
        const fileRow = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
        const pageRow = document.querySelector(`#sidebar-tree-root .tree-row[data-node-id="${CSS.escape(id)}"]`);
        const titleInput = document.querySelector(`[data-page-title-input="true"][data-document-id="${CSS.escape(id)}"]`);
        const fileTitle = fileRow instanceof HTMLElement ? fileRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "";
        const pageTitle = pageRow instanceof HTMLElement ? pageRow.querySelector(".tree-link-title")?.textContent?.trim() || "" : "";
        const inputValue = titleInput instanceof HTMLTextAreaElement ? titleInput.value : "";
        return fileTitle === `${expected}.md` && pageTitle === expected && inputValue === expected;
      },
      { id: documentId, expected: targetTitle },
      { timeout: UI_TIMEOUT_MS },
    );

    result.after = await readState(page, documentId);
    assert.equal(result.after.fileTreeTitle, `${targetTitle}.md`, "页面标题栏编辑后 File Tree 应同步显示 .md 文件名");
    assert.equal(result.after.pageTreeTitle, targetTitle, "页面标题栏编辑后 Page Tree 不应带 .md");
    assert.equal(result.after.titleInputValue, targetTitle, "页面标题输入框应保持页面标题");
    assert.equal(result.after.titleLocalApplied, "true", "标题保存事件应触发 Sidebar 本地同步");
    assert(!result.after.titleHistory.includes(targetTitle), `File Tree 标题同步过程中不应短暂显示裸标题：${JSON.stringify(result.after.titleHistory)}`);
    assert(result.after.titleHistory.includes(`${targetTitle}.md`), `File Tree 标题变化历史应包含 .md 文件名：${JSON.stringify(result.after.titleHistory)}`);

    result.ok = true;
  } finally {
    await fs.writeFile(path.join(OUT_DIR, "result.json"), `${JSON.stringify(result, null, 2)}\n`, "utf8");
    await browser.close().catch(() => {});
  }

  console.log(JSON.stringify(result, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
