import { createStore } from 'vuex';
import router from './router.js';
import apiClient from './apiClient.js';

const store = createStore({
  state: {
    token: localStorage.getItem('token') || null,
    username: localStorage.getItem('username') || '',
    currentClub: localStorage.getItem('currentClub') || null,
    clubs: (() => {
      try {
        return JSON.parse(localStorage.getItem('clubs')) || [];
      } catch (e) {
        console.error('Error parsing clubs from localStorage:', e);
        return [];
      }
    })(),
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
      localStorage.setItem('token', token);
      state.currentClub = null;
      localStorage.setItem('currentClub', null);
    },
    setUsername(state, username) {
      state.username = username;
      localStorage.setItem('username', username);
    },
    setClub(state, club) {
      state.currentClub = club;
      localStorage.setItem('currentClub', club);
    },
    setClubsMutation(state, clubs) {
      state.clubs = clubs;
      localStorage.setItem('clubs', JSON.stringify(clubs));
    },
    clearToken(state) {
      state.token = null;
      localStorage.removeItem('token');
      localStorage.removeItem('currentClub'); 
    },
    clearUsername(state) {
      state.username = '';
      localStorage.removeItem('username');
    }
  },
  actions: {
    async login({ commit }, { token, username }) {
      commit('setToken', token);
      commit('setUsername', username);
      const response = await apiClient.get('/clubs');
      commit('setClubsMutation', response.data);
    },
    logout({ commit }) {
      commit('clearToken');
      commit('clearUsername');
      router.push("/"); 
      window.location.reload();
    },

    setCurrentClub({ commit }, club) {
      commit('setClub', club);
    },
    setClubs({ commit }, clubs) {
      commit('setClubsMutation', clubs);
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    token: state => state.token,
    username: state => state.username,
    currentClub: state => state.currentClub,
    clubs: state => state.clubs,
    currentClubName: state => {
      const club = state.clubs.find(club => club.id === parseInt(state.currentClub));
      return club ? club.name : '';
    }
  },
});

export default store;
