/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck

export function createAtTooltip() {
  class AtTooltip {
    constructor() {
      this._panels = [];
      this._mouseHandler = null;
      this._keyHandler = null;
      this._repositionHandler = null;
    }

    open(anchorEl, builderFn, tag) {
      if (this.isOpenFor(tag)) {
        this.close();
        return;
      }
      this.close();
      const panelEntry = this._createPanelEntry({
        anchorEl,
        builderFn,
        mode: "anchor",
        point: null,
        rootTag: tag || null,
        tag: tag || null,
        parentIndex: -1,
      });
      this._panels = [panelEntry];
      this._positionAll();
      this._wireCloseHandlers();
      this._focusPanelSoon(panelEntry.panel);
    }

    openAtPoint(clientX, clientY, builderFn, tag) {
      if (this.isOpenFor(tag)) {
        this.close();
        return;
      }
      this.close();
      const panelEntry = this._createPanelEntry({
        anchorEl: null,
        builderFn,
        mode: "point",
        point: {
          x: Number(clientX) || 0,
          y: Number(clientY) || 0,
        },
        rootTag: tag || null,
        tag: tag || null,
        parentIndex: -1,
      });
      this._panels = [panelEntry];
      this._positionAll();
      this._wireCloseHandlers();
      this._focusPanelSoon(panelEntry.panel);
    }

    openChild(anchorEl, builderFn, tag) {
      if (!anchorEl) {
        return false;
      }
      const parentIndex = this._findOwningPanelIndex(anchorEl);
      if (parentIndex < 0) {
        return false;
      }
      const parentEntry = this._panels[parentIndex] || null;
      if (!parentEntry) {
        return false;
      }
      const normalizedTag = tag || null;
      const existingChild = this._panels[parentIndex + 1] || null;
      if (
        existingChild
        && existingChild.parentIndex === parentIndex
        && existingChild.anchorEl === anchorEl
        && existingChild.tag === normalizedTag
      ) {
        this._positionAll();
        return true;
      }
      this._closeFromIndex(parentIndex + 1);
      const panelEntry = this._createPanelEntry({
        anchorEl,
        builderFn,
        mode: "submenu",
        point: null,
        rootTag: parentEntry.rootTag,
        tag: normalizedTag,
        parentIndex,
      });
      this._panels.push(panelEntry);
      this._positionAll();
      return true;
    }

    closeChildren(anchorEl) {
      if (!anchorEl) {
        return false;
      }
      const parentIndex = this._findOwningPanelIndex(anchorEl);
      if (parentIndex < 0) {
        return false;
      }
      this._closeFromIndex(parentIndex + 1);
      return true;
    }

    _createPanelEntry(config) {
      const panel = document.createElement("div");
      panel.className = "at-tooltip-panel" + (config.mode === "submenu" ? " is-submenu" : "");
      panel.tabIndex = -1;
      panel.setAttribute("role", "menu");
      config.builderFn(panel);
      document.body.appendChild(panel);
      return {
        panel,
        anchorEl: config.anchorEl || null,
        point: config.point || null,
        rootTag: config.rootTag || null,
        tag: config.tag || null,
        mode: config.mode || "anchor",
        parentIndex: Number(config.parentIndex),
      };
    }

    _focusPanelSoon(panel) {
      setTimeout(() => {
        if (this._panels.some((entry) => entry.panel === panel)) {
          panel.focus();
        }
      }, 0);
    }

    _findOwningPanelIndex(element) {
      return this._panels.findIndex((entry) => (
        entry.panel === element
        || (entry.panel && typeof entry.panel.contains === "function" && entry.panel.contains(element))
      ));
    }

    _wireCloseHandlers() {
      if (this._mouseHandler || this._keyHandler || this._repositionHandler) {
        return;
      }
      this._mouseHandler = (event) => {
        const target = event.target;
        const clickedOpenPanel = this._panels.some((entry) => entry.panel?.contains?.(target));
        const clickedAnchor = this._panels.some((entry) => (
          entry.anchorEl
          && (target === entry.anchorEl || entry.anchorEl.contains?.(target))
        ));
        if (!clickedOpenPanel && !clickedAnchor) {
          this.close();
        }
      };
      this._keyHandler = (event) => {
        if (event.key === "Escape") {
          this.close();
        }
      };
      this._repositionHandler = () => {
        this._positionAll();
      };
      setTimeout(() => {
        document.addEventListener("mousedown", this._mouseHandler, { capture: true });
        document.addEventListener("keydown", this._keyHandler);
        document.addEventListener("scroll", this._repositionHandler, { capture: true, passive: true });
        window.addEventListener("resize", this._repositionHandler);
      }, 0);
    }

    _closeFromIndex(startIndex) {
      while (this._panels.length > startIndex) {
        const entry = this._panels.pop();
        if (entry?.panel?.parentNode) {
          entry.panel.parentNode.removeChild(entry.panel);
        }
      }
      if (this._panels.length <= 0) {
        this._teardownHandlers();
      }
    }

    _teardownHandlers() {
      if (this._mouseHandler) {
        document.removeEventListener("mousedown", this._mouseHandler, { capture: true });
        this._mouseHandler = null;
      }
      if (this._keyHandler) {
        document.removeEventListener("keydown", this._keyHandler);
        this._keyHandler = null;
      }
      if (this._repositionHandler) {
        document.removeEventListener("scroll", this._repositionHandler, { capture: true });
        window.removeEventListener("resize", this._repositionHandler);
        this._repositionHandler = null;
      }
    }

    _positionAll() {
      this._panels.forEach((entry, index) => {
        this._positionPanel(entry, index);
      });
    }

    _positionPanel(entry) {
      if (!entry?.panel) {
        return;
      }
      const panelRect = entry.panel.getBoundingClientRect();
      const panelW = Math.max(190, Math.ceil(panelRect.width) || 230);
      const panelH = Math.max(32, Math.ceil(panelRect.height) || 32);
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      let preferredTop = 8;
      let preferredLeft = 8;

      if (entry.mode === "submenu" && entry.anchorEl) {
        const anchorRect = entry.anchorEl.getBoundingClientRect();
        preferredLeft = anchorRect.right + 6;
        preferredTop = anchorRect.top - 6;
        if (preferredLeft + panelW > vw - 8) {
          preferredLeft = anchorRect.left - panelW - 6;
        }
      } else if (entry.anchorEl) {
        const anchorRect = entry.anchorEl.getBoundingClientRect();
        preferredLeft = anchorRect.left;
        preferredTop = anchorRect.bottom + 6;
        if (preferredTop + panelH > vh - 8) {
          preferredTop = anchorRect.top - panelH - 6;
        }
      } else if (entry.point) {
        preferredLeft = entry.point.x;
        preferredTop = entry.point.y + 6;
        if (preferredTop + panelH > vh - 8) {
          preferredTop = entry.point.y - panelH - 6;
        }
      }

      let left = preferredLeft;
      let top = preferredTop;
      if (left + panelW > vw - 8) {
        left = Math.max(8, vw - panelW - 8);
      }
      if (top + panelH > vh - 8) {
        top = Math.max(8, vh - panelH - 8);
      }
      if (top < 8) {
        top = 8;
      }
      entry.panel.style.left = `${left}px`;
      entry.panel.style.top = `${top}px`;
      entry.panel.style.maxHeight = `${Math.max(120, vh - top - 8)}px`;
    }

    close() {
      this._closeFromIndex(0);
      this._panels = [];
      this._teardownHandlers();
    }

    isOpenFor(tag) {
      if (!tag) {
        return false;
      }
      return this._panels.some((entry) => entry?.tag === tag || entry?.rootTag === tag);
    }

    makeItem(innerHtml, onClick, extraClass, options) {
      const btn = document.createElement("button");
      btn.type = "button";
      const presentationClass = String(options?.presentation || "").trim().toLowerCase() === "icon"
        ? " at-tooltip-icon-item"
        : "";
      btn.className = "at-tooltip-item" + presentationClass + (extraClass ? ` ${extraClass}` : "");
      btn.setAttribute("role", "menuitem");
      btn.innerHTML = innerHtml;
      if (options?.title) {
        btn.title = String(options.title);
      }
      if (options?.ariaLabel) {
        btn.setAttribute("aria-label", String(options.ariaLabel));
      }
      if (options && options.disabled) {
        btn.disabled = true;
      } else {
        btn.addEventListener("click", () => {
          onClick();
          this.close();
        });
      }
      return btn;
    }

    makeSubmenuItem(innerHtml, extraClass, options) {
      const btn = document.createElement("button");
      btn.type = "button";
      const presentationClass = String(options?.presentation || "").trim().toLowerCase() === "icon"
        ? " at-tooltip-icon-item"
        : "";
      btn.className = `at-tooltip-item has-submenu${presentationClass}${extraClass ? ` ${extraClass}` : ""}`;
      btn.setAttribute("role", "menuitem");
      btn.innerHTML = `${String(innerHtml || "")}<span class="at-tooltip-submenu-arrow" aria-hidden="true">›</span>`;
      if (options?.title) {
        btn.title = String(options.title);
      }
      if (options?.ariaLabel) {
        btn.setAttribute("aria-label", String(options.ariaLabel));
      }
      if (options && options.disabled) {
        btn.disabled = true;
      }
      return btn;
    }

    makeLabel(text) {
      const el = document.createElement("div");
      el.className = "at-tooltip-label";
      el.textContent = String(text || "");
      return el;
    }

    makeSeparator() {
      const el = document.createElement("div");
      el.className = "at-tooltip-separator";
      return el;
    }
  }

  return new AtTooltip();
}
