'use strict';

var chunkPZPCRXSV_cjs = require('./chunk-PZPCRXSV.cjs');
var classnames4 = require('classnames');
var React7 = require('react');
var toggle = require('@base-ui/react/toggle');
var toggleGroup = require('@base-ui/react/toggle-group');
var icons = require('@blueprintjs/icons');
var reactVirtual = require('@tanstack/react-virtual');
var button = require('@base-ui/react/button');
var input = require('@base-ui/react/input');
var pdfjsDist = require('pdfjs-dist');
var pdf_viewer_mjs = require('pdfjs-dist/web/pdf_viewer.mjs');
require('pdfjs-dist/web/pdf_viewer.css');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var classnames4__default = /*#__PURE__*/_interopDefault(classnames4);
var React7__default = /*#__PURE__*/_interopDefault(React7);

// src/pdf-viewer/components/PdfViewerAnnotationLayer.module.css
var PdfViewerAnnotationLayer_default = {};

// src/pdf-viewer/components/PdfViewerAnnotationLayer.tsx
function applyTransform(point, m) {
  return [m[0] * point[0] + m[2] * point[1] + m[4], m[1] * point[0] + m[3] * point[1] + m[5]];
}
function computeRectStyle(rect, transform, color) {
  const [x1, y1] = applyTransform([rect.x, rect.y], transform);
  const [x2, y2] = applyTransform([rect.x + rect.width, rect.y + rect.height], transform);
  return {
    left: Math.min(x1, x2),
    top: Math.min(y1, y2),
    width: Math.abs(x2 - x1),
    height: Math.abs(y2 - y1),
    ...color != null ? {
      "--osdk-pdf-annotation-color": color
    } : {}
  };
}
function useAnnotationHandlers(annotation, onClick) {
  const handleClick = React7.useCallback(() => {
    onClick?.(annotation);
  }, [onClick, annotation]);
  const handleKeyDown = React7.useCallback((e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      onClick?.(annotation);
    }
  }, [onClick, annotation]);
  return {
    handleClick,
    handleKeyDown
  };
}
function AnnotationItem({
  annotation,
  transform,
  onClick
}) {
  const {
    handleClick,
    handleKeyDown
  } = useAnnotationHandlers(annotation, onClick);
  const className = classnames4__default.default(PdfViewerAnnotationLayer_default.annotation, PdfViewerAnnotationLayer_default[annotation.type]);
  const multiRects = annotation.rects;
  const hasMultipleRects = multiRects != null && multiRects.length > 1;
  const style = React7.useMemo(() => computeRectStyle(annotation.rect, transform, annotation.color), [annotation, transform]);
  if (hasMultipleRects) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewerAnnotationLayer_default.annotationGroup,
      onClick: handleClick,
      onKeyDown: handleKeyDown,
      role: "button",
      tabIndex: 0,
      title: annotation.label,
      "data-annotation-id": annotation.id
    }, multiRects.map((rect, i) => /* @__PURE__ */ React7__default.default.createElement("div", {
      key: i,
      className,
      style: computeRectStyle(rect, transform, annotation.color)
    })));
  }
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className,
    style,
    onClick: handleClick,
    onKeyDown: handleKeyDown,
    role: "button",
    tabIndex: 0,
    title: annotation.label,
    "data-annotation-id": annotation.id
  });
}
function CustomAnnotationItem({
  annotation,
  pageHeight,
  scale,
  transform,
  onClick
}) {
  const {
    handleClick,
    handleKeyDown
  } = useAnnotationHandlers(annotation, onClick);
  const style = React7.useMemo(() => computeRectStyle(annotation.rect, transform, void 0), [annotation, transform]);
  const renderProps = React7.useMemo(() => ({
    annotation,
    scale,
    pageHeight,
    transform
  }), [annotation, scale, pageHeight, transform]);
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerAnnotationLayer_default.annotation,
    style,
    onClick: handleClick,
    onKeyDown: handleKeyDown,
    role: "button",
    tabIndex: 0,
    title: annotation.label,
    "data-annotation-id": annotation.id
  }, annotation.render(renderProps));
}
function PdfViewerAnnotationLayer({
  annotations,
  pageHeight,
  scale,
  transform,
  onAnnotationClick
}) {
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerAnnotationLayer_default.annotationLayer
  }, annotations.map((annotation) => annotation.type === "custom" ? /* @__PURE__ */ React7__default.default.createElement(CustomAnnotationItem, {
    key: annotation.id,
    annotation,
    pageHeight,
    scale,
    transform,
    onClick: onAnnotationClick
  }) : /* @__PURE__ */ React7__default.default.createElement(AnnotationItem, {
    key: annotation.id,
    annotation,
    transform,
    onClick: onAnnotationClick
  })));
}

// src/pdf-viewer/components/PdfViewerSidebarHeader.module.css
var PdfViewerSidebarHeader_default = {};

// src/pdf-viewer/components/PdfViewerSidebarHeader.tsx
var SIDEBAR_MODE_VALUE = Object.freeze(["thumbnails"]);
var OUTLINE_MODE_VALUE = Object.freeze(["outline"]);
function PdfViewerSidebarHeader({
  sidebarMode,
  onSidebarModeChange
}) {
  const value = sidebarMode === "thumbnails" ? SIDEBAR_MODE_VALUE : OUTLINE_MODE_VALUE;
  const handleValueChange = React7.useCallback((newValue) => {
    if (newValue.length > 0) {
      onSidebarModeChange(newValue[0]);
    }
  }, [onSidebarModeChange]);
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerSidebarHeader_default.sidebarHeader
  }, /* @__PURE__ */ React7__default.default.createElement(toggleGroup.ToggleGroup, {
    value,
    onValueChange: handleValueChange,
    className: PdfViewerSidebarHeader_default.toggleGroup
  }, /* @__PURE__ */ React7__default.default.createElement(toggle.Toggle, {
    value: "thumbnails",
    className: PdfViewerSidebarHeader_default.modeButton,
    "aria-label": "Page thumbnails"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.GridView, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement(toggle.Toggle, {
    value: "outline",
    className: PdfViewerSidebarHeader_default.modeButton,
    "aria-label": "Document outline"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Properties, {
    size: 16
  }))));
}

// src/pdf-viewer/components/PdfViewerOutlineSidebar.module.css
var PdfViewerOutlineSidebar_default = {};

// src/pdf-viewer/components/PdfViewerOutlineSidebar.tsx
var INDENT_PER_DEPTH = 16;
function PdfViewerOutlineSidebar({
  outlineItems,
  currentPage,
  onItemClick,
  sidebarMode,
  onSidebarModeChange,
  outlineIcons
}) {
  const activeIndex = React7.useMemo(() => {
    return computeActiveIndex(outlineItems, currentPage);
  }, [outlineItems, currentPage]);
  if (outlineItems.length === 0) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewerOutlineSidebar_default.sidebar
    }, /* @__PURE__ */ React7__default.default.createElement(PdfViewerSidebarHeader, {
      sidebarMode,
      onSidebarModeChange
    }), /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewerOutlineSidebar_default.emptyState
    }, /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewerOutlineSidebar_default.emptyStateText
    }, "No outline available")));
  }
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerOutlineSidebar_default.sidebar
  }, /* @__PURE__ */ React7__default.default.createElement(PdfViewerSidebarHeader, {
    sidebarMode,
    onSidebarModeChange
  }), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerOutlineSidebar_default.scrollContainer
  }, outlineItems.map((item, index) => /* @__PURE__ */ React7__default.default.createElement(PdfViewerOutlineItem, {
    key: index,
    item,
    isActive: index === activeIndex,
    onClick: onItemClick,
    iconComponent: outlineIcons?.[item.depth]
  }))));
}
function PdfViewerOutlineItem({
  item,
  isActive,
  onClick,
  iconComponent: IconComponent
}) {
  const handleClick = React7.useCallback(() => {
    onClick(item.pageNumber);
  }, [onClick, item.pageNumber]);
  const handleKeyDown = React7.useCallback((e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      onClick(item.pageNumber);
    }
  }, [onClick, item.pageNumber]);
  const itemClassName = classnames4__default.default(PdfViewerOutlineSidebar_default.outlineItem, isActive && PdfViewerOutlineSidebar_default.outlineItemActive, item.bold && PdfViewerOutlineSidebar_default.outlineItemBold, item.italic && PdfViewerOutlineSidebar_default.outlineItemItalic);
  const paddingLeft = INDENT_PER_DEPTH * item.depth + 12;
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: itemClassName,
    onClick: handleClick,
    onKeyDown: handleKeyDown,
    role: "button",
    tabIndex: 0,
    "aria-label": item.title,
    "aria-current": isActive ? "location" : void 0,
    style: {
      paddingLeft
    }
  }, IconComponent != null && /* @__PURE__ */ React7__default.default.createElement("span", {
    className: PdfViewerOutlineSidebar_default.outlineItemIcon
  }, /* @__PURE__ */ React7__default.default.createElement(IconComponent, null)), /* @__PURE__ */ React7__default.default.createElement("span", {
    className: PdfViewerOutlineSidebar_default.outlineItemTitle
  }, item.title));
}
function computeActiveIndex(items, currentPage) {
  const idx = items.findIndex((item) => item.pageNumber > currentPage);
  return idx === -1 ? items.length - 1 : idx - 1;
}

