import * as echarts from "echarts"

const tooltipCssText = [
  "z-index:2147483647!important",
  "pointer-events:none",
].join(";")

let installed = false

export function installEchartsTooltipGuard() {
  if (installed) return
  installed = true

  echarts.registerPreprocessor((option) => {
    normalizeTooltips(option)
  })
}

function normalizeTooltips(target, seen = new WeakSet()) {
  if (!target || typeof target !== "object") return
  if (seen.has(target)) return
  seen.add(target)

  if (Array.isArray(target)) {
    target.forEach((item) => normalizeTooltips(item, seen))
    return
  }

  if (target.tooltip && typeof target.tooltip === "object") {
    target.tooltip = normalizeTooltip(target.tooltip)
  }

  Object.keys(target).forEach((key) => {
    const value = target[key]
    if (!value || typeof value !== "object") return
    normalizeTooltips(value, seen)
  })
}

function normalizeTooltip(tooltip) {
  return {
    ...tooltip,
    appendToBody: tooltip.appendToBody ?? true,
    confine: tooltip.confine ?? false,
    extraCssText: mergeCssText(tooltip.extraCssText),
  }
}

function mergeCssText(cssText = "") {
  const trimmed = String(cssText || "").trim()
  if (!trimmed) return tooltipCssText
  if (/z-index\s*:/i.test(trimmed)) return trimmed
  return `${trimmed.replace(/;$/, "")};${tooltipCssText}`
}
