<template>
  <div class="training-stats">
    <h2>{{ $t('trainingStats.title') }}</h2>
    
    <div class="stats-overview">
      <div class="stats-summary">
        <div class="stat-card">
          <h3>{{ $t('trainingStats.activeMembers') }}</h3>
          <div class="stat-number">{{ activeMembers.length }}</div>
        </div>
        <div class="stat-card">
          <h3>{{ $t('trainingStats.averageParticipationCurrentMonth') }}</h3>
          <div class="stat-number">{{ averageParticipationCurrentMonth.toFixed(1) }}</div>
        </div>
        <div class="stat-card">
          <h3>{{ $t('trainingStats.averageParticipationLastMonth') }}</h3>
          <div class="stat-number">{{ averageParticipationLastMonth.toFixed(1) }}</div>
        </div>
        <div class="stat-card">
          <h3>{{ $t('trainingStats.averageParticipationQuarter') }}</h3>
          <div class="stat-number">{{ averageParticipationQuarter.toFixed(1) }}</div>
        </div>
        <div class="stat-card">
          <h3>{{ $t('trainingStats.averageParticipationHalfYear') }}</h3>
          <div class="stat-number">{{ averageParticipationHalfYear.toFixed(1) }}</div>
        </div>
        <div class="stat-card">
          <h3>{{ $t('trainingStats.averageParticipationYear') }}</h3>
          <div class="stat-number">{{ averageParticipationYear.toFixed(1) }}</div>
        </div>
      </div>
    </div>

    <!-- Trainingstage-Tabelle (standardmäßig aufgeklappt) -->
    <div class="collapsible-section">
      <div class="section-header" @click="toggleTrainingDays">
        <h3>{{ $t('trainingStats.trainingDays') }}</h3>
        <span class="toggle-icon">{{ showTrainingDays ? '▼' : '▶' }}</span>
      </div>
      <div v-if="showTrainingDays" class="section-content">
        <div class="training-days-container">
          <table class="training-days-table">
            <thead>
              <tr>
                <th>{{ $t('trainingStats.date') }}</th>
                <th>{{ $t('trainingStats.weekday') }}</th>
                <th>{{ $t('trainingStats.participants') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="day in trainingDays" :key="day.id">
                <td>{{ formatDate(day.date) }}</td>
                <td>{{ getWeekday(day.date) }}</td>
                <td>{{ day.participantCount }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Mitglieder-Tabelle (standardmäßig eingeklappt) -->
    <div class="collapsible-section">
      <div class="section-header" @click="toggleMembers">
        <h3>{{ $t('trainingStats.memberParticipations') }}</h3>
        <span class="toggle-icon">{{ showMembers ? '▼' : '▶' }}</span>
      </div>
      <div v-if="showMembers" class="section-content">
        <div class="members-table-container">
          <table class="members-table">
        <thead>
          <tr>
            <th @click="sortBy('name')" class="sortable-header">
              <div class="header-content">
                <span>{{ $t('trainingStats.name') }}</span>
                <span class="sort-icon">{{ getSortIcon('name') }}</span>
              </div>
            </th>
            <th>{{ $t('trainingStats.ttr') }}</th>
            <th>{{ $t('trainingStats.qttr') }}</th>
            <th>{{ $t('trainingStats.birthdate') }}</th>
            <th @click="sortBy('participation12Months')" class="sortable-header">
              <div class="header-content">
                <span>{{ $t('trainingStats.participations12Months') }}</span>
                <span class="sort-icon">{{ getSortIcon('participation12Months') }}</span>
              </div>
            </th>
            <th @click="sortBy('participation3Months')" class="sortable-header">
              <div class="header-content">
                <span>{{ $t('trainingStats.participations3Months') }}</span>
                <span class="sort-icon">{{ getSortIcon('participation3Months') }}</span>
              </div>
            </th>
            <th @click="sortBy('participationTotal')" class="sortable-header">
              <div class="header-content">
                <span>{{ $t('trainingStats.participationsTotal') }}</span>
                <span class="sort-icon">{{ getSortIcon('participationTotal') }}</span>
              </div>
            </th>
            <th @click="sortBy('lastTrainingTs')" class="sortable-header">
              <div class="header-content">
                <span>{{ $t('trainingStats.lastTraining') }}</span>
                <span class="sort-icon">{{ getSortIcon('lastTrainingTs') }}</span>
              </div>
            </th>
            <th>{{ $t('trainingStats.actions') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="member in sortedMembers" :key="member.id" class="member-row">
            <td>{{ member.firstName }} {{ member.lastName }}</td>
            <td>{{ member.ttr ?? '–' }}</td>
            <td>{{ member.qttr ?? '–' }}</td>
            <td>{{ formatBirthdate(member.birthDate) }}</td>
            <td>{{ member.participation12Months }}</td>
            <td>{{ member.participation3Months }}</td>
            <td>{{ member.participationTotal }}</td>
            <td>{{ formatDate(member.lastTraining) || '-' }}</td>
            <td>
              <button @click="showMemberDetails(member)" class="btn-primary btn-small">
                {{ $t('trainingStats.showDetails') }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
      </div>
    </div>

    <!-- Modal für Mitgliedsdetails -->
    <!-- Training Details Modal -->
    <TrainingDetailsDialog
      v-model="showDetailsModal"
      :member="selectedMember"
      @close="closeDetailsModal"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient';
import TrainingDetailsDialog from '../components/TrainingDetailsDialog.vue';

export default {
  name: 'TrainingStatsView',
  components: {
    TrainingDetailsDialog
  },
  computed: {
    ...mapGetters(['isAuthenticated', 'currentClub']),
    
    averageParticipation12Months() {
      if (this.trainingsCount12Months === 0) return 0;
      const total = this.activeMembers.reduce((sum, member) => sum + member.participation12Months, 0);
      return total / this.trainingsCount12Months;
    },
    
    averageParticipation3Months() {
      if (this.trainingsCount3Months === 0) return 0;
      const total = this.activeMembers.reduce((sum, member) => sum + member.participation3Months, 0);
      return total / this.trainingsCount3Months;
    },

    // Neue Zeiträume basierend auf verfügbaren Daten
    averageParticipationCurrentMonth() {
      const currentMonth = new Date().getMonth();
      const currentYear = new Date().getFullYear();
      const trainingsThisMonth = this.getTrainingsInPeriod(currentYear, currentMonth, currentYear, currentMonth);
      if (trainingsThisMonth === 0) return 0;
      const totalParticipants = this.getTotalParticipantsInPeriod(currentYear, currentMonth, currentYear, currentMonth);
      return totalParticipants / trainingsThisMonth;
    },

    averageParticipationLastMonth() {
      const lastMonth = new Date().getMonth() - 1;
      const year = lastMonth < 0 ? new Date().getFullYear() - 1 : new Date().getFullYear();
      const actualMonth = lastMonth < 0 ? 11 : lastMonth;
      const trainingsLastMonth = this.getTrainingsInPeriod(year, actualMonth, year, actualMonth);
      if (trainingsLastMonth === 0) return 0;
      const totalParticipants = this.getTotalParticipantsInPeriod(year, actualMonth, year, actualMonth);
      return totalParticipants / trainingsLastMonth;
    },

    averageParticipationQuarter() {
      // Finde das Quartal mit den meisten Trainingsdaten
      const quarters = [
        { year: 2024, startMonth: 0, endMonth: 2, name: 'Q1 2024' },
        { year: 2024, startMonth: 3, endMonth: 5, name: 'Q2 2024' },
        { year: 2024, startMonth: 6, endMonth: 8, name: 'Q3 2024' },
        { year: 2024, startMonth: 9, endMonth: 11, name: 'Q4 2024' },
        { year: 2025, startMonth: 0, endMonth: 2, name: 'Q1 2025' },
        { year: 2025, startMonth: 3, endMonth: 5, name: 'Q2 2025' },
        { year: 2025, startMonth: 6, endMonth: 8, name: 'Q3 2025' },
        { year: 2025, startMonth: 9, endMonth: 11, name: 'Q4 2025' }
      ];
      
      let bestQuarter = null;
      let maxTrainings = 0;
      
      for (const quarter of quarters) {
        const trainings = this.getTrainingsInPeriod(quarter.year, quarter.startMonth, quarter.year, quarter.endMonth);
        if (trainings > maxTrainings) {
          maxTrainings = trainings;
          bestQuarter = quarter;
        }
      }
      
      if (!bestQuarter || maxTrainings === 0) return 0;
      
      const totalParticipants = this.getTotalParticipantsInPeriod(bestQuarter.year, bestQuarter.startMonth, bestQuarter.year, bestQuarter.endMonth);
      return totalParticipants / maxTrainings;
    },

    averageParticipationHalfYear() {
      const now = new Date();
      const halfYearStartMonth = now.getMonth() < 6 ? 0 : 6;
      const halfYearEndMonth = now.getMonth() < 6 ? 5 : 11;
      const trainingsHalfYear = this.getTrainingsInPeriod(now.getFullYear(), halfYearStartMonth, now.getFullYear(), halfYearEndMonth);
      if (trainingsHalfYear === 0) return 0;
      const totalParticipants = this.getTotalParticipantsInPeriod(now.getFullYear(), halfYearStartMonth, now.getFullYear(), halfYearEndMonth);
      return totalParticipants / trainingsHalfYear;
    },

    averageParticipationYear() {
      const currentYear = new Date().getFullYear();
      const trainingsYear = this.getTrainingsInPeriod(currentYear, 0, currentYear, 11);
      if (trainingsYear === 0) return 0;
      const totalParticipants = this.getTotalParticipantsInPeriod(currentYear, 0, currentYear, 11);
      return totalParticipants / trainingsYear;
    },
    
    sortedMembers() {
      if (!this.activeMembers.length) return [];
      
      return [...this.activeMembers].sort((a, b) => {
        let aValue, bValue;
        
        if (this.sortField === 'name') {
          // Case-insensitive Namens-Sortierung mit localeCompare
          // Sortiere nach firstName lastName (wie in der Anzeige)
          const aName = `${a.firstName} ${a.lastName}`;
          const bName = `${b.firstName} ${b.lastName}`;
          return aName.localeCompare(bName, 'de', { sensitivity: 'base' }) * (this.sortDirection === 'asc' ? 1 : -1);
        } else {
          // Numerische Sortierung
          aValue = a[this.sortField] || 0;
          bValue = b[this.sortField] || 0;
          
          if (this.sortDirection === 'asc') {
            return aValue > bValue ? 1 : -1;
          } else {
            return aValue < bValue ? 1 : -1;
          }
        }
      });
    }
  },
  
  data() {
    return {
      activeMembers: [],
      trainingsCount12Months: 0,
      trainingsCount3Months: 0,
      trainingDays: [],
      showDetailsModal: false,
      selectedMember: {},
      loading: false,
      sortField: 'name',
      sortDirection: 'asc',
      showTrainingDays: true,
      showMembers: false
    };
  },
  
  async mounted() {
    if (this.currentClub) {
      await this.loadTrainingStats();
    }
  },
  
  watch: {
    currentClub: {
      handler(newClub) {
        if (newClub) {
          this.loadTrainingStats();
        }
      },
      immediate: true
    }
  },
  
  methods: {
    async loadTrainingStats() {
      if (!this.currentClub) return;
      
      this.loading = true;
      try {
        const response = await apiClient.get(`/training-stats/${this.currentClub}`);
        this.activeMembers = response.data.members || [];
        this.trainingsCount12Months = response.data.trainingsCount12Months || 0;
        this.trainingsCount3Months = response.data.trainingsCount3Months || 0;
        this.trainingDays = response.data.trainingDays || [];
      } catch (error) {
        // Kein Alert - es ist normal, dass nicht alle Daten verfügbar sind
      } finally {
        this.loading = false;
      }
    },

    // Hilfsmethoden für neue Zeiträume
    getTrainingsInPeriod(startYear, startMonth, endYear, endMonth) {
      return this.trainingDays.filter(day => {
        const dayDate = new Date(day.date);
        const dayYear = dayDate.getFullYear();
        const dayMonth = dayDate.getMonth();
        
        if (dayYear < startYear || dayYear > endYear) return false;
        if (dayYear === startYear && dayMonth < startMonth) return false;
        if (dayYear === endYear && dayMonth > endMonth) return false;
        
        return true;
      }).length;
    },

    getTotalParticipantsInPeriod(startYear, startMonth, endYear, endMonth) {
      // Summiere die Teilnehmerzahlen aller Trainingstage im Zeitraum
      return this.trainingDays.filter(day => {
        const dayDate = new Date(day.date);
        const dayYear = dayDate.getFullYear();
        const dayMonth = dayDate.getMonth();
        
        if (dayYear < startYear || dayYear > endYear) return false;
        if (dayYear === startYear && dayMonth < startMonth) return false;
        if (dayYear === endYear && dayMonth > endMonth) return false;
        
        return true;
      }).reduce((sum, day) => sum + (day.participantCount || 0), 0);
    },
    
    toggleTrainingDays() {
      this.showTrainingDays = !this.showTrainingDays;
    },
    
    toggleMembers() {
      this.showMembers = !this.showMembers;
    },
    
    getWeekday(dateString) {
      const date = new Date(dateString);
      const weekdays = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
      return weekdays[date.getDay()];
    },
    
    showMemberDetails(member) {
      this.selectedMember = member;
      this.showDetailsModal = true;
    },
    
    closeDetailsModal() {
      this.showDetailsModal = false;
      this.selectedMember = {};
    },
    
    formatBirthdate(birthDate) {
      if (!birthDate) return '-';
      const date = new Date(birthDate);
      return `${String(date.getDate()).padStart(2, '0')}.${String(date.getMonth() + 1).padStart(2, '0')}.${date.getFullYear()}`;
    },
    
    getBirthYear(birthDate) {
      if (!birthDate) return '-';
      const date = new Date(birthDate);
      return date.getFullYear();
    },
    
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${String(date.getDate()).padStart(2, '0')}.${String(date.getMonth() + 1).padStart(2, '0')}.${date.getFullYear()}`;
    },
    
    sortBy(field) {
      if (this.sortField === field) {
        // Wenn bereits nach diesem Feld sortiert wird, Richtung umkehren
        this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
      } else {
        // Neues Feld, Standardrichtung setzen
        this.sortField = field;
        this.sortDirection = 'desc';
      }
    },
    
    getSortIcon(field) {
      if (this.sortField !== field) {
        return '↕️'; // Neutral
      }
      return this.sortDirection === 'asc' ? '↑' : '↓';
    }
  }
};
</script>

<style scoped>
.training-stats {
  padding: 1.5rem;
  max-width: 1200px;
  margin: 0 auto;
}

.stats-overview {
  margin-bottom: 2rem;
}

.stats-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 0.8rem;
  margin-bottom: 1.5rem;
}

.stat-card {
  background: white;
  padding: 0.8rem;
  border-radius: var(--border-radius-large);
  box-shadow: var(--shadow-light);
  text-align: center;
  border: 1px solid var(--border-color);
}

.stat-card h3 {
  margin: 0 0 0.5rem 0;
  font-size: 0.7rem;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.025em;
}

.stat-number {
  font-size: 1.2rem;
  font-weight: 700;
  color: var(--primary-color);
}

.collapsible-section {
  background: white;
  border-radius: var(--border-radius-large);
  box-shadow: var(--shadow-light);
  border: 1px solid var(--border-color);
  margin-bottom: 1.5rem;
  overflow: hidden;
}

.section-header {
  padding: 1.25rem 1.5rem;
  background: var(--bg-light);
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
  transition: background-color 0.2s ease;
}

.section-header:hover {
  background: var(--primary-color);
  color: white;
}

.section-header:hover h3 {
  color: white;
}

.section-header h3 {
  margin: 0;
  font-size: 1.125rem;
  color: var(--text-primary);
  transition: color 0.2s ease;
}

.toggle-icon {
  font-size: 1rem;
  font-weight: bold;
  transition: transform 0.3s ease;
}

.section-content {
  padding: 0;
}

.training-days-container {
  overflow-x: auto;
}

.training-days-table {
  width: 100%;
  border-collapse: collapse;
}

.training-days-table th,
.training-days-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.training-days-table th {
  background: var(--bg-light);
  font-weight: 600;
  color: var(--text-primary);
}

.training-days-table tbody tr:hover {
  background: var(--bg-light);
}

.training-days-table tbody tr:last-child td {
  border-bottom: none;
}

.members-table-container {
  overflow-x: auto;
}

.members-table {
  width: 100%;
  border-collapse: collapse;
}

.members-table th {
  background: var(--bg-light);
  padding: 1rem;
  text-align: left;
  font-weight: 600;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-color);
}

.sortable-header {
  cursor: pointer;
  user-select: none;
  transition: background-color 0.2s ease;
}

.sortable-header:hover {
  background: var(--primary-color) !important;
  color: white !important;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
}

.sort-icon {
  font-size: 0.875rem;
  opacity: 0.7;
}

.members-table td {
  padding: 1rem;
  border-bottom: 1px solid var(--border-color);
  vertical-align: middle;
}

.members-table tr:hover {
  background: var(--bg-light);
}

.member-row {
  cursor: pointer;
}

.member-row:hover {
  background: var(--bg-light);
}

.btn-small {
  padding: 0.375rem 0.75rem;
  font-size: 0.75rem;
  min-height: 1.875rem;
}

/* Modal Styles */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: var(--border-radius-large);
  padding: 2rem;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: var(--shadow-heavy);
}

.close {
  position: absolute;
  top: 1rem;
  right: 1.5rem;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--text-secondary);
  font-weight: bold;
}

.close:hover {
  color: var(--text-primary);
}

.member-info {
  background: var(--bg-light);
  padding: 1rem;
  border-radius: var(--border-radius);
  margin-bottom: 1.5rem;
}

.member-info p {
  margin: 0.5rem 0;
}

.participation-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
}

.summary-item {
  background: white;
  padding: 1rem;
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
  text-align: center;
}

.summary-item .label {
  display: block;
  font-size: 0.875rem;
  color: var(--text-secondary);
  margin-bottom: 0.5rem;
}

.summary-item .value {
  display: block;
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--primary-color);
}

.training-details h4 {
  margin: 0 0 1rem 0;
  color: var(--text-primary);
}

.training-list {
  max-height: 400px;
  overflow-y: auto;
}

.training-item {
  display: grid;
  grid-template-columns: 120px 1fr 150px;
  gap: 1rem;
  padding: 0.75rem;
  border-bottom: 1px solid var(--border-color);
  align-items: center;
}

.training-item:last-child {
  border-bottom: none;
}

.training-item:hover {
  background: var(--bg-light);
}

.training-date {
  font-weight: 600;
  color: var(--text-primary);
}

.training-activity {
  color: var(--text-secondary);
}

.training-time {
  font-size: 0.875rem;
  color: var(--text-muted);
  text-align: right;
}

/* Responsive Design */
@media (max-width: 768px) {
  .training-stats {
    padding: 1rem;
  }
  
  .stats-summary {
    grid-template-columns: 1fr;
  }
  
  .members-table {
    font-size: 0.875rem;
  }
  
  .members-table th,
  .members-table td {
    padding: 0.75rem 0.5rem;
  }
  
  .modal-content {
    margin: 1rem;
    padding: 1.5rem;
  }
  
  .training-item {
    grid-template-columns: 1fr;
    gap: 0.5rem;
    text-align: center;
  }
  
  .training-time {
    text-align: center;
  }
}
</style>
