/**
 * TabataFit Player Store
 * Current workout state — ephemeral (not persisted)
 */

import { create } from 'zustand'
import type { Workout } from '../types'

type TimerPhase = 'PREP' | 'WORK' | 'REST' | 'COMPLETE'

interface PlayerState {
  workout: Workout | null
  phase: TimerPhase
  timeRemaining: number
  currentRound: number
  isPaused: boolean
  isRunning: boolean
  calories: number
  startedAt: number | null

  // Actions
  loadWorkout: (workout: Workout) => void
  setPhase: (phase: TimerPhase) => void
  setTimeRemaining: (time: number) => void
  setCurrentRound: (round: number) => void
  setPaused: (paused: boolean) => void
  setRunning: (running: boolean) => void
  addCalories: (amount: number) => void
  reset: () => void
}

export const usePlayerStore = create<PlayerState>((set) => ({
  workout: null,
  phase: 'PREP',
  timeRemaining: 10,
  currentRound: 1,
  isPaused: false,
  isRunning: false,
  calories: 0,
  startedAt: null,

  loadWorkout: (workout) =>
    set({
      workout,
      phase: 'PREP',
      timeRemaining: workout.prepTime,
      currentRound: 1,
      isPaused: false,
      isRunning: false,
      calories: 0,
      startedAt: null,
    }),

  setPhase: (phase) => set({ phase }),
  setTimeRemaining: (time) => set({ timeRemaining: time }),
  setCurrentRound: (round) => set({ currentRound: round }),
  setPaused: (paused) => set({ isPaused: paused }),
  setRunning: (running) =>
    set((state) => ({
      isRunning: running,
      startedAt: running && !state.startedAt ? Date.now() : state.startedAt,
    })),
  addCalories: (amount) => set((state) => ({ calories: state.calories + amount })),
  reset: () =>
    set({
      workout: null,
      phase: 'PREP',
      timeRemaining: 10,
      currentRound: 1,
      isPaused: false,
      isRunning: false,
      calories: 0,
      startedAt: null,
    }),
}))
