/**
 * Niwa AI — Embeddings / index progress tracker.
 *
 * Loaded only on the Niwa AI admin page.
 * Expects `niwaAdminEmbeddings` to be localized via wp_localize_script with:
 *   - nonce {string} AJAX nonce
 */
(function () {
    var cfg = window.niwaAdminEmbeddings;
    if (!cfg) {
        return;
    }

    var bar  = document.getElementById('niwa-embed-progress');
    var info = document.getElementById('niwa-embed-info');
    var pct  = document.getElementById('niwa-embed-percent');

    if (!bar || !info || !pct) {
        return;
    }

    var nonce = cfg.nonce || '';

    var consecutiveErrors = 0;

    function tick() {
        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 () {
            if (xhr.status !== 200) {
                consecutiveErrors++;
                info.textContent = 'Status check failed (HTTP ' + xhr.status + '). Retrying…';
                if (consecutiveErrors >= 5) {
                    clearInterval(timer);
                    info.textContent = 'Status check failed repeatedly. Please reload the page.';
                }
                return;
            }
            consecutiveErrors = 0;
            try {
                var res = JSON.parse(xhr.responseText);
                if (!res || !res.success) {
                    return;
                }
                var st      = res.data.stats || {};
                var total   = parseInt(st.total || 0, 10);
                var done    = parseInt(st.done || 0, 10);
                var pending = parseInt(st.pending || 0, 10);
                var percent = parseInt(res.data.percent || 0, 10);
                var idxDone  = parseInt(res.data.index_done || 0, 10);
                var idxTotal = parseInt(res.data.index_total || 0, 10);

                bar.style.width   = percent + '%';
                info.textContent  = 'Index: ' + idxDone + ' / ' + idxTotal + ' | Embeddings: ' + done + ' / ' + total + ' (Pending: ' + pending + ')';
                pct.textContent   = 'Progress: ' + percent + '%';

                if (pending <= 0 && idxDone >= idxTotal) {
                    clearInterval(timer);
                }
            } catch (e) { /* ignore parse errors */ }
        };
        xhr.onerror = function () {
            consecutiveErrors++;
            info.textContent = 'Connection error. Retrying…';
            if (consecutiveErrors >= 5) {
                clearInterval(timer);
                info.textContent = 'Connection lost. Please check your network and reload the page.';
            }
        };
        xhr.send('action=niwa_ai_embeddings_status&nonce=' + encodeURIComponent(nonce));
    }

    // Poll interval is sourced from Niwa AI → Performance settings
    // (`embeddings_status_poll_ms`). Falls back to 5s if NiwaAI config isn't
    // available (e.g. when this script runs outside the embeddings page
    // shell). Minimum clamp 1s guards against pathological saved values.
    var pollMs = 5000;
    if (window.NiwaAI && window.NiwaAI.poll && window.NiwaAI.poll.embeddings_status_poll_ms) {
        var parsed = parseInt(window.NiwaAI.poll.embeddings_status_poll_ms, 10);
        if (parsed && parsed >= 1000) {
            pollMs = parsed;
        }
    }
    var timer = setInterval(tick, pollMs);
    tick();
})();
