import { create } from 'zustand';

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

const MIC_KEY = 'llink:mic-device';
const CAMERA_KEY = 'llink:camera-device';

function load(key: string): SavedDevice | null {
  try {
    const raw = localStorage.getItem(key);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as SavedDevice;
    if (typeof parsed?.deviceId !== 'string') return null;
    return { deviceId: parsed.deviceId, label: parsed.label ?? '' };
  } catch {
    return null;
  }
}

function save(key: string, value: SavedDevice | null) {
  try {
    if (value) localStorage.setItem(key, JSON.stringify(value));
    else localStorage.removeItem(key);
  } catch {
    // Storage unavailable
  }
}

interface MediaDevicesState {
  mic: SavedDevice | null;
  camera: SavedDevice | null;
  setMic: (device: SavedDevice | null) => void;
  setCamera: (device: SavedDevice | null) => void;
}

export const useMediaDevicesStore = create<MediaDevicesState>((set) => ({
  mic: load(MIC_KEY),
  camera: load(CAMERA_KEY),
  setMic: (device) => {
    save(MIC_KEY, device);
    set({ mic: device });
  },
  setCamera: (device) => {
    save(CAMERA_KEY, device);
    set({ camera: device });
  },
}));
