"use client";

import { useState, useEffect, useRef } from "react";

export default function WebSocketTest() {
  const [isConnected, setIsConnected] = useState(false);
  const [messages, setMessages] = useState<string[]>([]);
  const [mounted, setMounted] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);
  
  // Ensure we're mounted on client before connecting
  useEffect(() => {
    setMounted(true);
  }, []);
  
  useEffect(() => {
    // Only connect after component is mounted on client
    if (!mounted) return;
    
    // Try connecting to test server on port 8770
    try {
      const ws = new WebSocket('ws://localhost:8770');
      
      ws.onopen = () => {
        console.log('Test WebSocket connected!');
        setIsConnected(true);
        wsRef.current = ws;
        
        // Send test message
        ws.send(JSON.stringify({ type: 'test', message: 'Hello from client!' }));
      };
      
      ws.onmessage = (event) => {
        console.log('Test WebSocket received:', event.data);
        setMessages(prev => [...prev, event.data]);
      };
      
      ws.onerror = (error) => {
        console.error('Test WebSocket error:', error);
        setIsConnected(false);
      };
      
      ws.onclose = () => {
        console.log('Test WebSocket closed');
        setIsConnected(false);
      };
    } catch (error) {
      console.error('Failed to create WebSocket:', error);
    }
    
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, [mounted]);
  
  // Don't render WebSocket status until mounted to avoid hydration issues
  if (!mounted) {
    return (
      <div className="p-4 bg-gray-800 rounded">
        <h3 className="text-white mb-2">WebSocket Test</h3>
        <div className="text-sm text-gray-400">
          Status: Loading...
        </div>
      </div>
    );
  }
  
  return (
    <div className="p-4 bg-gray-800 rounded">
      <h3 className="text-white mb-2">WebSocket Test</h3>
      <div className={`text-sm ${isConnected ? 'text-green-400' : 'text-red-400'}`}>
        Status: {isConnected ? 'Connected' : 'Disconnected'}
      </div>
      <div className="mt-2 text-xs text-gray-400">
        Messages: {messages.length}
      </div>
    </div>
  );
}