<script lang="ts">
  import { tick } from 'svelte';

  export let text: string;

  let showTooltip = false;
  let touchTimer: number;
  let isLongPress = false;
  let tooltipElement: HTMLSpanElement;
  let wrapperElement: HTMLSpanElement;
  let tooltipPosition = { align: 'center', vertical: 'top' };

  async function handleTouchStart() {
    isLongPress = false;
    touchTimer = window.setTimeout(async () => {
      showTooltip = true;
      isLongPress = true;
      await tick();
      await updateTooltipPosition();
    }, 500); // Show after 500ms press
  }

  function handleTouchEnd() {
    clearTimeout(touchTimer);
    if (isLongPress) {
      // Keep tooltip visible for a moment after long press release
      setTimeout(() => {
        showTooltip = false;
      }, 2000);
    }
  }

  async function handleClick() {
    // Toggle tooltip on click/tap
    if (!isLongPress) {
      showTooltip = !showTooltip;
      // Auto-hide after 3 seconds
      if (showTooltip) {
        await tick();
        await updateTooltipPosition();
        setTimeout(() => {
          showTooltip = false;
        }, 3000);
      }
    }
    isLongPress = false;
  }

  async function handleMouseEnter() {
    showTooltip = true;
    await tick();
    await updateTooltipPosition();
  }

  function handleMouseLeave() {
    showTooltip = false;
  }

  async function updateTooltipPosition() {
    // Wait for next frame to ensure rendering is complete
    await new Promise(resolve => requestAnimationFrame(resolve));

    if (!tooltipElement || !wrapperElement) return;

    const wrapperRect = wrapperElement.getBoundingClientRect();
    const tooltipRect = tooltipElement.getBoundingClientRect();
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    const padding = 10;

    // Calculate tooltip width and position
    const tooltipWidth = tooltipRect.width;
    const wrapperCenterX = wrapperRect.left + wrapperRect.width / 2;

    // Determine horizontal alignment
    let align = 'center';

    // Check if center alignment would overflow
    const centerLeft = wrapperCenterX - tooltipWidth / 2;
    const centerRight = wrapperCenterX + tooltipWidth / 2;

    if (centerLeft < padding) {
      // Would overflow left, align to left edge of wrapper
      align = 'left';
    } else if (centerRight > viewportWidth - padding) {
      // Would overflow right, align to right edge of wrapper
      align = 'right';
    }

    // Check vertical overflow
    let vertical = 'top';
    if (tooltipRect.top < padding) {
      vertical = 'bottom';
    }

    tooltipPosition = { align, vertical };
  }
</script>

<span
  bind:this={wrapperElement}
  class="tooltip-wrapper"
  on:mouseenter={handleMouseEnter}
  on:mouseleave={handleMouseLeave}
  on:touchstart={handleTouchStart}
  on:touchend={handleTouchEnd}
  on:touchcancel={handleTouchEnd}
  on:click={handleClick}
  role="button"
  tabindex="0"
  aria-label={text}
  aria-expanded={showTooltip}
>
  <slot />
  {#if showTooltip}
    <span
      bind:this={tooltipElement}
      class="tooltip-text"
      class:align-left={tooltipPosition.align === 'left'}
      class:align-right={tooltipPosition.align === 'right'}
      class:align-center={tooltipPosition.align === 'center'}
      class:position-bottom={tooltipPosition.vertical === 'bottom'}
      role="status"
      aria-live="polite"
    >
      {text}
    </span>
  {/if}
</span>

<style>
  .tooltip-wrapper {
    position: relative;
    display: inline-block;
    cursor: help;
    border-bottom: 1px dotted var(--fg-color);
    user-select: none;
  }

  .tooltip-text {
    position: absolute;
    bottom: 125%;
    background-color: var(--bg-color);
    color: var(--fg-color);
    border: 2px solid var(--border-color);
    padding: 0.5rem;
    z-index: 1000;
    width: max-content;
    max-width: min(300px, calc(100vw - 20px));
    font-size: 0.85rem;
    line-height: 1.4;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    word-wrap: break-word;
    white-space: normal;
  }

  /* Horizontal alignment variants */
  .tooltip-text.align-center {
    left: 50%;
    transform: translateX(-50%);
  }

  .tooltip-text.align-left {
    left: 0;
    right: auto;
    transform: none;
  }

  .tooltip-text.align-right {
    right: 0;
    left: auto;
    transform: none;
  }

  /* Vertical position variant (when tooltip would overflow top) */
  .tooltip-text.position-bottom {
    bottom: auto;
    top: 125%;
  }

  @media (prefers-color-scheme: dark) {
    .tooltip-text {
      box-shadow: 0 2px 8px rgba(255, 255, 255, 0.2);
    }
  }

  /* Arrow positioning for center-aligned tooltip */
  .tooltip-text.align-center::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: var(--border-color) transparent transparent transparent;
  }

  .tooltip-text.align-center.position-bottom::after {
    top: auto;
    bottom: 100%;
    border-color: transparent transparent var(--border-color) transparent;
  }

  /* Arrow positioning for left-aligned tooltip */
  .tooltip-text.align-left::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 1rem;
    border-width: 5px;
    border-style: solid;
    border-color: var(--border-color) transparent transparent transparent;
  }

  .tooltip-text.align-left.position-bottom::after {
    top: auto;
    bottom: 100%;
    border-color: transparent transparent var(--border-color) transparent;
  }

  /* Arrow positioning for right-aligned tooltip */
  .tooltip-text.align-right::after {
    content: '';
    position: absolute;
    top: 100%;
    right: 1rem;
    border-width: 5px;
    border-style: solid;
    border-color: var(--border-color) transparent transparent transparent;
  }

  .tooltip-text.align-right.position-bottom::after {
    top: auto;
    bottom: 100%;
    border-color: transparent transparent var(--border-color) transparent;
  }

  @media (max-width: 768px) {
    .tooltip-text {
      font-size: 0.8rem;
    }
  }
</style>
