<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">
            <div class="groups-card">
                <div class="groups-card-header">
                    <h4>{{ $t('tournaments.createGroups') }}</h4>
                    <div class="groups-card-meta">
                        <span class="groups-chip">{{ groups.length }} {{ $t('tournaments.group') }}</span>
                        <span class="groups-chip">{{ filteredGroupMatches.length }} {{ $t('tournaments.groupMatches') }}</span>
                    </div>
                </div>

                <div class="groups-settings">
                    <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>
                        {{ $t('tournaments.maxGroupSize') }}:
                        <input type="number" :value="maxGroupSize" @input="$emit('update:maxGroupSize', parseInt($event.target.value))" min="1" />
                    </label>
                </div>
                
                <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>

                <div class="groups-actions">
                    <button @click="$emit('create-groups')" class="btn-primary">{{ $t('tournaments.createGroups') }}</button>
                    <button @click="$emit('randomize-groups')" class="btn-secondary">{{ $t('tournaments.randomizeGroups') }}</button>
                    <button @click="$emit('reset-groups')" class="trash-btn">{{ $t('tournaments.resetGroups') }}</button>
                </div>
            </div>
        </section>

        <details v-if="isGroupTournament" class="merge-pools-box">
            <summary class="merge-summary">{{ $t('tournaments.mergeClasses') }}</summary>
            <div class="merge-pools-row">
                <label>
                    {{ $t('tournaments.sourceClass') }}:
                    <select v-model="mergeSourceClassId">
                        <option :value="null">—</option>
                        <option v-for="c in tournamentClasses" :key="c.id" :value="c.id">{{ c.name }}</option>
                    </select>
                </label>
                <label>
                    {{ $t('tournaments.targetClass') }}:
                    <select v-model="mergeTargetClassId">
                        <option :value="null">—</option>
                        <option v-for="c in tournamentClasses" :key="c.id" :value="c.id">{{ c.name }}</option>
                    </select>
                </label>
                <template v-if="mergePoolsReady">
                    <label>
                        {{ $t('tournaments.strategy') }}:
                        <select v-model="mergeStrategy">
                            <option value="singleGroup">{{ $t('tournaments.mergeSingleGroup') }}</option>
                            <option value="distribute">{{ $t('tournaments.mergeDistribute') }}</option>
                        </select>
                    </label>
                    <label>
                        <input type="checkbox" v-model="mergeSourceAsAK" />
                        {{ mergeOutOfCompetitionLabel }}
                    </label>
                </template>
            </div>
            <div class="merge-pools-actions">
                <button @click="requestMergePools" :disabled="!mergeSourceClassId || !mergeTargetClassId || String(mergeSourceClassId)===String(mergeTargetClassId)">
                    {{ $t('tournaments.apply') }}
                </button>
            </div>
        </details>

        <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>{{ $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 groupRankingsForGroup(group)" :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 groupRankingsForGroup(group)" :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 }}<span v-if="pl.gaveUp" class="gave-up-badge" :title="$t('tournaments.gaveUpHint')">{{ $t('tournaments.gaveUp') }}</span></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 groupRankingsForGroup(group)" 
                                        :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 ? handleMatchClick(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) }}.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </template>
            </template>
            <div v-if="filteredGroupMatches.length === 0" class="reset-controls reset-controls-spaced">
                <button @click="$emit('create-matches')" class="btn-primary">
                    ▶️ {{ $t('tournaments.createGroupMatches') }}
                </button>
                <button @click="$emit('cleanup-orphaned-matches')" class="btn-secondary">
                    🧹 {{ $t('tournaments.cleanupOrphanedMatches') }}
                </button>
            </div>
            <div v-if="filteredGroupMatches.length > 0" class="reset-controls reset-controls-spaced">
                <button @click="$emit('cleanup-orphaned-matches')" class="btn-secondary">
                    🧹 {{ $t('tournaments.cleanupOrphanedMatches') }}
                </button>
                <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',
        'cleanup-orphaned-matches',
        'create-matches',
        'highlight-match',
        'go-to-match',
        'merge-pools'
    ],
    data() {
        return {
            // Merge-UI (Pools)
            mergeSourceClassId: null,
            mergeTargetClassId: null,
            mergeStrategy: 'distribute', // 'singleGroup' | 'distribute'
            mergeSourceAsAK: false,
        };
    },
    computed: {
        filteredGroupMatches() {
            return this.filterMatchesByClass(this.matches.filter(m => m.round === 'group'));
        },
        mergePoolsReady() {
            return !!(
                this.mergeSourceClassId &&
                this.mergeTargetClassId &&
                String(this.mergeSourceClassId) !== String(this.mergeTargetClassId)
            );
        },
        mergeSourceClassName() {
            const id = this.mergeSourceClassId;
            if (!id) return '';
            const c = (this.tournamentClasses || []).find(x => String(x.id) === String(id));
            return c ? c.name : '';
        },
        mergeOutOfCompetitionLabel() {
            const base = this.$t && this.$t('tournaments.outOfCompetition');
            // Wenn Übersetzung vorhanden ist, ersetzen wir nur das "A" nicht zuverlässig -> lieber dynamisch bauen
            const src = this.mergeSourceClassName || 'Quelle';
            return `Spieler aus ${src} außer Konkurrenz`;
        }
    },
    methods: {
        groupRankingsForGroup(group) {
            const key = `${group.groupId}-${group.classId ?? 'null'}`;
            return this.groupRankings[key] || [];
        },
        filterMatchesByClass(matches) {
            // Wenn keine Klasse ausgewählt ist (null), zeige alle
            if (this.selectedViewClass === null || this.selectedViewClass === undefined || this.selectedViewClass === '' || this.selectedViewClass === '__all__' || this.selectedViewClass === 'all') {
                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 || this.selectedViewClass === '' || this.selectedViewClass === '__all__' || this.selectedViewClass === 'all') {
                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 id1 = (m) => m.player1?.id ?? m.player1Id;
            const id2 = (m) => m.player2?.id ?? m.player2Id;
            const match = this.matches.find(m => 
                m.round === 'group' && 
                m.groupId === groupId &&
                id1(m) != null && id2(m) != null &&
                ((id1(m) === player1Id && id2(m) === player2Id) ||
                 (id1(m) === player2Id && id2(m) === 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++;
                    }
                });
            }
            
            return {
                sets1,
                sets2,
                isFinished: match.isFinished,
                player1Won: sets1 > sets2,
                player2Won: sets2 > sets1
            };
        },
        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, group) {
            const groupId = group && typeof group === 'object' ? group.groupId : group;
            const groupPlayers = this.groupRankingsForGroup && group && typeof group === 'object' ? this.groupRankingsForGroup(group) : (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 ?? m.player1Id) === player.id || (m.player2?.id ?? m.player2Id) === player.id) &&
                    !m.isFinished &&
                    m.tournamentResults && m.tournamentResults.length > 0
                );
                
                playerMatches.forEach(match => {
                    const isPlayer1 = (match.player1?.id ?? match.player1Id) === 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) || 0;
        },
        handleMatchClick(player1Id, player2Id, groupId) {
            // Highlight das Match
            this.$emit('highlight-match', player1Id, player2Id, groupId);
            // Finde das Match und gehe zum Ergebnistab (player1/player2 können null sein, wenn Spieler gelöscht)
            const id1 = (m) => m.player1?.id ?? m.player1Id;
            const id2 = (m) => m.player2?.id ?? m.player2Id;
            const match = this.matches.find(m => 
                m.round === 'group' && 
                m.groupId === groupId &&
                id1(m) != null && id2(m) != null &&
                ((id1(m) === player1Id && id2(m) === player2Id) ||
                 (id1(m) === player2Id && id2(m) === player1Id))
            );
            if (match) {
                this.$emit('go-to-match', match.id);
            }
        },
        requestMergePools() {
            if (!this.mergeSourceClassId || !this.mergeTargetClassId) return;
            if (String(this.mergeSourceClassId) === String(this.mergeTargetClassId)) return;
            this.$emit('merge-pools', {
                sourceClassId: Number(this.mergeSourceClassId),
                targetClassId: Number(this.mergeTargetClassId),
                strategy: this.mergeStrategy,
                outOfCompetitionForSource: !!this.mergeSourceAsAK,
            });
        }
    }
};
</script>

