import React, { createContext, useContext } from 'react';
import type { Agent, Share, FleetAlert, PoolStatus, AIActivityEntry, WSMessage } from '../types';
import type { WSCommandResult } from '../types/ws';

/**
 * WSCommandResult with a monotonic sequence number attached by the provider.
 * Consumers should track `_seq` instead of array index to avoid the ring-buffer
 * drop bug that occurs when `.slice(-N)` trims the array but the stored index
 * remains >= N.
 */
export type SeqCommandResult = WSCommandResult & { _seq: number };

export interface WebSocketContextValue {
  isConnected: boolean;
  agents: Agent[];
  recentShares: Share[];
  fleetAlerts: FleetAlert[];
  poolStatus: PoolStatus[];
  aiActivity: AIActivityEntry[];
  agentLogs: Record<string, string>;
  commandResults: SeqCommandResult[];
  /** @deprecated Use commandResults instead. */
  latestMessage: WSMessage | null;
}

export const WebSocketContext = createContext<WebSocketContextValue>({
  isConnected: false,
  agents: [],
  recentShares: [],
  fleetAlerts: [],
  poolStatus: [],
  aiActivity: [],
  agentLogs: {},
  commandResults: [],
  latestMessage: null,
});

export function useWebSocketContext(): WebSocketContextValue {
  return useContext(WebSocketContext);
}
