import React from 'react';
import { createPortal } from 'react-dom';
import { useTextSelection } from '../hooks/useTextSelection';

function Portal(props) {
  const mountNode = props.mount || (typeof document !== 'undefined' ? document.body : null);
  
  if (!mountNode) {
    return null;
  }

  return createPortal(props.children, mountNode);
}

export function Popover(props) {
  const { children, selectionRef: target } = props;
  const textSelectionProps = useTextSelection(target);

  // If there's no selection or it's collapsed, don't render anything
  if (textSelectionProps.isCollapsed || !textSelectionProps.clientRect) {
    return null;
  }

  // Get the position of the selected text
  const { clientRect } = textSelectionProps;
  const popoverStyle = {
    position: 'absolute',
    left: `${clientRect.left + window.scrollX}px`,
    top: `${clientRect.top + window.scrollY + 40}px`,
    zIndex: 9999
  };

  return (
    <Portal mount={props.mount}>
      <div style={popoverStyle}>
        {typeof children === 'function' 
          ? children(textSelectionProps) 
          : children}
      </div>
    </Portal>
  );
}