<style scoped>
.group-controls {
    margin-bottom: 1rem;
}

.groups-card {
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    background: #fff;
    padding: 1rem;
    box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
}

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

.groups-card-header h4 {
    margin: 0;
    color: #1f2937;
}

.groups-card-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.groups-chip {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.2rem 0.55rem;
    border-radius: 999px;
    background: #f3f4f6;
    color: #4b5563;
    font-size: 0.85rem;
    font-weight: 700;
}

.groups-settings {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 0.9rem;
    margin-bottom: 1rem;
}

.groups-settings label,
.groups-per-class label {
    display: flex;
    flex-direction: column;
    gap: 0.3rem;
}

.groups-settings input,
.groups-per-class input,
.merge-pools-row select {
    padding: 0.55rem 0.7rem;
    border: 1px solid #d1d5db;
    border-radius: 10px;
    font-size: 0.95rem;
}

.groups-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 0.75rem;
    margin-top: 1rem;
}

.reset-controls-spaced {
    margin-top: 1rem;
}

.merge-pools-box {
    margin: 1rem 0 0 0;
    padding: 0.9rem 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    background: #fff;
    box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
}
.merge-summary {
    cursor: pointer;
    font-weight: 700;
    color: #1f2937;
}
.merge-pools-row {
    display: flex;
    gap: 0.75rem;
    flex-wrap: wrap;
    align-items: center;
    margin-top: 0.9rem;
}
.merge-pools-row label {
    display: flex;
    flex-direction: column;
    gap: 0.3rem;
}
.merge-pools-actions {
    margin-top: 0.9rem;
}
.groups-overview {
    margin-top: 1rem;
}
.group-table {
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    background: #fff;
    padding: 0.9rem;
    margin-bottom: 1rem;
    box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
    overflow-x: auto;
}
.gave-up-badge {
    margin-left: 0.35rem;
    padding: 0.1rem 0.35rem;
    font-size: 0.75rem;
    background: #f8d7da;
    color: #721c24;
    border-radius: 4px;
}

@media (max-width: 900px) {
    .groups-card-header {
        align-items: flex-start;
        flex-direction: column;
    }
}
</style>
