import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useState, useEffect, useRef } from 'react';
import { openWindow } from '../../shared/helpers';
export const LivePreviewContextContext = createContext(null);
const useLivePreview = (disabled = false) => {
    const activeRef = useRef(false);
    const [credentials, setCredentials] = useState(null);
    const [status, setStatus] = useState({
        loading: true,
        active: false,
        deploymentUrl: null,
    });
    useEffect(() => {
        if (disabled) {
            return;
        }
        const statusPoolingInterval = setInterval(() => {
            fetchStatus();
        }, 5000);
        fetchStatus();
        return () => {
            clearInterval(statusPoolingInterval);
        };
    }, []);
    // useEffect(() => {
    //   handleChange();
    // }, []);
    useEffect(() => {
        if (!status.loading && activeRef.current !== status.active) {
            handleChange();
        }
        activeRef.current = status.active;
    }, [activeRef, status.active, status.loading]);
    // useEffect(() => {
    //   if (!status.loading && status.active) {
    //     handleChange();
    //   }
    // }, [status]);
    const fetchStatus = () => {
        return fetch('playground/live-preview/status')
            .then((res) => res.json())
            .then((status) => {
            setStatus({
                loading: false,
                ...status,
            });
        });
    };
    const createTokenWithPayload = async (payload) => {
        const res = await fetch('playground/live-preview/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        return res.json();
    };
    const handleChange = async () => {
        if (status?.active) {
            const { token } = await createTokenWithPayload({});
            setCredentials({
                token: token?.token || null,
                apiUrl: status?.deploymentUrl || null,
            });
        }
        else {
            setCredentials(null);
        }
    };
    return {
        credentials,
        statusLivePreview: status,
        createTokenWithPayload,
        stopLivePreview: async () => {
            await fetch('playground/live-preview/stop');
            await fetchStatus();
            return true;
        },
        startLivePreview: () => {
            return new Promise((resolve, reject) => {
                const callbackUrl = encodeURIComponent(window.location.origin);
                const params = window.location.origin !== 'http://localhost:4000' &&
                    new URLSearchParams({ callbackUrl }).toString();
                const wn = openWindow({
                    url: `https://cubecloud.dev/auth/live-preview${params ? `?${params}` : ''}`,
                });
                if (!wn) {
                    console.error('The popup was blocked by the browser');
                    reject();
                    return;
                }
                const interval = setInterval(() => {
                    if (wn.closed) {
                        clearInterval(interval);
                        resolve(true);
                        fetchStatus();
                    }
                }, 1000);
            });
        },
    };
};
export function LivePreviewContextProvider({ disabled = false, children, }) {
    const devModeHooks = useLivePreview(disabled);
    return (_jsx(LivePreviewContextContext.Provider, { value: {
            ...devModeHooks,
            livePreviewDisabled: disabled,
        }, children: children }));
}
//# sourceMappingURL=LivePreviewContextProvider.js.map