/**
 * Non-side-effect class export for `<tooltip-ui>`.
 *
 * Importing this file gives you the class(es) without auto-registering the tag.
 * Useful for test isolation, subclassing with tag-name override, or selective
 * composition.
 *
 * The auto-register path stays at `@adia-ai/web-components/components/tooltip`
 * (which imports this file + calls `defineIfFree()`).
 *
 * @see ../../USAGE.md#registration--auto-vs-explicit
 */

/**
 * <tooltip-ui text="Helpful tip" placement="top">
 *   <button-ui text="Hover me"></button-ui>
 * </tooltip-ui>
 *
 * <!-- Pointer-follow mode: used by chart-ui to show a richer card that
 *      tracks the cursor across datums. -->
 * <tooltip-ui follows="pointer" for="my-chart" indicator="dot"></tooltip-ui>
 *
 * Tooltip popup. Two modes:
 *
 * 1. `follows="trigger"` (default) — wraps children and shows on hover/focus,
 *    anchored to the trigger via @core/anchor.js + Popover API.
 * 2. `follows="pointer"` — subscribes to `chart-hover`/`chart-leave` events
 *    from `[for]`, renders a card with label + indicator + value rows, and
 *    positions at the pointer coordinates. Used by chart-ui / heatmap-ui.
 *
 * No click interaction — hover/focus only.
 */

import { UIElement } from '../../core/element.js';
import { anchorPopover } from '../../core/anchor.js';

export class UITooltip extends UIElement {
  static properties = {
    text:      { type: String,  default: '',         reflect: true },
    placement: { type: String,  default: 'top',      reflect: true },
    delay:     { type: Number,  default: 400,        reflect: true },
    follows:   { type: String,  default: 'trigger',  reflect: true },
    for:       { type: String,  default: '',         reflect: true },
    indicator: { type: String,  default: 'none',     reflect: true },
  };

  static template = () => null;

  #popover = null;
  #timer = null;
  #cleanup = null;

  /* Pointer-follow mode state */
  #target = null;
  #lastDetail = null;

