import React, { useState, useRef, useEffect } from 'react';

interface Props {
  term: string;
  definition: string;
  children: React.ReactNode;
}

const Tooltip: React.FC<Props> = ({ term, definition, children }) => {
  const [isVisible, setIsVisible] = useState(false);
  const [position, setPosition] = useState<'top' | 'bottom'>('top');
  const triggerRef = useRef<HTMLSpanElement>(null);
  const tooltipRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (isVisible && triggerRef.current && tooltipRef.current) {
      const triggerRect = triggerRef.current.getBoundingClientRect();
      const tooltipRect = tooltipRef.current.getBoundingClientRect();
      
      // Check if tooltip would go off-screen at the top
      if (triggerRect.top - tooltipRect.height - 12 < 0) {
        setPosition('bottom');
      } else {
        setPosition('top');
      }
    }
  }, [isVisible]);

  return (
    <span className="relative inline-block">
      <span
        ref={triggerRef}
        onMouseEnter={() => setIsVisible(true)}
        onMouseLeave={() => setIsVisible(false)}
        className="border-b-2 border-dashed border-brand-400 dark:border-brand-500 cursor-help transition-colors hover:border-brand-600 dark:hover:border-brand-400 hover:text-brand-600 dark:hover:text-brand-400"
      >
        {children}
      </span>
      
      {isVisible && (
        <div
          ref={tooltipRef}
          className={`
            absolute z-50 w-72 p-4 rounded-xl shadow-2xl
            bg-white dark:bg-gray-900 
            border border-gray-200 dark:border-gray-700
            animate-in fade-in zoom-in-95 duration-200
            ${position === 'top' 
              ? 'bottom-full mb-3 left-1/2 -translate-x-1/2' 
              : 'top-full mt-3 left-1/2 -translate-x-1/2'
            }
          `}
        >
          {/* Arrow */}
          <div 
            className={`
              absolute w-3 h-3 bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700
              transform rotate-45
              ${position === 'top' 
                ? 'bottom-0 left-1/2 -translate-x-1/2 translate-y-1.5 border-r border-b' 
                : 'top-0 left-1/2 -translate-x-1/2 -translate-y-1.5 border-l border-t'
              }
            `}
          />
          
          <div className="relative">
            <div className="text-xs font-bold uppercase tracking-wider text-brand-600 dark:text-brand-400 mb-2">
              Definition
            </div>
            <div className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-1">
              {term}
            </div>
            <div className="text-sm text-gray-600 dark:text-gray-300 leading-relaxed">
              {definition}
            </div>
          </div>
        </div>
      )}
    </span>
  );
};

export default Tooltip;

