window.wizard = wc_el_inv_wizard || {};

function notifyDialog(message, options)
{
    options = options || {};

    if (!window.Swal || 'function' !== typeof window.Swal.fire) {
        window.alert(message);
        return Promise.resolve();
    }

    return window.Swal.fire({
        title: options.title || '',
        text: message,
        icon: options.icon || 'info',
        timer: options.timer || 2200,
        timerProgressBar: true,
        showConfirmButton: false,
    }).then(function () {
        return true;
    });
}

if ('dev' === window.wizard.mode) {
    console.log('window.wizard', window.wizard);
}

/**
 * getWizardPopupFeatures
 * Size the popup from the opener viewport so it adapts to different screens.
 * @returns {string}
 */
function getWizardPopupFeatures()
{
    const viewportWidth = Math.max(
        window.innerWidth || 0,
        document.documentElement ? document.documentElement.clientWidth : 0,
        screen.availWidth || 0
    );
    const viewportHeight = Math.max(
        window.innerHeight || 0,
        document.documentElement ? document.documentElement.clientHeight : 0,
        screen.availHeight || 0
    );

    const popupWidth = Math.max(320, Math.min(viewportWidth, Math.floor(viewportWidth * 0.8)));
    const popupHeight = Math.max(600, Math.min(viewportHeight, Math.floor(viewportHeight * 0.85)));
    const left = Math.max(0, Math.floor((viewportWidth - popupWidth) / 2) + (window.screenX || window.screenLeft || 0));
    const top = Math.max(0, Math.floor((viewportHeight - popupHeight) / 2) + (window.screenY || window.screenTop || 0));

    return `width=${popupWidth},height=${popupHeight},top=${top},left=${left},resizable=yes,scrollbars=yes`;
}

/**
 * openNewWindow
 * @param url
 */
function openNewWindow(url)
{
    const windowFeatures = getWizardPopupFeatures();
    const popup = window.open(url, "otpWindow", windowFeatures);

    if (!popup) {
        notifyDialog(window.wizard.loading_popup, {icon: 'warning'});
    } else {
        popup.opener = null;
    }

    monitorWindow(popup);
}

/**
 * monitorWindow
 * @param popup
 */
function monitorWindow(popup)
{
    const checkIntervalMs = 1000; // 1 seconds
    const maxWaitTime = 60000 * 5; // 5 minutes
    let elapsed = 0;

    const checkInterval = setInterval(() => {
        elapsed += checkIntervalMs;
        console.log('listening... ', elapsed);

        if (!popup || popup.closed || elapsed >= maxWaitTime) {
            const loadingOverlay = document.getElementById("loading-overlay");
            clearInterval(checkInterval);

            if (elapsed >= maxWaitTime) {
                console.log("Timeout: Process took too long.");
                notifyDialog(window.wizard.loading_expired, {icon: 'warning'});
            } else {
                console.log("The window has been closed.");
            }

            loadingOverlay.classList.add("hidden");
            loadingOverlay.classList.remove("loading");
            handleWindowClosed();
        } else {
            try {
                const popupUrl = popup.location.href;
                if (popupUrl.includes("wp-admin/admin.php?page=wc_el_inv-options-page")) {
                    clearInterval(checkInterval);
                    console.log("Redirect detected: ", popupUrl);
                    popup.close();
                    handleProcessCompleted(popupUrl);
                }
            } catch (error) {
                // Ignore CORS error
            }
        }
    }, 1000);
}

/**
 * handleProcessCompleted
 * @param url
 */
function handleProcessCompleted(url)
{
    const loadingOverlay = document.getElementById("loading-overlay");
    const params = new URLSearchParams(new URL(url).search);
    const userId = params.get("user_id");
    const licenseKey = params.get("license_key");
    const status = params.get("status");

    if ('completed' === status && userId) {
        console.log("Process completed! User ID:", userId, "License Key:", licenseKey);
        loadingOverlay.innerText = window.wizard.loading_setup
        loadingOverlay.classList.add("loading");

        jQuery.ajax({
            url: window.wizard.ajax_url,
            method: "POST",
            data: {
                action: "wizard_config_get",
                security: window.wizard.nonce,
                user_id: userId,
                license_key: licenseKey.toString()
            },
            success: function (response) {
                console.log('response', response);
                notifyDialog(window.wizard.completed, {icon: 'success'}).then(() => {
                    let url = window.wizard.pop_general_page;
                    url = url.replace(/&#038;/g, "&");
                    console.log('url', url);
                    loadingOverlay.classList.add("hidden");
                    loadingOverlay.classList.remove("loading");
                    window.location = url;
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                let errorObj = JSON.parse(xhr.responseText);
                console.log('error')
                console.log(errorObj);
                loadingOverlay.classList.add("hidden");
                loadingOverlay.classList.remove("loading");
            },
            complete: function () {
                console.log('wizard_config_get > complete');
                loadingOverlay.classList.add("hidden");
                loadingOverlay.classList.remove("loading");
            },
        });

    } else {
        notifyDialog(window.wizard.config_error, {icon: 'error'});
        console.log(userId, status, licenseKey)
        loadingOverlay.classList.add("hidden");
        loadingOverlay.classList.remove("loading");
    }
}

/**
 * handleWindowClosed
 */
function handleWindowClosed()
{
    notifyDialog(window.wizard.window_closed, {icon: 'info'}).then(() => {
        window.location = window.wizard.handle_window_closed;
    });
}

window.addEventListener("load", function () {
    const loadingOverlay = document.getElementById("loading-overlay");
    setTimeout(() => {
        if (loadingOverlay) {
            loadingOverlay.classList.remove("hidden");
            loadingOverlay.classList.add("loading");
        }
        const site = window.wizard._site;
        let url = `${window.wizard._domain}/otp-login/?site=${encodeURIComponent(site)}&platform=wordpress&lang=${window.wizard._locale}&pv=${window.wizard._pv}&v=${window.wizard._code}`;
        url = url.replace(/%3A/g, ":").replace(/%2F/g, "/");
        openNewWindow(url);
    }, 2000);
});