  connected() {
    if (this.follows === 'pointer') {
      this.#attachPointerFollow();
    } else {
      this.addEventListener('mouseenter', this.#onEnter);
      this.addEventListener('focusin', this.#onEnter);
      this.addEventListener('mouseleave', this.#onLeave);
      this.addEventListener('focusout', this.#onLeave);
    }
  }

  disconnected() {
    this.removeEventListener('mouseenter', this.#onEnter);
    this.removeEventListener('focusin', this.#onEnter);
    this.removeEventListener('mouseleave', this.#onLeave);
    this.removeEventListener('focusout', this.#onLeave);
    this.#detachPointerFollow();
    this.#hide();
  }

  render() {
    // Trigger mode: update popover text if already showing
    if (this.#popover && this.follows !== 'pointer') {
      this.#popover.textContent = this.text;
    }
    // Pointer mode: re-paint content with current indicator if visible
    if (this.#popover && this.follows === 'pointer' && this.#lastDetail) {
      this.#paintPointerContent(this.#lastDetail);
    }
  }

  #onEnter = () => {
    if (!this.text) return;
    if (this.#timer) clearTimeout(this.#timer);
    this.#timer = setTimeout(() => this.#show(), this.delay);
  };

  #onLeave = () => {
    if (this.#timer) { clearTimeout(this.#timer); this.#timer = null; }
    this.#hide();
  };

  #show() {
    if (this.#popover) return;

    const el = document.createElement('div');
    const id = `tooltip-${Date.now()}`;
    el.id = id;
    el.setAttribute('popover', 'manual');
    el.setAttribute('role', 'tooltip');
    el.classList.add('tooltip-popup');
    el.textContent = this.text;
    document.body.appendChild(el);

    // Link trigger to tooltip for screen readers
    this.setAttribute('aria-describedby', id);

    try { el.showPopover(); } catch (_) { /* popover not supported */ }

    this.#popover = el;
    this.#cleanup = anchorPopover(this, el, { placement: this.placement, gap: 6 });
  }

  #hide() {
    if (this.#timer) { clearTimeout(this.#timer); this.#timer = null; }
    if (!this.#popover) return;

    this.removeAttribute('aria-describedby');
    this.#cleanup?.();
    this.#cleanup = null;

    try { this.#popover.hidePopover(); } catch (_) { /* popover not supported */ }
    this.#popover.remove();
    this.#popover = null;
    this.#lastDetail = null;
  }

  /* ── Pointer-follow mode (chart/heatmap integration) ─────────────── */

  #attachPointerFollow() {
    this.#detachPointerFollow();
    if (!this.for) return;

    const root = this.getRootNode();
    this.#target = (root && root.getElementById) ? root.getElementById(this.for) : document.getElementById(this.for);
    if (!this.#target) {
      // Warn once per (element, id) pair
      if (!UITooltip._warnedMissing) UITooltip._warnedMissing = new WeakSet();
      if (!UITooltip._warnedMissing.has(this)) {
        console.warn(`[tooltip-ui] follows="pointer" [for="${this.for}"] did not resolve to an element.`);
        UITooltip._warnedMissing.add(this);
      }
      return;
    }

    this.#target.addEventListener('chart-hover', this.#onChartHover);
    this.#target.addEventListener('chart-leave', this.#onChartLeave);
  }

  #detachPointerFollow() {
    if (this.#target) {
      this.#target.removeEventListener('chart-hover', this.#onChartHover);
      this.#target.removeEventListener('chart-leave', this.#onChartLeave);
    }
    this.#target = null;
  }

  #onChartLeave = () => this.#hide();

  #onChartHover = (event) => {
    const detail = event.detail;
    if (!detail) return;
    this.#lastDetail = detail;

    if (!this.#popover) {
      this.#popover = this.#createPopover();
      this.#copySeriesColorsFromTarget();
      try { this.#popover.showPopover(); } catch (_) { /* unsupported */ }
    }

    this.#paintPointerContent(detail);
    this.#positionAtPointer(detail.pointerX, detail.pointerY);
  };

  #createPopover() {
    const el = document.createElement('div');
    el.setAttribute('popover', 'manual');
    el.setAttribute('role', 'tooltip');
    el.setAttribute('data-follows', 'pointer');
    el.setAttribute('data-indicator', this.indicator || 'none');
    el.classList.add('tooltip-popup');
    document.body.appendChild(el);
    return el;
  }

  /* Copy per-series `--color-{key}` custom properties from the target chart
     to the popover so inner rows can reference them. The popover lives in
     the top layer and does NOT inherit custom properties from the host,
     so we bridge them explicitly at show time. */
  #copySeriesColorsFromTarget() {
    if (!this.#target || !this.#popover) return;
    /* Prefer inline style on the target (what chart-ui's #injectSeriesColors
       writes). Fall back to computed style resolution for any --color-* vars
       the author set on ancestors. */
    const inline = this.#target.style;
    for (let i = 0; i < inline.length; i++) {
      const name = inline[i];
      if (name.startsWith('--color-')) {
        this.#popover.style.setProperty(name, inline.getPropertyValue(name));
      }
    }
    /* Also copy the 10 categorical palette slots so the fallback
       `var(--color-{key}, var(--chart-{slot}))` resolves. */
    const cs = getComputedStyle(this.#target);
    for (let i = 0; i < 10; i++) {
      const v = cs.getPropertyValue(`--chart-${i}`).trim();
      if (v) this.#popover.style.setProperty(`--chart-${i}`, v);
    }
  }

  #paintPointerContent(detail) {
    if (!this.#popover) return;
    const { label, value, pct, series, slot, payload } = detail;
    const indicator = this.indicator || 'none';

    /* OD-CHART-05 — when `detail.payload` is an array (multi-series hover),
       render one row per payload entry with the hovered series marked.
       Fall back to the top-level single-datum shape for back-compat with
       charts that don't emit a payload (categorical, single-series). */
    const rows = Array.isArray(payload) && payload.length > 0
      ? payload
      : [{ series, label, value, pct, slot, hovered: true }];

    const parts = [];

    /* Label at the top — shared across all rows when a payload is
       present (all series are at the same X column). */
    if (label != null) {
      parts.push(`<span data-tip-role="label">${this.#esc(String(label))}</span>`);
    }

    for (const row of rows) {
      const rSeries = row.series ?? null;
      const rValue  = row.value;
      const rPct    = row.pct;
      const rSlot   = row.slot != null ? row.slot : 0;
      const indicatorColor = rSeries
        ? `var(--color-${rSeries}, var(--chart-${rSlot}))`
        : `var(--chart-${rSlot})`;

      if (rValue == null && rPct == null) continue;

      const valueStr = rValue != null ? this.#esc(String(rValue)) : '';
      const pctStr = rPct != null ? `<span data-tip-role="pct"> (${rPct}%)</span>` : '';
      const indEl = indicator !== 'none'
        ? `<span data-indicator style="--tooltip-indicator-color: ${indicatorColor}"></span>`
        : '';
      const nameEl = rSeries
        ? `<span data-tip-role="name">${this.#esc(rSeries)}</span>`
        : '';
      const hoveredAttr = row.hovered ? ' data-hovered' : '';

      parts.push(`<span data-tip-row${hoveredAttr}>${indEl}${nameEl}<span data-tip-role="value">${valueStr}${pctStr}</span></span>`);
    }

    this.#popover.setAttribute('data-indicator', indicator);
    this.#popover.setAttribute('aria-live', 'polite');
    this.#popover.innerHTML = parts.join('');
  }

  #positionAtPointer(x, y) {
    if (!this.#popover || x == null || y == null) return;
    const gap = 12;
    const edgePad = 8;
    const popover = this.#popover;
    popover.style.position = 'fixed';
    popover.style.left = '0';
    popover.style.top = '0';
    /* Force reflow to read offset dimensions now that content changed */
    const tw = popover.offsetWidth  || 0;
    const th = popover.offsetHeight || 0;
    /* Default: centered horizontally above the cursor, gap px clear of
       the cursor. Clamp horizontally to viewport with edgePad on each
       side (short tooltips near the viewport edge scoot inward rather
       than drifting off-screen). Flip vertically when there's not
       enough room above. */
    let px = x - tw / 2;
    let py = y - th - gap;
    if (px < edgePad)                        px = edgePad;
    if (px + tw > window.innerWidth - edgePad) px = window.innerWidth - tw - edgePad;
    if (py < edgePad)                        py = y + gap;
    popover.style.left = `${px}px`;
    popover.style.top  = `${py}px`;
  }

  #esc(s) {
    return String(s)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  }
}
