import { useEffect } from 'react';
import { useGatewayWebSocketStore } from '~/store/gateway-websocket';
import { useTokenStore } from '~/store/token';

export function GatewayWebSocketConnectionManager() {
    const connectWebSocket = useGatewayWebSocketStore((state) => state.connect);
    const disconnectWebSocket = useGatewayWebSocketStore((state) => state.disconnect);
    const wsStatus = useGatewayWebSocketStore((state) => state.status);

    const token = useTokenStore((state) =>
        state.token,
    );

    useEffect(() => {
        console.debug(`WS Manager: Status (${wsStatus})`);

        if (!!token) {
            // Connect if we should be connected and are currently idle, disconnected, or errored out
            if (wsStatus === 'IDLE' || wsStatus === 'DISCONNECTED' || wsStatus === 'ERROR') {
                console.log("WS Manager: Conditions met. Calling connect...");
                // Pass the stable token getter function reference
                connectWebSocket(() => token);
            }
        } else {
            // Disconnect if we shouldn't be connected and are currently in any connected/connecting state
            if (wsStatus !== 'IDLE' && wsStatus !== 'DISCONNECTED') {
                console.log("WS Manager: Conditions no longer met. Calling disconnect...");
                disconnectWebSocket(true); // Intentional disconnect
            }
        }

        // The disconnect logic for component unmount (e.g., user logs out entirely)
        return () => {
            // Check status on unmount to avoid disconnecting if already idle/disconnected
            const currentStatus = useGatewayWebSocketStore.getState().status;
            if (currentStatus !== 'IDLE' && currentStatus !== 'DISCONNECTED') {
                console.log("WS Manager: Unmounting. Calling disconnect...");
                // Ensure Zustand has the latest state before calling disconnect
                useGatewayWebSocketStore.getState().disconnect(true); // Intentional disconnect on unmount
            }
        };
        // Dependencies: connect/disconnect actions, auth status, route location
    }, [connectWebSocket, disconnectWebSocket]);

    // This component doesn't render anything itself
    return null;
}