<template>
  <div class="training-stats">
    <h2>{{ $t('trainingStats.title') }}</h2>

    <div class="stats-filters">
      <label class="stats-filter">
        <span>Wochentag</span>
        <select v-model="selectedWeekday">
          <option value="all">Alle</option>
          <option v-for="option in weekdayOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
        </select>
      </label>
      <label class="stats-filter">
        <span>{{ $t('trainingStats.trainingDayFilter') }}</span>
        <select v-model="selectedTrainingDay">
          <option value="all">{{ $t('trainingStats.allTrainingDays') }}</option>
          <option v-for="option in trainingDayOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
        </select>
      </label>
      <label class="stats-filter">
        <span>Trainingsgruppe</span>
        <select v-model="selectedTrainingGroup">
          <option value="all">Alle</option>
          <option v-for="group in trainingGroupOptions" :key="group.value" :value="group.value">{{ group.label }}</option>
        </select>
      </label>
    </div>
    
    <div class="collapsible-section">
      <div class="section-header" @click="togglePanel('overview')">
        <h3>{{ $t('trainingStats.panelSummary') }}</h3>
        <span class="section-header-right">
          <span class="toggle-icon">{{ panels.overview ? '▼' : '▶' }}</span>
        </span>
      </div>
      <div v-show="panels.overview" class="section-content">
        <div class="stats-overview panel-body-padding">
          <div class="stats-summary">
            <div class="stat-card">
              <h3>Aktive Mitglieder</h3>
              <div class="stat-number">{{ filteredMembers.length }}</div>
            </div>
            <div class="stat-card">
              <h3>Trainingstage 12 Monate</h3>
              <div class="stat-number">{{ filteredTrainingDays.length }}</div>
            </div>
            <div class="stat-card">
              <h3>Ø Teilnehmer je Training</h3>
              <div class="stat-number">{{ filteredOverview.averageParticipants.toFixed(1) }}</div>
            </div>
            <div class="stat-card">
              <h3>Teilnahmen gesamt</h3>
              <div class="stat-number">{{ filteredOverview.totalParticipants }}</div>
            </div>
            <div class="stat-card">
              <h3>Anwesenheitsquote 12 Monate</h3>
              <div class="stat-number">{{ filteredOverview.attendanceRate.toFixed(1) }}%</div>
            </div>
            <div class="stat-card">
              <h3>Nicht im Training</h3>
              <div class="stat-number">{{ filteredMembers.filter((member) => member.notInTraining).length }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="stats-panels-grid">
      <div class="collapsible-section stats-panel-collapsible">
        <div class="section-header" @click="togglePanel('monthlyTrend')">
          <h3>{{ $t('trainingStats.panelMonthlyTrend') }}</h3>
          <span class="section-header-right">
            <span class="section-meta">{{ filteredMonthlyTrend.length }} Monate</span>
            <span class="toggle-icon">{{ panels.monthlyTrend ? '▼' : '▶' }}</span>
          </span>
        </div>
        <div v-show="panels.monthlyTrend" class="section-content">
          <div class="trend-list panel-body-padding">
            <div v-for="month in filteredMonthlyTrend" :key="month.key" class="trend-row">
              <div class="trend-meta">
                <strong>{{ month.label }}</strong>
                <span>{{ month.trainingCount }} Trainingstage</span>
              </div>
              <div class="trend-bar-track">
                <div class="trend-bar-fill" :style="{ width: `${getMonthBarWidth(month.averageParticipants)}%` }"></div>
              </div>
              <div class="trend-value">{{ month.averageParticipants.toFixed(1) }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="collapsible-section stats-panel-collapsible">
        <div class="section-header" @click="togglePanel('weekdayStats')">
          <h3>{{ $t('trainingStats.panelWeekdayStats') }}</h3>
          <span class="section-header-right">
            <span class="section-meta">{{ filteredWeekdayStats.length }} Wochentage</span>
            <span class="toggle-icon">{{ panels.weekdayStats ? '▼' : '▶' }}</span>
          </span>
        </div>
        <div v-show="panels.weekdayStats" class="section-content">
          <div class="weekday-grid panel-body-padding">
            <div v-for="day in filteredWeekdayStats" :key="day.weekday" class="weekday-card">
              <strong>{{ day.weekday }}</strong>
              <span>{{ day.trainingCount }} Termine</span>
              <span>Ø {{ day.averageParticipants.toFixed(1) }} Teilnehmer</span>
            </div>
          </div>
        </div>
      </div>

      <div class="collapsible-section stats-panel-collapsible">
        <div class="section-header" @click="togglePanel('memberStructure')">
          <h3>{{ $t('trainingStats.panelMemberStructure') }}</h3>
          <span class="section-header-right">
            <span class="toggle-icon">{{ panels.memberStructure ? '▼' : '▶' }}</span>
          </span>
        </div>
        <div v-show="panels.memberStructure" class="section-content">
          <div class="distribution-grid panel-body-padding">
            <div class="distribution-card">
              <strong>Sehr aktiv</strong>
              <span>{{ filteredMemberDistribution.highlyActive }}</span>
              <small>mind. 75 % der Trainingstage</small>
            </div>
            <div class="distribution-card">
              <strong>Regelmäßig</strong>
              <span>{{ filteredMemberDistribution.regular }}</span>
              <small>40 bis unter 75 %</small>
            </div>
            <div class="distribution-card">
              <strong>Gelegentlich</strong>
              <span>{{ filteredMemberDistribution.occasional }}</span>
              <small>unter 40 %</small>
            </div>
            <div class="distribution-card">
              <strong>Ohne Teilnahme</strong>
              <span>{{ filteredMemberDistribution.inactive }}</span>
              <small>0 Teilnahmen in 12 Monaten</small>
            </div>
          </div>
        </div>
      </div>

      <div class="collapsible-section stats-panel-collapsible stats-panel-highlight">
        <div class="section-header" @click="togglePanel('bestDay')">
          <h3>{{ $t('trainingStats.panelBestDay') }}</h3>
          <span class="section-header-right">
            <span class="toggle-icon">{{ panels.bestDay ? '▼' : '▶' }}</span>
          </span>
        </div>
        <div v-show="panels.bestDay" class="section-content">
          <div class="panel-body-padding">
            <div v-if="filteredOverview.bestTrainingDay" class="highlight-block">
              <strong>{{ formatDate(filteredOverview.bestTrainingDay.date) }}</strong>
              <span>{{ getWeekday(filteredOverview.bestTrainingDay.date) }}</span>
              <div class="highlight-number">{{ filteredOverview.bestTrainingDay.participantCount }}</div>
              <small>Teilnehmer beim bestbesuchten Training der letzten 12 Monate</small>
            </div>
            <div v-else class="highlight-block">
              <strong>Keine Daten</strong>
            </div>
          </div>
        </div>
      </div>

      <div class="collapsible-section stats-panel-collapsible">
        <div class="section-header" @click="togglePanel('groupPerformance')">
          <h3>{{ $t('trainingStats.panelGroupPerformance') }}</h3>
          <span class="section-header-right">
            <span class="section-meta">{{ groupPerformance.length }} Gruppen</span>
            <span class="toggle-icon">{{ panels.groupPerformance ? '▼' : '▶' }}</span>
          </span>
        </div>
        <div v-show="panels.groupPerformance" class="section-content">
          <div class="group-performance-list panel-body-padding">
            <div v-for="group in groupPerformance" :key="group.name" class="group-performance-row">
              <div class="group-performance-meta">
                <strong>{{ group.name }}</strong>
                <span>{{ group.memberCount }} Mitglieder</span>
              </div>
              <div class="group-performance-stats">
                <span>{{ group.averageParticipations12Months.toFixed(1) }} Ø Teilnahmen / 12 Monate</span>
                <span>{{ group.participationRate.toFixed(1) }}% Anwesenheit</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="collapsible-section stats-panel-collapsible">
        <div class="section-header" @click="togglePanel('ageGroup')">
          <h3>{{ $t('trainingStats.panelAgeGroups') }}</h3>
          <span class="section-header-right">
            <span class="section-meta">{{ ageGroupStats.length }} Klassen</span>
            <span class="toggle-icon">{{ panels.ageGroup ? '▼' : '▶' }}</span>
          </span>
        </div>
        <div v-show="panels.ageGroup" class="section-content">
          <div class="distribution-grid panel-body-padding">
            <div v-for="entry in ageGroupStats" :key="entry.label" class="distribution-card">
              <strong>{{ entry.label }}</strong>
              <span>{{ entry.memberCount }}</span>
              <small>{{ entry.averageParticipations12Months.toFixed(1) }} Ø Teilnahmen / 12 Monate</small>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="collapsible-section">
      <div class="section-header" @click="togglePanel('trainingDays')">
        <h3>{{ $t('trainingStats.trainingDays') }}</h3>
        <span class="toggle-icon">{{ panels.trainingDays ? '▼' : '▶' }}</span>
      </div>
      <div v-show="panels.trainingDays" 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>
                <th>{{ $t('trainingStats.attendingMembers') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="day in filteredTrainingDays" :key="day.id">
                <td>{{ formatDate(day.date) }}</td>
                <td>{{ getWeekday(day.date) }}</td>
                <td>{{ day.participantCount }}</td>
                <td>
                  <div v-if="day.participants && day.participants.length" class="training-day-members">
                    <span
                      v-for="participant in day.participants"
                      :key="participant.id"
                      class="training-day-member-chip"
                    >
                      {{ participant.firstName }} {{ participant.lastName }}
                    </span>
                  </div>
                  <span v-else class="training-day-empty">{{ $t('trainingStats.noParticipants') }}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- Mitglieder-Tabelle -->
    <div class="collapsible-section">
      <div class="section-header" @click="togglePanel('members')">
        <h3>{{ $t('trainingStats.memberParticipations') }}</h3>
        <span class="toggle-icon">{{ panels.members ? '▼' : '▶' }}</span>
      </div>
      <div v-show="panels.members" 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';

const WEEKDAY_NAMES = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];

export default {
  name: 'TrainingStatsView',
  components: {
    TrainingDetailsDialog
  },
  computed: {
    ...mapGetters(['isAuthenticated', 'currentClub']),
    
    sortedMembers() {
      if (!this.filteredMembers.length) return [];
      
      return [...this.filteredMembers].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;
          }
        }
      });
    },

    weekdayOptions() {
      return WEEKDAY_NAMES.map((label, index) => ({ value: String(index), label }));
    },

    trainingGroupOptions() {
      const groups = new Map();
      this.activeMembers.forEach((member) => {
        (member.trainingGroups || []).forEach((group) => {
          if (!groups.has(String(group.id))) {
            groups.set(String(group.id), { value: String(group.id), label: group.name });
          }
        });
      });
      return Array.from(groups.values()).sort((a, b) => a.label.localeCompare(b.label, 'de'));
    },

    trainingDaysByWeekday() {
      if (this.selectedWeekday === 'all') {
        return this.trainingDays;
      }

      return this.trainingDays.filter((day) => String(new Date(day.date).getDay()) === this.selectedWeekday);
    },

    trainingDayOptions() {
      return this.trainingDaysByWeekday.map((day) => ({
        value: String(day.id),
        label: `${this.formatDate(day.date)} (${this.getWeekday(day.date)})`,
      }));
    },

    selectedTrainingDayParticipantIds() {
      if (this.selectedTrainingDay === 'all') {
        return null;
      }

      const selectedDay = this.trainingDays.find((day) => String(day.id) === String(this.selectedTrainingDay));
      if (!selectedDay || !Array.isArray(selectedDay.participants)) {
        return new Set();
      }

      return new Set(selectedDay.participants.map((participant) => Number(participant.id)).filter((id) => Number.isFinite(id)));
    },

    filteredMembers() {
      let members = this.activeMembers;

      if (this.selectedTrainingGroup !== 'all') {
        members = members.filter((member) =>
          (member.trainingGroups || []).some((group) => String(group.id) === this.selectedTrainingGroup)
        );
      }

      if (this.selectedTrainingDayParticipantIds) {
        members = members.filter((member) => this.selectedTrainingDayParticipantIds.has(Number(member.id)));
      }

      return members;
    },

    filteredTrainingDays() {
      if (this.selectedTrainingDay === 'all') {
        return this.trainingDaysByWeekday;
      }

      return this.trainingDaysByWeekday.filter((day) => String(day.id) === String(this.selectedTrainingDay));
    },

    filteredOverview() {
      const totalParticipants = this.filteredTrainingDays.reduce((sum, day) => sum + (day.participantCount || 0), 0);
      const averageParticipants = this.filteredTrainingDays.length > 0 ? totalParticipants / this.filteredTrainingDays.length : 0;
      const denominatorMembers = this.filteredMembers.length || 0;
      const attendanceRate = denominatorMembers > 0 && this.filteredTrainingDays.length > 0
        ? (totalParticipants / (denominatorMembers * this.filteredTrainingDays.length)) * 100
        : 0;
      const bestTrainingDay = this.filteredTrainingDays.reduce((best, day) => {
        if (!best || (day.participantCount || 0) > (best.participantCount || 0)) {
          return day;
        }
        return best;
      }, null);

      return {
        totalParticipants,
        averageParticipants,
        attendanceRate,
        bestTrainingDay
      };
    },

    filteredMonthlyTrend() {
      const months = new Map();

      this.filteredTrainingDays.forEach((day) => {
        const date = new Date(day.date);
        const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        if (!months.has(key)) {
          months.set(key, {
            key,
            label: `${String(date.getMonth() + 1).padStart(2, '0')}.${date.getFullYear()}`,
            trainingCount: 0,
            participantCount: 0,
            averageParticipants: 0
          });
        }
        const entry = months.get(key);
        entry.trainingCount += 1;
        entry.participantCount += day.participantCount || 0;
      });

      return Array.from(months.values())
        .sort((a, b) => a.key.localeCompare(b.key))
        .map((entry) => ({
          ...entry,
          averageParticipants: entry.trainingCount > 0 ? entry.participantCount / entry.trainingCount : 0
        }));
    },

    filteredWeekdayStats() {
      const buckets = new Map();

      this.filteredTrainingDays.forEach((day) => {
        const date = new Date(day.date);
        const weekdayIndex = date.getDay();
        const key = String(weekdayIndex);
        if (!buckets.has(key)) {
          buckets.set(key, {
            weekday: WEEKDAY_NAMES[weekdayIndex],
            weekdayIndex,
            trainingCount: 0,
            participantCount: 0,
            averageParticipants: 0
          });
        }
        const entry = buckets.get(key);
        entry.trainingCount += 1;
        entry.participantCount += day.participantCount || 0;
      });

      return Array.from(buckets.values())
        .sort((a, b) => a.weekdayIndex - b.weekdayIndex)
        .map((entry) => ({
          ...entry,
          averageParticipants: entry.trainingCount > 0 ? entry.participantCount / entry.trainingCount : 0
        }));
    },

    filteredMemberDistribution() {
      return {
        highlyActive: this.filteredMembers.filter((member) => (member.participationRate12Months || 0) >= 0.75).length,
        regular: this.filteredMembers.filter((member) => (member.participationRate12Months || 0) >= 0.4 && (member.participationRate12Months || 0) < 0.75).length,
        occasional: this.filteredMembers.filter((member) => (member.participationRate12Months || 0) > 0 && (member.participationRate12Months || 0) < 0.4).length,
        inactive: this.filteredMembers.filter((member) => (member.participation12Months || 0) === 0).length
      };
    },

    groupPerformance() {
      const groups = new Map();

      this.filteredMembers.forEach((member) => {
        const memberGroups = member.trainingGroups || [];
        if (memberGroups.length === 0) {
          if (!groups.has('ohne-gruppe')) {
            groups.set('ohne-gruppe', { name: 'Ohne Trainingsgruppe', memberCount: 0, totalParticipations12Months: 0, participationRateSum: 0 });
          }
          const entry = groups.get('ohne-gruppe');
          entry.memberCount += 1;
          entry.totalParticipations12Months += member.participation12Months || 0;
          entry.participationRateSum += member.participationRate12Months || 0;
          return;
        }

        memberGroups.forEach((group) => {
          const key = String(group.id);
          if (!groups.has(key)) {
            groups.set(key, { name: group.name, memberCount: 0, totalParticipations12Months: 0, participationRateSum: 0 });
          }
          const entry = groups.get(key);
          entry.memberCount += 1;
          entry.totalParticipations12Months += member.participation12Months || 0;
          entry.participationRateSum += member.participationRate12Months || 0;
        });
      });

      return Array.from(groups.values())
        .map((entry) => ({
          ...entry,
          averageParticipations12Months: entry.memberCount > 0 ? entry.totalParticipations12Months / entry.memberCount : 0,
          participationRate: entry.memberCount > 0 ? (entry.participationRateSum / entry.memberCount) * 100 : 0
        }))
        .sort((a, b) => b.averageParticipations12Months - a.averageParticipations12Months);
    },

    ageGroupStats() {
      const buckets = [
        { label: 'U7', memberCount: 0, totalParticipations12Months: 0, match: (age) => age !== null && age <= 6 },
        { label: 'U9', memberCount: 0, totalParticipations12Months: 0, match: (age) => age !== null && age >= 7 && age <= 8 },
        { label: 'U11', memberCount: 0, totalParticipations12Months: 0, match: (age) => age !== null && age >= 9 && age <= 10 },
        { label: 'U13', memberCount: 0, totalParticipations12Months: 0, match: (age) => age !== null && age >= 11 && age <= 12 },
        { label: 'U15', memberCount: 0, totalParticipations12Months: 0, match: (age) => age !== null && age >= 13 && age <= 14 },
        { label: 'U19', memberCount: 0, totalParticipations12Months: 0, match: (age) => age !== null && age >= 15 && age <= 18 },
        { label: 'Erwachsene', memberCount: 0, totalParticipations12Months: 0, match: (age) => age !== null && age >= 19 }
      ];

      this.filteredMembers.forEach((member) => {
        const age = this.getAge(member.birthDate);
        const bucket = buckets.find((entry) => entry.match(age));
        if (!bucket) return;
        bucket.memberCount += 1;
        bucket.totalParticipations12Months += member.participation12Months || 0;
      });

      return buckets
        .map((entry) => ({
          ...entry,
          averageParticipations12Months: entry.memberCount > 0 ? entry.totalParticipations12Months / entry.memberCount : 0
        }));
    }
  },
  
  data() {
    return {
      activeMembers: [],
      trainingsCount12Months: 0,
      trainingsCount3Months: 0,
      trainingDays: [],
      overview: {
        activeMembersCount: 0,
        totalParticipants12Months: 0,
        averageParticipants12Months: 0,
        attendanceRate12Months: 0,
        inactiveMembersCount: 0,
        bestTrainingDay: null
      },
      weekdayStats: [],
      monthlyTrend: [],
      memberDistribution: {
        highlyActive: 0,
        regular: 0,
        occasional: 0,
        inactive: 0
      },
      selectedWeekday: 'all',
      selectedTrainingDay: 'all',
      selectedTrainingGroup: 'all',
      showDetailsModal: false,
      selectedMember: {},
      loading: false,
      sortField: 'name',
      sortDirection: 'asc',
      panels: {
        overview: false,
        monthlyTrend: false,
        weekdayStats: false,
        memberStructure: false,
        bestDay: false,
        groupPerformance: false,
        ageGroup: false,
        trainingDays: false,
        members: false
      }
    };
  },
  
  async mounted() {
    if (this.currentClub) {
      await this.loadTrainingStats();
    }
  },
  
  watch: {
    currentClub: {
      handler(newClub) {
        if (newClub) {
          this.loadTrainingStats();
        }
      },
      immediate: true
    },
    selectedWeekday() {
      if (this.selectedTrainingDay === 'all') return;
      const hasSelectedDay = this.trainingDaysByWeekday.some((day) => String(day.id) === String(this.selectedTrainingDay));
      if (!hasSelectedDay) {
        this.selectedTrainingDay = 'all';
      }
    }
  },
  
  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 || [];
        this.overview = response.data.overview || this.overview;
        this.weekdayStats = response.data.weekdayStats || [];
        this.monthlyTrend = response.data.monthlyTrend || [];
        this.memberDistribution = response.data.memberDistribution || this.memberDistribution;
      } catch (error) {
        // Kein Alert - es ist normal, dass nicht alle Daten verfügbar sind
      } finally {
        this.loading = false;
      }
    },

    togglePanel(key) {
      if (!Object.prototype.hasOwnProperty.call(this.panels, key)) return;
      this.panels = { ...this.panels, [key]: !this.panels[key] };
    },

    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()}`;
    },

    getAge(birthDate) {
      if (!birthDate) return null;
      const today = new Date();
      const birth = new Date(birthDate);
      if (Number.isNaN(birth.getTime())) return null;
      let age = today.getFullYear() - birth.getFullYear();
      const monthDiff = today.getMonth() - birth.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
      }
      return age;
    },
    
    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' ? '↑' : '↓';
    },

    getMonthBarWidth(value) {
      const maxValue = Math.max(...this.filteredMonthlyTrend.map((entry) => entry.averageParticipants || 0), 1);
      return (value / maxValue) * 100;
    }
  }
};
</script>

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

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

.stats-filters {
  display: flex;
  gap: 0.9rem;
  flex-wrap: wrap;
  margin-bottom: 1.25rem;
}

.stats-filter {
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
  flex: 1 1 220px;
}

.stats-filter span {
  font-size: 0.88rem;
  font-weight: 600;
  color: var(--text-secondary);
}

.stats-filter select {
  width: 100%;
}

.stats-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(160px, 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);
}

.stats-panels-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.stats-panels-grid > .collapsible-section {
  margin-bottom: 0;
}

.stats-panel-collapsible .section-header {
  margin-bottom: 0;
}

.section-header-right {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.section-meta {
  font-size: 0.85rem;
  color: var(--text-secondary);
}

.section-header:hover .section-meta {
  color: inherit;
  opacity: 0.95;
}

.panel-body-padding {
  padding: 0 1.15rem 1.15rem;
}

.stats-overview.panel-body-padding {
  margin-bottom: 0;
}

.collapsible-section.stats-panel-highlight {
  background: linear-gradient(135deg, rgba(47, 122, 95, 0.08), rgba(255, 255, 255, 0.98));
}

.stats-panel {
  background: white;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-large);
  box-shadow: var(--shadow-light);
  padding: 1.1rem 1.15rem;
}

.stats-panel-highlight {
  background: linear-gradient(135deg, rgba(47, 122, 95, 0.08), rgba(255, 255, 255, 0.98));
}

.panel-header {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 1rem;
  margin-bottom: 0.9rem;
}

.panel-header h3 {
  margin: 0;
  font-size: 1rem;
  color: var(--text-primary);
}

.panel-header span {
  color: var(--text-secondary);
  font-size: 0.85rem;
}

.trend-list {
  display: flex;
  flex-direction: column;
  gap: 0.7rem;
}

.trend-row {
  display: grid;
  grid-template-columns: minmax(92px, 120px) minmax(0, 1fr) 52px;
  gap: 0.75rem;
  align-items: center;
}

.trend-meta {
  display: flex;
  flex-direction: column;
  gap: 0.15rem;
}

.trend-meta strong {
  font-size: 0.92rem;
  color: var(--text-primary);
}

.trend-meta span {
  font-size: 0.78rem;
  color: var(--text-secondary);
}

.trend-bar-track {
  height: 0.7rem;
  border-radius: 999px;
  background: var(--bg-light);
  overflow: hidden;
}

.trend-bar-fill {
  height: 100%;
  border-radius: inherit;
  background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
}

.trend-value {
  text-align: right;
  font-weight: 700;
  color: var(--primary-color);
}

.weekday-grid,
.distribution-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 0.75rem;
}

.weekday-card,
.distribution-card {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
  padding: 0.85rem 0.9rem;
  border-radius: 14px;
  background: var(--bg-light);
  border: 1px solid var(--border-color);
}

.weekday-card strong,
.distribution-card strong {
  color: var(--text-primary);
}

.weekday-card span,
.distribution-card small {
  color: var(--text-secondary);
}

.distribution-card span {
  font-size: 1.35rem;
  font-weight: 700;
  color: var(--primary-color);
}

.highlight-block {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 0.35rem;
}

.highlight-block strong {
  font-size: 1.05rem;
  color: var(--text-primary);
}

.highlight-block span,
.highlight-block small {
  color: var(--text-secondary);
}

.highlight-number {
  font-size: 2.2rem;
  line-height: 1;
  font-weight: 800;
  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;
}

.training-day-members {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
}

.training-day-member-chip {
  display: inline-flex;
  align-items: center;
  padding: 0.2rem 0.55rem;
  border-radius: 999px;
  background: rgba(26, 130, 172, 0.12);
  color: var(--text-color);
  font-size: 0.8rem;
  line-height: 1.2;
}

.training-day-empty {
  color: var(--text-muted);
  font-size: 0.9rem;
}

.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-filters {
    flex-direction: column;
    gap: 0.75rem;
  }

  .stats-filter {
    flex-basis: auto;
  }
  
  .stats-summary {
    grid-template-columns: 1fr;
  }

  .stats-panels-grid,
  .weekday-grid,
  .distribution-grid {
    grid-template-columns: 1fr;
  }

  .trend-row {
    grid-template-columns: 1fr;
  }

  .panel-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .section-header {
    padding: 1rem;
  }

  .trend-value {
    text-align: left;
  }
  
  .members-table {
    font-size: 0.875rem;
  }
  
  .members-table th,
  .members-table td {
    padding: 0.75rem 0.5rem;
  }

  .training-days-container,
  .members-table-container {
    margin: 0 -0.25rem;
  }
  
  .modal-content {
    margin: 1rem;
    padding: 1.5rem;
  }
  
  .training-item {
    grid-template-columns: 1fr;
    gap: 0.5rem;
    text-align: center;
  }
  
  .training-time {
    text-align: center;
  }
}

@media (max-width: 480px) {
  .training-stats {
    padding: 0.85rem;
  }

  .stats-panel {
    padding: 0.95rem;
  }

  .highlight-number {
    font-size: 1.9rem;
  }

  .training-days-table th,
  .training-days-table td,
  .members-table th,
  .members-table td {
    padding: 0.65rem 0.45rem;
  }
}
</style>
