"use strict";

/**
 * D43 页面交互冒烟测试（Node DOM 桩，不启动、不控制真实浏览器）
 * 运行：node scripts/ui-smoke.js
 *
 * 目的：在没有浏览器的环境下执行 index.html 的内联脚本，模拟：
 * 初始渲染 → 权重变化 → 权重错误 → 补齐空值/负数/合法值 → 撤销 → 重置 → 导出 CSV。
 * 只验证 JS 运行时与 DOM 接线，不替代真实浏览器的视觉/布局验收。
 */

const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const assert = require("node:assert/strict");

const ROOT = path.join(__dirname, "..");
const html = fs.readFileSync(path.join(ROOT, "index.html"), "utf8");
const RentCore = require(path.join(ROOT, "rent-core.js"));

let passed = 0;
let failed = 0;
const failures = [];

function test(name, fn) {
  try {
    fn();
    passed += 1;
    console.log("PASS  " + name);
  } catch (error) {
    failed += 1;
    failures.push(name);
    console.error("FAIL  " + name);
    console.error(String(error && error.stack ? error.stack : error).replace(/^/gm, "      "));
  }
}

// ---------------------------------------------------------------------------
// 最小 DOM 桩：只覆盖 index.html 实际用到的接口
// ---------------------------------------------------------------------------

class El {
  constructor(id, tag, attrs) {
    this.id = id || "";
    this.tagName = String(tag || "div").toUpperCase();
    this.attributes = attrs || {};
    this.value = Object.prototype.hasOwnProperty.call(this.attributes, "value")
      ? String(this.attributes.value)
      : "";
    this.textContent = "";
    this.innerHTML = "";
    this.hidden = Object.prototype.hasOwnProperty.call(this.attributes, "hidden");
    this.className = this.attributes.class || "";
    this.style = {};
    this.listeners = {};
    this.children = [];
    this.parentNode = null;
    this.removed = false;
    this.clicked = false;
    this.focused = false;
    this.selected = false;
  }

  get value() {
    return this._value === undefined || this._value === null ? "" : String(this._value);
  }

  set value(next) {
    this._value = next === undefined || next === null ? "" : String(next);
  }

  setAttribute(name, value) {
    this.attributes[name] = String(value);
    if (name === "value") this.value = String(value);
  }

  removeAttribute(name) {
    delete this.attributes[name];
  }

  addEventListener(type, handler) {
    if (!this.listeners[type]) this.listeners[type] = [];
    this.listeners[type].push(handler);
  }

  dispatch(type, event) {
    const merged = Object.assign(
      {
        type,
        target: this,
        currentTarget: this,
        preventDefault() {},
        stopPropagation() {}
      },
      event || {}
    );
    (this.listeners[type] || []).forEach((handler) => handler(merged));
  }

  focus() { this.focused = true; }
  select() { this.selected = true; }

  appendChild(child) {
    child.parentNode = this;
    this.children.push(child);
  }

  remove() {
    this.removed = true;
    if (this.parentNode) {
      this.parentNode.children = this.parentNode.children.filter((item) => item !== this);
      this.parentNode = null;
    }
  }

  click() {
    this.clicked = true;
    this.dispatch("click");
  }
}

const elements = new Map();
const idRegex = /<([a-zA-Z][a-zA-Z0-9-]*)\b([^>]*\bid="([^"]+)"[^>]*)>/g;
let match;
while ((match = idRegex.exec(html)) !== null) {
  const tag = match[1];
  const attrsText = match[2];
  const id = match[3];
  const attrs = {};
  const attrRegex = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*"([^"]*)"/g;
  let attrMatch;
  while ((attrMatch = attrRegex.exec(attrsText)) !== null) {
    attrs[attrMatch[1]] = attrMatch[2];
  }
  if (/\bhidden\b/.test(attrsText.replace(/=\s*"[^"]*"/g, ""))) {
    attrs.hidden = "";
  }
  elements.set(id, new El(id, tag, attrs));
}

// 内嵌 spec JSON 的内容需要作为 textContent 提供
const specMatch = html.match(/<script type="application\/json" id="spec-data">([\s\S]*?)<\/script>/);
assert.ok(specMatch, "index.html 缺少 spec-data");
elements.get("spec-data").textContent = specMatch[1];

const body = new El("", "body", {});
const createdLinks = [];
const blobs = [];

const document = {
  body,
  getElementById(id) {
    return elements.get(id) || null;
  },
  createElement(tag) {
    const el = new El("", tag, {});
    if (String(tag).toLowerCase() === "a") createdLinks.push(el);
    return el;
  }
};

class BlobStub {
  constructor(parts, options) {
    this.parts = parts || [];
    this.type = options && options.type;
    this.text = this.parts.join("");
    blobs.push(this);
  }
}