// src/pdf-viewer/components/PdfViewerSearchBar.module.css
var PdfViewerSearchBar_default = {};

// src/pdf-viewer/components/PdfViewerSearchBar.tsx
function PdfViewerSearchBar({
  query,
  totalMatches,
  currentMatchIndex,
  onQueryChange,
  onNext,
  onPrev,
  onClose
}) {
  const handleInputChange = React7.useCallback((e) => {
    onQueryChange(e.target.value);
  }, [onQueryChange]);
  const handleKeyDown = React7.useCallback((e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      if (e.shiftKey) {
        onPrev();
      } else {
        onNext();
      }
    } else if (e.key === "Escape") {
      e.preventDefault();
      onClose();
    }
  }, [onNext, onPrev, onClose]);
  const matchDisplay = totalMatches > 0 ? `${currentMatchIndex + 1} of ${totalMatches}` : query.length > 0 ? "No results" : "";
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerSearchBar_default.searchBar
  }, /* @__PURE__ */ React7__default.default.createElement("input", {
    autoFocus: true,
    className: PdfViewerSearchBar_default.searchInput,
    type: "text",
    value: query,
    onChange: handleInputChange,
    onKeyDown: handleKeyDown,
    placeholder: "Find in document...",
    "aria-label": "Search in PDF"
  }), matchDisplay.length > 0 && /* @__PURE__ */ React7__default.default.createElement("span", {
    className: PdfViewerSearchBar_default.matchCount
  }, matchDisplay), /* @__PURE__ */ React7__default.default.createElement("button", {
    className: PdfViewerSearchBar_default.navButton,
    onClick: onPrev,
    disabled: totalMatches === 0,
    "aria-label": "Previous match",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.ChevronUp, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement("button", {
    className: PdfViewerSearchBar_default.navButton,
    onClick: onNext,
    disabled: totalMatches === 0,
    "aria-label": "Next match",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.ChevronDown, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement("button", {
    className: PdfViewerSearchBar_default.closeButton,
    onClick: onClose,
    "aria-label": "Close search",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Cross, {
    size: 16
  })));
}

// src/pdf-viewer/constants.ts
var EMPTY_ANNOTATION_ARRAY = [];
var EMPTY_STRING = "";
var PAGE_WIDTH_SCALE_VALUE = "page-width";
var SCALE_STEP = 0.25;
var MIN_SCALE = 0.25;
var MAX_SCALE = 5;
var DEFAULT_PAGE_HEIGHT = 792;
var THUMBNAIL_GAP = 12;
var THUMBNAIL_SCALE = 0.2;
var DEVICE_PIXEL_RATIO = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
var OUTLINE_HEADING_SIZE_RATIO = 1.15;
var OUTLINE_MAX_HEADING_LENGTH = 200;
var FIND_EVENT = "find";
var UPDATE_FIND_CONTROL_STATE_EVENT = "updatefindcontrolstate";
var UPDATE_FIND_MATCHES_COUNT_EVENT = "updatefindmatchescount";
var PAGE_CHANGING_EVENT = "pagechanging";
var SCALE_CHANGING_EVENT = "scalechanging";
var PAGE_RENDERED_EVENT = "pagerendered";
var PAGES_LOADED_EVENT = "pagesloaded";
var ANNOTATION_LAYER_RENDERED_EVENT = "annotationlayerrendered";

// src/pdf-viewer/components/PdfViewerThumbnail.module.css
var PdfViewerThumbnail_default = {};

// src/pdf-viewer/components/PdfViewerThumbnail.tsx
function PdfViewerThumbnail({
  document,
  pageNumber,
  isActive,
  onClick
}) {
  const canvasRef = React7.useRef(null);
  const renderTaskRef = React7.useRef(null);
  const [dimensions, setDimensions] = React7.useState(void 0);
  React7.useEffect(() => {
    let cancelled = false;
    void document.getPage(pageNumber).then((page) => {
      if (cancelled || canvasRef.current == null) {
        return;
      }
      const viewport = page.getViewport({
        scale: THUMBNAIL_SCALE
      });
      const canvas = canvasRef.current;
      const context = canvas.getContext("2d");
      if (context == null) {
        return;
      }
      canvas.width = Math.floor(viewport.width * DEVICE_PIXEL_RATIO);
      canvas.height = Math.floor(viewport.height * DEVICE_PIXEL_RATIO);
      canvas.style.width = `${Math.floor(viewport.width)}px`;
      canvas.style.height = `${Math.floor(viewport.height)}px`;
      setDimensions({
        width: Math.floor(viewport.width),
        height: Math.floor(viewport.height)
      });
      if (renderTaskRef.current != null) {
        renderTaskRef.current.cancel();
      }
      context.setTransform(DEVICE_PIXEL_RATIO, 0, 0, DEVICE_PIXEL_RATIO, 0, 0);
      const renderTask = page.render({
        canvasContext: context,
        viewport
      });
      renderTaskRef.current = renderTask;
      void renderTask.promise.catch((err) => {
        if (err instanceof Error && err.message.includes("cancelled")) {
          return;
        }
        throw err;
      });
    });
    return () => {
      cancelled = true;
      if (renderTaskRef.current != null) {
        renderTaskRef.current.cancel();
        renderTaskRef.current = null;
      }
    };
  }, [document, pageNumber]);
  const handleKeyDown = React7.useCallback((e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      onClick();
    }
  }, [onClick]);
  const containerClassName = classnames4__default.default(PdfViewerThumbnail_default.thumbnailContainer, isActive && PdfViewerThumbnail_default.active);
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: containerClassName,
    onClick,
    onKeyDown: handleKeyDown,
    role: "button",
    tabIndex: 0,
    "aria-label": `Page ${pageNumber}`,
    "aria-current": isActive ? "page" : void 0,
    style: dimensions != null ? {
      width: dimensions.width,
      height: dimensions.height
    } : void 0
  }, /* @__PURE__ */ React7__default.default.createElement("canvas", {
    ref: canvasRef,
    className: PdfViewerThumbnail_default.canvas
  }));
}

// src/pdf-viewer/components/PdfViewerSidebar.module.css
var PdfViewerSidebar_default = {};

// src/pdf-viewer/components/PdfViewerSidebar.tsx
function PdfViewerSidebar({
  document,
  numPages,
  currentPage,
  onPageClick,
  sidebarMode,
  onSidebarModeChange
}) {
  const scrollContainerRef = React7.useRef(null);
  const estimatedItemHeight = Math.floor(DEFAULT_PAGE_HEIGHT * THUMBNAIL_SCALE) + THUMBNAIL_GAP + 20;
  const virtualizer = reactVirtual.useVirtualizer({
    count: numPages,
    getScrollElement: () => scrollContainerRef.current,
    estimateSize: () => estimatedItemHeight,
    overscan: 2
  });
  React7.useEffect(function syncActiveThumbnail() {
    virtualizer.scrollToIndex(currentPage - 1, {
      align: "auto"
    });
  }, [currentPage, virtualizer]);
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerSidebar_default.sidebar
  }, /* @__PURE__ */ React7__default.default.createElement(PdfViewerSidebarHeader, {
    sidebarMode,
    onSidebarModeChange
  }), /* @__PURE__ */ React7__default.default.createElement("div", {
    ref: scrollContainerRef,
    className: PdfViewerSidebar_default.scrollContainer
  }, /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerSidebar_default.thumbnailsContainer,
    style: {
      height: virtualizer.getTotalSize()
    }
  }, virtualizer.getVirtualItems().map((virtualItem) => {
    const pageNumber = virtualItem.index + 1;
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      key: virtualItem.key,
      className: PdfViewerSidebar_default.thumbnailWrapper,
      style: {
        top: virtualItem.start,
        height: virtualItem.size
      }
    }, /* @__PURE__ */ React7__default.default.createElement("div", null, /* @__PURE__ */ React7__default.default.createElement(PdfViewerThumbnail, {
      document,
      pageNumber,
      isActive: pageNumber === currentPage,
      onClick: () => onPageClick(pageNumber)
    }), /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewerSidebar_default.pageNumber
    }, pageNumber)));
  }))));
}

// src/pdf-viewer/components/PdfViewerToolbar.module.css
var PdfViewerToolbar_default = {};

