function scheduleFrame(callback) {
  if (typeof globalThis.requestAnimationFrame === "function") {
    return { kind: "frame", id: globalThis.requestAnimationFrame(callback) };
  }
  return { kind: "timeout", id: globalThis.setTimeout(callback, 16) };
}
function cancelFrame(handle) {
  if (handle?.kind === "frame") globalThis.cancelAnimationFrame?.(handle.id);
  if (handle?.kind === "timeout") globalThis.clearTimeout?.(handle.id);
}

export function createConversationEventBatch({ flush, schedule = scheduleFrame, cancel = cancelFrame }) {
  let entries = [];
  let handle;
  let scheduledToken;

  function drain(token) {
    if (token !== scheduledToken) return;
    handle = undefined;
    scheduledToken = undefined;
    if (entries.length === 0) return;
    const pending = entries;
    entries = [];
    flush(pending);
  }

  return {
    push(entry) {
      entries.push(entry);
      if (handle !== undefined) return;
      const token = Symbol("conversation-event-batch");
      scheduledToken = token;
      handle = schedule(() => drain(token));
    },
    clear() {
      if (handle !== undefined) cancel(handle);
      entries = [];
      handle = undefined;
      scheduledToken = undefined;
    }
  };
}
