import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const __dirname = dirname(fileURLToPath(import.meta.url));
const source = readFileSync(join(__dirname, "SystemPermissionView.vue"), "utf8");
const mainStyles = readFileSync(join(__dirname, "../styles/main.css"), "utf8");

function extractHeaderSource() {
  const start = source.indexOf('<header class="system-permission-hero');
  const end = source.indexOf("</header>", start);
  return start >= 0 && end >= 0 ? source.slice(start, end + "</header>".length) : "";
}

describe("SystemPermissionView organization mind map fitting", () => {
  it("auto-fits the mind map after initial organization data loads", () => {
    assert.match(source, /import\s*\{\s*computed,\s*nextTick,\s*onMounted,\s*reactive,\s*ref,\s*watch\s*\}\s*from\s*"vue"/);
    assert.match(source, /async function requestMindMapFitToScreen\(/);
    assert.match(source, /onMounted\(async\s*\(\)\s*=>\s*\{\s*await loadAll\(\);\s*await requestMindMapFitToScreen\(\);\s*\}\);/);
  });

  it("auto-fits when users return to mind map mode without showing a toast", () => {
    assert.match(source, /watch\(\s*\[\s*permissionMainTab,\s*orgViewMode\s*\]/);
    assert.match(source, /requestMindMapFitToScreen\(\);/);
    assert.match(source, /requestMindMapFitToScreen\(\{\s*showToast:\s*true,\s*closeMenu:\s*true\s*\}\)/);
  });
});

describe("SystemPermissionView page tab placement", () => {
  it("places the organization/role tab switch directly beside the page title", () => {
    const headerSource = extractHeaderSource();
    assert.ok(headerSource.includes('class="system-permission-title-row"'));
    assert.ok(headerSource.includes("<h3>系统权限管理</h3>"));
    assert.ok(headerSource.includes('class="system-permission-main-tabs admin-tab-switcher"'));
    assert.ok(headerSource.indexOf("<h3>系统权限管理</h3>") < headerSource.indexOf('class="system-permission-main-tabs admin-tab-switcher"'));
    assert.equal((source.match(/class="system-permission-main-tabs admin-tab-switcher"/g) || []).length, 1);
  });
});

describe("SystemPermissionView maintenance scrolling", () => {
  it("enables normal vertical scrolling for role maintenance without changing mind map overflow", () => {
    assert.ok(source.includes(`:class="{ 'system-permission-page--maintenance': permissionMainTab === 'maintenance' }"`));
    assert.match(mainStyles, /\.system-permission-page\.system-permission-page--maintenance\s*\{[\s\S]*?overflow-y:\s*auto;/);
    assert.match(mainStyles, /\.system-permission-page\.system-permission-page--maintenance\s+\.system-permission-maintenance-card\s*\{[\s\S]*?overflow:\s*visible;/);
  });
});
