import { createStore } from 'vuex';
import router from './router.js';
import apiClient from './apiClient.js';
import { safeSessionStorage, safeLocalStorage } from './utils/storage.js';
import i18n from './i18n';

const store = createStore({
  state: {
    token: safeSessionStorage.getItem('token'),
    username: safeSessionStorage.getItem('username') || '',
    currentClub: safeSessionStorage.getItem('currentClub'),
    clubs: (() => {
      try {
        const stored = safeLocalStorage.getItem('clubs');
        return stored ? JSON.parse(stored) : [];
      } catch (e) {
        return [];
      }
    })(),
    permissions: (() => {
      try {
        const stored = safeLocalStorage.getItem('clubPermissions');
        return stored ? JSON.parse(stored) : {};
      } catch (e) {
        return {};
      }
    })(), // { clubId: { role, isOwner, permissions: {...} } }
    dialogs: [], // Array von offenen Dialogen
    dialogCounter: 0, // Zähler für eindeutige Dialog-IDs
    sidebarCollapsed: (() => {
      const savedState = safeLocalStorage.getItem('sidebarCollapsed');
      if (savedState !== null) {
        return savedState === 'true';
      }
      // Standardmäßig kollabiert auf mobilen Geräten
      return window.innerWidth <= 480;
    })(),
    language: (() => {
      const saved = safeLocalStorage.getItem('userLanguage');
      if (saved) {
        return saved;
      }
      // Browser-Sprache wird in i18n/index.js erkannt
      return null;
    })(),
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
      if (token) {
        safeSessionStorage.setItem('token', token);
      } else {
        safeSessionStorage.removeItem('token');
      }
      state.currentClub = null;
      safeSessionStorage.removeItem('currentClub');
      // Permissions sind user-spezifisch -> immer zurücksetzen, wenn Token gesetzt wird
      state.permissions = {};
      safeLocalStorage.removeItem('clubPermissions');
    },
    setUsername(state, username) {
      state.username = username;
      if (username) {
        safeSessionStorage.setItem('username', username);
      } else {
        safeSessionStorage.removeItem('username');
      }
    },
    setClub(state, club) {
      state.currentClub = club;
      if (club) {
        safeSessionStorage.setItem('currentClub', club);
      } else {
        safeSessionStorage.removeItem('currentClub');
      }
    },
    setClubsMutation(state, clubs) {
      state.clubs = clubs;
      safeLocalStorage.setItem('clubs', JSON.stringify(clubs));
    },
    setPermissions(state, { clubId, permissions }) {
      state.permissions = {
        ...state.permissions,
        [clubId]: permissions
      };
      safeLocalStorage.setItem('clubPermissions', JSON.stringify(state.permissions));
    },
    clearPermissions(state) {
      state.permissions = {};
      safeLocalStorage.removeItem('clubPermissions');
    },
    setSidebarCollapsed(state, collapsed) {
      state.sidebarCollapsed = collapsed;
      safeLocalStorage.setItem('sidebarCollapsed', collapsed.toString());
    },
    setLanguage(state, language) {
      state.language = language;
      safeLocalStorage.setItem('userLanguage', language);
    },
    clearToken(state) {
      state.token = null;
      safeSessionStorage.removeItem('token');
      safeSessionStorage.removeItem('currentClub'); 
    },
    clearUsername(state) {
      state.username = '';
      safeSessionStorage.removeItem('username');
    },
    // Dialog-Mutations
    openDialog(state, dialog) {
      const id = ++state.dialogCounter;
      const newDialog = {
        id,
        ...dialog,
        isMinimized: false,
        zIndex: 1000 + state.dialogs.length,
        position: { x: 0, y: 0 } // Position wird durch CSS festgelegt
      };
      state.dialogs.push(newDialog);
    },
    closeDialog(state, dialogId) {
      state.dialogs = state.dialogs.filter(dialog => dialog.id !== dialogId);
    },
    minimizeDialog(state, dialogId) {
      const dialog = state.dialogs.find(d => d.id === dialogId);
      if (dialog) {
        dialog.isMinimized = true;
      }
    },
    restoreDialog(state, dialogId) {
      const dialog = state.dialogs.find(d => d.id === dialogId);
      if (dialog) {
        dialog.isMinimized = false;
        // Dialog in den Vordergrund bringen
        const maxZIndex = Math.max(...state.dialogs.map(d => d.zIndex));
        dialog.zIndex = maxZIndex + 1;
      }
    },
    bringDialogToFront(state, dialogId) {
      const dialog = state.dialogs.find(d => d.id === dialogId);
      if (dialog) {
        const maxZIndex = Math.max(...state.dialogs.map(d => d.zIndex));
        dialog.zIndex = maxZIndex + 1;
      }
    }
  },
  actions: {
    async login({ commit }, { token, username }) {
      commit('setToken', token);
      commit('setUsername', username);
      commit('clearPermissions');
      const response = await apiClient.get('/clubs');
      commit('setClubsMutation', response.data);
    },
    logout({ commit }) {
      commit('clearToken');
      commit('clearUsername');
      commit('clearPermissions');
      router.push('/login'); // Leitet den Benutzer zur Login-Seite um
      // window.location.reload() entfernt, um Endlos-Neuladeschleife zu verhindern
    },

    async setCurrentClub({ commit, dispatch }, club) {
      commit('setClub', club);
      // Load permissions for this club
      await dispatch('loadPermissions', club);
    },
    
    async loadPermissions({ commit }, clubId) {
      try {
        const response = await apiClient.get(`/permissions/${clubId}`);
        const data = response.data || {};
        const normalized = {
          role: data.role ?? 'member',
          isOwner: data.isOwner ?? false,
          permissions: data.permissions ?? {}
        };
        commit('setPermissions', { clubId, permissions: normalized });
      } catch (error) {
        console.error('Error loading permissions:', error);
        // Set default permissions (read-only)
        commit('setPermissions', { 
          clubId, 
          permissions: { 
            role: 'member', 
            isOwner: false, 
            permissions: {} 
          } 
        });
      }
    },
    setClubs({ commit }, clubs) {
      commit('setClubsMutation', clubs);
    },
    toggleSidebar({ commit, state }) {
      commit('setSidebarCollapsed', !state.sidebarCollapsed);
    },
    setLanguage({ commit }, language) {
      commit('setLanguage', language);
      // Aktualisiere auch die i18n-Instanz
      i18n.global.locale = language;
    },
    // Dialog-Actions
    openDialog({ commit }, dialog) {
      commit('openDialog', dialog);
    },
    closeDialog({ commit }, dialogId) {
      commit('closeDialog', dialogId);
    },
    minimizeDialog({ commit }, dialogId) {
      commit('minimizeDialog', dialogId);
    },
    restoreDialog({ commit }, dialogId) {
      commit('restoreDialog', dialogId);
    },
    bringDialogToFront({ commit }, dialogId) {
      commit('bringDialogToFront', dialogId);
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    token: state => state.token,
    username: state => state.username,
    currentClub: state => state.currentClub,
    clubs: state => state.clubs,
    sidebarCollapsed: state => state.sidebarCollapsed,
    language: state => state.language,
    currentClubName: state => {
      const club = state.clubs.find(club => club.id === parseInt(state.currentClub));
      return club ? club.name : '';
    },
    // Permission getters
    currentPermissions: state => {
      if (!state.currentClub) return null;
      return state.permissions[state.currentClub] || null;
    },
    hasPermission: (state) => (resource, action) => {
      if (!state.currentClub) return false;
      const perms = state.permissions[state.currentClub];
      if (!perms) return false;
      if (perms.isOwner) return true;
      if (resource === 'mytischtennis') return true; // MyTischtennis für alle
      const permissionsMap = perms.permissions || {};
      const resourcePerms = permissionsMap[resource];
      if (!resourcePerms) return false;
      return resourcePerms[action] === true;
    },
    isClubOwner: state => {
      if (!state.currentClub) return false;
      const perms = state.permissions[state.currentClub];
      return perms?.isOwner || false;
    },
    userRole: state => {
      if (!state.currentClub) return null;
      const perms = state.permissions[state.currentClub];
      return perms?.role || null; // null wenn nicht geladen, nicht 'member'
    },
    // Dialog-Getters
    dialogs: state => state.dialogs,
    minimizedDialogs: state => state.dialogs.filter(dialog => dialog.isMinimized),
    activeDialogs: state => state.dialogs.filter(dialog => !dialog.isMinimized)
  },
});

export default store;
