<script>
// adom-video-post frontend eval channel (app-creator SKILL.md §7b).
//
// Long-polls /eval/pending, runs each pending snippet as an async
// function body with `ctx = window.__appCtx || {}`, POSTs the
// return value (or error) to /eval/:id/result, and loops. The UI
// pages just need to define window.__appCtx with whatever state
// they want eval snippets to touch.
//
// The snippet is evaluated via `new (async function(){}).constructor`
// so `await` is supported and `return` at the top level works.
(function () {
  if (window.__adomEvalClientStarted) return;
  window.__adomEvalClientStarted = true;

  async function runOne(job) {
    let result;
    try {
      const AsyncFn = (async function () {}).constructor;
      const fn = new AsyncFn('ctx', job.code);
      const value = await fn(window.__appCtx || {});
      result = { ok: true, value: value === undefined ? null : value };
    } catch (e) {
      result = {
        ok: false,
        error: e && e.message ? e.message : String(e),
        stack: e && e.stack ? e.stack : null,
      };
    }
    try {
      await fetch('eval/' + encodeURIComponent(job.id) + '/result', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(result),
      });
    } catch (_) {
      // Swallow — the CLI caller will just time out waiting for the
      // result. We don't want the poll loop to die because one
      // result POST failed.
    }
  }

  async function pollLoop() {
    while (true) {
      try {
        const r = await fetch('eval/pending');
        if (r.status === 204) continue; // long-poll timeout, go again
        if (!r.ok) {
          await new Promise((x) => setTimeout(x, 1000));
          continue;
        }
        const job = await r.json();
        if (job && job.id && typeof job.code === 'string') {
          runOne(job); // fire-and-forget so a slow snippet doesn't block the next poll
        }
      } catch (_) {
        await new Promise((x) => setTimeout(x, 1000));
      }
    }
  }

  pollLoop();
})();
</script>