import Echo from 'laravel-echo';

import Pusher from 'pusher-js';
window.Pusher = Pusher;

if (document.querySelector('[data-requires-reverb]')) {
    window.Echo = new Echo({
        broadcaster: 'reverb',
        key: import.meta.env.VITE_REVERB_APP_KEY,
        wsHost: import.meta.env.VITE_REVERB_HOST,
        wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
        wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
        wsPath: import.meta.env.VITE_REVERB_PATH ?? '',
        forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
        enabledTransports: ['ws', 'wss'],
    });

    // Handle WebSocket connection status events
    const dispatchStatus = (connected) => {
        window.dispatchEvent(new CustomEvent('ws-status', {
            detail: { connected }
        }));
    };

    window.Echo.connector.pusher.connection.bind('connected', () => dispatchStatus(true));
    window.Echo.connector.pusher.connection.bind('unavailable', () => dispatchStatus(false));
    window.Echo.connector.pusher.connection.bind('disconnected', () => dispatchStatus(false));
    window.Echo.connector.pusher.connection.bind('failed', () => dispatchStatus(false));
}
