<template>
    <div class="club-view">
        <header class="club-header">
            <div>
                <h2>{{ $t('club.title') }} {{ club.name }}</h2>
            </div>
        </header>

        <div v-if="accessAllowed" class="club-content">
            <section v-if="openRequests.length > 0" class="club-card">
                <h3>{{ $t('club.openAccessRequests') }}</h3>
            </section>
            <section class="club-card">
                <div class="club-card-header">
                    <h3>{{ $t('club.members') }}</h3>
                    <span class="club-badge">{{ displayedMembers.length }}</span>
                </div>
                <ul class="members">
                    <li v-for="member in displayedMembers" :key="member.id" class="member-item">
                        <span class="gender-symbol" :class="'gender-' + (member.gender || 'unknown')" :title="labelGender(member.gender)">{{ genderSymbol(member.gender) }}</span>
                        <span class="gender-name" :class="['gender-' + (member.gender || 'unknown'), { 'is-test': member.testMembership }]">
                            {{ member.lastName }}, {{ member.firstName }}
                        </span>
                    </li>
                </ul>
            </section>
            <section class="club-card">
                <h3>{{ $t('club.diary') }}</h3>
            </section>
        </div>
        <div v-else class="club-card club-access-card">
            <div v-if="accessRequested" class="access-requested">
                {{ $t('club.accessRequestPending') }}
            </div>
            <div v-else class="club-no-access">
                <p>{{ $t('club.noAccess') }}</p>
                <button @click="requestAccess" :disabled="accessRequested">{{ $t('club.requestAccess') }}</button>
            </div>
        </div>
    </div>

    
    <!-- Info Dialog -->
    <InfoDialog
        v-model="infoDialog.isOpen"
        :title="infoDialog.title"
        :message="infoDialog.message"
        :details="infoDialog.details"
        :type="infoDialog.type"
    />
    
    <!-- Confirm Dialog -->
    <ConfirmDialog
        v-model="confirmDialog.isOpen"
        :title="confirmDialog.title"
        :message="confirmDialog.message"
        :details="confirmDialog.details"
        :type="confirmDialog.type"
        @confirm="handleConfirmResult(true)"
        @cancel="handleConfirmResult(false)"
    />
</template>

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

