/**
 * Fancy tooltip system with zoom-aware positioning.
 * Event delegation on [data-tooltip] elements with show/hide delays.
 */

export function initTooltips(): void {
  const el = document.getElementById('fancyTooltip');
  if (!el) return;
  const fancyTooltip: HTMLElement = el;

  const tooltipTitle = fancyTooltip.querySelector('.tooltip-title') as HTMLElement;
  const tooltipDesc = fancyTooltip.querySelector('.tooltip-desc') as HTMLElement;
  let showTimeout: ReturnType<typeof setTimeout> | null = null;
  let hideTimeout: ReturnType<typeof setTimeout> | null = null;
  let _currentEl: Element | null = null;

  function getZoom(): number {
    const z = getComputedStyle(document.documentElement).getPropertyValue('--zoom');
    return parseFloat(z) || 1;
  }

  function positionTooltip(el: Element): void {
    const zoom = getZoom();
    const margin = 16;

    fancyTooltip.style.transform = `scale(${zoom})`;
    fancyTooltip.style.transformOrigin = 'top left';

    const rect = el.getBoundingClientRect();
    const tipRect = fancyTooltip.getBoundingClientRect();
    const tipW = tipRect.width;
    const tipH = tipRect.height;

    let left = rect.left + rect.width / 2 - tipW / 2;
    let top = rect.bottom + 8;

    if (left < margin) left = margin;
    if (left + tipW > window.innerWidth - margin) left = window.innerWidth - tipW - margin;

    if (top + tipH > window.innerHeight - margin) {
      top = rect.top - tipH - 8;
      fancyTooltip.style.transformOrigin = 'bottom left';
    } else {
      fancyTooltip.style.transformOrigin = 'top left';
    }

    if (top < margin) top = margin;

    fancyTooltip.style.left = left + 'px';
    fancyTooltip.style.top = top + 'px';
  }

  function showFancyTooltip(el: Element): void {
    const title = (el as HTMLElement).dataset.tooltip || '';
    const desc = (el as HTMLElement).dataset.tooltipDesc || '';
    if (!title) return;

    if (hideTimeout) { clearTimeout(hideTimeout); hideTimeout = null; }

    tooltipTitle.textContent = title;
    tooltipDesc.textContent = desc;
    positionTooltip(el);
    _currentEl = el;

    if (fancyTooltip.classList.contains('visible')) return;

    if (showTimeout) clearTimeout(showTimeout);
    showTimeout = setTimeout(() => {
      fancyTooltip.classList.add('visible');
    }, 250);
  }

  function hideFancyTooltip(): void {
    if (showTimeout) { clearTimeout(showTimeout); showTimeout = null; }

    hideTimeout = setTimeout(() => {
      fancyTooltip.classList.remove('visible');
      _currentEl = null;
    }, 80);
  }

  document.querySelectorAll('[data-tooltip]').forEach(el => {
    el.addEventListener('mouseenter', () => showFancyTooltip(el));
    el.addEventListener('mouseleave', hideFancyTooltip);
    el.addEventListener('mousedown', () => {
      if (showTimeout) clearTimeout(showTimeout);
      if (hideTimeout) clearTimeout(hideTimeout);
      fancyTooltip.classList.remove('visible');
      _currentEl = null;
    });
  });
}
