// useCameraCheck.ts
import { useState, useCallback } from "react";

type DeviceCheckState = {
  hasCamera: boolean;
  hasMicrophone: boolean;
  cameraError: string | null;
  microphoneError: string | null;
};

type DeviceCheckResult = DeviceCheckState & {
  isChecking: boolean;
  checkDevices: () => Promise<DeviceCheckState>;
};

export const useDeviceCheck = (): DeviceCheckResult => {
  const [state, setState] = useState<DeviceCheckState>({
    hasCamera: false,
    hasMicrophone: false,
    cameraError: null,
    microphoneError: null,
  });
  const [isChecking, setIsChecking] = useState(false);

  const checkDevices = useCallback(async () => {
    setIsChecking(true);

    let result: DeviceCheckState = {
      hasCamera: false,
      hasMicrophone: false,
      cameraError: null,
      microphoneError: null,
    };

    try {
      const devices = await navigator.mediaDevices.enumerateDevices();
      const videoDevices = devices.filter((d) => d.kind === "videoinput");
      const audioDevices = devices.filter((d) => d.kind === "audioinput");

      result.hasCamera = videoDevices.length > 0;
      result.hasMicrophone = audioDevices.length > 0;

      if (!result.hasCamera) {
        result.cameraError = "No camera device found. Please connect a camera.";
      }

      if (!result.hasMicrophone) {
        result.microphoneError =
          "No microphone found. Please connect a microphone.";
      }

      // ✅ Do not grab a real stream here!
      // Just checking availability is enough
    } catch (err) {
      console.error("Media devices error:", err);
      result = {
        hasCamera: false,
        hasMicrophone: false,
        cameraError: "An error occurred while checking devices.",
        microphoneError: "An error occurred while checking devices.",
      };
    } finally {
      setState(result);
      setIsChecking(false);
    }

    return result;
  }, []);

  return {
    ...state,
    isChecking,
    checkDevices,
  };
};
