// ============================================================
// useDeviceList — 设备枚举 Hook
// 职责：枚举摄像头/麦克风设备列表，监听设备热插拔
// 注意：首次枚举需要先有一次成功的 getUserMedia 授权
// ============================================================

import { useCallback, useEffect, useState } from "react";

export interface DeviceInfo {
  deviceId: string;
  label: string;
}

export function useDeviceList() {
  const [cameras, setCameras] = useState<DeviceInfo[]>([]);
  const [mics, setMics] = useState<DeviceInfo[]>([]);

  /** 枚举当前可用的音视频输入设备 */
  const refreshDevices = useCallback(async () => {
    try {
      const devices = await navigator.mediaDevices.enumerateDevices();
      setCameras(
        devices
          .filter((d) => d.kind === "videoinput")
          .map((d) => ({ deviceId: d.deviceId, label: d.label || `摄像头 ${d.deviceId.slice(0, 4)}` }))
      );
      setMics(
        devices
          .filter((d) => d.kind === "audioinput")
          .map((d) => ({ deviceId: d.deviceId, label: d.label || `麦克风 ${d.deviceId.slice(0, 4)}` }))
      );
    } catch (err) {
      console.warn("[DeviceList] 枚举设备失败:", err);
    }
  }, []);

  // 监听设备热插拔
  useEffect(() => {
    navigator.mediaDevices.addEventListener("devicechange", refreshDevices);
    return () => navigator.mediaDevices.removeEventListener("devicechange", refreshDevices);
  }, [refreshDevices]);

  return { cameras, mics, refreshDevices };
}
