import { create } from 'zustand'

const REPLAY_DAY = '2026-03-01'
const TICK_MS = 30 * 60 * 1000 // 30 minutes

export const REPLAY_START = `${REPLAY_DAY}T00:00:00.000Z`
export const REPLAY_END = `${REPLAY_DAY}T23:30:00.000Z`

function parseTime(iso: string): number {
  return new Date(iso).getTime()
}

export function getTicks(): string[] {
  const ticks: string[] = []
  let t = parseTime(REPLAY_START)
  const end = parseTime(REPLAY_END)
  while (t <= end) {
    ticks.push(new Date(t).toISOString())
    t += TICK_MS
  }
  return ticks
}

export const REPLAY_TICKS = getTicks()

export interface PlaybackState {
  /** 是否开启回放模式 */
  isReplayMode: boolean
  /** 当前回放时刻 (ISO) */
  playbackTime: string
  /** 是否正在自动播放 */
  isPlaying: boolean
  /** 播放速度 (秒/刻度) */
  speedSecPerTick: number
  setReplayMode: (v: boolean) => void
  setPlaybackTime: (iso: string) => void
  setIsPlaying: (v: boolean) => void
  stepForward: () => void
  stepBack: () => void
  setSpeed: (sec: number) => void
}

export const usePlaybackStore = create<PlaybackState>((set, get) => ({
  isReplayMode: false,
  playbackTime: REPLAY_END,
  isPlaying: false,
  speedSecPerTick: 2,

  setReplayMode: (v) => set({ isReplayMode: v, isPlaying: false }),

  setPlaybackTime: (iso) => {
    const ticks = REPLAY_TICKS
    if (ticks.includes(iso)) {
      set({ playbackTime: iso })
      return
    }
    const idx = ticks.findIndex((t) => t >= iso)
    const clamp = Math.max(0, Math.min(idx < 0 ? ticks.length - 1 : idx, ticks.length - 1))
    set({ playbackTime: ticks[clamp] })
  },

  setIsPlaying: (v) => set({ isPlaying: v }),

  stepForward: () => {
    const { playbackTime } = get()
    const ticks = REPLAY_TICKS
    const i = ticks.indexOf(playbackTime)
    if (i < ticks.length - 1) set({ playbackTime: ticks[i + 1] })
    else set({ isPlaying: false })
  },

  stepBack: () => {
    const { playbackTime } = get()
    const ticks = REPLAY_TICKS
    const i = ticks.indexOf(playbackTime)
    if (i > 0) set({ playbackTime: ticks[i - 1] })
  },

  setSpeed: (sec) => set({ speedSecPerTick: sec }),
}))
