<template>
  <div class="main">
    <div v-if="isAuthenticated" class="navigation">
      <div>
        Verein:
        <select v-model="selectedClub">
          <option value="">---</option>
          <option value="new">Neuer Verein</option>
          <option v-for="club in clubs" :key="club.id" :value="club.id">{{ club.name }}</option>
        </select>
        <button @click="loadClub">-&gt;</button>
      </div>
      <template v-if="selectedClub">
        <a href="/members">Mitglieder</a>
        <a href="/diary">Tagebuch</a>
        <button>Freigaben</button>
      </template>
      <div>
        <button @click="logout()">Ausloggen</button>
      </div>
    </div>
    <div v-else class="navigation">
      <a href="/login">Einloggen</a>
      <a href="/register">Registrieren</a>
    </div>
    <router-view class="content"></router-view>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import apiClient from './apiClient.js';

export default {
  name: 'App',
  data() {
    console.log(import.meta.env);
    return {
      selectedClub: null,
    };
  },
  computed: {
    ...mapGetters(['isAuthenticated', 'currentClub', 'clubs']),
  },
  watch: {
    selectedClub(newVal) {
      this.setCurrentClub(newVal);
    },
    currentClub(newVal) {
      if (newVal === 'new') {
        this.$router.push('/createclub');
      } else if (newVal) {
        this.$router.push(`/showclub/${newVal}`);
      }
    }
  },
  methods: {
    ...mapActions(['setCurrentClub', 'setClubs', 'logout']),
    loadClub() {
      this.setCurrentClub(this.currentClub);
      this.$router.push(`/showclub/${this.currentClub}`);
    },
  },
  async mounted() {
    const response = await apiClient.get('/clubs');
    this.setClubs(response.data);
    if (this.currentClub) {
      this.selectedClub = this.currentClub;
    }
  }
};
</script>

<style>
.main {
  display: flex;
  height: 100%;
  overflow: hidden;
}
.navigation {
  width: 10em;
  background-color: #e0e0e0;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
}
</style>
