import { create } from 'zustand'

export interface DeviceCache {
  logcat?: unknown[]
  networkRequests?: unknown[]
}

interface AppState {
  /** Device whose info is shown in the Devices panel. */
  selectedDeviceId: string | null
  setSelectedDeviceId: (id: string | null) => void

  /** Device being actively monitored by all feature panels (Logcat, Network, etc.). */
  profiledDeviceId: string | null
  setProfiledDeviceId: (id: string | null) => void

  deviceCache: Record<string, DeviceCache>
  patchDeviceCache: (deviceId: string, patch: Partial<DeviceCache>) => void
  clearDeviceCache: (deviceId: string) => void
}

export const useAppStore = create<AppState>((set) => ({
  selectedDeviceId: null,
  setSelectedDeviceId: (id) => set({ selectedDeviceId: id }),

  profiledDeviceId: null,
  setProfiledDeviceId: (id) => set({ profiledDeviceId: id }),

  deviceCache: {},
  patchDeviceCache: (deviceId, patch) =>
    set((s) => ({
      deviceCache: {
        ...s.deviceCache,
        [deviceId]: { ...s.deviceCache[deviceId], ...patch },
      },
    })),
  clearDeviceCache: (deviceId) =>
    set((s) => {
      const next = { ...s.deviceCache }
      delete next[deviceId]
      return { deviceCache: next }
    }),
}))
