import { useState, useRef, useEffect, type ReactNode } from 'react';

interface Props {
  content: string;
  children: ReactNode;
}

export const Tooltip = ({ content, children }: Props) => {
  const [show, setShow] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setShow(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <div 
      ref={containerRef}
      style={{ position: 'relative', display: 'inline-flex' }}
      onMouseEnter={() => setShow(true)}
      onMouseLeave={() => setShow(false)}
      onClick={(e) => {
        e.stopPropagation();
        setShow(!show);
      }}
    >
      {children}
      {show && (
        <div style={{
          position: 'absolute',
          bottom: '100%',
          left: '50%',
          transform: 'translateX(-50%)',
          marginBottom: '8px',
          backgroundColor: 'var(--bg-card)',
          border: '1px solid var(--border-color)',
          padding: '0.5rem 0.75rem',
          borderRadius: '8px',
          width: 'max-content',
          maxWidth: '220px',
          zIndex: 9999,
          boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
          color: 'var(--text-main)',
          fontSize: '0.8rem',
          lineHeight: 1.4,
          textAlign: 'center',
          pointerEvents: 'none'
        }}>
          {content}
        </div>
      )}
    </div>
  );
};
