import React, { useState, useRef, ReactNode } from 'react';
import { createPortal } from 'react-dom';

interface GameTooltipProps {
    content: ReactNode;
    children: ReactNode;
    className?: string; // Class for the wrapper
}

/**
 * GameTooltip
 * 
 * Wraps an element and displays a custom, instant game-style tooltip on hover.
 * Uses React Portal to render outside the DOM hierarchy to avoid overflow/z-index issues.
 * Follows the mouse cursor.
 */
export const GameTooltip: React.FC<GameTooltipProps> = ({ content, children, className = '' }) => {
    const [isVisible, setIsVisible] = useState(false);
    const [position, setPosition] = useState({ x: 0, y: 0 });
    const tooltipRef = useRef<HTMLDivElement>(null);

    const updatePosition = (e: React.MouseEvent) => {
        // Offset from cursor
        const offsetX = 5;
        const offsetY = 5;

        // Get zoom factor (CSS zoom on <html> shifts coordinate space)
        const zoom = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--zoom-factor')) || 1;

        // clientX/Y are in physical viewport coords, but position:fixed uses CSS coords (divided by zoom)
        let x = e.clientX / zoom - offsetX;
        let y = e.clientY / zoom - offsetY;

        // Simple boundary check (can be expanded if needed)
        if (tooltipRef.current) {
            const rect = tooltipRef.current.getBoundingClientRect();
            const viewW = window.innerWidth / zoom;
            const viewH = window.innerHeight / zoom;
            if (x + rect.width / zoom > viewW) {
                x = e.clientX / zoom - rect.width / zoom + offsetX;
            }
            if (y + rect.height / zoom > viewH) {
                y = e.clientY / zoom - rect.height / zoom + offsetY;
            }
        }

        setPosition({ x, y });
    };

    const handleMouseEnter = (e: React.MouseEvent) => {
        setIsVisible(true);
        updatePosition(e);
    };

    const handleMouseMove = (e: React.MouseEvent) => {
        updatePosition(e);
    };

    const handleMouseLeave = () => {
        setIsVisible(false);
    };

    const handleClick = () => {
        // Hide tooltip on click so it doesn't interfere with dropdowns/menus
        setIsVisible(false);
    };

    // Render the tooltip portal
    const tooltip = isVisible && content ? (
        createPortal(
            <div
                ref={tooltipRef}
                style={{
                    position: 'fixed',
                    top: position.y,
                    left: position.x,
                    zIndex: 100000,
                    pointerEvents: 'none', // Ensure mouse doesn't get stuck on the tooltip itself
                    maxWidth: '300px'
                }}
                className="game-tooltip-content"
            >
                <div style={{
                    background: 'var(--game-bg-tooltip, #151515)',
                    border: '1px solid var(--game-border-color, #333)',
                    clipPath: 'var(--game-clip-path)',
                    padding: '0.5rem 0.8rem',
                    boxShadow: 'var(--game-shadow-tooltip, 0 4px 12px rgba(0,0,0,0.5))',
                    color: 'var(--game-text-primary, #ddd)',
                    fontSize: '0.85rem',
                    backdropFilter: 'blur(4px)'
                }}>
                    {content}
                </div>
            </div>,
            document.body
        )
    ) : null;

    return (
        <>
            <div
                className={`game-tooltip-wrapper ${className}`}
                onMouseEnter={handleMouseEnter}
                onMouseMove={handleMouseMove}
                onMouseLeave={handleMouseLeave}
                onClick={handleClick}
                style={{ display: 'contents' }} // Use contents so the wrapper doesn't affect layout
            >
                {children}
            </div>
            {tooltip}
        </>
    );
};
