export function createSleepTimer(now: () => number = () => Date.now()) {
  let deadline: number | null = null;
  let chapterId: string | null = null;
  return {
    setMinutes(minutes: 15 | 30 | 45 | 60) {
      deadline = now() + minutes * 60_000;
      chapterId = null;
    },
    setChapterEnd(id: string) {
      deadline = null;
      chapterId = id;
    },
    cancel() {
      deadline = null;
      chapterId = null;
    },
    remainingMs(): number | null {
      return deadline === null ? null : Math.max(0, deadline - now());
    },
    shouldStop(): boolean {
      return deadline !== null && now() >= deadline;
    },
    shouldStopAtChapterBoundary(currentChapterId: string, nextChapterId: string | null): boolean {
      return chapterId !== null && chapterId === currentChapterId && nextChapterId !== currentChapterId;
    },
    mode(): { type: "off" } | { type: "minutes"; remainingMs: number } | { type: "chapter"; chapterId: string } {
      if (deadline !== null) return { type: "minutes", remainingMs: Math.max(0, deadline - now()) };
      if (chapterId !== null) return { type: "chapter", chapterId };
      return { type: "off" };
    },
  };
}
