import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { Question } from '@/types'

interface TestStore {
  partId: number
  partName: string
  questions: Question[]
  answers: (number | null)[]
  isSubmitted: boolean
  timeUsed: number // seconds elapsed when submitted

  startExam: (partId: number, partName: string, questions: Question[]) => void
  setAnswer: (questionIndex: number, answerIndex: number) => void
  submitExam: (timeUsed: number) => void
  reset: () => void
}

export const useTestStore = create<TestStore>()(
  persist(
    (set) => ({
      partId: 2,
      partName: '',
      questions: [],
      answers: [],
      isSubmitted: false,
      timeUsed: 0,

      startExam: (partId, partName, questions) =>
        set({
          partId,
          partName,
          questions,
          answers: new Array(questions.length).fill(null),
          isSubmitted: false,
          timeUsed: 0,
        }),

      setAnswer: (questionIndex, answerIndex) =>
        set((state) => {
          const answers = [...state.answers]
          answers[questionIndex] = answerIndex
          return { answers }
        }),

      submitExam: (timeUsed) => set({ isSubmitted: true, timeUsed }),

      reset: () =>
        set({ partId: 2, partName: '', questions: [], answers: [], isSubmitted: false, timeUsed: 0 }),
    }),
    { name: 'test-store' },
  ),
)
