import { create } from "zustand";
import { devtools } from "zustand/middleware";

type Answer = {
  step: number;
  answer: string;
};

interface QuizViewStore {
  answers: Answer[];
}

export const useQuizViewStore = create<QuizViewStore>()(
  devtools(
    (set, get) => ({
      answers: [],
    }),
    {
      name: "quizView",
    }
  )
);

export const updateAnswer = (step: number, answer: string) => {
  const answers = [...useQuizViewStore.getState().answers];
  const answerIndex = answers.findIndex((answer) => step === answer.step);

  if (answerIndex < 0) {
    answers.push({ step, answer });
  } else {
    answers[answerIndex] = { step, answer };
  }

  useQuizViewStore.setState({ answers });
};
