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';
import { getProductConfig, resolveCurrentProduct } from './config/products.js';

const initialProduct = resolveCurrentProduct();
const initialProductConfig = getProductConfig(initialProduct);

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;
    })(),
    appProduct: initialProduct,
    appBrand: initialProductConfig.brandName,
    defaultHomeRoute: initialProductConfig.defaultHomeRoute,
  },
  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);
    },
    setAppProduct(state, product) {
      const config = getProductConfig(product);
      state.appProduct = config.id;
      state.appBrand = config.brandName;
      state.defaultHomeRoute = config.defaultHomeRoute;
    },
    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;
      let position = { x: 48, y: 48 };
      if (
        dialog.position &&
        Number.isFinite(dialog.position.x) &&
        Number.isFinite(dialog.position.y)
      ) {
        position = { x: dialog.position.x, y: dialog.position.y };
      } else if (typeof window !== 'undefined') {
        position = {
          x: Math.max(16, Math.round(window.innerWidth * 0.05)),
          y: Math.max(16, Math.round(window.innerHeight * 0.05)),
        };
      }
      const newDialog = {
        id,
        ...dialog,
        isMinimized: false,
        zIndex: 1000 + state.dialogs.length,
        position,
        width: dialog.width != null ? dialog.width : null,
        height: dialog.height != null ? dialog.height : null,
      };
      state.dialogs.push(newDialog);
    },
    updateDialogBounds(state, { dialogId, position, width, height }) {
      const d = state.dialogs.find((x) => x.id === dialogId);
      if (!d) return;
      if (position && Number.isFinite(position.x) && Number.isFinite(position.y)) {
        d.position = { x: position.x, y: position.y };
      }
      if (width !== undefined) d.width = width;
      if (height !== undefined) d.height = height;
    },
    closeDialog(state, dialogId) {
      state.dialogs = state.dialogs.filter(dialog => dialog.id !== dialogId);
    },
    clearAllDialogs(state) {
      state.dialogs = [];
    },
    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('clearAllDialogs');
      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',
          roles: Array.isArray(data.roles) ? data.roles : [],
          isOwner: data.isOwner ?? false,
          isAdmin: data.isAdmin ?? (data.role === 'admin'),
          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', 
            roles: [],
            isOwner: false, 
            isAdmin: 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);
    },
    updateDialogBounds({ commit }, payload) {
      commit('updateDialogBounds', payload);
    },
  },
  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,
    appProduct: state => state.appProduct,
    appBrand: state => state.appBrand,
    defaultHomeRoute: state => state.defaultHomeRoute,
    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];
      if (perms?.isAdmin) return 'admin';
      return perms?.role || null;
    },
    userRoles: state => {
      if (!state.currentClub) return [];
      const perms = state.permissions[state.currentClub];
      return Array.isArray(perms?.roles) ? perms.roles : [];
    },
    isAdminRole: state => {
      if (!state.currentClub) return false;
      const perms = state.permissions[state.currentClub];
      return perms?.isAdmin || false;
    },
    // 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;