// src/pdf-viewer/components/PdfViewerToolbar.tsx
function PdfViewerToolbar({
  currentPage,
  numPages,
  scale,
  autoSize,
  sidebarOpen,
  onPageChange,
  onZoomIn,
  onZoomOut,
  onAutoSizeToggle,
  onSearchOpen,
  onSidebarToggle,
  onDownload,
  enableDownload,
  onRotateLeft,
  onRotateRight,
  enableHighlight,
  highlightModeActive,
  onHighlightToggle,
  enableFormSave = false,
  onFormSave
}) {
  const [pageInputValue, setPageInputValue] = React7.useState(String(currentPage));
  React7.useEffect(function syncPageInput() {
    setPageInputValue(String(currentPage));
  }, [currentPage]);
  const handlePrevPage = React7.useCallback(() => {
    if (currentPage > 1) {
      const newPage = currentPage - 1;
      onPageChange(newPage);
      setPageInputValue(String(newPage));
    }
  }, [currentPage, onPageChange]);
  const handleNextPage = React7.useCallback(() => {
    if (currentPage < numPages) {
      const newPage = currentPage + 1;
      onPageChange(newPage);
      setPageInputValue(String(newPage));
    }
  }, [currentPage, numPages, onPageChange]);
  const handlePageInputChange = React7.useCallback((e) => {
    setPageInputValue(e.target.value);
  }, []);
  const handlePageInputKeyDown = React7.useCallback((e) => {
    if (e.key === "Enter") {
      const page = parseInt(pageInputValue, 10);
      if (!isNaN(page) && page >= 1 && page <= numPages) {
        onPageChange(page);
      } else {
        setPageInputValue(String(currentPage));
      }
    }
  }, [pageInputValue, numPages, onPageChange, currentPage]);
  const handlePageInputBlur = React7.useCallback(() => {
    setPageInputValue(String(currentPage));
  }, [currentPage]);
  const scalePercent = `${Math.round(scale * 100)}%`;
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.toolbar
  }, /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onSidebarToggle,
    "aria-label": sidebarOpen ? "Close sidebar" : "Open sidebar",
    title: sidebarOpen ? "Close sidebar" : "Open sidebar",
    "aria-pressed": sidebarOpen,
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Menu, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.separator
  }), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.toolbarGroup
  }, /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: handlePrevPage,
    disabled: currentPage <= 1,
    "aria-label": "Previous page",
    title: "Previous page",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.ChevronLeft, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement(input.Input, {
    className: PdfViewerToolbar_default.pageInput,
    type: "text",
    value: pageInputValue,
    onChange: handlePageInputChange,
    onKeyDown: handlePageInputKeyDown,
    onBlur: handlePageInputBlur,
    "aria-label": "Page number"
  }), /* @__PURE__ */ React7__default.default.createElement("span", {
    className: PdfViewerToolbar_default.pageCount
  }, "of ", numPages), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: handleNextPage,
    disabled: currentPage >= numPages,
    "aria-label": "Next page",
    title: "Next page",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.ChevronRight, {
    size: 16
  }))), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.separator
  }), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.toolbarGroup
  }, /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onZoomOut,
    disabled: scale <= MIN_SCALE,
    "aria-label": "Zoom out",
    title: "Zoom out",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Minus, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement("span", {
    className: PdfViewerToolbar_default.scaleDisplay
  }, scalePercent), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onZoomIn,
    disabled: scale >= MAX_SCALE,
    "aria-label": "Zoom in",
    title: "Zoom in",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Plus, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: classnames4__default.default(PdfViewerToolbar_default.toolbarButton, autoSize && PdfViewerToolbar_default.toolbarButtonActive),
    onClick: onAutoSizeToggle,
    "aria-label": autoSize ? "Disable fit to width" : "Fit to width",
    title: autoSize ? "Disable fit to width" : "Fit to width",
    "aria-pressed": autoSize,
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.ZoomToFit, {
    size: 16
  }))), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.separator
  }), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.toolbarGroup
  }, /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onRotateLeft,
    "aria-label": "Rotate left",
    title: "Rotate left",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.RotatePage, {
    size: 16
  })), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onRotateRight,
    "aria-label": "Rotate right",
    title: "Rotate right",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.RotatePage, {
    size: 16,
    style: {
      transform: "scaleX(-1)"
    }
  }))), enableHighlight && /* @__PURE__ */ React7__default.default.createElement(React7__default.default.Fragment, null, /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.separator
  }), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: classnames4__default.default(PdfViewerToolbar_default.toolbarButton, highlightModeActive && PdfViewerToolbar_default.toolbarButtonActive),
    onClick: onHighlightToggle,
    "aria-label": highlightModeActive ? "Disable highlight mode" : "Enable highlight mode",
    title: highlightModeActive ? "Disable highlight mode" : "Enable highlight mode",
    "aria-pressed": highlightModeActive,
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Highlight, {
    size: 16
  }))), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.separator
  }), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onSearchOpen,
    "aria-label": "Search",
    title: "Search",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Search, {
    size: 16
  })), enableDownload && /* @__PURE__ */ React7__default.default.createElement(React7__default.default.Fragment, null, /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.separator
  }), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onDownload,
    "aria-label": "Download",
    title: "Download",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.Download, {
    size: 16
  }))), enableFormSave && /* @__PURE__ */ React7__default.default.createElement(React7__default.default.Fragment, null, /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewerToolbar_default.separator
  }), /* @__PURE__ */ React7__default.default.createElement(button.Button, {
    className: PdfViewerToolbar_default.toolbarButton,
    onClick: onFormSave,
    "aria-label": "Save form",
    title: "Save form",
    type: "button"
  }, /* @__PURE__ */ React7__default.default.createElement(icons.FloppyDisk, {
    size: 16
  }))));
}
function usePdfAnnotationsByPage(annotations) {
  return React7.useMemo(() => {
    const result = {};
    for (const ann of annotations) {
      (result[ann.page] ??= []).push(ann);
    }
    return result;
  }, [annotations]);
}
function getViewerContainer(viewer) {
  return viewer.container;
}
function normalizeFieldType(type) {
  switch (type) {
    case "checkbox":
    case "radiobutton":
    case "combobox":
    case "listbox":
      return type;
    default:
      return "text";
  }
}
function toFormFieldValue(storageValue, fieldType) {
  if (fieldType === "checkbox") {
    if (typeof storageValue === "boolean") {
      return storageValue;
    }
    return storageValue !== "Off" && storageValue !== false;
  }
  if (fieldType === "radiobutton") {
    return typeof storageValue === "string" ? storageValue : "";
  }
  if (typeof storageValue === "string") {
    return storageValue;
  }
  if (Array.isArray(storageValue)) {
    return storageValue.map(String);
  }
  return "";
}
function toStorageValue(formValue, fieldType) {
  if (fieldType === "checkbox") {
    if (typeof formValue === "boolean") {
      return formValue;
    }
    return formValue !== "Off" && formValue !== "";
  }
  return formValue;
}
function usePdfFormFields({
  pdfViewerRef,
  eventBusRef,
  document,
  formData,
  onFormSubmit,
  onFormChange
}) {
  const [hasFormFields, setHasFormFields] = React7.useState(false);
  const onFormSubmitRef = React7.useRef(onFormSubmit);
  const onFormChangeRef = React7.useRef(onFormChange);
  const formDataRef = React7.useRef(formData);
  React7.useEffect(function syncCallbackRefs() {
    onFormSubmitRef.current = onFormSubmit;
    onFormChangeRef.current = onFormChange;
    formDataRef.current = formData;
  }, [onFormSubmit, onFormChange, formData]);
  const fieldMapRef = React7.useRef(/* @__PURE__ */ new Map());
  const nameToIdsRef = React7.useRef(/* @__PURE__ */ new Map());
  React7.useEffect(function buildFieldMap() {
    const doc = document;
    if (doc == null) {
      fieldMapRef.current.clear();
      nameToIdsRef.current.clear();
      setHasFormFields(false);
      return;
    }
    let cancelled = false;
    void doc.getFieldObjects().then((fieldObjects) => {
      if (cancelled || fieldObjects == null) {
        setHasFormFields(false);
        return;
      }
      const fieldMap = /* @__PURE__ */ new Map();
      const nameToIds = /* @__PURE__ */ new Map();
      for (const [fieldName, objects] of Object.entries(fieldObjects)) {
        const ids = [];
        for (const obj of objects) {
          const typedObj = obj;
          if (typedObj.id == null) continue;
          const fieldType = normalizeFieldType(typedObj.type ?? "text");
          fieldMap.set(typedObj.id, {
            fieldName,
            fieldType,
            exportValues: typedObj.exportValues,
            page: typedObj.page ?? 0
          });
          ids.push(typedObj.id);
        }
        if (ids.length > 0) {
          nameToIds.set(fieldName, ids);
        }
      }
      fieldMapRef.current = fieldMap;
      nameToIdsRef.current = nameToIds;
      setHasFormFields(fieldMap.size > 0);
    });
    return () => {
      cancelled = true;
    };
  }, [document]);
  const populateFields = React7.useCallback(() => {
    const data = formDataRef.current;
    const doc = document;
    const pdfViewer = pdfViewerRef.current;
    if (data == null || doc == null || pdfViewer == null) return;
    if (fieldMapRef.current.size === 0) return;
    const storage = doc.annotationStorage;
    const container = getViewerContainer(pdfViewer);
    for (const [fieldName, value] of Object.entries(data)) {
      const ids = nameToIdsRef.current.get(fieldName);
      if (ids == null) continue;
      for (const id of ids) {
        const entry = fieldMapRef.current.get(id);
        if (entry == null) continue;
        const el = container?.querySelector(`[data-element-id="${CSS.escape(id)}"]`);
        if (entry.fieldType === "radiobutton") {
          const optionValue = entry.exportValues ?? (el instanceof HTMLInputElement ? el.value : void 0);
          const isSelected = optionValue === String(value);
          storage.setValue(id, {
            value: isSelected ? entry.exportValues ?? String(value) : "Off"
          });
          if (el instanceof HTMLInputElement) {
            el.checked = isSelected;
          }
        } else {
          const storageVal = toStorageValue(value, entry.fieldType);
          storage.setValue(id, {
            value: storageVal
          });
          if (el == null) continue;
          if (entry.fieldType === "checkbox" && el instanceof HTMLInputElement) {
            el.checked = typeof storageVal === "boolean" ? storageVal : storageVal !== "Off";
          } else if (el instanceof HTMLSelectElement) {
            el.value = String(value);
          } else if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
            el.value = String(value);
          }
        }
      }
    }
  }, [document, pdfViewerRef]);
  React7.useEffect(function populateFormData() {
    const eventBus = eventBusRef.current;
    if (eventBus == null || document == null || formDataRef.current == null) {
      return;
    }
    populateFields();
    const onAnnotationLayerRendered = () => {
      populateFields();
    };
    eventBus.on(ANNOTATION_LAYER_RENDERED_EVENT, onAnnotationLayerRendered);
    return () => {
      eventBus.off(ANNOTATION_LAYER_RENDERED_EVENT, onAnnotationLayerRendered);
    };
  }, [eventBusRef, document, hasFormFields, populateFields]);
  React7.useEffect(function listenForFieldChanges() {
    const pdfViewer = pdfViewerRef.current;
    if (pdfViewer == null || document == null) {
      return;
    }
    const container = getViewerContainer(pdfViewer);
    if (container == null) return;
    const listeners = /* @__PURE__ */ new Map();
    function handleFieldChange(el) {
      const id = el.getAttribute("data-element-id");
      if (id == null) return;
      const entry = fieldMapRef.current.get(id);
      if (entry == null) return;
      let value;
      if (entry.fieldType === "checkbox" && el instanceof HTMLInputElement) {
        value = el.checked;
      } else if (entry.fieldType === "radiobutton" && el instanceof HTMLInputElement) {
        value = el.checked ? entry.exportValues ?? el.value : "";
      } else {
        value = el.value;
      }
      onFormChangeRef.current?.(entry.fieldName, value);
    }
    function attachListeners(root) {
      const elements = root.querySelectorAll?.(".annotationLayer input, .annotationLayer select, .annotationLayer textarea");
      if (elements == null) return;
      for (const el of elements) {
        if (listeners.has(el)) continue;
        const handler = () => {
          handleFieldChange(el);
        };
        el.addEventListener("input", handler);
        el.addEventListener("change", handler);
        listeners.set(el, handler);
      }
    }
    attachListeners(container);
    const observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        for (const node of mutation.addedNodes) {
          if (node instanceof Element) {
            attachListeners(node);
          }
        }
      }
    });
    observer.observe(container, {
      childList: true,
      subtree: true
    });
    return () => {
      observer.disconnect();
      for (const [el, handler] of listeners) {
        el.removeEventListener("input", handler);
        el.removeEventListener("change", handler);
      }
      listeners.clear();
    };
  }, [pdfViewerRef, document]);
  const submitFormData = React7.useCallback(() => {
    const doc = document;
    if (doc == null) return;
    const storage = doc.annotationStorage;
    const allValues = storage.getAll();
    const result = {};
    const resolvedRadios = /* @__PURE__ */ new Set();
    for (const [id, entry] of fieldMapRef.current) {
      const {
        fieldName,
        fieldType
      } = entry;
      if (fieldType === "radiobutton") {
        if (resolvedRadios.has(fieldName)) continue;
        resolvedRadios.add(fieldName);
        const groupIds = nameToIdsRef.current.get(fieldName) ?? [];
        let selectedValue = "";
        for (const radioId of groupIds) {
          const stored2 = allValues?.[radioId];
          const val = stored2 != null && typeof stored2 === "object" && "value" in stored2 ? stored2.value : stored2;
          if (val === true || typeof val === "string" && val !== "Off") {
            const radioEntry = fieldMapRef.current.get(radioId);
            selectedValue = radioEntry?.exportValues ?? String(val);
            break;
          }
        }
        result[fieldName] = selectedValue;
        continue;
      }
      const stored = allValues?.[id];
      const rawValue = stored != null && typeof stored === "object" && "value" in stored ? stored.value : stored;
      if (fieldName in result) continue;
      result[fieldName] = toFormFieldValue(rawValue, fieldType);
    }
    onFormSubmitRef.current?.(result);
  }, [document]);
  return {
    hasFormFields,
    submitFormData
  };
}
function rgbArrayToHex(color) {
  const r = Math.round(color[0] * 255);
  const g = Math.round(color[1] * 255);
  const b = Math.round(color[2] * 255);
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
}
function quadPointsToRects(quadPoints) {
  const rects = [];
  for (let i = 0; i < quadPoints.length; i += 8) {
    const x1 = quadPoints[i];
    const y1 = quadPoints[i + 1];
    const x2 = quadPoints[i + 2];
    const y3 = quadPoints[i + 5];
    const x = Math.min(x1, x2);
    const y = Math.min(y1, y3);
    const width = Math.abs(x2 - x1);
    const height = Math.abs(y1 - y3);
    rects.push({
      x,
      y,
      width,
      height
    });
  }
  return rects;
}
function usePdfHighlightMode({
  pdfViewerRef,
  document,
  enabled,
  onTextHighlight,
  onHighlightDelete
}) {
  const [highlightModeActive, setHighlightModeActive] = React7.useState(false);
  const onTextHighlightRef = React7.useRef(onTextHighlight);
  const onHighlightDeleteRef = React7.useRef(onHighlightDelete);
  const knownEditorIdsRef = React7.useRef(/* @__PURE__ */ new Set());
  const editorEventsRef = React7.useRef(/* @__PURE__ */ new Map());
  React7.useEffect(function syncCallbackRef() {
    onTextHighlightRef.current = onTextHighlight;
    onHighlightDeleteRef.current = onHighlightDelete;
  }, [onTextHighlight, onHighlightDelete]);
  React7.useEffect(function syncHighlightMode() {
    const pdfViewer = pdfViewerRef.current;
    if (pdfViewer == null || document == null) {
      return;
    }
    try {
      if (highlightModeActive && enabled) {
        pdfViewer.annotationEditorMode = {
          mode: pdfjsDist.AnnotationEditorType.HIGHLIGHT
        };
      } else {
        pdfViewer.annotationEditorMode = {
          mode: pdfjsDist.AnnotationEditorType.NONE
        };
      }
    } catch {
    }
  }, [pdfViewerRef, document, highlightModeActive, enabled]);
  React7.useEffect(function deactivateOnDisable() {
    if (!enabled) {
      setHighlightModeActive(false);
    }
  }, [enabled]);
  const prevDocumentRef = React7.useRef(void 0);
  React7.useEffect(function clearOnDocumentChange() {
    if (document !== prevDocumentRef.current) {
      knownEditorIdsRef.current.clear();
      editorEventsRef.current.clear();
      prevDocumentRef.current = document;
    }
  }, [document]);
  React7.useEffect(function listenForHighlights() {
    if (document == null || !highlightModeActive || !enabled) {
      return;
    }
    const storage = document.annotationStorage;
    const previousOnAnnotationEditor = storage.onAnnotationEditor;
    const originalRemove = storage.remove.bind(storage);
    storage.remove = (key) => {
      const savedEvent = editorEventsRef.current.get(key);
      if (savedEvent != null) {
        editorEventsRef.current.delete(key);
        knownEditorIdsRef.current.delete(key);
        onHighlightDeleteRef.current?.(savedEvent);
      }
      originalRemove(key);
    };
    storage.onAnnotationEditor = (type) => {
      if (type !== "highlight") {
        return;
      }
      const allEntries = storage.getAll();
      if (allEntries == null) {
        return;
      }
      for (const [id, entry] of Object.entries(allEntries)) {
        if (knownEditorIdsRef.current.has(id)) {
          continue;
        }
        if (typeof entry === "object" && entry != null && "serialize" in entry && typeof entry.serialize === "function") {
          knownEditorIdsRef.current.add(id);
          const serialized = entry.serialize(false);
          if (serialized == null || serialized.annotationType !== pdfjsDist.AnnotationEditorType.HIGHLIGHT) {
            continue;
          }
          const rects = serialized.quadPoints != null ? quadPointsToRects(serialized.quadPoints) : [];
          if (rects.length === 0) {
            continue;
          }
          const color = Array.isArray(serialized.color) ? rgbArrayToHex(serialized.color) : "#fff066";
          const selectedText = typeof entry.div?.getAttribute === "function" ? entry.div.getAttribute("aria-label") ?? "" : "";
          const event = {
            editorId: id,
            page: serialized.pageIndex + 1,
            rects,
            selectedText,
            color
          };
          editorEventsRef.current.set(id, event);
          onTextHighlightRef.current?.(event);
        }
      }
    };
    return () => {
      storage.onAnnotationEditor = previousOnAnnotationEditor;
      storage.remove = originalRemove;
    };
  }, [document, highlightModeActive, enabled]);
  const toggleHighlightMode = React7.useCallback(() => {
    setHighlightModeActive((prev) => !prev);
  }, []);
  const deleteHighlight = React7.useCallback((editorId) => {
    if (document == null) return;
    const storage = document.annotationStorage;
    const savedEvent = editorEventsRef.current.get(editorId);
    if (savedEvent != null) {
      editorEventsRef.current.delete(editorId);
      knownEditorIdsRef.current.delete(editorId);
      onHighlightDeleteRef.current?.(savedEvent);
    }
    const allEntries = storage.getAll();
    const entry = allEntries?.[editorId];
    if (hasDiv(entry) && entry.div instanceof HTMLElement) {
      entry.div.remove();
    }
    storage.remove(editorId);
  }, [document]);
  return {
    highlightModeActive,
    toggleHighlightMode,
    deleteHighlight
  };
}
function hasDiv(obj) {
  return obj != null && typeof obj === "object" && "div" in obj;
}
var EMPTY_OUTLINE = [];
function usePdfOutline(document) {
  const [outlineItems, setOutlineItems] = React7.useState(EMPTY_OUTLINE);
  React7.useEffect(function loadOutline() {
    if (document == null) {
      setOutlineItems(EMPTY_OUTLINE);
      return;
    }
    let cancelled = false;
    void (async () => {
      try {
        const outline = await document.getOutline();
        if (cancelled) return;
        if (outline != null && outline.length > 0) {
          const items2 = await resolveBookmarkOutline(document, outline);
          if (!cancelled) {
            setOutlineItems(items2);
          }
          return;
        }
        const items = await extractHeadingsFromText(document);
        if (!cancelled) {
          setOutlineItems(items.length > 0 ? items : EMPTY_OUTLINE);
        }
      } catch {
        if (!cancelled) {
          setOutlineItems(EMPTY_OUTLINE);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [document]);
  return outlineItems;
}
async function resolveBookmarkOutline(document, outline) {
  const items = [];
  const resolveItems = async (nodes, depth) => {
    for (const node of nodes) {
      let pageNumber = 1;
      try {
        if (typeof node.dest === "string") {
          const dest = await document.getDestination(node.dest);
          if (dest != null) {
            const pageIndex = await document.getPageIndex(dest[0]);
            pageNumber = pageIndex + 1;
          }
        } else if (Array.isArray(node.dest) && node.dest.length > 0) {
          const pageIndex = await document.getPageIndex(node.dest[0]);
          pageNumber = pageIndex + 1;
        }
      } catch {
      }
      items.push({
        title: node.title,
        depth,
        pageNumber,
        bold: node.bold,
        italic: node.italic
      });
      if (node.items.length > 0) {
        await resolveItems(node.items, depth + 1);
      }
    }
  };
  await resolveItems(outline, 0);
  return items;
}
function isTextItem(item) {
  return "str" in item && "transform" in item;
}
function roundFontSize(size) {
  return Math.round(size * 10) / 10;
}
function getFontSize(item) {
  if (item.height > 0) {
    return item.height;
  }
  const transform = item.transform;
  if (Array.isArray(transform) && transform.length >= 4) {
    return Math.sqrt(transform[2] * transform[2] + transform[3] * transform[3]);
  }
  return 0;
}
async function extractHeadingsFromText(document) {
  const numPages = document.numPages;
  const pageContents = await Promise.all(Array.from({
    length: numPages
  }, (_, i) => document.getPage(i + 1).then((page) => page.getTextContent())));
  const sizeCounts = /* @__PURE__ */ new Map();
  for (const textContent of pageContents) {
    for (const rawItem of textContent.items) {
      const item = rawItem;
      if (!isTextItem(item) || item.str.trim().length === 0) {
        continue;
      }
      const fontSize = getFontSize(item);
      if (fontSize > 0) {
        const rounded = roundFontSize(fontSize);
        sizeCounts.set(rounded, (sizeCounts.get(rounded) ?? 0) + 1);
      }
    }
  }
  let bodySize = 0;
  let maxCount = 0;
  for (const [size, count] of sizeCounts) {
    if (count > maxCount) {
      maxCount = count;
      bodySize = size;
    }
  }
  if (bodySize === 0) {
    return [];
  }
  const headingThreshold = bodySize * OUTLINE_HEADING_SIZE_RATIO;
  const headingSizes = /* @__PURE__ */ new Set();
  for (const [size] of sizeCounts) {
    if (size >= headingThreshold) {
      headingSizes.add(size);
    }
  }
  if (headingSizes.size === 0) {
    return [];
  }
  const sortedSizes = [...headingSizes].sort((a, b) => b - a);
  const sizeToDepth = /* @__PURE__ */ new Map();
  for (let i = 0; i < sortedSizes.length; i++) {
    sizeToDepth.set(sortedSizes[i], i);
  }
  const candidateHeadings = [];
  for (let pageIdx = 0; pageIdx < pageContents.length; pageIdx++) {
    const textContent = pageContents[pageIdx];
    const pageNumber = pageIdx + 1;
    let lineItems = [];
    let linePageNumber = pageNumber;
    let lineFontName = "";
    let lineHeadingFontSize = 0;
    let lastFlushWasHeading = false;
    const flushLine = () => {
      if (lineItems.length === 0) return;
      let headingChars = 0;
      let totalChars = 0;
      for (const li of lineItems) {
        const len = li.text.trim().length;
        totalChars += len;
        if (sizeToDepth.has(roundFontSize(li.fontSize))) {
          headingChars += len;
        }
      }
      if (totalChars > 0 && headingChars / totalChars > 0.5) {
        const fullText = lineItems.map((li) => li.text).join("").trim();
        if (fullText.length > 0) {
          candidateHeadings.push({
            text: fullText,
            fontSize: lineHeadingFontSize,
            pageNumber: linePageNumber,
            fontName: lineFontName,
            contiguous: lastFlushWasHeading
          });
        }
        lastFlushWasHeading = true;
      } else {
        lastFlushWasHeading = false;
      }
      lineItems = [];
      lineHeadingFontSize = 0;
    };
    for (const rawItem of textContent.items) {
      const item = rawItem;
      if (!isTextItem(item)) {
        continue;
      }
      const fontSize = getFontSize(item);
      const rounded = roundFontSize(fontSize);
      const isHeadingSized = sizeToDepth.has(rounded);
      if (isHeadingSized && lineHeadingFontSize === 0) {
        lineHeadingFontSize = rounded;
        linePageNumber = pageNumber;
        lineFontName = item.fontName;
      }
      if (lineHeadingFontSize > 0) {
        lineItems.push({
          text: item.str,
          fontSize
        });
      }
      if (item.hasEOL) {
        flushLine();
      }
    }
    flushLine();
  }
  const mergedHeadings = [];
  for (const heading of candidateHeadings) {
    const prev = mergedHeadings[mergedHeadings.length - 1];
    if (prev != null && heading.contiguous && Math.abs(prev.fontSize - heading.fontSize) < 0.1) {
      prev.text += " " + heading.text;
    } else {
      mergedHeadings.push({
        ...heading
      });
    }
  }
  return mergedHeadings.filter((heading) => heading.text.trim().length <= OUTLINE_MAX_HEADING_LENGTH).map((heading) => ({
    title: heading.text.trim(),
    depth: sizeToDepth.get(heading.fontSize) ?? 0,
    pageNumber: heading.pageNumber,
    bold: false,
    italic: false
  }));
}
function usePdfAnnotationPortals(pdfViewerRef, eventBusRef, document) {
  const [portalTargets, setPortalTargets] = React7.useState([]);
  React7.useEffect(function subscribePageEvents() {
    const eventBus = eventBusRef.current;
    const pdfViewer = pdfViewerRef.current;
    if (eventBus == null || pdfViewer == null) {
      return;
    }
    const measurePage = (pageNumber, containerRect, scrollContainer2) => {
      const pageView = pdfViewer.getPageView(pageNumber - 1);
      if (pageView?.div == null || pageView?.viewport == null) {
        return null;
      }
      const div = pageView.div;
      const divRect = div.getBoundingClientRect();
      if (divRect.width <= 0 || divRect.height <= 0) {
        return null;
      }
      return {
        pageNumber,
        // Assumes scrollContainer has zero border/padding; otherwise overlays will be offset.
        left: divRect.left - containerRect.left + scrollContainer2.scrollLeft,
        top: divRect.top - containerRect.top + scrollContainer2.scrollTop,
        width: divRect.width,
        height: divRect.height,
        // viewBox is [xMin, yMin, width, height] and we need the original height before scaling
        pageHeight: pageView.viewport.viewBox[3],
        scale: pageView.viewport.scale,
        transform: pageView.viewport.transform.slice()
      };
    };
    const readContainer = () => {
      const scrollContainer2 = pdfViewer.container;
      if (scrollContainer2 == null) {
        return null;
      }
      return {
        rect: scrollContainer2.getBoundingClientRect(),
        el: scrollContainer2
      };
    };
    const handlePageRendered = (evt) => {
      const container = readContainer();
      if (container == null) {
        return;
      }
      const next = measurePage(evt.pageNumber, container.rect, container.el);
      setPortalTargets((prev) => {
        const filtered = prev.filter((t) => t.pageNumber !== evt.pageNumber);
        if (next == null) {
          return filtered;
        }
        return [...filtered, next].sort((a, b) => a.pageNumber - b.pageNumber);
      });
    };
    let rafHandle = null;
    const flushRemeasure = () => {
      rafHandle = null;
      setPortalTargets((prev) => {
        if (prev.length === 0) {
          return prev;
        }
        const container = readContainer();
        if (container == null) {
          return prev;
        }
        const next = [];
        for (const target of prev) {
          const remeasured = measurePage(target.pageNumber, container.rect, container.el);
          if (remeasured != null) {
            next.push(remeasured);
          }
        }
        return next;
      });
    };
    const remeasureAll = () => {
      if (rafHandle != null) {
        return;
      }
      rafHandle = requestAnimationFrame(flushRemeasure);
    };
    eventBus.on(PAGE_RENDERED_EVENT, handlePageRendered);
    eventBus.on("scalechanging", remeasureAll);
    eventBus.on("rotationchanging", remeasureAll);
    const scrollContainer = pdfViewer.container;
    let containerObserver;
    if (scrollContainer != null && typeof ResizeObserver !== "undefined") {
      containerObserver = new ResizeObserver(remeasureAll);
      containerObserver.observe(scrollContainer);
    }
    return () => {
      eventBus.off(PAGE_RENDERED_EVENT, handlePageRendered);
      eventBus.off("scalechanging", remeasureAll);
      eventBus.off("rotationchanging", remeasureAll);
      containerObserver?.disconnect();
      if (rafHandle != null) {
        cancelAnimationFrame(rafHandle);
        rafHandle = null;
      }
      setPortalTargets([]);
    };
  }, [document]);
  return portalTargets;
}
var pdfWorkerUrl = new URL("pdfjs-dist/build/pdf.worker.min.mjs", chunkPZPCRXSV_cjs.importMetaUrl);
function toDocumentParams(src) {
  if (src instanceof Blob) {
    return src.arrayBuffer().then((data) => ({
      data
    }));
  }
  return Promise.resolve(typeof src === "string" ? {
    url: src
  } : {
    data: src
  });
}
var pdfWorker = {
  workerInitialized: false,
  ensureWorker() {
    pdfjsDist.GlobalWorkerOptions.workerSrc = pdfWorkerUrl.href;
    this.workerInitialized = true;
  }
};
function usePdfDocument(src) {
  const [document, setDocument] = React7.useState(void 0);
  const [numPages, setNumPages] = React7.useState(0);
  const [loading, setLoading] = React7.useState(true);
  const [error, setError] = React7.useState(void 0);
  React7.useEffect(function loadPdfDocument() {
    pdfWorker.ensureWorker();
    setLoading(true);
    setError(void 0);
    let cancelled = false;
    let loadingTask;
    const startLoad = (params) => {
      if (cancelled) {
        return;
      }
      loadingTask = pdfjsDist.getDocument(params);
      loadingTask.promise.then((pdf) => {
        if (!cancelled) {
          setDocument(pdf);
          setNumPages(pdf.numPages);
          setLoading(false);
        }
      }, (err) => {
        if (!cancelled) {
          setError(err instanceof Error ? err : new Error(String(err)));
          setLoading(false);
        }
      });
    };
    toDocumentParams(src).then(startLoad, (err) => {
      if (!cancelled) {
        setError(err instanceof Error ? err : new Error(String(err)));
        setLoading(false);
      }
    });
    return () => {
      cancelled = true;
      void loadingTask?.destroy();
    };
  }, [src]);
  return {
    document,
    numPages,
    loading,
    error
  };
}
function usePdfViewer(containerRef, viewerRef, document, initialScale, initialPage) {
  const pdfViewerRef = React7.useRef(null);
  const eventBusRef = React7.useRef(null);
  const findControllerRef = React7.useRef(null);
  React7.useEffect(function initializePdfViewer() {
    const container = containerRef.current;
    const viewer = viewerRef.current;
    if (container == null || viewer == null || document == null) {
      return;
    }
    const eventBus = new pdf_viewer_mjs.EventBus();
    const linkService = new pdf_viewer_mjs.PDFLinkService({
      eventBus
    });
    const findController = new pdf_viewer_mjs.PDFFindController({
      linkService,
      eventBus,
      updateMatchesCountOnProgress: true
    });
    const pdfViewer = new pdf_viewer_mjs.PDFViewer({
      container,
      viewer,
      eventBus,
      linkService,
      findController,
      removePageBorders: true,
      annotationEditorMode: pdfjsDist.AnnotationEditorType.NONE,
      annotationEditorHighlightColors: "yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F"
    });
    linkService.setViewer(pdfViewer);
    linkService.setDocument(document);
    findController.setDocument(document);
    pdfViewer.setDocument(document);
    const onPagesLoaded = () => {
      if (initialScale != null) {
        pdfViewer.currentScale = initialScale;
      }
      if (initialPage != null && initialPage > 1) {
        pdfViewer.currentPageNumber = initialPage;
        pdfViewer.scrollPageIntoView({
          pageNumber: initialPage
        });
      }
      eventBus.off(PAGES_LOADED_EVENT, onPagesLoaded);
    };
    eventBus.on(PAGES_LOADED_EVENT, onPagesLoaded);
    eventBusRef.current = eventBus;
    findControllerRef.current = findController;
    pdfViewerRef.current = pdfViewer;
    return () => {
      pdfViewerRef.current = null;
      eventBusRef.current = null;
      findControllerRef.current = null;
      pdfViewer.cleanup();
    };
  }, [containerRef, viewerRef, document]);
  return {
    pdfViewerRef,
    eventBusRef,
    findControllerRef
  };
}
function usePdfViewerSync({
  pdfViewerRef,
  eventBusRef,
  containerRef,
  document,
  scale,
  autoSize,
  onScaleChange,
  onPageChange
}) {
  const lastScaleRef = React7.useRef(scale);
  React7.useEffect(function syncScaleToViewer() {
    const pdfViewer = pdfViewerRef.current;
    if (pdfViewer == null || autoSize) {
      return;
    }
    if (Math.abs(lastScaleRef.current - scale) > 1e-3) {
      lastScaleRef.current = scale;
      pdfViewer.currentScale = scale;
    }
  }, [pdfViewerRef, scale, autoSize]);
  React7.useEffect(function syncAutoSizeToViewer() {
    const pdfViewer = pdfViewerRef.current;
    const eventBus = eventBusRef.current;
    if (pdfViewer == null || !autoSize) {
      return;
    }
    const applyPageWidth = () => {
      pdfViewer.currentScaleValue = PAGE_WIDTH_SCALE_VALUE;
    };
    if (pdfViewer.pagesCount > 0) {
      applyPageWidth();
    }
    if (eventBus != null) {
      eventBus.on(PAGES_LOADED_EVENT, applyPageWidth);
      return () => {
        eventBus.off(PAGES_LOADED_EVENT, applyPageWidth);
      };
    }
  }, [pdfViewerRef, eventBusRef, autoSize, document]);
  React7.useEffect(function observeContainerResize() {
    const container = containerRef.current;
    const pdfViewer = pdfViewerRef.current;
    if (container == null || pdfViewer == null || !autoSize) {
      return;
    }
    const observer = new ResizeObserver(() => {
      pdfViewer.currentScaleValue = PAGE_WIDTH_SCALE_VALUE;
    });
    observer.observe(container);
    return () => {
      observer.disconnect();
    };
  }, [containerRef, pdfViewerRef, autoSize, document]);
  React7.useEffect(function subscribeViewerEvents() {
    const eventBus = eventBusRef.current;
    if (eventBus == null) {
      return;
    }
    const handlePageChanging = (evt) => {
      onPageChange(evt.pageNumber);
    };
    const handleScaleChanging = (evt) => {
      lastScaleRef.current = evt.scale;
      onScaleChange(evt.scale);
    };
    eventBus.on(PAGE_CHANGING_EVENT, handlePageChanging);
    eventBus.on(SCALE_CHANGING_EVENT, handleScaleChanging);
    return () => {
      eventBus.off(PAGE_CHANGING_EVENT, handlePageChanging);
      eventBus.off(SCALE_CHANGING_EVENT, handleScaleChanging);
    };
  }, [eventBusRef, document, onPageChange, onScaleChange]);
  const scrollToPage = React7.useCallback((page) => {
    const pdfViewer = pdfViewerRef.current;
    if (pdfViewer != null) {
      pdfViewer.currentPageNumber = page;
    }
  }, [pdfViewerRef]);
  return {
    scrollToPage
  };
}
function usePdfViewerCore({
  src,
  initialPage = 1,
  initialScale = 1,
  initialAutoSize = false
}) {
  const {
    document,
    numPages,
    loading,
    error
  } = usePdfDocument(src);
  const [scale, setScale] = React7.useState(initialScale);
  const [currentPage, setCurrentPage] = React7.useState(initialPage);
  const [autoSize, setAutoSize] = React7.useState(initialAutoSize);
  const containerRef = React7.useRef(null);
  const viewerRef = React7.useRef(null);
  const {
    pdfViewerRef,
    eventBusRef,
    findControllerRef
  } = usePdfViewer(containerRef, viewerRef, document, initialScale, initialPage);
  const handleScaleChange = React7.useCallback((newScale) => {
    setScale(newScale);
  }, []);
  const handlePageChange = React7.useCallback((page) => {
    setCurrentPage(page);
  }, []);
  const {
    scrollToPage: syncScrollToPage
  } = usePdfViewerSync({
    pdfViewerRef,
    eventBusRef,
    containerRef,
    document,
    scale,
    autoSize,
    onScaleChange: handleScaleChange,
    onPageChange: handlePageChange
  });
  const scrollToPage = React7.useCallback((page) => {
    setCurrentPage(page);
    syncScrollToPage(page);
  }, [syncScrollToPage]);
  const portalTargets = usePdfAnnotationPortals(pdfViewerRef, eventBusRef, document);
  return React7.useMemo(() => ({
    document,
    numPages,
    loading,
    error,
    containerRef,
    viewerRef,
    currentPage,
    scrollToPage,
    scale,
    setScale,
    autoSize,
    setAutoSize,
    portalTargets,
    pdfViewerRef,
    eventBusRef,
    findControllerRef
  }), [document, numPages, loading, error, currentPage, scrollToPage, scale, setScale, autoSize, setAutoSize, portalTargets]);
}
function usePdfViewerSearch(eventBusRef, findControllerRef, document) {
  const [query, setQueryState] = React7.useState(EMPTY_STRING);
  const [totalMatches, setTotalMatches] = React7.useState(0);
  const [currentMatchIndex, setCurrentMatchIndex] = React7.useState(0);
  const [isSearchOpen, setIsSearchOpen] = React7.useState(false);
  const dispatchFind = React7.useCallback((queryString, findPrevious) => {
    eventBusRef.current?.dispatch(FIND_EVENT, {
      source: void 0,
      type: "",
      query: queryString,
      caseSensitive: false,
      highlightAll: true,
      phraseSearch: true,
      findPrevious
    });
  }, [eventBusRef]);
  const dispatchFindAgain = React7.useCallback((findPrevious) => {
    eventBusRef.current?.dispatch(FIND_EVENT, {
      source: void 0,
      type: "again",
      query,
      caseSensitive: false,
      highlightAll: true,
      phraseSearch: true,
      findPrevious
    });
  }, [eventBusRef, query]);
  const setQuery = React7.useCallback((input) => {
    setQueryState(input);
    if (input === EMPTY_STRING) {
      setTotalMatches(0);
      setCurrentMatchIndex(0);
      dispatchFind(EMPTY_STRING, false);
      return;
    }
    dispatchFind(input, false);
  }, [dispatchFind]);
  const nextMatch = React7.useCallback(() => {
    dispatchFindAgain(false);
  }, [dispatchFindAgain]);
  const prevMatch = React7.useCallback(() => {
    dispatchFindAgain(true);
  }, [dispatchFindAgain]);
  const openSearch = React7.useCallback(() => {
    setIsSearchOpen(true);
  }, []);
  const closeSearch = React7.useCallback(() => {
    setIsSearchOpen(false);
    setQueryState(EMPTY_STRING);
    setTotalMatches(0);
    setCurrentMatchIndex(0);
    dispatchFind(EMPTY_STRING, false);
  }, [dispatchFind]);
  React7.useEffect(function subscribeSearchEvents() {
    const eventBus = eventBusRef.current;
    if (eventBus == null) {
      return;
    }
    const handleMatchesCount = (evt) => {
      setTotalMatches(evt.matchesCount.total);
      setCurrentMatchIndex(evt.matchesCount.current > 0 ? evt.matchesCount.current - 1 : 0);
    };
    const handleControlState = (evt) => {
      setTotalMatches(evt.matchesCount.total);
      setCurrentMatchIndex(evt.matchesCount.current > 0 ? evt.matchesCount.current - 1 : 0);
    };
    eventBus.on(UPDATE_FIND_MATCHES_COUNT_EVENT, handleMatchesCount);
    eventBus.on(UPDATE_FIND_CONTROL_STATE_EVENT, handleControlState);
    return () => {
      eventBus.off(UPDATE_FIND_MATCHES_COUNT_EVENT, handleMatchesCount);
      eventBus.off(UPDATE_FIND_CONTROL_STATE_EVENT, handleControlState);
    };
  }, [eventBusRef, findControllerRef, document]);
  return React7.useMemo(() => ({
    query,
    totalMatches,
    currentMatchIndex,
    isSearchOpen,
    setQuery,
    nextMatch,
    prevMatch,
    openSearch,
    closeSearch
  }), [query, totalMatches, currentMatchIndex, isSearchOpen, setQuery, nextMatch, prevMatch, openSearch, closeSearch]);
}
function usePdfViewerState({
  src,
  initialPage,
  initialScale,
  initialAutoSize,
  initialSidebarOpen = false,
  sidebarMode: sidebarModeProp = "thumbnails",
  onDownload
}) {
  const core = usePdfViewerCore({
    src,
    initialPage,
    initialScale,
    initialAutoSize
  });
  const [rotation, setRotation] = React7.useState(0);
  const [sidebarOpen, setSidebarOpen] = React7.useState(initialSidebarOpen);
  const [sidebarMode, setSidebarMode] = React7.useState(sidebarModeProp);
  const search = usePdfViewerSearch(core.eventBusRef, core.findControllerRef, core.document);
  const outlineItems = usePdfOutline(core.document);
  React7.useEffect(function syncSidebarMode() {
    setSidebarMode(sidebarModeProp);
  }, [sidebarModeProp]);
  React7.useEffect(function syncRotationToViewer() {
    const pdfViewer = core.pdfViewerRef.current;
    if (pdfViewer != null) {
      pdfViewer.pagesRotation = rotation;
    }
  }, [core.pdfViewerRef, rotation]);
  const prevRotationRef = React7.useRef(rotation);
  React7.useEffect(function reapplyAutoSizeAfterRotation() {
    if (prevRotationRef.current === rotation) {
      return;
    }
    prevRotationRef.current = rotation;
    const pdfViewer = core.pdfViewerRef.current;
    if (pdfViewer == null || !core.autoSize) {
      return;
    }
    pdfViewer.currentScaleValue = PAGE_WIDTH_SCALE_VALUE;
  }, [core.pdfViewerRef, core.autoSize, rotation]);
  React7.useEffect(function registerSearchShortcut() {
    const handleKeyDown = (e) => {
      if ((e.ctrlKey || e.metaKey) && e.key === "f") {
        e.preventDefault();
        search.openSearch();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [search.openSearch]);
  const zoomIn = React7.useCallback(() => {
    core.setAutoSize(false);
    core.setScale(Math.min(core.scale + SCALE_STEP, MAX_SCALE));
  }, [core.scale, core.setScale, core.setAutoSize]);
  const zoomOut = React7.useCallback(() => {
    core.setAutoSize(false);
    core.setScale(Math.max(core.scale - SCALE_STEP, MIN_SCALE));
  }, [core.scale, core.setScale, core.setAutoSize]);
  const toggleAutoSize = React7.useCallback(() => {
    core.setAutoSize(!core.autoSize);
  }, [core.autoSize, core.setAutoSize]);
  const rotateLeft = React7.useCallback(() => {
    setRotation((prev) => (prev - 90 + 360) % 360);
  }, []);
  const rotateRight = React7.useCallback(() => {
    setRotation((prev) => (prev + 90) % 360);
  }, []);
  const toggleSidebar = React7.useCallback(() => {
    setSidebarOpen((prev) => !prev);
  }, []);
  const download = React7.useCallback((filename) => {
    if (core.document == null) {
      return;
    }
    void core.document.getData().then((data) => {
      const blob = new Blob([data.buffer], {
        type: "application/pdf"
      });
      const url = URL.createObjectURL(blob);
      const resolvedFilename = resolveDownloadFilename(src, filename);
      const a = globalThis.document.createElement("a");
      a.href = url;
      a.download = resolvedFilename;
      a.click();
      URL.revokeObjectURL(url);
      onDownload?.({
        success: true,
        filename: resolvedFilename
      });
    }).catch((err) => {
      onDownload?.({
        success: false,
        error: err instanceof Error ? err : new Error("Failed to download PDF")
      });
    });
  }, [core.document, src, onDownload]);
  return React7.useMemo(() => ({
    ...core,
    zoomIn,
    zoomOut,
    toggleAutoSize,
    rotation,
    rotateLeft,
    rotateRight,
    sidebarOpen,
    sidebarMode,
    setSidebarMode,
    toggleSidebar,
    search,
    outlineItems,
    download
  }), [core, zoomIn, zoomOut, toggleAutoSize, rotation, rotateLeft, rotateRight, sidebarOpen, sidebarMode, setSidebarMode, toggleSidebar, search, outlineItems, download]);
}
function resolveDownloadFilename(src, filename) {
  if (filename != null) {
    return filename;
  }
  if (typeof src === "string") {
    return src.split("/").pop()?.split("?")[0] || "document.pdf";
  }
  return "document.pdf";
}
var PdfAnnotationOverlay = ({
  target,
  annotations,
  onAnnotationClick
}) => {
  const style = React7.useMemo(() => ({
    position: "absolute",
    left: target.left,
    top: target.top,
    width: target.width,
    height: target.height,
    pointerEvents: "none",
    zIndex: 1
  }), [target.left, target.top, target.width, target.height]);
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    style
  }, /* @__PURE__ */ React7__default.default.createElement(PdfViewerAnnotationLayer, {
    annotations,
    pageHeight: target.pageHeight,
    scale: target.scale,
    transform: target.transform,
    onAnnotationClick
  }));
};

// src/pdf-viewer/PdfViewer.module.css
var PdfViewer_default = {};

// src/pdf-viewer/PdfViewer.tsx
var BasePdfViewer = /* @__PURE__ */ React7.forwardRef(function BasePdfViewer2({
  src,
  annotations = EMPTY_ANNOTATION_ARRAY,
  onAnnotationClick,
  onDownload,
  enableHighlight = false,
  onTextHighlight,
  onHighlightDelete,
  formData,
  onFormSubmit,
  onFormChange,
  initialPage = 1,
  initialScale = 1,
  initialAutoSize = false,
  initialSidebarOpen = false,
  enableDownload = false,
  downloadFileName,
  sidebarMode: sidebarModeProp = "thumbnails",
  outlineIcons,
  className
}, ref) {
  const viewer = usePdfViewerState({
    src,
    initialPage,
    initialScale,
    initialAutoSize,
    initialSidebarOpen,
    sidebarMode: sidebarModeProp,
    onDownload
  });
  const {
    highlightModeActive,
    toggleHighlightMode,
    deleteHighlight
  } = usePdfHighlightMode({
    pdfViewerRef: viewer.pdfViewerRef,
    document: viewer.document,
    enabled: enableHighlight,
    onTextHighlight,
    onHighlightDelete
  });
  React7.useImperativeHandle(ref, () => ({
    scrollToPage: viewer.scrollToPage,
    deleteHighlight
  }), [viewer.scrollToPage, deleteHighlight]);
  const {
    hasFormFields,
    submitFormData
  } = usePdfFormFields({
    pdfViewerRef: viewer.pdfViewerRef,
    eventBusRef: viewer.eventBusRef,
    document: viewer.document,
    formData,
    onFormSubmit,
    onFormChange
  });
  const annotationsByPage = usePdfAnnotationsByPage(annotations);
  const handleDownload = React7.useCallback(() => {
    viewer.download(downloadFileName);
  }, [viewer, downloadFileName]);
  const rootClassName = classnames4__default.default(PdfViewer_default.pdfViewer, className);
  if (viewer.loading) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: rootClassName
    }, /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewer_default.loadingContainer
    }, /* @__PURE__ */ React7__default.default.createElement(icons.Spin, {
      className: PdfViewer_default.spinnerIcon
    }), "Loading\u2026"));
  }
  if (viewer.error != null) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: rootClassName
    }, /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewer_default.errorContainer
    }, /* @__PURE__ */ React7__default.default.createElement(icons.Error, {
      className: PdfViewer_default.errorIcon
    }), "Failed to load PDF: ", viewer.error.message));
  }
  if (viewer.document == null) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: rootClassName
    }, /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewer_default.loadingContainer
    }, "No document"));
  }
  return /* @__PURE__ */ React7__default.default.createElement("div", {
    className: rootClassName
  }, /* @__PURE__ */ React7__default.default.createElement(PdfViewerToolbar, {
    currentPage: viewer.currentPage,
    numPages: viewer.numPages,
    scale: viewer.scale,
    autoSize: viewer.autoSize,
    sidebarOpen: viewer.sidebarOpen,
    onPageChange: viewer.scrollToPage,
    onZoomIn: viewer.zoomIn,
    onZoomOut: viewer.zoomOut,
    onAutoSizeToggle: viewer.toggleAutoSize,
    onSearchOpen: viewer.search.openSearch,
    onSidebarToggle: viewer.toggleSidebar,
    onDownload: handleDownload,
    enableDownload,
    onRotateLeft: viewer.rotateLeft,
    onRotateRight: viewer.rotateRight,
    enableHighlight,
    highlightModeActive,
    onHighlightToggle: toggleHighlightMode,
    enableFormSave: onFormSubmit != null && hasFormFields,
    onFormSave: submitFormData
  }), viewer.search.isSearchOpen && /* @__PURE__ */ React7__default.default.createElement(PdfViewerSearchBar, {
    query: viewer.search.query,
    totalMatches: viewer.search.totalMatches,
    currentMatchIndex: viewer.search.currentMatchIndex,
    onQueryChange: viewer.search.setQuery,
    onNext: viewer.search.nextMatch,
    onPrev: viewer.search.prevMatch,
    onClose: viewer.search.closeSearch
  }), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewer_default.contentArea
  }, viewer.sidebarOpen && viewer.sidebarMode === "thumbnails" && /* @__PURE__ */ React7__default.default.createElement(PdfViewerSidebar, {
    document: viewer.document,
    numPages: viewer.numPages,
    currentPage: viewer.currentPage,
    onPageClick: viewer.scrollToPage,
    sidebarMode: viewer.sidebarMode,
    onSidebarModeChange: viewer.setSidebarMode
  }), viewer.sidebarOpen && viewer.sidebarMode === "outline" && /* @__PURE__ */ React7__default.default.createElement(PdfViewerOutlineSidebar, {
    outlineItems: viewer.outlineItems,
    currentPage: viewer.currentPage,
    onItemClick: viewer.scrollToPage,
    sidebarMode: viewer.sidebarMode,
    onSidebarModeChange: viewer.setSidebarMode,
    outlineIcons
  }), /* @__PURE__ */ React7__default.default.createElement("div", {
    className: PdfViewer_default.scrollContainerWrapper
  }, /* @__PURE__ */ React7__default.default.createElement("div", {
    ref: viewer.containerRef,
    className: PdfViewer_default.scrollContainer
  }, /* @__PURE__ */ React7__default.default.createElement("div", {
    ref: viewer.viewerRef,
    className: "pdfViewer"
  }), viewer.portalTargets.map((target) => {
    const pageAnnotations = annotationsByPage[target.pageNumber] ?? EMPTY_ANNOTATION_ARRAY;
    if (pageAnnotations.length === 0) {
      return null;
    }
    return /* @__PURE__ */ React7__default.default.createElement(PdfAnnotationOverlay, {
      key: target.pageNumber,
      target,
      annotations: pageAnnotations,
      onAnnotationClick
    });
  })))));
});
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function(n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}
async function fetchMediaContents(media) {
  const result = await media.fetchContents();
  return result.arrayBuffer();
}
function PdfViewer({
  media,
  className,
  ...pdfViewerProps
}) {
  const [src, setSrc] = React7.useState(void 0);
  const [loading, setLoading] = React7.useState(true);
  const [error, setError] = React7.useState(void 0);
  React7.useEffect(function fetchMediaSource() {
    let cancelled = false;
    setLoading(true);
    setError(void 0);
    setSrc(void 0);
    fetchMediaContents(media).then((buffer) => {
      if (!cancelled) {
        setSrc(buffer);
        setLoading(false);
      }
    }).catch((err) => {
      if (!cancelled) {
        setError(err instanceof Error ? err : new Error(String(err)));
        setLoading(false);
      }
    });
    return () => {
      cancelled = true;
    };
  }, [media]);
  const rootClassName = classnames4__default.default(PdfViewer_default.pdfViewer, className);
  if (loading) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: rootClassName
    }, /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewer_default.loadingContainer
    }, /* @__PURE__ */ React7__default.default.createElement(icons.Spin, {
      className: PdfViewer_default.spinnerIcon
    }), "Loading\u2026"));
  }
  if (error != null) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: rootClassName
    }, /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewer_default.errorContainer
    }, /* @__PURE__ */ React7__default.default.createElement(icons.Error, {
      className: PdfViewer_default.errorIcon
    }), "Failed to load PDF: ", error.message));
  }
  if (src == null) {
    return /* @__PURE__ */ React7__default.default.createElement("div", {
      className: rootClassName
    }, /* @__PURE__ */ React7__default.default.createElement("div", {
      className: PdfViewer_default.loadingContainer
    }, "No document"));
  }
  return /* @__PURE__ */ React7__default.default.createElement(BasePdfViewer, _extends({
    src,
    className
  }, pdfViewerProps));
}

