import { Tooltip, Button } from './chunk-FKEFVCK4.js';
import { forwardRef, useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { useTheme, css } from '@emotion/react';
import { jsxs, jsx } from '@emotion/react/jsx-runtime';

var PDF_FALLBACK_LABELS = {
  toolbarLabel: "PDF viewer toolbar",
  prevPage: "Previous page",
  nextPage: "Next page",
  zoomIn: "Zoom in",
  zoomOut: "Zoom out",
  fitWidth: "Fit width",
  fitPage: "Fit page",
  download: "Download",
  print: "Print",
  pageOf: (current, total) => `Page ${current} of ${total}`
};
function Icon({ size = 16, children }) {
  return /* @__PURE__ */ jsx(
    "svg",
    {
      width: size,
      height: size,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      strokeWidth: 1.8,
      strokeLinecap: "round",
      strokeLinejoin: "round",
      "aria-hidden": true,
      focusable: false,
      children
    }
  );
}
var ChevronLeftIcon = ({ size }) => /* @__PURE__ */ jsx(Icon, { size, children: /* @__PURE__ */ jsx("polyline", { points: "15 18 9 12 15 6" }) });
var ChevronRightIcon = ({ size }) => /* @__PURE__ */ jsx(Icon, { size, children: /* @__PURE__ */ jsx("polyline", { points: "9 18 15 12 9 6" }) });
var ZoomInIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("circle", { cx: "11", cy: "11", r: "7" }),
  /* @__PURE__ */ jsx("line", { x1: "21", y1: "21", x2: "16.65", y2: "16.65" }),
  /* @__PURE__ */ jsx("line", { x1: "11", y1: "8", x2: "11", y2: "14" }),
  /* @__PURE__ */ jsx("line", { x1: "8", y1: "11", x2: "14", y2: "11" })
] });
var ZoomOutIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("circle", { cx: "11", cy: "11", r: "7" }),
  /* @__PURE__ */ jsx("line", { x1: "21", y1: "21", x2: "16.65", y2: "16.65" }),
  /* @__PURE__ */ jsx("line", { x1: "8", y1: "11", x2: "14", y2: "11" })
] });
var FitWidthIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("path", { d: "M3 12h18" }),
  /* @__PURE__ */ jsx("polyline", { points: "7 8 3 12 7 16" }),
  /* @__PURE__ */ jsx("polyline", { points: "17 8 21 12 17 16" })
] });
var DownloadIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }),
  /* @__PURE__ */ jsx("polyline", { points: "7 10 12 15 17 10" }),
  /* @__PURE__ */ jsx("line", { x1: "12", y1: "15", x2: "12", y2: "3" })
] });
var PrintIcon = ({ size }) => /* @__PURE__ */ jsxs(Icon, { size, children: [
  /* @__PURE__ */ jsx("polyline", { points: "6 9 6 2 18 2 18 9" }),
  /* @__PURE__ */ jsx("path", { d: "M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" }),
  /* @__PURE__ */ jsx("rect", { x: "6", y: "14", width: "12", height: "8" })
] });
function PdfViewerToolbar({
  currentPage,
  numPages,
  zoom,
  minZoom,
  maxZoom,
  onPrev,
  onNext,
  onGoToPage,
  onZoomIn,
  onZoomOut,
  onFitWidth,
  onDownload,
  onPrint,
  config,
  labelOverrides,
  isLoading,
  "aria-label": ariaLabelProp
}) {
  const theme = useTheme();
  const labels = { ...PDF_FALLBACK_LABELS, ...labelOverrides };
  const resolvedAriaLabel = ariaLabelProp ?? labels.toolbarLabel;
  const showDownload = config.download === true && !!onDownload;
  const showPrint = config.print === true && !!onPrint;
  const showPageInput = config.pageInput !== false;
  const [inputValue, setInputValue] = useState(String(currentPage));
  useEffect(() => {
    setInputValue(String(currentPage));
  }, [currentPage]);
  const commitPage = useCallback(() => {
    const parsed = parseInt(inputValue, 10);
    if (Number.isFinite(parsed) && parsed >= 1 && parsed <= Math.max(1, numPages)) {
      onGoToPage(parsed);
    } else {
      setInputValue(String(currentPage));
    }
  }, [inputValue, numPages, currentPage, onGoToPage]);
  const handleInputChange = useCallback((e) => {
    setInputValue(e.target.value);
  }, []);
  const containerCss = css`
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 4px;
    padding: 6px 10px;
    border-bottom: ${theme.borders.width.thin} solid ${theme.colors.border.subtle};
    color: ${theme.colors.text.primary};
    background-color: ${theme.colors.bg.muted};
    border-radius: ${theme.componentRadius.md} ${theme.componentRadius.md} 0 0;
  `;
  const separatorCss = css`
    width: ${theme.borders.width.thin};
    align-self: stretch;
    min-height: 16px;
    margin: 2px 4px;
    background: ${theme.colors.border.subtle};
  `;
  const pageInfoCss = css`
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: ${theme.typography.fontSize.xs};
    color: ${theme.colors.text.secondary};
    user-select: none;
    white-space: nowrap;
  `;
  const pageInputCss = css`
    appearance: none;
    -webkit-appearance: none;
    background-color: transparent;
    border: 1px solid ${theme.colors.border.subtle};
    border-radius: ${theme.componentRadius.sm};
    color: ${theme.colors.text.primary};
    font-family: ${theme.typography.fontFamily.sans};
    font-size: ${theme.typography.fontSize.xs};
    height: 24px;
    width: 48px;
    padding: 0 6px;
    text-align: center;
    outline: none;

    &:hover {
      border-color: ${theme.colors.border.default};
    }
    &:focus {
      border-color: ${theme.colors.primary[500]};
      box-shadow: 0 0 0 2px ${theme.colors.primary[100]};
    }

    /* hide spin buttons */
    &::-webkit-outer-spin-button,
    &::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
    }
    -moz-appearance: textfield;
  `;
  const zoomLabelCss = css`
    min-width: 44px;
    text-align: center;
    font-variant-numeric: tabular-nums;
    font-size: ${theme.typography.fontSize.xs};
    color: ${theme.colors.text.secondary};
    user-select: none;
  `;
  const spacerCss = css`
    flex: 1;
  `;
  const zoomPercent = Math.round(zoom * 100);
  const navDisabled = isLoading || numPages <= 0;
  const prevDisabled = navDisabled || currentPage <= 1;
  const nextDisabled = navDisabled || currentPage >= numPages;
  const zoomOutDisabled = zoom <= minZoom + 1e-6;
  const zoomInDisabled = zoom >= maxZoom - 1e-6;
  return /* @__PURE__ */ jsxs("div", { role: "toolbar", "aria-label": resolvedAriaLabel, css: containerCss, children: [
    /* @__PURE__ */ jsx(Tooltip, { content: labels.prevPage, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.prevPage,
        isDisabled: prevDisabled,
        onClick: onPrev,
        children: /* @__PURE__ */ jsx(ChevronLeftIcon, { size: 15 })
      }
    ) }),
    /* @__PURE__ */ jsxs("span", { css: pageInfoCss, children: [
      showPageInput ? /* @__PURE__ */ jsx(
        "input",
        {
          type: "number",
          min: 1,
          max: Math.max(1, numPages),
          step: 1,
          value: inputValue,
          disabled: navDisabled,
          onChange: handleInputChange,
          onBlur: commitPage,
          onKeyDown: (e) => {
            if (e.key === "Enter") {
              e.preventDefault();
              commitPage();
            }
          },
          "aria-label": "Current page",
          css: pageInputCss
        }
      ) : /* @__PURE__ */ jsx("span", { children: currentPage }),
      /* @__PURE__ */ jsx("span", { "aria-hidden": true, children: "/" }),
      /* @__PURE__ */ jsx("span", { "data-testid": "pdf-num-pages", children: numPages || 0 })
    ] }),
    /* @__PURE__ */ jsx(Tooltip, { content: labels.nextPage, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.nextPage,
        isDisabled: nextDisabled,
        onClick: onNext,
        children: /* @__PURE__ */ jsx(ChevronRightIcon, { size: 15 })
      }
    ) }),
    /* @__PURE__ */ jsx("span", { css: separatorCss, "aria-hidden": true }),
    /* @__PURE__ */ jsx(Tooltip, { content: labels.zoomOut, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.zoomOut,
        isDisabled: zoomOutDisabled,
        onClick: onZoomOut,
        children: /* @__PURE__ */ jsx(ZoomOutIcon, { size: 15 })
      }
    ) }),
    /* @__PURE__ */ jsxs("span", { css: zoomLabelCss, "aria-live": "polite", "aria-atomic": "true", children: [
      zoomPercent,
      "%"
    ] }),
    /* @__PURE__ */ jsx(Tooltip, { content: labels.zoomIn, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.zoomIn,
        isDisabled: zoomInDisabled,
        onClick: onZoomIn,
        children: /* @__PURE__ */ jsx(ZoomInIcon, { size: 15 })
      }
    ) }),
    /* @__PURE__ */ jsx(Tooltip, { content: labels.fitWidth, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.fitWidth,
        onClick: onFitWidth,
        children: /* @__PURE__ */ jsx(FitWidthIcon, { size: 15 })
      }
    ) }),
    /* @__PURE__ */ jsx("span", { css: spacerCss }),
    showDownload && /* @__PURE__ */ jsx(Tooltip, { content: labels.download, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.download,
        onClick: onDownload,
        children: /* @__PURE__ */ jsx(DownloadIcon, { size: 15 })
      }
    ) }),
    showPrint && /* @__PURE__ */ jsx(Tooltip, { content: labels.print, placement: "top", children: /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "light",
        color: "default",
        size: "sm",
        isIconOnly: true,
        "aria-label": labels.print,
        onClick: onPrint,
        children: /* @__PURE__ */ jsx(PrintIcon, { size: 15 })
      }
    ) })
  ] });
}
function toCssLength(value) {
  if (value === null || value === void 0) return null;
  return typeof value === "number" ? `${value}px` : value;
}
function buildContainerCss(theme, opts) {
  const widthCss = toCssLength(opts.width) ?? "100%";
  const heightCss = toCssLength(opts.height) ?? "600px";
  return css`
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    width: ${widthCss};
    height: ${heightCss};
    min-width: 0;
    background-color: ${theme.colors.bg.surface};
    border: ${theme.borders.width.thin} solid ${theme.colors.border.default};
    border-radius: ${theme.componentRadius.md};
    overflow: hidden;
    color: ${theme.colors.text.primary};
    font-family: ${theme.typography.fontFamily.sans};

    @media (prefers-reduced-motion: reduce) {
      *,
      *::before,
      *::after {
        animation-duration: 0.001ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.001ms !important;
      }
    }
  `;
}
function buildScrollAreaCss(theme) {
  return css`
    flex: 1 1 auto;
    min-height: 0;
    overflow: auto;
    background-color: ${theme.colors.bg.muted};
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding: 16px;
    outline: none;

    &:focus-visible {
      box-shadow: inset 0 0 0 2px ${theme.colors.primary[500]};
    }
  `;
}
function buildCanvasCss(theme) {
  return css`
    display: block;
    background-color: ${theme.colors.bg.canvas};
    box-shadow: ${theme.shadows.sm};
    max-width: none;
  `;
}
function buildStatusOverlayCss(theme) {
  return css`
    flex: 1 1 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24px;
    text-align: center;
    color: ${theme.colors.text.secondary};
    font-size: ${theme.typography.fontSize.sm};
  `;
}
function buildPageAnnouncerCss() {
  return css`
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
  `;
}
async function sourceToBuffer(source) {
  if (typeof source === "string") {
    const res = await fetch(source);
    if (!res.ok) {
      throw new Error(`Failed to fetch PDF (${res.status} ${res.statusText})`);
    }
    return await res.arrayBuffer();
  }
  if (source instanceof URL) {
    const res = await fetch(source.toString());
    if (!res.ok) {
      throw new Error(`Failed to fetch PDF (${res.status} ${res.statusText})`);
    }
    return await res.arrayBuffer();
  }
  if (source instanceof ArrayBuffer) {
    return source.slice(0);
  }
  if (source instanceof Uint8Array) {
    const copy = new Uint8Array(source.byteLength);
    copy.set(source);
    return copy;
  }
  if (typeof Blob !== "undefined" && source instanceof Blob) {
    return await source.arrayBuffer();
  }
  throw new Error("Unsupported PDF source type");
}
function clamp(n, min, max) {
  return Math.max(min, Math.min(max, n));
}
function resolveDefaultZoomMode(defaultZoom) {
  if (defaultZoom === "page-fit") return "fit";
  if (defaultZoom === "page-width") return "width";
  return "custom";
}
function resolveDefaultZoomValue(defaultZoom) {
  if (typeof defaultZoom === "number") return defaultZoom;
  return 1;
}
function resolveDefaultWorkerSrc() {
  try {
    return new URL("pdfjs-dist/build/pdf.worker.mjs", import.meta.url).toString();
  } catch {
    return null;
  }
}
var PdfViewer = forwardRef(function PdfViewer2(props, ref) {
  const {
    source,
    defaultPage = 1,
    page: pageProp,
    onPageChange,
    zoom: zoomProp,
    onZoomChange,
    defaultZoom = "page-width",
    minZoom = 0.25,
    maxZoom = 4,
    showToolbar = true,
    toolbar,
    onLoad,
    onError,
    loadingFallback,
    errorFallback,
    workerSrc,
    width,
    height,
    className,
    style,
    id,
    "aria-label": ariaLabel = "PDF document",
    ...rest
  } = props;
  const theme = useTheme();
  const [numPages, setNumPages] = useState(0);
  const [internalPage, setInternalPage] = useState(Math.max(1, defaultPage));
  const currentPage = pageProp ?? internalPage;
  const [zoomMode, setZoomMode] = useState(
    () => resolveDefaultZoomMode(defaultZoom)
  );
  const [internalZoom, setInternalZoom] = useState(
    () => resolveDefaultZoomValue(defaultZoom)
  );
  const effectiveZoom = zoomProp ?? internalZoom;
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const containerRef = useRef(null);
  const scrollAreaRef = useRef(null);
  const canvasRef = useRef(null);
  const pdfDocRef = useRef(null);
  const renderTaskRef = useRef(null);
  const pdfjsRef = useRef(null);
  const onLoadRef = useRef(onLoad);
  const onErrorRef = useRef(onError);
  const onPageChangeRef = useRef(onPageChange);
  const onZoomChangeRef = useRef(onZoomChange);
  useEffect(() => {
    onLoadRef.current = onLoad;
  }, [onLoad]);
  useEffect(() => {
    onErrorRef.current = onError;
  }, [onError]);
  useEffect(() => {
    onPageChangeRef.current = onPageChange;
  }, [onPageChange]);
  useEffect(() => {
    onZoomChangeRef.current = onZoomChange;
  }, [onZoomChange]);
  const toolbarConfig = useMemo(() => toolbar ?? {}, [toolbar]);
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (source === void 0 || source === null || source === "") {
      setError(new Error("PDF source is empty"));
      setIsLoading(false);
      onErrorRef.current?.(new Error("PDF source is empty"));
      return;
    }
    let cancelled = false;
    setIsLoading(true);
    setError(null);
    (async () => {
      try {
        const mod = await import(
          /* @vite-ignore */
          'pdfjs-dist'
        );
        if (cancelled) return;
        pdfjsRef.current = mod;
        const resolvedWorker = workerSrc ?? resolveDefaultWorkerSrc();
        if (resolvedWorker && (workerSrc || !mod.GlobalWorkerOptions.workerSrc)) {
          mod.GlobalWorkerOptions.workerSrc = resolvedWorker;
        }
        const data = await sourceToBuffer(source);
        if (cancelled) return;
        const loadingTask = mod.getDocument({ data });
        const doc = await loadingTask.promise;
        if (cancelled) {
          void doc.destroy();
          return;
        }
        const prev = pdfDocRef.current;
        pdfDocRef.current = doc;
        if (prev) {
          try {
            void prev.destroy();
          } catch {
          }
        }
        setNumPages(doc.numPages);
        setIsLoading(false);
        onLoadRef.current?.({ numPages: doc.numPages });
      } catch (err) {
        if (cancelled) return;
        const e = err instanceof Error ? err : new Error(String(err));
        setError(e);
        setIsLoading(false);
        onErrorRef.current?.(e);
      }
    })();
    return () => {
      cancelled = true;
      const task = renderTaskRef.current;
      if (task) {
        try {
          task.cancel();
        } catch {
        }
        renderTaskRef.current = null;
      }
      const doc = pdfDocRef.current;
      if (doc) {
        try {
          void doc.destroy();
        } catch {
        }
        pdfDocRef.current = null;
      }
    };
  }, [source, workerSrc]);
  useEffect(() => {
    if (typeof window === "undefined") return;
    const doc = pdfDocRef.current;
    const canvas = canvasRef.current;
    if (!doc || !canvas) return;
    if (numPages <= 0) return;
    const safePage = clamp(currentPage, 1, numPages);
    let cancelled = false;
    const prevTask = renderTaskRef.current;
    if (prevTask) {
      try {
        prevTask.cancel();
      } catch {
      }
      renderTaskRef.current = null;
    }
    const isStale = () => cancelled || pdfDocRef.current !== doc;
    (async () => {
      try {
        const pageObj = await doc.getPage(safePage);
        if (isStale()) return;
        let scale = effectiveZoom;
        if (zoomMode === "width" && scrollAreaRef.current) {
          const baseViewport = pageObj.getViewport({ scale: 1 });
          const containerW = scrollAreaRef.current.clientWidth - 32;
          if (containerW > 0 && baseViewport.width > 0) {
            scale = clamp(containerW / baseViewport.width, minZoom, maxZoom);
          }
        } else if (zoomMode === "fit" && scrollAreaRef.current) {
          const baseViewport = pageObj.getViewport({ scale: 1 });
          const containerW = scrollAreaRef.current.clientWidth - 32;
          const containerH = scrollAreaRef.current.clientHeight - 32;
          if (containerW > 0 && containerH > 0 && baseViewport.width > 0 && baseViewport.height > 0) {
            scale = clamp(
              Math.min(containerW / baseViewport.width, containerH / baseViewport.height),
              minZoom,
              maxZoom
            );
          }
        }
        const viewport = pageObj.getViewport({ scale });
        canvas.width = Math.max(1, Math.floor(viewport.width));
        canvas.height = Math.max(1, Math.floor(viewport.height));
        canvas.style.width = `${Math.floor(viewport.width)}px`;
        canvas.style.height = `${Math.floor(viewport.height)}px`;
        const ctx = canvas.getContext("2d");
        if (!ctx) return;
        if (isStale()) return;
        const task = pageObj.render({ canvasContext: ctx, viewport });
        renderTaskRef.current = task;
        await task.promise;
        if (isStale()) return;
        renderTaskRef.current = null;
      } catch (err) {
        if (isStale()) return;
        const name = err?.name;
        if (name === "RenderingCancelledException") return;
        const e = err instanceof Error ? err : new Error(String(err));
        setError(e);
        onErrorRef.current?.(e);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [currentPage, effectiveZoom, zoomMode, numPages, minZoom, maxZoom]);
  useEffect(() => {
    if (zoomProp !== void 0) {
      setZoomMode("custom");
    }
  }, [zoomProp]);
  const goToPage = useCallback(
    (next) => {
      const safe = clamp(next, 1, Math.max(1, numPages));
      if (pageProp === void 0) {
        setInternalPage(safe);
      }
      onPageChangeRef.current?.(safe);
    },
    [numPages, pageProp]
  );
  const setZoomValue = useCallback(
    (next) => {
      const safe = clamp(next, minZoom, maxZoom);
      setZoomMode("custom");
      if (zoomProp === void 0) {
        setInternalZoom(safe);
      }
      onZoomChangeRef.current?.(safe);
    },
    [minZoom, maxZoom, zoomProp]
  );
  const handlePrev = useCallback(() => goToPage(currentPage - 1), [goToPage, currentPage]);
  const handleNext = useCallback(() => goToPage(currentPage + 1), [goToPage, currentPage]);
  const handleZoomIn = useCallback(() => {
    setZoomValue(Math.min(maxZoom, effectiveZoom + 0.1));
  }, [effectiveZoom, maxZoom, setZoomValue]);
  const handleZoomOut = useCallback(() => {
    setZoomValue(Math.max(minZoom, effectiveZoom - 0.1));
  }, [effectiveZoom, minZoom, setZoomValue]);
  const handleFitWidth = useCallback(() => {
    setZoomMode("width");
  }, []);
  const handleDownload = useCallback(() => {
    if (typeof window === "undefined" || typeof source !== "string") return;
    try {
      const a = document.createElement("a");
      a.href = source;
      a.download = "";
      a.target = "_blank";
      a.rel = "noopener noreferrer";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } catch {
    }
  }, [source]);
  const handlePrint = useCallback(() => {
    if (typeof window === "undefined") return;
    try {
      window.print();
    } catch {
    }
  }, []);
  const handleKeyDown = useCallback(
    (e) => {
      if (e.defaultPrevented) return;
      switch (e.key) {
        case "ArrowLeft":
        case "PageUp":
          e.preventDefault();
          handlePrev();
          break;
        case "ArrowRight":
        case "PageDown":
          e.preventDefault();
          handleNext();
          break;
        case "+":
        case "=":
          e.preventDefault();
          handleZoomIn();
          break;
        case "-":
        case "_":
          e.preventDefault();
          handleZoomOut();
          break;
        case "0":
          e.preventDefault();
          handleFitWidth();
          break;
      }
    },
    [handlePrev, handleNext, handleZoomIn, handleZoomOut, handleFitWidth]
  );
  const containerCss = buildContainerCss(theme, { width, height });
  const scrollAreaCss = buildScrollAreaCss(theme);
  const canvasCss = buildCanvasCss(theme);
  const overlayCss = buildStatusOverlayCss(theme);
  const announcerCss = buildPageAnnouncerCss();
  const showError = error !== null;
  const showLoading = !showError && isLoading;
  const showCanvas = !showError;
  const errorContent = showError ? typeof errorFallback === "function" ? errorFallback(error) : errorFallback ?? /* @__PURE__ */ jsxs("span", { children: [
    "Failed to load PDF: ",
    error.message
  ] }) : null;
  const loadingContent = showLoading ? loadingFallback ?? /* @__PURE__ */ jsx("span", { children: "Loading PDF\u2026" }) : null;
  const setContainerRef = (el) => {
    containerRef.current = el;
    if (typeof ref === "function") {
      ref(el);
    } else if (ref) {
      ref.current = el;
    }
  };
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref: setContainerRef,
      role: "region",
      "aria-label": ariaLabel,
      id,
      className,
      style,
      css: containerCss,
      "data-loading": showLoading || void 0,
      "data-error": showError || void 0,
      ...rest,
      children: [
        showToolbar && /* @__PURE__ */ jsx(
          PdfViewerToolbar,
          {
            currentPage,
            numPages,
            zoom: effectiveZoom,
            minZoom,
            maxZoom,
            onPrev: handlePrev,
            onNext: handleNext,
            onGoToPage: goToPage,
            onZoomIn: handleZoomIn,
            onZoomOut: handleZoomOut,
            onFitWidth: handleFitWidth,
            onDownload: typeof source === "string" ? handleDownload : void 0,
            onPrint: handlePrint,
            config: toolbarConfig,
            isLoading
          }
        ),
        showError ? /* @__PURE__ */ jsx("div", { role: "alert", css: overlayCss, children: errorContent }) : /* @__PURE__ */ jsxs(
          "div",
          {
            ref: scrollAreaRef,
            tabIndex: 0,
            role: "group",
            "aria-label": "PDF page area",
            onKeyDown: handleKeyDown,
            css: scrollAreaCss,
            "data-slot": "pdf-viewer-mount",
            children: [
              showCanvas && /* @__PURE__ */ jsx(
                "canvas",
                {
                  ref: canvasRef,
                  css: canvasCss,
                  role: "img",
                  "aria-label": "PDF page content",
                  "data-testid": "pdf-canvas"
                }
              ),
              showLoading && /* @__PURE__ */ jsx("div", { css: overlayCss, "data-slot": "pdf-viewer-loading", children: loadingContent })
            ]
          }
        ),
        /* @__PURE__ */ jsx("span", { css: announcerCss, "aria-live": "polite", "data-slot": "pdf-viewer-announcer", children: numPages > 0 ? `Page ${currentPage} of ${numPages}` : "" })
      ]
    }
  );
});
PdfViewer.displayName = "PdfViewer";

export { PdfViewer };
//# sourceMappingURL=pdf-viewer.js.map
//# sourceMappingURL=pdf-viewer.js.map