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

const assert = require("node:assert");
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 CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

function fileUrl(localPath) {
  return `file://${localPath}`;
}

function localMdDocumentId(relativePath) {
  return `local-md:${relativePath.replaceAll("/", "~2F")}`;
}

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}:task462`,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "markdown_edit", "asset_upload"],
    }, null, 2)}\n`,
    "utf8",
  );
}

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 main() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task462-error-placeholder-"));
  const relativePath = "README.md";
  writeWorkspaceManifest(root, "user_real");
  fs.writeFileSync(path.join(root, relativePath), "# Page\n\n正文\n", "utf8");

  const browser = await chromium.launch({
    headless: true,
    executablePath: CHROMIUM_EXECUTABLE_PATH,
  });
  const context = await browser.newContext({
    viewport: { width: 1360, height: 900 },
    extraHTTPHeaders: {
      "x-mnote-actor-id": "user_real",
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();

  try {
    await quickLogin(page);
    await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
    await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });

    // ======== Test 1: Open non-existent resource → error placeholder tab ========
    console.log("Test 1: Open non-existent asset → error placeholder tab");
    const fakeAssetId = `local-file:nonexistent/error-test-${Date.now()}.md`;
    
    // Dispatch tree.asset.open with a non-existent local asset
    await page.evaluate(({ fakeAssetId }) => {
      window.dispatchEvent(new CustomEvent("tree.asset.open", {
        detail: {
          assetId: fakeAssetId,
          documentId: document.body?.dataset?.documentId || "",
          title: "error-test.md",
          assetType: "attachment",
        },
      }));
    }, { fakeAssetId });

    // Wait for the error tab to appear (since the file doesn't exist, it should create an error tab)
    await page.waitForTimeout(1000);

    // Check error placeholder created: the resource tab panel should have an error indicator
    const errorPanelState = await page.evaluate(() => {
      const errorPanel = document.querySelector('[data-resource-tab-error="true"]');
      const activeTab = document.querySelector('.mnote-main-tab.is-active:not([data-mnote-main-tab="page"])');
      const allResourceTabs = document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
      // Count how many tabs have error content
      const errorTabs = Array.from(allResourceTabs).filter(tab => {
        const identity = tab.getAttribute('data-mnote-main-tab') || '';
        const panel = document.querySelector(`[data-mnote-resource-tab-panel="${CSS.escape(identity)}"]`);
        return panel && panel.querySelector('[data-resource-tab-error="true"]');
      });
      return {
        hasErrorPanel: !!errorPanel,
        errorPanelText: errorPanel?.textContent || "",
        activeTabExists: !!activeTab,
        totalResourceTabs: allResourceTabs.length,
        errorTabCount: errorTabs.length,
      };
    });
    
    console.log(`  Error panel state: ${JSON.stringify(errorPanelState)}`);
    assert.equal(errorPanelState.hasErrorPanel, true, `missing error placeholder: ${JSON.stringify(errorPanelState)}`);
    assert.match(errorPanelState.errorPanelText, /资源打开失败/, `error panel should explain failure: ${JSON.stringify(errorPanelState)}`);
    assert.equal(errorPanelState.activeTabExists, true, `error tab should stay active: ${JSON.stringify(errorPanelState)}`);
    assert.equal(errorPanelState.errorTabCount, 1, `one error tab should be registered: ${JSON.stringify(errorPanelState)}`);

    const pageTabReachable = await page.evaluate(() => {
      const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
      return pageTab instanceof HTMLElement;
    });
    assert.ok(pageTabReachable, "Page tab should always be present");

    // ======== Test 2: Error tab close button → removes tab ========
    console.log("Test 2: Close error tab → cleans up");
    
    // Try to close any open resource tab
    await page.evaluate(() => {
      const resourceTab = document.querySelector('.mnote-main-tab.is-active:not([data-mnote-main-tab="page"])');
      if (resourceTab instanceof HTMLElement) {
        const closeBtn = resourceTab.querySelector('.mnote-main-tab-close');
        if (closeBtn instanceof HTMLElement) {
          closeBtn.click();
        }
      }
    });
    await page.waitForTimeout(300);

    const afterCloseState = await page.evaluate(() => {
      return {
        resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
        pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
        errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
      };
    });
    console.log(`  After close: ${JSON.stringify(afterCloseState)}`);
    
    // Page tab should be active after closing all resource tabs
    assert.ok(afterCloseState.pageTabActive, "Page tab should be active after closing error tab");

    // ======== Test 3: Multiple sequential opens with failure ========
    console.log("Test 3: Sequential failed opens should not cause runaway tabs");
    
    const fakeIds = [];
    for (let i = 0; i < 3; i++) {
      fakeIds.push(`local-file:nonexistent/test-${i}-${Date.now()}.md`);
    }

    for (const fakeId of fakeIds) {
      await page.evaluate(({ fakeId }) => {
        window.dispatchEvent(new CustomEvent("tree.asset.open", {
          detail: {
            assetId: fakeId,
            documentId: document.body?.dataset?.documentId || "",
            title: `test-${fakeId.split("-")[1]}.md`,
            assetType: "attachment",
          },
        }));
      }, { fakeId });
    }
    await page.waitForTimeout(500);

    const afterMultipleState = await page.evaluate(() => {
      return {
        resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
        errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
        pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
      };
    });
    console.log(`  After multiple failed opens: ${JSON.stringify(afterMultipleState)}`);
    
    // Should not have runaway tabs (at most the 3 we opened, some may not create tabs if they fail fast)
    assert.ok(afterMultipleState.resourceTabs <= fakeIds.length,
      `Should not exceed ${fakeIds.length} resource tabs: ${afterMultipleState.resourceTabs}`);

    // ======== Test 4: Recover after error state ========
    console.log("Test 4: Close all error tabs and verify page tab is cleanly active");
    
    // Close all resource tabs
    await page.evaluate(() => {
      const allResourceTabs = document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
      allResourceTabs.forEach(tab => {
        const closeBtn = tab.querySelector('.mnote-main-tab-close');
        if (closeBtn instanceof HTMLElement) closeBtn.click();
      });
    });
    await page.waitForTimeout(500);

    const finalState = await page.evaluate(() => {
      return {
        resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
        pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
        pagePanelHidden: document.querySelector('[data-mnote-page-tab-panel]')?.hidden || false,
        resourceHostHidden: document.querySelector('[data-mnote-resource-tab-host]')?.hidden ?? true,
        errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
      };
    });
    console.log(`  Final state: ${JSON.stringify(finalState)}`);

    assert.ok(finalState.pageTabActive, "Page tab should be active after cleanup");
    assert.equal(finalState.resourceTabs, 0, "All resource tabs should be removed");
    assert.equal(finalState.errorPanels, 0, "All error panels should be removed");
    assert.equal(finalState.pagePanelHidden, false, "Page panel should not be hidden");

    console.log(JSON.stringify({ ok: true, root }, null, 2));
  } finally {
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }
}

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