/** Poll GET /v1/print/jobs/:id until printed or dead. */
async function pollPrintJob(printJobId, opts = {}) {
  const timeoutMs = opts.timeoutMs ?? 60_000;
  const intervalMs = opts.intervalMs ?? 400;
  const onUpdate = opts.onUpdate;
  const start = Date.now();
  while (Date.now() - start < timeoutMs) {
    const res = await fetch(
      `/v1/print/jobs/${encodeURIComponent(printJobId)}`,
    );
    if (!res.ok) {
      throw new Error("Print job not found");
    }
    const job = await res.json();
    if (onUpdate) onUpdate(job);
    if (job.state === "printed") return { ok: true, job };
    if (job.state === "dead") return { ok: false, job };
    await new Promise((r) => setTimeout(r, intervalMs));
  }
  throw new Error("Print timed out — check printer power and queue");
}

if (typeof window !== "undefined") {
  window.pollPrintJob = pollPrintJob;
}
