import { useState, useRef, useEffect } from 'react';
import { HelpCircle } from 'lucide-react';

interface InfoTooltipProps {
    content: string;
    size?: number;
}

export default function InfoTooltip({ content, size = 16 }: InfoTooltipProps) {
    const [isVisible, setIsVisible] = useState(false);
    const tooltipRef = useRef<HTMLDivElement>(null);

    // Close on click outside
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (tooltipRef.current && !tooltipRef.current.contains(event.target as Node)) {
                setIsVisible(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    return (
        <div className="relative inline-flex items-center ml-1" ref={tooltipRef}>
            <button
                type="button"
                onClick={(e) => {
                    e.stopPropagation();
                    setIsVisible(!isVisible);
                }}
                className="text-[var(--color-text-tertiary)] hover:text-[var(--color-primary)] focus:outline-none transition-colors"
                aria-label="More information"
            >
                <HelpCircle size={size} />
            </button>

            {isVisible && (
                <div
                    className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 w-64 max-w-[90vw] p-3 bg-slate-800 text-white text-xs rounded-lg shadow-xl z-50 animate-scale-in text-center leading-relaxed"
                    onClick={(e) => e.stopPropagation()}
                    style={{
                        // Ensure it doesn't overflow screen on mobile
                        left: '50%',
                        transform: 'translateX(-50%)',
                    }}
                >
                    {content}
                    {/* Arrow */}
                    <div className="absolute top-full left-1/2 -translate-x-1/2 -mt-1 border-4 border-transparent border-t-slate-800" />
                </div>
            )}
        </div>
    );
}
