// Adds a highlight to the currently hovered / focused / clicked element
export async function installElementHighlighter(
  page: import("@playwright/test").Page
) {
  await page.addInitScript(() => {
    type PWWindow = Window & { __pw_highlighter_installed__?: boolean };
    const w = window as unknown as PWWindow;
    if (w.__pw_highlighter_installed__) return;
    w.__pw_highlighter_installed__ = true;

    const style = document.createElement("style");
    style.innerHTML = `
      .__pw-highlight__ {
        outline: 3px solid #ff1744 !important; /* kräftiges Rot */
        outline-offset: 2px !important;
        box-shadow: 0 0 0 2px rgba(255, 23, 68, 0.25) !important; /* leichte Aura */
        transition: box-shadow 80ms ease-out;
      }
      .__pw-highlight-click__ {
        outline: 4px solid #e0002b !important; /* noch stärkeres Rot beim Klick */
        outline-offset: 2px !important;
        box-shadow: 0 0 0 3px rgba(224, 0, 43, 0.35) !important;
      }
      /* Ganze Tabellenzeile hervorheben */
      .__pw-highlight-row__ * {
        outline: 2px dashed rgba(255, 23, 68, 0.8) !important;
        outline-offset: 1px !important;
      }
    `;
    document.head.appendChild(style);

    let lastEl: Element | null = null;
    let lastRow: Element | null = null;
    function mark(el: EventTarget | null) {
      if (!(el instanceof Element)) return;
      if (lastEl === el) return;
      if (lastEl) lastEl.classList.remove("__pw-highlight__");
      lastEl = el;
      lastEl.classList.add("__pw-highlight__");

      // Tabellenzeile (tr oder role="row") komplett markieren
      const row = (el.closest &&
        (el.closest("tr") || el.closest('[role="row"]'))) as Element | null;
      if (lastRow && lastRow !== row)
        lastRow.classList.remove("__pw-highlight-row__");
      if (row) {
        row.classList.add("__pw-highlight-row__");
        lastRow = row;
      }
    }

    let clickTimeout: number | undefined;

    window.addEventListener("mouseover", (e) => mark(e.target), true);
    window.addEventListener("focus", (e) => mark(e.target), true);
    window.addEventListener(
      "click",
      (e) => {
        mark(e.target);
        if (lastEl instanceof Element) {
          lastEl.classList.add("__pw-highlight-click__");
          if (clickTimeout) window.clearTimeout(clickTimeout);
          const el = lastEl;
          clickTimeout = window.setTimeout(() => {
            el.classList.remove("__pw-highlight-click__");
          }, 600);
        }
      },
      true
    );
  });
}
