"use client";
var s;
(function(a) {
  a[a.Marker = 0] = "Marker", a[a.Element = 1] = "Element";
})(s || (s = {}));
const c = { type: s.Marker };
class m {
  constructor(e) {
    this.treeAdapter = e, this.entries = [], this.bookmark = null;
  }
  //Noah Ark's condition
  //OPTIMIZATION: at first we try to find possible candidates for exclusion using
  //lightweight heuristics without thorough attributes check.
  _getNoahArkConditionCandidates(e, t) {
    const n = [], l = t.length, h = this.treeAdapter.getTagName(e), i = this.treeAdapter.getNamespaceURI(e);
    for (let r = 0; r < this.entries.length; r++) {
      const o = this.entries[r];
      if (o.type === s.Marker)
        break;
      const { element: d } = o;
      if (this.treeAdapter.getTagName(d) === h && this.treeAdapter.getNamespaceURI(d) === i) {
        const A = this.treeAdapter.getAttrList(d);
        A.length === l && n.push({ idx: r, attrs: A });
      }
    }
    return n;
  }
  _ensureNoahArkCondition(e) {
    if (this.entries.length < 3)
      return;
    const t = this.treeAdapter.getAttrList(e), n = this._getNoahArkConditionCandidates(e, t);
    if (n.length < 3)
      return;
    const l = new Map(t.map((i) => [i.name, i.value]));
    let h = 0;
    for (let i = 0; i < n.length; i++) {
      const r = n[i];
      r.attrs.every((o) => l.get(o.name) === o.value) && (h += 1, h >= 3 && this.entries.splice(r.idx, 1));
    }
  }
  //Mutations
  insertMarker() {
    this.entries.unshift(c);
  }
  pushElement(e, t) {
    this._ensureNoahArkCondition(e), this.entries.unshift({
      type: s.Element,
      element: e,
      token: t
    });
  }
  insertElementAfterBookmark(e, t) {
    const n = this.entries.indexOf(this.bookmark);
    this.entries.splice(n, 0, {
      type: s.Element,
      element: e,
      token: t
    });
  }
  removeEntry(e) {
    const t = this.entries.indexOf(e);
    t !== -1 && this.entries.splice(t, 1);
  }
  /**
   * Clears the list of formatting elements up to the last marker.
   *
   * @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker
   */
  clearToLastMarker() {
    const e = this.entries.indexOf(c);
    e === -1 ? this.entries.length = 0 : this.entries.splice(0, e + 1);
  }
  //Search
  getElementEntryInScopeWithTagName(e) {
    const t = this.entries.find((n) => n.type === s.Marker || this.treeAdapter.getTagName(n.element) === e);
    return t && t.type === s.Element ? t : null;
  }
  getElementEntry(e) {
    return this.entries.find((t) => t.type === s.Element && t.element === e);
  }
}
export {
  s as EntryType,
  m as FormattingElementList
};
