<template>
  <div class="club-statistics-page">
    <header class="statistics-hero card">
      <div class="statistics-hero-copy">
        <p class="statistics-eyebrow">TT-Verein</p>
        <h2>Statistiken</h2>
        <p class="statistics-summary">
          Auswertungen zu Mitgliederentwicklung, Altersstruktur, Beitragsentwicklung und Sponsorenentwicklung.
        </p>
      </div>
      <button type="button" class="btn-secondary" @click="loadStatistics" :disabled="loading || !currentClub">
        {{ loading ? 'Lädt…' : 'Neu laden' }}
      </button>
    </header>

    <section v-if="!currentClub" class="card empty-state">
      <h3>Kein Verein ausgewählt</h3>
      <p>Bitte zuerst einen Verein auswählen, um Statistiken zu laden.</p>
    </section>

    <template v-else>
      <p v-if="loadError" class="state-banner state-banner-error">{{ loadError }}</p>

      <div class="statistics-accordion">
        <details class="card statistics-section-card">
          <summary class="statistics-section-trigger">
            <div>
              <h3>Mitgliederentwicklung</h3>
              <p>Mitgliederbestand, Neuzugänge und laufende Entwicklung über die letzten Monate.</p>
            </div>
            <span class="statistics-section-indicator" aria-hidden="true"></span>
          </summary>

          <div class="statistics-section-content">
            <div class="stats-overview-grid">
              <article class="stat-card">
                <span class="stat-label">Aktive Mitglieder</span>
                <strong class="stat-value">{{ statistics.overview?.activeMembers ?? 0 }}</strong>
              </article>
              <article class="stat-card">
                <span class="stat-label">Inaktive Mitglieder</span>
                <strong class="stat-value">{{ statistics.overview?.inactiveMembers ?? 0 }}</strong>
              </article>
              <article class="stat-card">
                <span class="stat-label">Testmitglieder</span>
                <strong class="stat-value">{{ statistics.overview?.testMembers ?? 0 }}</strong>
              </article>
              <article class="stat-card">
                <span class="stat-label">Neu in diesem Jahr</span>
                <strong class="stat-value">{{ statistics.overview?.createdThisYear ?? 0 }}</strong>
              </article>
            </div>

            <div class="stats-table-wrap">
              <table class="stats-table">
                <thead>
                  <tr>
                    <th>Monat</th>
                    <th>Neue Mitglieder</th>
                    <th>Bestand zum Monatsende</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="entry in statistics.memberDevelopment?.monthly || []" :key="entry.key">
                    <td>{{ entry.label }}</td>
                    <td>{{ entry.newMembers }}</td>
                    <td>{{ entry.memberCountSnapshot }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </details>

        <details class="card statistics-section-card">
          <summary class="statistics-section-trigger">
            <div>
              <h3>Altersstruktur</h3>
              <p>Verteilung der aktiven Mitglieder nach Altersgruppen und Datenabdeckung beim Geburtsdatum.</p>
            </div>
            <span class="statistics-section-indicator" aria-hidden="true"></span>
          </summary>

          <div class="statistics-section-content">
            <div class="stats-overview-grid stats-overview-grid-compact">
              <article class="stat-card">
                <span class="stat-label">Mit Geburtsdatum</span>
                <strong class="stat-value">{{ statistics.ageStructure?.knownBirthdates ?? 0 }}</strong>
              </article>
              <article class="stat-card">
                <span class="stat-label">Ohne Geburtsdatum</span>
                <strong class="stat-value">{{ statistics.ageStructure?.missingBirthdates ?? 0 }}</strong>
              </article>
            </div>

            <div class="bar-list">
              <article v-for="bucket in statistics.ageStructure?.buckets || []" :key="bucket.key" class="bar-row">
                <div class="bar-row-head">
                  <strong>{{ bucket.label }}</strong>
                  <span>{{ bucket.count }}</span>
                </div>
                <div class="bar-track">
                  <div class="bar-fill" :style="{ width: ageBucketWidth(bucket.count) }"></div>
                </div>
              </article>
            </div>
          </div>
        </details>

        <details class="card statistics-section-card">
          <summary class="statistics-section-trigger">
            <div>
              <h3>Beitragsentwicklung</h3>
              <p>Offene, bezahlte und überfällige Forderungen im Zeitverlauf.</p>
            </div>
            <span class="statistics-section-indicator" aria-hidden="true"></span>
          </summary>

          <div class="statistics-section-content">
            <div class="stats-overview-grid stats-overview-grid-compact stats-overview-grid-three">
              <article class="stat-card">
                <span class="stat-label">Offene Forderungen</span>
                <strong class="stat-value">{{ statistics.contributionDevelopment?.totals?.openCount ?? 0 }}</strong>
                <small>{{ formatEuro(statistics.contributionDevelopment?.totals?.openAmountCents) }}</small>
              </article>
              <article class="stat-card">
                <span class="stat-label">Bezahlt</span>
                <strong class="stat-value">{{ statistics.contributionDevelopment?.totals?.paidCount ?? 0 }}</strong>
                <small>{{ formatEuro(statistics.contributionDevelopment?.totals?.paidAmountCents) }}</small>
              </article>
              <article class="stat-card">
                <span class="stat-label">Überfällig</span>
                <strong class="stat-value">{{ statistics.contributionDevelopment?.totals?.overdueCount ?? 0 }}</strong>
                <small>{{ formatEuro(statistics.contributionDevelopment?.totals?.overdueAmountCents) }}</small>
              </article>
            </div>

            <div class="stats-table-wrap">
              <table class="stats-table">
                <thead>
                  <tr>
                    <th>Monat</th>
                    <th>Offen</th>
                    <th>Bezahlt</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="entry in statistics.contributionDevelopment?.monthly || []" :key="entry.key">
                    <td>{{ entry.label }}</td>
                    <td>{{ entry.openCount }} / {{ formatEuro(entry.openAmountCents) }}</td>
                    <td>{{ entry.paidCount }} / {{ formatEuro(entry.paidAmountCents) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </details>

        <details class="card statistics-section-card">
          <summary class="statistics-section-trigger">
            <div>
              <h3>Sponsorenentwicklung</h3>
              <p>Auswertung der Sponsoringanfragen als aktuelle verfügbare Datengrundlage.</p>
            </div>
            <span class="statistics-section-indicator" aria-hidden="true"></span>
          </summary>

          <div class="statistics-section-content">
            <div class="stats-overview-grid">
              <article class="stat-card">
                <span class="stat-label">Sponsoringanfragen gesamt</span>
                <strong class="stat-value">{{ statistics.sponsorDevelopment?.totals?.totalRequests ?? 0 }}</strong>
              </article>
              <article class="stat-card">
                <span class="stat-label">Offen oder in Bearbeitung</span>
                <strong class="stat-value">{{ statistics.sponsorDevelopment?.totals?.openRequests ?? 0 }}</strong>
              </article>
              <article class="stat-card">
                <span class="stat-label">Überführt</span>
                <strong class="stat-value">{{ statistics.sponsorDevelopment?.totals?.convertedRequests ?? 0 }}</strong>
              </article>
              <article class="stat-card">
                <span class="stat-label">Archiviert oder abgelehnt</span>
                <strong class="stat-value">{{ statistics.sponsorDevelopment?.totals?.archivedRequests ?? 0 }}</strong>
              </article>
            </div>

            <div class="stats-table-wrap">
              <table class="stats-table">
                <thead>
                  <tr>
                    <th>Monat</th>
                    <th>Anfragen</th>
                    <th>Offen</th>
                    <th>Überführt</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="entry in statistics.sponsorDevelopment?.monthly || []" :key="entry.key">
                    <td>{{ entry.label }}</td>
                    <td>{{ entry.totalRequests }}</td>
                    <td>{{ entry.openRequests }}</td>
                    <td>{{ entry.convertedRequests }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </details>
      </div>
    </template>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import { safeErrorMessage } from '../utils/dialogUtils.js';

function createEmptyStatistics() {
  return {
    overview: {},
    memberDevelopment: { monthly: [] },
    ageStructure: { buckets: [] },
    contributionDevelopment: { totals: {}, monthly: [] },
    sponsorDevelopment: { totals: {}, monthly: [] },
  };
}

export default {
  name: 'ClubStatisticsView',
  data() {
    return {
      loading: false,
      loadError: '',
      statistics: createEmptyStatistics(),
    };
  },
  computed: {
    ...mapGetters(['currentClub']),
    maxAgeBucketCount() {
      const buckets = this.statistics.ageStructure?.buckets || [];
      return buckets.reduce((max, bucket) => Math.max(max, Number(bucket.count || 0)), 0);
    },
  },
  watch: {
    currentClub: {
      immediate: true,
      async handler(newClub) {
        if (!newClub) {
          this.statistics = createEmptyStatistics();
          return;
        }
        await this.loadStatistics();
      }
    }
  },
  methods: {
    async loadStatistics() {
      if (!this.currentClub) return;
      this.loading = true;
      this.loadError = '';
      try {
        const response = await apiClient.get(`/club-statistics/${this.currentClub}`);
        if (!response || response.status < 200 || response.status >= 300) {
          throw new Error(response?.data?.error || 'Statistiken konnten nicht geladen werden.');
        }

        const payload = response.data;
        if (!payload || typeof payload !== 'object' || Array.isArray(payload) || !payload.overview) {
          throw new Error('Ungültige Antwort für Vereinsstatistiken.');
        }

        this.statistics = payload;
      } catch (error) {
        this.statistics = createEmptyStatistics();
        this.loadError = safeErrorMessage(error, 'Statistiken konnten nicht geladen werden.');
      } finally {
        this.loading = false;
      }
    },
    formatEuro(amountCents) {
      const amount = Number(amountCents || 0) / 100;
      return new Intl.NumberFormat('de-DE', {
        style: 'currency',
        currency: 'EUR',
      }).format(amount);
    },
    ageBucketWidth(count) {
      const max = this.maxAgeBucketCount || 1;
      return `${Math.max(8, (Number(count || 0) / max) * 100)}%`;
    },
  },
};
</script>

<style scoped>
.club-statistics-page {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-width: 1180px;
}

.statistics-hero,
.empty-state,
.statistics-section-card {
  padding: 1.25rem;
}

.statistics-hero {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
}

.statistics-eyebrow {
  margin: 0 0 0.35rem;
  color: var(--text-light);
  text-transform: uppercase;
  letter-spacing: 0.08em;
  font-size: 0.8rem;
}

.statistics-summary {
  margin: 0.35rem 0 0;
  color: var(--text-secondary);
  max-width: 72ch;
}

.statistics-accordion {
  display: grid;
  gap: 1rem;
}

.statistics-section-trigger {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  text-align: left;
  background: transparent;
  border: none;
  padding: 0;
  cursor: pointer;
  list-style: none;
}

.statistics-section-trigger::-webkit-details-marker {
  display: none;
}

.statistics-section-trigger h3 {
  margin: 0;
}

.statistics-section-trigger p {
  margin: 0.35rem 0 0;
  color: var(--text-secondary);
}

.statistics-section-indicator {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  border-radius: 999px;
  background: rgba(24, 70, 54, 0.08);
  color: var(--primary-strong);
  font-size: 1.25rem;
  font-weight: 700;
  flex-shrink: 0;
}

.statistics-section-indicator::before {
  content: '+';
}

.statistics-section-card[open] .statistics-section-indicator::before {
  content: '−';
}

.statistics-section-content {
  margin-top: 1rem;
  display: grid;
  gap: 1rem;
}

.stats-overview-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 1rem;
}

.stats-overview-grid-compact {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.stats-overview-grid-three {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.stat-card {
  padding: 1rem;
  border: 1px solid rgba(24, 70, 54, 0.12);
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.88);
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
}

.stat-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.stat-value {
  font-size: 1.8rem;
  line-height: 1;
}

.stats-table-wrap {
  overflow-x: auto;
}

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

.stats-table th,
.stats-table td {
  padding: 0.8rem 0.9rem;
  border-bottom: 1px solid rgba(24, 70, 54, 0.08);
  text-align: left;
  vertical-align: top;
}

.stats-table th {
  color: var(--text-on-primary);
  font-size: 0.86rem;
  font-weight: 700;
}

.bar-list {
  display: grid;
  gap: 0.9rem;
}

.bar-row {
  display: grid;
  gap: 0.45rem;
}

.bar-row-head {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
}

.bar-track {
  width: 100%;
  height: 0.8rem;
  border-radius: 999px;
  background: rgba(24, 70, 54, 0.08);
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  border-radius: 999px;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
}

@media (max-width: 960px) {
  .stats-overview-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 640px) {
  .statistics-hero {
    flex-direction: column;
  }

  .stats-overview-grid {
    grid-template-columns: 1fr;
  }
}
</style>
