/**
 * dom-lite.js — 极简 DOM 模拟器（仅用于自检，不参与页面运行）
 * ---------------------------------------------------------------------------
 * 目的：在 **不启动浏览器、不控制 GUI** 的前提下，用 Node 真实执行 index.html 内的
 * 交互脚本，验证"改参数即时重算 / 表格-图联动 / 导出 CSV 与说明"等运行时行为。
 *
 * 能力范围（够用即可，不追求完整 HTML 规范）：
 *   - 解析 index.html 的标签、属性、文本与嵌套结构
 *   - getElementById / querySelector(All) / closest / classList / dataset
 *   - innerHTML 赋值时重新解析子树（用于表格行、SVG 柱组等动态内容）
 *   - 捕获 Blob 下载（记录文件名与内容），便于断言导出结果
 *
 * 依赖：Node 内置 vm 模块。运行时无需任何第三方包。
 */
'use strict';

var vm = require('vm');

var VOID_TAGS = { br: 1, hr: 1, img: 1, input: 1, meta: 1, link: 1, source: 1, area: 1, base: 1, col: 1, embed: 1, param: 1, track: 1, wbr: 1 };

/* ----------------------------- 选择器解析 ----------------------------- */

function parseSimpleSelector(sel) {
  var out = { tag: null, id: null, classes: [], attrs: [] };
  var re = /([.#]?)([A-Za-z0-9_-]+)|\[([A-Za-z0-9_-]+)(?:=["']?([^\]"']*)["']?)?\]/g;
  var m;
  while ((m = re.exec(sel))) {
    if (m[3]) { out.attrs.push([m[3], m[4] === undefined ? '' : m[4]]); }
    else if (m[1] === '.') out.classes.push(m[2]);
    else if (m[1] === '#') out.id = m[2];
    else out.tag = m[2].toUpperCase();
  }
  return out;
}

function matchesSimple(node, simple) {
  if (!node || node.nodeType !== 1) return false;
  if (simple.tag && node.tagName !== simple.tag) return false;
  if (simple.id && node.getAttribute('id') !== simple.id) return false;
  for (var i = 0; i < simple.classes.length; i++) {
    if (!node.classList.contains(simple.classes[i])) return false;
  }
  for (var j = 0; j < simple.attrs.length; j++) {
    if (node.getAttribute(simple.attrs[j][0]) !== simple.attrs[j][1]) return false;
  }
  return true;
}

function ancestors(node) {
  var list = [];
  var p = node.parentNode;
  while (p) { list.push(p); p = p.parentNode; }
  return list;
}

function matchesSelector(node, selector) {
  var parts = selector.trim().split(/\s+/);
  var last = parseSimpleSelector(parts.pop());
  if (!matchesSimple(node, last)) return false;
  var anc = ancestors(node);
  for (var i = parts.length - 1; i >= 0; i--) {
    var simple = parseSimpleSelector(parts[i]);
    var found = false;
    for (var j = 0; j < anc.length; j++) {
      if (matchesSimple(anc[j], simple)) { found = true; anc = anc.slice(j); break; }
    }
    if (!found) return false;
  }
  return true;
}

/* ----------------------------- 元素实现 ----------------------------- */

function createClassList(el) {
  function classes() {
    var raw = el.getAttribute('class') || '';
    return raw.split(/\s+/).filter(function (c) { return c; });
  }
  function write(list) { el.setAttribute('class', list.join(' ')); }
  return {
    contains: function (c) { return classes().indexOf(c) >= 0; },
    add: function (c) { var l = classes(); if (l.indexOf(c) < 0) { l.push(c); write(l); } },
    remove: function (c) { write(classes().filter(function (x) { return x !== c; })); },
    toggle: function (c, force) {
      var has = this.contains(c);
      var want = force === undefined ? !has : !!force;
      if (want) this.add(c); else this.remove(c);
      return want;
    },
    get length() { return classes().length; },
    toString: function () { return classes().join(' '); }
  };
}

function El(tag, attrs, doc) {
  this.nodeType = 1;
  this.tagName = String(tag).toUpperCase();
  this.attrs = attrs || {};
  this.childNodes = [];
  this.parentNode = null;
  // 浏览器语义：input 的 value 初始来自 value 属性，且赋值为字符串
  this._value = this.attrs.value !== undefined ? String(this.attrs.value) : '';
  this._innerHTML = '';
  this._textContent = '';
  this.listeners = {};
  this.classList = createClassList(this);
  this._doc = doc;
  this.scrollTop = 0;
}

// 浏览器语义：a.href / a.download 是"属性式"属性，赋值即写入 attribute
['href', 'download', 'type', 'name', 'id'].forEach(function (prop) {
  Object.defineProperty(El.prototype, prop, {
    get: function () { return this.getAttribute(prop) || ''; },
    set: function (v) { this.setAttribute(prop, v); },
    configurable: true
  });
});

Object.defineProperty(El.prototype, 'value', {
  get: function () { return this._value; },
  set: function (v) { this._value = v === null || v === undefined ? '' : String(v); }
});

Object.defineProperty(El.prototype, 'innerHTML', {
  get: function () { return this._innerHTML; },
  set: function (v) {
    this._innerHTML = String(v);
    this.childNodes = [];
    var doc = this._doc;
    parseInto(String(v), this, doc);
  }
});

Object.defineProperty(El.prototype, 'textContent', {
  get: function () { return this._textContent; },
  set: function (v) { this._textContent = String(v); }
});

Object.defineProperty(El.prototype, 'children', {
  get: function () { return this.childNodes.filter(function (c) { return c.nodeType === 1; }); }
});

Object.defineProperty(El.prototype, 'firstChild', {
  get: function () { return this.childNodes[0] || null; }
});

El.prototype.getAttribute = function (name) {
  var v = this.attrs[name];
  return v === undefined ? null : v;
};
El.prototype.setAttribute = function (name, value) { this.attrs[name] = String(value); };
El.prototype.removeAttribute = function (name) { delete this.attrs[name]; };
El.prototype.hasAttribute = function (name) { return this.attrs[name] !== undefined; };

El.prototype.appendChild = function (child) {
  child.parentNode = this;
  this.childNodes.push(child);
  if (child.getAttribute && child.getAttribute('id')) this._doc.register(child);
  return child;
};
El.prototype.removeChild = function (child) {
  var i = this.childNodes.indexOf(child);
  if (i >= 0) this.childNodes.splice(i, 1);
  child.parentNode = null;
  return child;
};
El.prototype.insertAdjacentHTML = function (pos, html) {
  this.innerHTML = this.innerHTML + html;
};
El.prototype.addEventListener = function (type, fn) {
  (this.listeners[type] = this.listeners[type] || []).push(fn);
};
El.prototype.removeEventListener = function (type, fn) {
  var l = this.listeners[type] || [];
  var i = l.indexOf(fn);
  if (i >= 0) l.splice(i, 1);
};
El.prototype.dispatch = function (type, event) {
  var ev = event || {};
  ev.type = type;
  ev.preventDefault = ev.preventDefault || function () {};
  ev.stopPropagation = ev.stopPropagation || function () {};
  ev.target = ev.target || this;
  // 浏览器语义：事件沿父链冒泡
  var node = this;
  while (node) {
    (node.listeners[type] || []).forEach(function (fn) { fn.call(node, ev); });
    if (ev._stopped) break;
    node = node.parentNode;
  }
  return ev;
};
El.prototype.click = function () {
  this._doc._recordDownload(this);
  return this.dispatch('click', { target: this });
};
El.prototype.focus = function () { this._doc.activeElement = this; };
El.prototype.select = function () {};
El.prototype.querySelector = function (sel) {
  var all = this.querySelectorAll(sel);
  return all.length ? all[0] : null;
};
// 在本节点子树内查找（浏览器语义：只看后代，不含自身）
El.prototype.querySelectorAll = function (sel) {
  var out = [];
  var walk = function (node) {
    node.childNodes.forEach(function (c) {
      if (c.nodeType !== 1) return;
      if (matchesSelector(c, sel)) out.push(c);
      walk(c);
    });
  };
  walk(this);
  return out;
};
El.prototype.closest = function (sel) {
  var cur = this;
  while (cur && cur.nodeType === 1) {
    if (matchesSelector(cur, sel)) return cur;
    cur = cur.parentNode;
  }
  return null;
};
El.prototype.matches = function (sel) { return matchesSelector(this, sel); };

/* ----------------------------- 解析器 ----------------------------- */

function parseAttrs(raw) {
  var attrs = {};
  var re = /([A-Za-z0-9_:.-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
  var m;
  while ((m = re.exec(raw || ''))) {
    var name = m[1];
    var val = m[2] !== undefined ? m[2] : (m[3] !== undefined ? m[3] : (m[4] !== undefined ? m[4] : ''));
    attrs[name] = val;
  }
  return attrs;
}

function parseInto(html, root, doc) {
  var stack = [root];
  var re = /<!--[\s\S]*?-->|<!DOCTYPE[^>]*>|<\/([A-Za-z][\w:-]*)\s*>|<([A-Za-z][\w:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/g;
  var m;
  while ((m = re.exec(html))) {
    if (m[0].indexOf('<!--') === 0 || m[0].toUpperCase().indexOf('<!DOCTYPE') === 0) continue;
    if (m[1]) { // closing tag
      for (var i = stack.length - 1; i > 0; i--) {
        if (stack[i].tagName === m[1].toUpperCase()) { stack.length = i; break; }
      }
      continue;
    }
    var tag = m[2];
    var attrs = parseAttrs(m[3]);
    var el = doc.createElement(tag, attrs);
    var parent = stack[stack.length - 1];
    parent.appendChild(el);
    if (!m[4] && !VOID_TAGS[tag.toLowerCase()]) stack.push(el);
  }
  return root;
}

/* ----------------------------- 文档 / 窗口 ----------------------------- */

function createDocument(html) {
  var doc = {
    readyState: 'complete',
    activeElement: null,
    allNodes: [],
    downloads: [],
    _blobs: {},
    _blobSeq: 0
  };

  doc.createElement = function (tag, attrs) {
    var el = new El(tag, attrs, doc);
    doc.allNodes.push(el);
    if (attrs && attrs.id) doc.byId[attrs.id] = el;
    return el;
  };

  doc.byId = {};

  doc.register = function (el) {
    var id = el.getAttribute('id');
    if (id && !doc.byId[id]) doc.byId[id] = el;
  };

  doc._recordDownload = function (a) {
    var href = a.getAttribute('href') || '';
    if (href.indexOf('blob:') === 0) {
      doc.downloads.push({ filename: a.getAttribute('download') || '', content: doc._blobs[href] || '' });
    }
  };

  doc.getElementById = function (id) { return doc.byId[id] || null; };

  doc.querySelector = function (sel) {
    var all = doc.querySelectorAll(sel);
    return all.length ? all[0] : null;
  };

  doc.querySelectorAll = function (sel) {
    var out = [];
    var roots = [doc.body].concat(doc.detachedRoots || []);
    roots.forEach(function (r) {
      if (matchesSelector(r, sel)) out.push(r);
      r.childNodes.forEach(function (c) {
        if (c.nodeType !== 1) return;
        out = out.concat(c.querySelectorAll ? c.querySelectorAll(sel) : []);
      });
    });
    return out;
  };

  doc.addEventListener = function () {};
  doc.removeEventListener = function () {};
  doc.execCommand = function () { return true; };

  // 解析整页
  var root = doc.createElement('#root', {});
  parseInto(html, root, doc);

  // 用真实 <body> 节点替换占位 body，使 doc.querySelectorAll 能覆盖整页
  var realBody = null;
  (function findBody(node) {
    if (realBody) return;
    node.childNodes.forEach(function (c) {
      if (realBody || c.nodeType !== 1) return;
      if (c.tagName === 'BODY') { realBody = c; return; }
      findBody(c);
    });
  })(root);
  if (realBody) {
    realBody.parentNode = null;
    doc.body = realBody;
  }

  return doc;
}

/**
 * 在沙箱中执行 index.html 的内联脚本。
 * @param {string} html     index.html 全文
 * @param {object} core     energy-core.js 导出的核心对象
 * @returns {{doc:Object, window:Object, downloads:Array}}
 */
function runPage(html, core) {
  var doc = createDocument(html);

  var scripts = [];
  var re = /<script([^>]*)>([\s\S]*?)<\/script>/gi;
  var m;
  while ((m = re.exec(html))) {
    var attrs = parseAttrs(m[1]);
    if (attrs.src) continue;           // 外部脚本：模拟已加载
    scripts.push(m[2]);
  }
  if (!scripts.length) throw new Error('未找到内联脚本');

  var sandbox = {
    document: doc,
    console: console,
    Blob: function Blob(parts, opts) {
      this.parts = parts || [];
      this.type = (opts && opts.type) || '';
      this.text = function () { return this.parts.join(''); };
    },
    URL: {
      createObjectURL: function (blob) {
        var id = 'blob:' + (++doc._blobSeq);
        doc._blobs[id] = typeof blob.text === 'function' ? blob.text() : String(blob);
        return id;
      },
      revokeObjectURL: function () {}
    },
    setTimeout: function (fn) { return 0; },
    clearTimeout: function () {},
    Math: Math, JSON: JSON, Date: Date, Object: Object, Array: Array, String: String,
    Number: Number, isFinite: isFinite, isNaN: isNaN, parseFloat: parseFloat, parseInt: parseInt,
    Error: Error, RegExp: RegExp, encodeURIComponent: encodeURIComponent
  };
  sandbox.window = sandbox;
  sandbox.self = sandbox;
  sandbox.globalThis = sandbox;
  sandbox.EnergyCore = core;
  sandbox.navigator = { clipboard: null };  // 走 execCommand 兜底分支

  var ctx = vm.createContext(sandbox);
  scripts.forEach(function (code) {
    vm.runInContext(code, ctx, { filename: 'index.html#inline' });
  });

  sandbox.print = function () { sandbox.__printed = true; };

  return { doc: doc, window: sandbox, downloads: doc.downloads };
}

module.exports = { createDocument: createDocument, runPage: runPage, El: El };