const urlStub = {
  createObjectURL(blob) {
    return "blob:d43-" + blobs.length;
  },
  revokeObjectURL() {}
};

const sandbox = {
  document,
  Blob: BlobStub,
  URL: urlStub,
  setTimeout(fn) {
    fn();
    return 0;
  },
  clearTimeout() {},
  console
};
sandbox.RentCore = RentCore;
vm.createContext(sandbox);

const mainScriptMatch = html.match(/<script>\s*([\s\S]*?)<\/script>\s*<\/body>/);
assert.ok(mainScriptMatch, "未能提取主脚本");

const id = (name) => elements.get(name);
const dispatchInput = (name, value) => {
  const el = id(name);
  el.value = String(value);
  el.dispatch("input");
};

let initError = null;
try {
  vm.runInContext(mainScriptMatch[1], sandbox, { filename: "index-inline.js" });
} catch (error) {
  initError = error;
}

// ---------------------------------------------------------------------------
// 初始渲染
// ---------------------------------------------------------------------------

test("内联脚本执行无异常，未落入致命错误页", () => {
  assert.equal(initError, null, "初始化抛出异常：" + (initError && initError.message));
  assert.equal(id("fatal").hidden, true, "页面显示致命错误：" + id("fatal").textContent);
});

test("默认结论：B ¥31,200、排名 2/3、待补 1 项、首期最低 A ¥6,300", () => {
  assert.equal(id("stat-cheapest").textContent, "¥31,200");
  assert.equal(id("stat-ranked").textContent, "2 / 3");
  assert.equal(id("stat-pending").textContent, "1 项");
  assert.equal(id("stat-cash").textContent, "¥6,300");
  assert.equal(id("supplement-badge").textContent, "1 项待补");
});

test("默认表格：A/B 有名次，C 年成本与名次为待补/未参与", () => {
  const table = id("compare-body").innerHTML;
  assert.ok(table.includes("青禾公寓"));
  assert.ok(table.includes("白桥小屋"));
  assert.ok(table.includes("河畔居"));
  assert.ok(table.includes("¥35,400"));
  assert.ok(table.includes("¥31,200"));
  assert.ok(table.includes("第 1 名"));
  assert.ok(table.includes("未参与综合排名"));
  assert.ok(table.includes("服务费 <span class=\"pending-text\">待补</span>"));
});

test("默认权重公式与归一化明细已渲染", () => {
  const formula = id("weight-formula").innerHTML;
  assert.ok(formula.includes("0.400"));
  assert.ok(formula.includes("0.300"));
  assert.ok(formula.includes("100 ×"));
  const detail = id("score-cards").innerHTML;
  assert.ok(detail.includes("70.0"));
  assert.ok(detail.includes("30.0"));
  assert.ok(detail.includes("综合分 = 100 ×"));
  assert.equal(id("detail-empty").hidden, true);
});

test("默认待补横幅与补齐面板文案正确", () => {
  assert.equal(id("missing-banner").hidden, false);
  assert.ok(id("missing-banner").innerHTML.includes("去补齐"));
  assert.ok(id("supplement-lede").textContent.includes("不会把缺失值当作 0"));
  assert.ok(id("supplement-state").textContent.includes("待补"));
});

// ---------------------------------------------------------------------------
// 权重交互
// ---------------------------------------------------------------------------

test("权重 0 / 100 / 0：A 得 100 分且 C 仍不参与", () => {
  dispatchInput("weight-cost", 0);
  dispatchInput("weight-commute", 100);
  dispatchInput("weight-area", 0);

  assert.equal(id("weight-error").textContent, "");
  assert.ok(id("score-cards").innerHTML.includes("100.0"));
  assert.equal(id("stat-ranked").textContent, "2 / 3");
  assert.ok(id("compare-body").innerHTML.includes("未参与综合排名"));
});

test("权重全为 0：显示错误并暂停综合排名，不崩溃", () => {
  dispatchInput("weight-cost", 0);
  dispatchInput("weight-commute", 0);
  dispatchInput("weight-area", 0);

  assert.ok(id("weight-error").textContent.includes("大于 0"));
  assert.equal(id("stat-ranked").textContent, "暂停");
  assert.ok(id("weight-formula").innerHTML.includes("权重未就绪"));
  assert.ok(id("compare-body").innerHTML.includes("权重待修正"));
  assert.ok(id("detail-empty").textContent.includes("权重输入有误"));
});

test("权重留空：提示空值错误而不是静默按 0", () => {
  id("weight-commute").value = "";
  id("weight-commute").dispatch("input");

  assert.ok(id("weight-error").textContent.includes("通勤时间权重不能为空"));
  assert.equal(id("weight-commute").attributes["aria-invalid"], "true");
  assert.equal(id("stat-ranked").textContent, "暂停");
});

