---
/**
 * Tooltip Component
 * Shows additional information on hover with CSS Anchor Positioning (with fallback)
 */
import type { HTMLAttributes } from 'astro/types';
import { cn } from '@/lib/cn';

interface Props extends HTMLAttributes<'span'> {
  content: string;
  position?: 'top' | 'bottom' | 'left' | 'right';
  delay?: number;
}

const { content, position = 'top', delay = 200, class: className, ...attrs } = Astro.props;

---

<span
  class={cn('tooltip-wrapper', className)}
  data-tooltip
  data-tooltip-delay={delay}
  data-tooltip-position={position}
  {...attrs}
>
  <slot />
  <span
    class="tooltip-bubble"
    role="tooltip"
    data-tooltip-content
  >
    {content}
  </span>
</span>

<script>
  function initTooltips() {
    const tooltips = document.querySelectorAll<HTMLElement>('[data-tooltip]');
    tooltips.forEach((wrapper) => {
      if (wrapper.dataset.tooltipInit) return;
      wrapper.dataset.tooltipInit = 'true';

      const tooltip = wrapper.querySelector<HTMLElement>('[data-tooltip-content]');
      const delay = parseInt(wrapper.getAttribute('data-tooltip-delay') || '200', 10);
      let timeout: ReturnType<typeof setTimeout>;

      function show() {
        timeout = setTimeout(() => {
          tooltip?.classList.add('visible');
        }, delay);
      }

      function hide() {
        clearTimeout(timeout);
        tooltip?.classList.remove('visible');
      }

      wrapper.addEventListener('mouseenter', show);
      wrapper.addEventListener('mouseleave', hide);
      wrapper.addEventListener('focusin', show);
      wrapper.addEventListener('focusout', hide);
    });
  }

  initTooltips();
  document.addEventListener('astro:page-load', initTooltips);
</script>