import InfoDialog from '../components/InfoDialog.vue';
import ConfirmDialog from '../components/ConfirmDialog.vue';
export default {
    name: "ClubView",
    data() {
        return {
            // Dialog States
            infoDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info'
            },
            confirmDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info',
                resolveCallback: null
            },
            club: {
                name: '',
            },
            openRequests: [],
            accessAllowed: false,
            accessRequested: false
        }
    },
    methods: {
        // Dialog Helper Methods
        async showInfo(title, message, details = '', type = 'info') {
            this.infoDialog = buildInfoConfig({ title, message, details, type });
        },
        
        async showConfirm(title, message, details = '', type = 'info', options = {}) {
            return new Promise((resolve) => {
                this.confirmDialog = buildConfirmConfig({
                    title,
                    message,
                    details,
                    type,
                    resolveCallback: resolve,
                    ...options,
                });
            });
        },
        
        handleConfirmResult(confirmed) {
            if (this.confirmDialog.resolveCallback) {
                this.confirmDialog.resolveCallback(confirmed);
                this.confirmDialog.resolveCallback = null;
            }
            this.confirmDialog.isOpen = false;
        },
        
        getClubId() {
            return this.currentClub || this.$route.params.clubId;
        },
        canAccessClub() {
            return this.isClubOwner || this.userRole === 'admin'
                || this.hasPermission('members', 'read')
                || this.hasPermission('diary', 'read')
                || this.hasPermission('statistics', 'read')
                || this.hasPermission('tournaments', 'read')
                || this.hasPermission('schedule', 'read');
        },
        async loadClub() {
            try {
                const clubId = this.getClubId();
                this.accessRequested = false;
                const response = await apiClient.get(`/clubs/${clubId}`);
                // apiClient behandelt 4xx als "erfolgreich" -> Status selbst prüfen
                if (response.status === 403 && response.data?.status) {
                    const club = this.clubs.find(c => String(c.id) === String(clubId));
                    this.club = club || { name: '' };
                    this.accessAllowed = false;
                    this.accessRequested = response.data.status === 'requested';
                    return;
                }
                if (response.status >= 400) {
                    throw new Error('club_access_error');
                }
                this.club = response.data || { name: '' };
                this.accessAllowed = true;
            } catch (error) {
                this.accessAllowed = false;
                const message = safeErrorMessage(error, this.$t('club.accessDenied'));
                await this.showInfo(this.$t('messages.error'), message, '', 'error');
            }
        },
        async loadOpenRequests() {
            try {
                if (!this.accessAllowed) return;
                const clubId = this.getClubId();
                const response = await apiClient.get(`/clubmembers/notapproved/${clubId}`);
                this.openRequests = response.data;
            } catch (error) {
                this.showInfo(this.$t('messages.error'), this.$t('club.errorLoadingRequests'), '', 'error');
            }
        }, 
        async requestAccess() {
            try {
                if (this.accessRequested) return;
                const clubId = this.getClubId();
                const response = await apiClient.get(`/clubs/request/${clubId}`);
                if (response.status === 200) {
                    this.accessRequested = true;
                    await this.showInfo(this.$t('messages.info'), this.$t('club.accessRequested'), '', 'info');
                }
            } catch (error) {
                if (error?.response?.status === 409) {
                    this.accessRequested = true;
                    await this.showInfo(this.$t('messages.info'), this.$t('club.accessRequested'), '', 'info');
                    return;
                }
                const message = safeErrorMessage(error, this.$t('club.accessRequestFailed'));
                await this.showInfo(this.$t('messages.error'), message, '', 'error');
            }
        },
        labelGender(g) {
            const v = (g || 'unknown');
            if (v === 'male') return this.$t('members.genderMale');
            if (v === 'female') return this.$t('members.genderFemale');
            if (v === 'diverse') return this.$t('members.genderDiverse');
            return this.$t('members.genderUnknown');
        },
        genderSymbol(g) {
            const v = (g || 'unknown');
            if (v === 'male') return '♂';
            if (v === 'female') return '♀';
            if (v === 'diverse') return '⚧';
            return '';
        }
    },
    computed: {
        ...mapGetters(['isAuthenticated', 'currentClub', 'clubs', 'hasPermission', 'isClubOwner', 'userRole']),
        displayedMembers() {
            const members = Array.isArray(this.club.members) ? this.club.members : [];
            const onlyActive = members.filter(m => m && (m.active === true));
            return onlyActive.sort((a, b) => {
                const lnA = (a.lastName || '').toLowerCase();
                const lnB = (b.lastName || '').toLowerCase();
                if (lnA && !lnB) return -1;
                if (!lnA && lnB) return 1;
                if (lnA && lnB) {
                    const cmp = lnA.localeCompare(lnB, 'de-DE');
                    if (cmp !== 0) return cmp;
                }
                const fnA = (a.firstName || '').toLowerCase();
                const fnB = (b.firstName || '').toLowerCase();
                return fnA.localeCompare(fnB, 'de-DE');
            });
        }
    },
    async mounted() {
        await this.loadClub();
        if (this.accessAllowed) {
            await this.loadOpenRequests();
        }
    }
}
</script>

<style lang="scss" scoped>
.club-view {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.club-header,
.club-card {
    border: 1px solid var(--border-color, #dee2e6);
    border-radius: 12px;
    background: #fff;
    padding: 1rem;
}

.club-header h2,
.club-card h3 {
    margin: 0;
}

.club-content {
    display: grid;
    gap: 1rem;
}

.club-card-header {
    display: flex;
    justify-content: space-between;
    gap: 0.75rem;
    align-items: center;
    margin-bottom: 0.75rem;
}

.club-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 2rem;
    padding: 0.2rem 0.55rem;
    border-radius: 999px;
    background: #eef2f5;
    color: #4b5563;
    font-weight: 700;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

.members { margin-top: .25rem; }
.member-item {
    padding: 0.45rem 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
.member-item:last-child {
    border-bottom: none;
}
.gender-symbol, .gender-name { background: transparent; border: none; }
.gender-name.gender-male { color: #1a73e8; }
.gender-name.gender-female { color: #d81b60; }
.gender-name.gender-diverse { color: #6a1b9a; }
.gender-name.gender-unknown { color: #444; }
.gender-symbol.gender-male { color: #1a73e8; }
.gender-symbol.gender-female { color: #d81b60; }
.gender-symbol.gender-diverse { color: #6a1b9a; }
.gender-symbol.gender-unknown { color: #444; }
.gender-symbol { margin-right: .35rem; opacity: .9; font-size: 1.05em; display: inline-block; width: 1.1em; text-align: center; }
.is-test { font-style: italic; }
.access-requested {
    color: #2e7d32;
    font-weight: 600;
}

.club-no-access {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.85rem;
}

.club-no-access p {
    margin: 0;
}

@media (max-width: 640px) {
    .club-header,
    .club-card {
        padding: 0.85rem;
    }

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

    .club-no-access button {
        width: 100%;
    }
}
</style>