exports.BasePdfViewer = BasePdfViewer;
exports.EMPTY_ANNOTATION_ARRAY = EMPTY_ANNOTATION_ARRAY;
exports.PdfAnnotationOverlay = PdfAnnotationOverlay;
exports.PdfViewer = PdfViewer;
exports.PdfViewerAnnotationLayer = PdfViewerAnnotationLayer;
exports.PdfViewerOutlineSidebar = PdfViewerOutlineSidebar;
exports.PdfViewerSearchBar = PdfViewerSearchBar;
exports.PdfViewerSidebar = PdfViewerSidebar;
exports.PdfViewerToolbar = PdfViewerToolbar;
exports.PdfViewer_default = PdfViewer_default;
exports.usePdfAnnotationPortals = usePdfAnnotationPortals;
exports.usePdfAnnotationsByPage = usePdfAnnotationsByPage;
exports.usePdfDocument = usePdfDocument;
exports.usePdfFormFields = usePdfFormFields;
exports.usePdfHighlightMode = usePdfHighlightMode;
exports.usePdfOutline = usePdfOutline;
exports.usePdfViewer = usePdfViewer;
exports.usePdfViewerCore = usePdfViewerCore;
exports.usePdfViewerSearch = usePdfViewerSearch;
exports.usePdfViewerState = usePdfViewerState;
exports.usePdfViewerSync = usePdfViewerSync;
//# sourceMappingURL=chunk-XJDMSVW4.cjs.map
//# sourceMappingURL=chunk-XJDMSVW4.cjs.map