#!/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", "task438-filetree-title-md-active-reveal-smoke");

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) {
  await page.getByRole("button", { name: "新建页面" }).click({ timeout: UI_TIMEOUT_MS });
  await page.waitForURL((url) => url.pathname.startsWith("/documents/"), { 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 readFileTreeState(page, documentId) {
  return page.evaluate((id) => {
    const root = document.getElementById("sidebar-file-tree-root");
    const row = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
    const indexRow = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="index:${CSS.escape(id)}"]`);
    const selectedRows = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-selected='true']")).map((node) => ({
      rowId: node.getAttribute("data-row-id") || "",
      rowKind: node.getAttribute("data-row-kind") || "",
      title: node.textContent?.trim() || "",
    }));
    const rect = row instanceof HTMLElement ? row.getBoundingClientRect() : null;
    const rootRect = root instanceof HTMLElement ? root.getBoundingClientRect() : null;
    const visible = Boolean(rect && rootRect && rect.bottom >= rootRect.top && rect.top <= rootRect.bottom);
    return {
      rowExists: row instanceof HTMLElement,
      rowId: row instanceof HTMLElement ? row.getAttribute("data-row-id") || "" : "",
      rowKind: row instanceof HTMLElement ? row.getAttribute("data-row-kind") || "" : "",
      rowTitle: row instanceof HTMLElement ? row.querySelector(".tree-link-title")?.textContent?.trim() || "" : "",
      objectIdentity: row instanceof HTMLElement ? row.getAttribute("data-object-identity") || "" : "",
      indexRowExists: indexRow instanceof HTMLElement,
      selectedRows,
      visible,
      scrollTop: root instanceof HTMLElement ? root.scrollTop : null,
      rootText: root instanceof HTMLElement ? root.textContent?.slice(0, 2000) || "" : "",
    };
  }, 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 navigationEvents = [];
  page.on("framenavigated", (frame) => {
    if (frame === page.mainFrame()) navigationEvents.push(frame.url());
  });

  const result = { ok: false, baseUrl: BASE_URL, documentId: null, beforeClick: null, afterClick: null, navigationEvents };

  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.beforeClick = await readFileTreeState(page, documentId);
    assert.equal(result.beforeClick.rowExists, true, "File Tree 应出现页面 markdown row");
    assert.equal(result.beforeClick.indexRowExists, false, "File Tree 不应再显示 index.md row");
    assert.match(result.beforeClick.rowTitle, /\.md$/, "页面正文 row 应显示为 .md 文件名");
    assert.match(result.beforeClick.objectIdentity, /"objectKind":"page"/, "页面正文 row 应保持 page object identity");

    await page.evaluate((id) => {
      const root = document.getElementById("sidebar-file-tree-root");
      const row = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
      if (root instanceof HTMLElement) root.scrollTop = root.scrollHeight;
      if (row instanceof HTMLElement) row.scrollIntoView({ block: "nearest" });
      const button = row instanceof HTMLElement ? row.querySelector('[data-rust-action="open"], .tree-link') : null;
      if (button instanceof HTMLElement) button.click();
    }, documentId);

    await page.waitForFunction(
      (id) => {
        const row = document.querySelector(`#sidebar-file-tree-root .tree-row[data-row-id="doc:${CSS.escape(id)}"]`);
        return row instanceof HTMLElement && row.getAttribute("data-selected") === "true";
      },
      documentId,
      { timeout: UI_TIMEOUT_MS },
    );
    result.afterClick = await readFileTreeState(page, documentId);
    assert.deepEqual(
      result.afterClick.selectedRows.map((row) => row.rowId),
      [`doc:${documentId}`],
      "点击页面正文 row 后 selected 应留在 .md row",
    );
    assert.equal(result.afterClick.visible, true, "点击长列表下方页面后目标 row 应仍在视口内");

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