test("重置恢复默认权重与 C 待补状态", () => {
  id("reset-btn").dispatch("click");

  assert.equal(id("weight-cost").value, "40");
  assert.equal(id("weight-commute").value, "30");
  assert.equal(id("weight-area").value, "30");
  assert.equal(id("weight-error").textContent, "");
  assert.equal(id("stat-ranked").textContent, "2 / 3");
  assert.equal(id("supplement-input").value, "");
  assert.ok(id("supplement-state").textContent.includes("待补"));
  assert.equal(id("supplement-undo").hidden, true);
});

// ---------------------------------------------------------------------------
// 补齐交互
// ---------------------------------------------------------------------------

test("补填空值被拦截，C 仍待补", () => {
  id("supplement-input").value = "";
  id("supplement-form").dispatch("submit");

  assert.ok(id("supplement-error").textContent.includes("不能为空"));
  assert.ok(id("supplement-error").textContent.includes("不会被当作 0"));
  assert.equal(id("supplement-input").attributes["aria-invalid"], "true");
  assert.equal(id("stat-pending").textContent, "1 项");
});

test("补齐负数被拦截，并提示负数错误", () => {
  id("supplement-input").value = "-5";
  id("supplement-form").dispatch("submit");

  assert.ok(id("supplement-error").textContent.includes("不能为负数"));
  assert.equal(id("stat-ranked").textContent, "2 / 3");
});

test("补齐 150：C 年成本 ¥38,100、首期 ¥6,450、综合第 3", () => {
  id("supplement-input").value = "150";
  id("supplement-form").dispatch("submit");

  assert.equal(id("supplement-error").textContent, "");
  assert.equal(id("stat-ranked").textContent, "3 / 3");
  assert.equal(id("stat-cheapest").textContent, "¥31,200");
  assert.equal(id("stat-pending").textContent, "0 项");
  assert.equal(id("supplement-badge").textContent, "费用已齐全");
  assert.equal(id("supplement-undo").hidden, false);

  const table = id("compare-body").innerHTML;
  assert.ok(table.includes("¥38,100"));
  assert.ok(table.includes("¥6,450"));
  assert.ok(table.includes("服务费已补齐"));
  assert.ok(table.includes("第 3 名"));

  const detail = id("score-cards").innerHTML;
  assert.ok(detail.includes("48.2"));
  assert.ok(detail.includes("70.0"));
  assert.ok(id("supplement-state").textContent.includes("用户补齐"));
});

test("修改 C 为 0 可更新，并按明确 0 计算", () => {
  id("supplement-input").value = "0";
  id("supplement-form").dispatch("submit");

  assert.equal(id("stat-ranked").textContent, "3 / 3");
  assert.ok(id("compare-body").innerHTML.includes("¥36,300"));
  assert.equal(id("supplement-error").textContent, "");
});

test("撤销补齐：C 回到待补，不保留 0", () => {
  id("supplement-undo").dispatch("click");

  assert.equal(id("supplement-input").value, "");
  assert.equal(id("stat-ranked").textContent, "2 / 3");
  assert.equal(id("stat-pending").textContent, "1 项");
  assert.equal(id("supplement-badge").textContent, "1 项待补");
  assert.ok(id("supplement-state").textContent.includes("待补"));
  assert.ok(id("compare-body").innerHTML.includes("未参与综合排名"));
});

// ---------------------------------------------------------------------------
// 导出
// ---------------------------------------------------------------------------

test("导出 CSV：Blob 带 BOM、待补标记与下载文件名", () => {
  id("export-btn").dispatch("click");

  assert.ok(blobs.length >= 1, "未创建 Blob");
  const blob = blobs[blobs.length - 1];
  assert.equal(blob.type, "text/csv;charset=utf-8");
  assert.equal(blob.text.charCodeAt(0), 0xfeff, "缺少 BOM");
  assert.ok(blob.text.includes("待补"));
  assert.ok(blob.text.includes("年度消费成本(元)"));

  const link = createdLinks[createdLinks.length - 1];
  assert.ok(link, "未创建下载链接");
  assert.ok(/^d43-rent-comparison-\d{8}-\d{4}\.csv$/.test(link.download), "文件名异常：" + link.download);
  assert.equal(link.clicked, true);
  assert.equal(link.removed, true);
});

// ---------------------------------------------------------------------------
// 汇总
// ---------------------------------------------------------------------------

console.log("");
console.log("==================================================");
console.log("交互冒烟：" + passed + " 通过，" + failed + " 失败，共 " + (passed + failed) + " 项");
console.log("==================================================");

if (failed > 0) {
  console.error("失败项：" + failures.join("；"));
  process.exit(1);
}