// assets/js/flow/status.js
(function (w) {
  async function afbGetStatusOnce({ ajaxUrl, requestId }) {
    const fd = new FormData();
    fd.append('action', 'afb_status');
    fd.append('request_id', requestId);

    const res  = await fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' });
    const json = await res.json().catch(() => ({}));

    if (!json || json.success !== true) throw new Error('Status check failed');
    return json.data || {};
  }

  async function afbPollStatus({ ajaxUrl, requestId, onTick = () => {}, intervalMS = 1000, timeoutMS = 180000 }) {
    const start = Date.now();
    async function once() {
      const st = await afbGetStatusOnce({ ajaxUrl, requestId });
      onTick(st);

      if (st.phase === 'done') return true;
      if (st.phase === 'error') throw new Error('Server reported an error phase');
      return false;
    }

    while (true) {
      if (Date.now() - start > timeoutMS) throw new Error('Timed out waiting for server');
      const finished = await once();
      if (finished) return;
      await new Promise(r => setTimeout(r, intervalMS));
    }
  }

  async function afbWaitForSubmissionReady({ ajaxUrl, requestId, intervalMS = 1200, timeoutMS = 45000 }) {
    const start = Date.now();
    while (true) {
      if (Date.now() - start > timeoutMS) throw new Error('Timed out verifying submission status');

      const st = await afbGetStatusOnce({ ajaxUrl, requestId });
      const phase = String(st.phase || '');
      if (st.task_gid && ['upload', 'enrich', 'done'].includes(phase)) {
        return st;
      }
      if (phase === 'error') throw new Error('Server reported an error phase');

      await new Promise(r => setTimeout(r, intervalMS));
    }
  }

  w.afbFlowStatus = { afbPollStatus, afbGetStatusOnce, afbWaitForSubmissionReady };
})(window);
