import { useCallback, useState, useEffect } from 'react';
import clampPercentage from '../utils/clampPercentage';
function checkHasBoundingBox(entry) {
  return !!entry.boundingBox;
}
function convertTargetLocationToBoundingBox(id, targetLocationEntries) {
  if (!targetLocationEntries || targetLocationEntries.length === 0) {
    return undefined;
  }

  // Adding extra space (-0.25 for left and top, +0.5 for width and height) to provide paddings for bounding boxes
  return targetLocationEntries.filter(checkHasBoundingBox).map((item, index) => ({
    id: `bbox-${id}-${index + 1}`,
    x: clampPercentage(item.boundingBox.left * 100 - 0.25),
    y: clampPercentage(item.boundingBox.top * 100 - 0.25),
    width: clampPercentage((item.boundingBox.right - item.boundingBox.left) * 100 + 0.5),
    height: clampPercentage((item.boundingBox.bottom - item.boundingBox.top) * 100 + 0.5),
    pageNumber: item.page + 1
  }));
}
const METADATA_FIELD_SELECTOR = '[data-metadata-field]';
const BOUNDING_BOX_SELECTOR = '.ba-BoundingBoxHighlightRect';
function useMetadataFieldSelection(getPreview) {
  const [selectedMetadataFieldId, setSelectedMetadataFieldId] = useState(null);
  const handleDeselectMetadataField = useCallback(() => {
    setSelectedMetadataFieldId(null);
    const preview = getPreview();
    if (!preview) {
      return;
    }
    preview.hideBoundingBoxHighlights?.();
  }, [getPreview]);
  useEffect(() => {
    if (!selectedMetadataFieldId) {
      return undefined;
    }
    const handleClickOutside = event => {
      const target = event.target;
      const clickedOnAllowedElement = target?.closest?.(METADATA_FIELD_SELECTOR) || target?.closest?.(BOUNDING_BOX_SELECTOR);
      if (!clickedOnAllowedElement) {
        handleDeselectMetadataField();
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [selectedMetadataFieldId, handleDeselectMetadataField]);
  const handleSelectMetadataField = useCallback(field => {
    const preview = getPreview();
    if (!preview || !preview.showBoundingBoxHighlights) {
      return;
    }
    if (!field || !field.id) {
      handleDeselectMetadataField();
      return;
    }
    const boundingBoxes = convertTargetLocationToBoundingBox(field.id, field.targetLocation);
    if (!boundingBoxes || boundingBoxes.length === 0) {
      handleDeselectMetadataField();
      return;
    }
    setSelectedMetadataFieldId(field.id);
    preview.showBoundingBoxHighlights(boundingBoxes);
  }, [getPreview, handleDeselectMetadataField]);
  return {
    selectedMetadataFieldId,
    handleSelectMetadataField
  };
}
export default useMetadataFieldSelection;
//# sourceMappingURL=useMetadataFieldSelection.js.map