'use client';
import { useEffect } from 'react';
import { DEFAULT_DEV_REFRESH_PATH, DEFAULT_DEV_REFRESH_PORT, } from '../dev/browser.js';
export function DevRefresh({ enabled = process.env.NODE_ENV !== 'production', wsPort = DEFAULT_DEV_REFRESH_PORT, path = DEFAULT_DEV_REFRESH_PATH, reconnectMs = 1000, }) {
    useEffect(() => {
        if (!enabled || Number(wsPort) <= 0 || typeof window === 'undefined' || window.__gradialDevRefresh) {
            return undefined;
        }
        window.__gradialDevRefresh = true;
        let reconnectTimer;
        let socket;
        let active = true;
        const connect = () => {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            socket = new WebSocket(`${protocol}//${window.location.hostname}:${Number(wsPort)}${path}`);
            socket.addEventListener('message', (event) => {
                try {
                    const message = JSON.parse(event.data);
                    if (message?.type === 'content-updated') {
                        window.location.reload();
                    }
                }
                catch {
                    // Ignore non-Gradial dev server frames.
                }
            });
            socket.addEventListener('close', () => {
                if (active) {
                    reconnectTimer = setTimeout(connect, Number(reconnectMs));
                }
            });
        };
        connect();
        return () => {
            active = false;
            window.__gradialDevRefresh = false;
            if (reconnectTimer) {
                clearTimeout(reconnectTimer);
            }
            socket?.close();
        };
    }, [enabled, wsPort, path, reconnectMs]);
    return null;
}
