<script lang="ts">
    /**
     * Tooltip component for displaying additional information on hover/focus.
     * Uses position:fixed to escape overflow:hidden containers.
     */

    import type { Snippet } from "svelte"

    type Props = {
        /** Tooltip text to display */
        text: string
        /** Optional CSS class for the trigger wrapper */
        class?: string
        /** Child content (trigger element) */
        children: Snippet
    }

    let { text, class: className = "", children }: Props = $props()

    let visible = $state(false)
    let triggerEl: HTMLSpanElement | undefined = $state()
    let tooltipStyle = $state("")

    function updatePosition() {
        if (!triggerEl) return
        const rect = triggerEl.getBoundingClientRect()
        const top = rect.top - 8 // 8px gap above trigger
        const left = rect.left
        tooltipStyle = `top:${top}px;left:${left}px;transform:translateY(-100%)`
    }

    function show() {
        updatePosition()
        visible = true
    }

    function hide() {
        visible = false
    }
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
    bind:this={triggerEl}
    class="inline-block {className}"
    onmouseenter={show}
    onmouseleave={hide}
    onfocusin={show}
    onfocusout={hide}
>
    {@render children()}
    {#if visible && text}
        <span
            role="tooltip"
            class="fixed px-3 py-2 text-sm leading-snug
                   bg-gray-800 text-white rounded-lg shadow-lg
                   whitespace-normal text-left z-50
                   pointer-events-none animate-fade-in"
            style="max-width:320px;{tooltipStyle}"
        >
            {text}
            <!-- Arrow -->
            <span class="absolute top-full left-3 border-4 border-transparent border-t-gray-800"></span>
        </span>
    {/if}
</span>

<style>
    @keyframes fade-in {
        from {
            opacity: 0;
            transform: translateY(calc(-100% + 4px));
        }
        to {
            opacity: 1;
            transform: translateY(-100%);
        }
    }

    .animate-fade-in {
        animation: fade-in 0.15s ease-out forwards;
    }
</style>
