import { createSlice } from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';

function shuffle<T>(array:Array<T>):Array<T> {
  let currentIndex = array.length;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

interface ListsState {
  lists: string[][]; // хранит перемещаемые элементы каждого списка ответов
  correctAnswers:string[][];
  isTestingDone:boolean
}

const initialState: ListsState = {
   lists: [],
   correctAnswers:[],
   isTestingDone:false
};

const listsSlice = createSlice({
  name: 'lists',
  initialState,
  reducers: {
    addList: (state, action: PayloadAction<{index: number; items: string[]}>)=>{
      const { index, items } = action.payload;
      state.lists.splice(index, 1, items); 
      state.correctAnswers.splice(index, 1, items); 
      
    },
    setDraggedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => {
        const { index, items } = action.payload;
        if (index >= 0 && index < state.lists.length) {
           state.lists[index] = items; // обновляем конкретный список
        }
    },
    mixUp: (state) => {
        state.lists=state.lists.map((list)=>
        {
          return shuffle(list); 
        })
    },
    stopTesting:(state)=>{
      state.isTestingDone=true;
    },
    startTesting:(state)=>{
      state.isTestingDone=false;
    }
  },
});

// Экспортируем действия и редьюсер
export const { addList, setDraggedItems,mixUp,startTesting,stopTesting } = listsSlice.actions;
export type {ListsState}
export default listsSlice.reducer;