// ============================================================
// WebSocketManager — WebSocket 连接生命周期管理
// 职责：管理连接状态、消息分发
// ============================================================

import { useEffect, useState } from "react";
import { wsClient } from "../../lib/websocket";
import type { ConnectionStatus } from "../../lib/websocket";
import type { ServerMessage } from "../../types";

export function useWebSocketManager() {
  const [status, setStatus] = useState<ConnectionStatus>(wsClient.status);
  const [lastMessage, setLastMessage] = useState<ServerMessage | null>(null);

  useEffect(() => {
    const unsubStatus = wsClient.onStatusChange(setStatus);
    const unsubMessage = wsClient.onMessage(setLastMessage);

    return () => {
      unsubStatus();
      unsubMessage();
    };
  }, []);

  return {
    status,
    lastMessage,
    connect: (token?: string, conversationId?: string) => wsClient.connect(token, conversationId),
    disconnect: () => wsClient.disconnect(),
    send: wsClient.send.bind(wsClient),
  };
}
