/**
 * Niwa AI — Codex OAuth device-flow polling.
 *
 * Loaded only on the Niwa AI admin page when a device verification is active.
 * Expects `niwaAdminOAuthPoll` to be localized via wp_localize_script with:
 *   - nonce      {string}  AJAX nonce
 *   - interval   {number}  Poll interval in seconds
 *   - connectedUrl {string} Redirect URL on success
 */
(function () {
    var cfg = window.niwaAdminOAuthPoll;
    if (!cfg) {
        return;
    }

    var st = document.getElementById('niwa-codex-oauth-status');
    if (!st) {
        return;
    }

    var nonce        = cfg.nonce || '';
    var interval     = Math.max(2, parseInt(cfg.interval, 10) || 5);
    var connectedUrl = cfg.connectedUrl || '';

    var consecutiveErrors = 0;
    var currentPage = '';

    try {
        currentPage = new URL(window.location.href).searchParams.get('page') || '';
    } catch (e) {
        currentPage = '';
    }

    function buildConnectedUrl(serverUrl) {
        if (serverUrl) {
            return serverUrl;
        }
        try {
            var url = new URL(window.location.href);
            url.searchParams.set('niwa_oauth', 'connected');
            url.searchParams.delete('niwa_oauth_message');
            return url.toString();
        } catch (e) {
            return connectedUrl || window.location.href;
        }
    }

    function poll() {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', window.ajaxurl, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xhr.onload = function () {
            consecutiveErrors = 0;
            try {
                var res = JSON.parse(xhr.responseText || '{}');
                if (!res) {
                    return;
                }
                if (res.success && res.data) {
                    if (res.data.connected) {
                        st.textContent = 'Codex OAuth connected.';
                        window.location = buildConnectedUrl(res.data.redirect_url || '');
                        return;
                    }
                    if (res.data.pending && res.data.message) {
                        st.textContent = res.data.message;
                        return;
                    }
                }
                if (res.data && res.data.message) {
                    st.textContent = res.data.message;
                }
            } catch (e) { /* ignore parse errors */ }
        };
        xhr.onerror = function () {
            consecutiveErrors++;
            st.textContent = 'Connection error. Retrying…';
            if (consecutiveErrors >= 10) {
                st.textContent = 'Connection lost. Please check your network and reload the page.';
            }
        };
        var body = 'action=niwa_ai_codex_oauth_poll&nonce=' + encodeURIComponent(nonce);
        if (currentPage) {
            body += '&page=' + encodeURIComponent(currentPage);
        }
        xhr.send(body);
    }

    setInterval(poll, interval * 1000);
    poll();
})();
