"use client";

import { useEffect, useCallback, useState, ReactNode } from "react";
import { useAgentUpdates } from "@/hooks/useAgentUpdates";
import { useMarketData } from "@/hooks/useMarketData";
import { ToastContainer, useToast } from "@/components/ui/Toast";

// WebSocket Manager Component for global WebSocket management
function WebSocketManager() {
  const { addToast } = useToast();

  const handleToast = useCallback(
    (message: string, type: "success" | "error" | "warning" | "info") => {
      addToast(message, type);
    },
    [addToast],
  );

  // Initialize agent WebSocket connection - Direct connect to backend to avoid proxy upgrade issues
  const { isConnected: isAgentConnected } = useAgentUpdates({
    url: typeof window !== "undefined" ? `ws://${window.location.hostname}:8000/ws` : "ws://localhost:8000/ws",
    onToast: handleToast,
    enabled: true,
  });

  // Initialize market data WebSocket connection - Direct connect to backend
  const { isConnected: isMarketConnected } = useMarketData({
    url: typeof window !== "undefined" ? `ws://${window.location.hostname}:8000/ws/market` : "ws://localhost:8000/ws/market",
    enabled: true,
  });

  useEffect(() => {
    console.log("[WebSocketManager] Connection status:", {
      agent: isAgentConnected,
      market: isMarketConnected,
    });
  }, [isAgentConnected, isMarketConnected]);

  return null;
}

// Toast Provider Component
function ToastProvider({ children }: { children: ReactNode }) {
  const { toasts, removeToast } = useToast();

  return (
    <>
      {children}
      <ToastContainer
        toasts={toasts}
        onRemove={removeToast}
        position="top-right"
      />
    </>
  );
}

export function Providers({ children }: { children: ReactNode }) {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return <>{children}</>;
  }

  return (
    <ToastProvider>
      <WebSocketManager />
      {children}
    </ToastProvider>
  );
}
