<template>
    <div class="tab-content">
        <TournamentClassSelector
            v-if="selectedDate && selectedDate !== 'new'"
            :model-value="selectedViewClass"
            :tournament-classes="tournamentClasses"
            :selected-date="selectedDate"
            @update:modelValue="$emit('update:selectedViewClass', $event)"
        />
        <section v-if="isGroupTournament" class="group-controls">
            <label>
                {{ $t('tournaments.advancersPerGroup') }}:
                <input type="number" :value="advancingPerGroup" @input="$emit('update:advancingPerGroup', parseInt($event.target.value))" min="1" @change="$emit('modus-change')" />
            </label>
            <label style="margin-left:1em">
                {{ $t('tournaments.maxGroupSize') }}:
                <input type="number" :value="maxGroupSize" @input="$emit('update:maxGroupSize', parseInt($event.target.value))" min="1" />
            </label>
            
            <div v-if="selectedViewClass !== null && selectedViewClass !== undefined" class="groups-per-class">
                <h4>{{ $t('tournaments.groupsPerClass') }}</h4>
                <p class="groups-per-class-hint">{{ $t('tournaments.groupsPerClassHint') }}</p>
                <div class="class-group-config">
                    <label class="class-group-label">
                        <span class="class-group-name">
                            {{ selectedViewClass === '__none__' ? $t('tournaments.withoutClass') : getClassName(selectedViewClass) }}
                        </span>
                        <span v-if="selectedViewClass !== '__none__'" class="class-group-type" :class="{ 'doubles': isClassDoubles(selectedViewClass) }">
                            ({{ isClassDoubles(selectedViewClass) ? $t('tournaments.doubles') : $t('tournaments.singles') }})
                        </span>
                        <input 
                            type="number" 
                            :value="groupsPerClassInput"
                            @input="$emit('update:groupsPerClassInput', parseInt($event.target.value))"
                            min="0" 
                            @change="$emit('group-count-change')" 
                            class="class-group-input"
                            :placeholder="$t('tournaments.numberOfGroups')"
                        />
                        <span class="class-group-unit">{{ $t('tournaments.group') }}</span>
                    </label>
                </div>
            </div>
            <div v-else class="groups-per-class">
                <label>
                    {{ $t('tournaments.numberOfGroups') }}:
                    <input
                        type="number"
                        :value="numberOfGroups"
                        min="1"
                        @input="$emit('update:numberOfGroups', Math.max(1, parseInt($event.target.value || '1', 10) || 1))"
                        @change="$emit('group-count-change')"
                    />
                </label>
            </div>

            <button @click="$emit('create-groups')">{{ $t('tournaments.createGroups') }}</button>
            <button @click="$emit('randomize-groups')">{{ $t('tournaments.randomizeGroups') }}</button>
            <button @click="$emit('reset-groups')">{{ $t('tournaments.resetGroups') }}</button>
        </section>
    <section v-if="groups.length" class="groups-overview">
            <h3>{{ $t('tournaments.groupsOverview') }}</h3>
            <template v-for="(classGroups, classId) in groupsByClass" :key="classId">
                <template v-if="shouldShowClass(classId === 'null' ? null : parseInt(classId))">
                    <div v-if="classId !== 'null' && classId !== 'undefined'" class="class-section">
                        <h4 class="class-header">
                            {{ getClassName(classId) }}
                        </h4>
                    </div>
                    <div v-for="group in classGroups" :key="group.groupId" class="group-table">
                        <h4>{{ group.groupLabel || ($t('tournaments.groupNumber') + ' ' + group.groupNumber) }}</h4>
                        <table>
                            <thead>
                                <tr>
                                    <th>{{ $t('tournaments.index') }}</th>
                                    <th>{{ $t('tournaments.position') }}</th>
                                    <th>{{ $t('tournaments.player') }}</th>
                                    <th>{{ $t('tournaments.points') }}</th>
                                    <th>{{ $t('tournaments.sets') }}</th>
                                    <th>{{ $t('tournaments.diff') }}</th>
                                    <th>{{ $t('tournaments.pointsRatio') }}</th>
                                    <th v-for="(opponent, idx) in groupRankings[group.groupId]" :key="`opp-${opponent.id}`">
                                        G{{ String.fromCharCode(96 + group.groupNumber) }}{{ idx + 1 }}
                                    </th>
                                    <th>{{ $t('tournaments.livePosition') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(pl, idx) in groupRankings[group.groupId]" :key="pl.id">
                                    <td><strong>G{{ String.fromCharCode(96 + group.groupNumber) }}{{ idx + 1 }}</strong></td>
                                    <td>{{ pl.position }}.</td>
                                    <td><span v-if="pl.seeded" class="seeded-star">★</span>{{ pl.name }}</td>
                                    <td>{{ (pl.matchesWon || 0) * 2 }}:{{ (pl.matchesLost || 0) * 2 }}</td>
                                    <td>{{ pl.setsWon }}:{{ pl.setsLost }}</td>
                                    <td>
                                        {{ pl.setDiff >= 0 ? '+' + pl.setDiff : pl.setDiff }}
                                    </td>
                                    <td>
                                        {{ Math.abs(pl.pointsWon || 0) }}:{{ Math.abs(pl.pointsLost || 0) }}
                                        <span v-if="(Math.abs(pl.pointsWon || 0) - Math.abs(pl.pointsLost || 0)) !== 0" class="points-diff">
                                            ({{ (Math.abs(pl.pointsWon || 0) - Math.abs(pl.pointsLost || 0)) >= 0 ? '+' : '' }}{{ Math.abs(pl.pointsWon || 0) - Math.abs(pl.pointsLost || 0) }})
                                        </span>
                                    </td>
                                    <td v-for="(opponent, oppIdx) in groupRankings[group.groupId]" 
                                        :key="`match-${pl.id}-${opponent.id}`"
                                        :class="['match-cell', { 'clickable': idx !== oppIdx, 'active-group-cell': activeGroupCells.includes(`match-${pl.id}-${opponent.id}`), 'diagonal-cell': idx === oppIdx }]"
                                        @click="idx !== oppIdx ? $emit('highlight-match', pl.id, opponent.id, group.groupId) : null">
                                        <span v-if="idx === oppIdx" class="diagonal"></span>
                                        <span v-else-if="getMatchLiveResult(pl.id, opponent.id, group.groupId)" 
                                              :class="getMatchCellClasses(pl.id, opponent.id, group.groupId)">
                                            {{ getMatchDisplayText(pl.id, opponent.id, group.groupId) }}
                                        </span>
                                        <span v-else class="no-match">-</span>
                                    </td>
                                    <td>{{ getLivePosition(pl.id, group.groupId) }}.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </template>
            </template>
            <div v-if="filteredGroupMatches.length === 0" class="reset-controls" style="margin-top:1rem">
                <button @click="$emit('create-matches')" class="btn-primary">
                    ▶️ Gruppenspiele berechnen
                </button>
            </div>
            <div v-if="filteredGroupMatches.length > 0" class="reset-controls" style="margin-top:1rem">
                <button @click="$emit('reset-matches')" class="trash-btn">
                    🗑️ {{ $t('tournaments.resetGroupMatches') }}
                </button>
            </div>
        </section>
    </div>
</template>

<script>
import TournamentClassSelector from './TournamentClassSelector.vue';

export default {
    name: 'TournamentGroupsTab',
    components: {
        TournamentClassSelector
    },
    props: {
        selectedDate: {
            type: [String, Number],
            default: null
        },
        selectedViewClass: {
            type: [Number, String, null],
            default: null
        },
        tournamentClasses: {
            type: Array,
            required: true
        },
        isGroupTournament: {
            type: Boolean,
            required: true
        },
        advancingPerGroup: {
            type: Number,
            required: true
        },
        maxGroupSize: {
            type: Number,
            default: null
        },
        groupsPerClassInput: {
            type: Number,
            default: 0
        },
        numberOfGroups: {
            type: Number,
            required: true
        },
        groups: {
            type: Array,
            required: true
        },
        groupsByClass: {
            type: Object,
            required: true
        },
        groupRankings: {
            type: Object,
            required: true
        },
        activeGroupCells: {
            type: Array,
            default: () => []
        },
        matches: {
            type: Array,
            required: true
        }
    },
    emits: [
        'update:selectedViewClass',
        'update:advancingPerGroup',
        'update:maxGroupSize',
        'update:groupsPerClassInput',
        'update:numberOfGroups',
        'modus-change',
        'group-count-change',
        'create-groups',
        'randomize-groups',
        'reset-groups',
        'reset-matches',
    'create-matches',
        'highlight-match'
    ],
    computed: {
        filteredGroupMatches() {
            return this.filterMatchesByClass(this.matches.filter(m => m.round === 'group'));
        }
    },
    methods: {
        filterMatchesByClass(matches) {
            // Wenn keine Klasse ausgewählt ist (null), zeige alle
            if (this.selectedViewClass === null || this.selectedViewClass === undefined) {
                return matches;
            }
            // Wenn "Ohne Klasse" ausgewählt ist
            if (this.selectedViewClass === '__none__' || this.selectedViewClass === 'null') {
                return matches.filter(m => m.classId === null || m.classId === undefined);
            }
            // Filtere nach der ausgewählten Klasse
            const selectedId = Number(this.selectedViewClass);
            if (Number.isNaN(selectedId)) {
                return matches;
            }
            return matches.filter(m => {
                const matchClassId = m.classId;
                if (matchClassId === null || matchClassId === undefined) {
                    return false;
                }
                return Number(matchClassId) === selectedId;
            });
        },
        shouldShowClass(classId) {
            // Wenn keine Klasse ausgewählt ist (null), zeige alle
            if (this.selectedViewClass === null || this.selectedViewClass === undefined) {
                return true;
            }
            // Wenn "Ohne Klasse" ausgewählt ist
            if (this.selectedViewClass === '__none__' || this.selectedViewClass === 'null') {
                return classId === null;
            }
            // Vergleiche als Zahlen, um String/Number-Probleme zu vermeiden
            const selectedId = Number(this.selectedViewClass);
            const compareId = Number(classId);
            // Prüfe auf NaN (falls Parsing fehlschlägt)
            if (Number.isNaN(selectedId) || Number.isNaN(compareId)) {
                return false;
            }
            return selectedId === compareId;
        },
        getClassName(classId) {
            if (classId === null || classId === '__none__' || classId === 'null' || classId === 'undefined' || classId === undefined) {
                return this.$t('tournaments.withoutClass');
            }
            try {
                const classIdNum = typeof classId === 'string' ? parseInt(classId) : classId;
                const classItem = this.tournamentClasses.find(c => c.id === classIdNum);
                return classItem ? classItem.name : '';
            } catch (e) {
                return '';
            }
        },
        isClassDoubles(classId) {
            if (classId === null || classId === '__none__' || classId === 'null' || classId === undefined) {
                return false;
            }
            const classIdNum = typeof classId === 'string' ? parseInt(classId) : classId;
            const classItem = this.tournamentClasses.find(c => c.id === classIdNum);
            return classItem ? Boolean(classItem.isDoubles) : false;
        },
        getMatchLiveResult(player1Id, player2Id, groupId) {
            const match = this.matches.find(m => 
                m.round === 'group' && 
                m.groupId === groupId &&
                ((m.player1.id === player1Id && m.player2.id === player2Id) ||
                 (m.player1.id === player2Id && m.player2.id === player1Id))
            );
            
            if (!match) return null;
            
            // Berechne aktuelle Sätze aus tournamentResults
            let sets1 = 0, sets2 = 0;
            if (match.tournamentResults && match.tournamentResults.length > 0) {
                match.tournamentResults.forEach(result => {
                    if (result.pointsPlayer1 > result.pointsPlayer2) {
                        sets1++;
                    } else if (result.pointsPlayer2 > result.pointsPlayer1) {
                        sets2++;
                    }
                });
            }

            const rowPlayerIsPlayer1 = match.player1.id === player1Id;
            const displaySets1 = rowPlayerIsPlayer1 ? sets1 : sets2;
            const displaySets2 = rowPlayerIsPlayer1 ? sets2 : sets1;

            return {
                sets1: displaySets1,
                sets2: displaySets2,
                isFinished: match.isFinished,
                player1Won: displaySets1 > displaySets2,
                player2Won: displaySets2 > displaySets1
            };
        },
        getMatchDisplayText(player1Id, player2Id, groupId) {
            const liveResult = this.getMatchLiveResult(player1Id, player2Id, groupId);
            if (!liveResult) return '-';
            return `${liveResult.sets1}:${liveResult.sets2}`;
        },
        getMatchCellClasses(player1Id, player2Id, groupId) {
            const liveResult = this.getMatchLiveResult(player1Id, player2Id, groupId);
            if (!liveResult) return ['no-match'];
            
            const classes = ['match-result'];
            
            if (liveResult.isFinished) {
                if (liveResult.player1Won) {
                    classes.push('match-finished-win');
                } else if (liveResult.player2Won) {
                    classes.push('match-finished-loss');
                } else {
                    classes.push('match-finished-tie');
                }
            } else {
                classes.push('match-live');
            }
            
            return classes;
        },
        getLivePosition(playerId, groupId) {
            const groupPlayers = this.groupRankings[groupId] || [];
            const liveStats = groupPlayers.map(player => {
                let livePoints = player.points || 0;
                let liveSetsWon = player.setsWon || 0;
                let liveSetsLost = player.setsLost || 0;
                
                const playerMatches = this.matches.filter(m => 
                    m.round === 'group' && 
                    m.groupId === groupId &&
                    (m.player1.id === player.id || m.player2.id === player.id) &&
                    !m.isFinished &&
                    m.tournamentResults && m.tournamentResults.length > 0
                );
                
                playerMatches.forEach(match => {
                    const isPlayer1 = match.player1.id === player.id;
                    match.tournamentResults.forEach(result => {
                        if (isPlayer1) {
                            if (result.pointsPlayer1 > result.pointsPlayer2) {
                                livePoints += 1;
                                liveSetsWon += 1;
                            } else if (result.pointsPlayer2 > result.pointsPlayer1) {
                                liveSetsLost += 1;
                            }
                        } else {
                            if (result.pointsPlayer2 > result.pointsPlayer1) {
                                livePoints += 1;
                                liveSetsWon += 1;
                            } else if (result.pointsPlayer1 > result.pointsPlayer2) {
                                liveSetsLost += 1;
                            }
                        }
                    });
                });
                
                return {
                    id: player.id,
                    points: livePoints,
                    setsWon: liveSetsWon,
                    setsLost: liveSetsLost,
                    setDiff: liveSetsWon - liveSetsLost
                };
            });
            
            liveStats.sort((a, b) => {
                if (b.points !== a.points) return b.points - a.points;
                if (b.setDiff !== a.setDiff) return b.setDiff - a.setDiff;
                return 0;
            });
            
            const position = liveStats.findIndex(p => p.id === playerId) + 1;
            return position || groupPlayers.findIndex(p => p.id === playerId) + 1;
        }
    }
};
</script>
