import { create } from 'zustand'

/** 回放日期范围：覆盖 2 月 28 日（盟军打击伊朗 → 伊朗反击），与 DB attacked_at / struck_at 对齐 */
const REPLAY_START_ISO = '2026-02-28T00:00:00.000Z'
const REPLAY_END_ISO = '2026-03-01T23:30:00.000Z'

export const REPLAY_START = REPLAY_START_ISO
export const REPLAY_END = REPLAY_END_ISO

export type ReplayScale = '30m' | '1h' | '1d'

const SCALE_MS: Record<ReplayScale, number> = {
  '30m': 30 * 60 * 1000,
  '1h': 60 * 60 * 1000,
  '1d': 24 * 60 * 60 * 1000,
}

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

/** 按刻度生成回放时间点；不传 scale 时默认 30 分钟 */
export function getTicks(scale: ReplayScale = '30m'): string[] {
  const step = SCALE_MS[scale]
  const ticks: string[] = []
  let t = parseTime(REPLAY_START)
  const end = parseTime(REPLAY_END)
  while (t <= end) {
    ticks.push(new Date(t).toISOString())
    t += step
  }
  return ticks
}

export interface PlaybackState {
  /** 是否开启回放模式 */
  isReplayMode: boolean
  /** 当前回放时刻 (ISO) */
  playbackTime: string
  /** 回放刻度：30分钟 / 1小时 / 1天 */
  replayScale: ReplayScale
  /** 是否正在自动播放 */
  isPlaying: boolean
  /** 播放速度 (秒/刻度) */
  speedSecPerTick: number
  setReplayMode: (v: boolean) => void
  setPlaybackTime: (iso: string) => void
  setReplayScale: (scale: ReplayScale) => 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,
  replayScale: '30m',
  isPlaying: false,
  speedSecPerTick: 2,

  setReplayMode: (v) =>
    set({
      isReplayMode: v,
      isPlaying: false,
      ...(v ? { playbackTime: REPLAY_START } : {}),
    }),

  setPlaybackTime: (iso) => {
    const { replayScale } = get()
    const ticks = getTicks(replayScale)
    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] })
  },

  setReplayScale: (scale) => {
    const { playbackTime } = get()
    const ticks = getTicks(scale)
    const idx = ticks.findIndex((t) => t >= playbackTime)
    const clamp = Math.max(0, Math.min(idx < 0 ? ticks.length - 1 : idx, ticks.length - 1))
    set({ replayScale: scale, playbackTime: ticks[clamp] })
  },

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

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

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

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