import {
  isMediaDevicesSupported,
  isValidType
} from "./chunk-XS2KC4AS.js";
import {
  __async
} from "./chunk-W7FAWX6T.js";

// src/components/QRReader/hooks.ts
import { useEffect, useRef } from "react";
var useQRReader = ({
  scanDelay: delayBetweenScanAttempts = 500,
  constraints: video,
  onResult,
  videoId
}) => {
  const mountedRef = useRef(true);
  useEffect(() => {
    const readQRCode = () => __async(void 0, null, function* () {
      const { BrowserQRCodeReader } = yield import(
        /* webpackChunkName: "zxing" */
        "@zxing/browser"
      );
      const codeReader = new BrowserQRCodeReader(void 0, {
        delayBetweenScanAttempts
      });
      if (!isMediaDevicesSupported() && onResult) {
        const message = 'MediaDevices API has no support for your browser. You can fix this by running "npm i webrtc-adapter"';
        onResult(null, new Error(message), codeReader);
      }
      if (video && isValidType(video, "constraints", "object")) {
        codeReader.decodeFromConstraints(
          { video },
          videoId,
          (result, error, controls) => {
            if (mountedRef.current === false) {
              controls.stop();
              return;
            }
            if (typeof result !== "undefined" && onResult) {
              controls.stop();
              onResult(result, error, codeReader);
            }
          }
        ).catch((error) => {
          if (onResult) {
            onResult(null, error, codeReader);
          }
        });
      }
    });
    mountedRef.current = true;
    void readQRCode();
    return () => {
      mountedRef.current = false;
    };
  }, [delayBetweenScanAttempts, onResult, video, videoId]);
};

export {
  useQRReader
};
