import { createStore } from 'vuex';
import axios from '../axios';
import router from '../router';

const rawStoredToken = localStorage.getItem('token');
const storedToken =
  rawStoredToken && rawStoredToken !== 'undefined' && rawStoredToken !== 'null'
    ? rawStoredToken
    : '';

if (!storedToken) {
  // Altlasten aus früheren Login-Bugs bereinigen
  localStorage.removeItem('isLoggedIn');
  localStorage.removeItem('token');
}

let user = [];
try {
  user = JSON.parse(localStorage.getItem('user')) || null;
} catch (e) {
  user = [];
}

export default createStore({
  state: {
    isLoggedIn: localStorage.getItem('isLoggedIn') === 'true' && !!storedToken,
    user: user,
    token: storedToken,
    menuData: [],
    /** gesetzt, wenn /menu-data fehlschlägt (z. B. DB weg) — nicht mit „Seite nicht gefunden“ verwechseln */
    menuLoadError: null,
    pageContent: '',
    pageTitle: '',
    selectedPage: '',
  },
  mutations: {
    setLogin(state, { user, token }) {
      state.isLoggedIn = true;
      state.user = user;
      state.token = token;
      localStorage.setItem('isLoggedIn', 'true');
      localStorage.setItem('user', JSON.stringify(user));
      localStorage.setItem('token', token);
    },
    logout(state) {
      state.isLoggedIn = false;
      state.user = null;
      state.token = '';
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('user');
      localStorage.removeItem('token');
    },
    setMenuData(state, menuData) {
      state.menuData = menuData;
      state.menuLoadError = null;
    },
    setMenuLoadError(state, message) {
      state.menuLoadError = message;
    },
    SET_PAGE_CONTENT(state, content) {
      state.pageContent = content;
    },
    UPDATE_PAGE_CONTENT(state, content) {
      state.pageContent = content;
    },
    setPageTitle(state, title) {
      state.pageTitle = title;
    },
    setSelectedPage(state, page) {
      state.selectedPage = page;
    },
  },
  actions: {
    async loadMenuData({ commit }) {
      try {
        const response = await axios.get('/menu-data');
        commit('setMenuData', response.data);
      } catch (error) {
        console.error('Fehler beim Laden der Menü-Daten:', error);
        const fromApi =
          error.response?.data &&
          typeof error.response.data === 'object' &&
          error.response.data.error;
        const msg =
          typeof fromApi === 'string'
            ? fromApi
            : 'Die Website ist vorübergehend nicht vollständig erreichbar. Bitte versuchen Sie es später erneut.';
        commit('setMenuLoadError', msg);
      }
    },
    async loadPageContent({ commit }, link) {
      try {
        const response = await axios.get(`/page-content?link=${link}`);
        commit('SET_PAGE_CONTENT', response.data.content || '');
      } catch (error) {
        console.error('Fehler beim Laden des Seiteninhalts:', error);
      }
    },
    async savePageContent({ state }, { link, name }) {
      try {
        const contentToSave = state.pageContent;

        await axios.post('/page-content', {
          link,
          name,
          content: contentToSave,
        });

        alert('Seiteninhalt gespeichert!');
      } catch (error) {
        console.error('Fehler beim Speichern des Seiteninhalts:', error);
      }
    },
    setPageTitle({ commit }, title) {
      commit('setPageTitle', title);
    },
    setSelectedPage({ commit }, page) {
      commit('setSelectedPage', page);
    },
    login({ commit }, { user, token }) {
      commit('setLogin', { user, token });
    },
    async logout({ commit }) {
      try {
        await axios.post('/auth/logout');
      } catch (error) {
        console.error('Fehler beim Logout:', error);
      } finally {
        commit('logout');
        // Navigation nach Logout mit replace, damit die Login-Seite direkt erreichbar ist
        if (router.currentRoute.value.path !== '/auth/login') {
          router.replace('/auth/login');
        }
      }
    }
  },
  getters: {
    isLoggedIn: state => state.isLoggedIn,
    user: state => state.user,
    menuData: state => state.menuData,
    pageContent: state => state.pageContent,
    pageTitle: state => state.pageTitle,
    selectedPage: state => state.selectedPage,
    menuLoadError: state => state.menuLoadError,
  }
});
