import { create } from "zustand";

/**
 * 番茄钟内存状态（不持久化，只保留剩余秒数 + 阶段 + 运行标志）
 */
type Phase = "work" | "break";

interface PomodoroTimer {
  phase: Phase;
  remaining: number;
  running: boolean;
  workSec: number;
  breakSec: number;
  setConfig: (c: { workSec: number; breakSec: number }) => void;
  start: () => void;
  pause: () => void;
  reset: () => void;
  /** 1 秒 tick；返回 true 表示该秒发生了阶段切换 */
  tick: () => boolean;
}

export const usePomodoroStore = create<PomodoroTimer>((set, get) => ({
  phase: "work",
  remaining: 25 * 60,
  running: false,
  workSec: 25 * 60,
  breakSec: 5 * 60,

  setConfig({ workSec, breakSec }) {
    const s = get();
    set({ workSec, breakSec });
    if (!s.running) {
      set({ remaining: s.phase === "work" ? workSec : breakSec });
    }
  },

  start() {
    set({ running: true });
  },

  pause() {
    set({ running: false });
  },

  reset() {
    const s = get();
    set({
      running: false,
      phase: "work",
      remaining: s.workSec,
    });
  },

  tick() {
    const s = get();
    if (!s.running) return false;
    if (s.remaining > 1) {
      set({ remaining: s.remaining - 1 });
      return false;
    }
    const nextPhase: Phase = s.phase === "work" ? "break" : "work";
    const nextRemaining = nextPhase === "work" ? s.workSec : s.breakSec;
    set({ phase: nextPhase, remaining: nextRemaining });
    return true;
  },
}));
