<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)"
        />
        <div class="results-summary">
            <span v-if="filteredGroupMatches.length" class="results-chip">{{ filteredGroupMatches.length }} {{ $t('tournaments.groupMatches') }}</span>
            <span v-if="filteredKnockoutMatches.length" class="results-chip">{{ filteredKnockoutMatches.length }} {{ $t('tournaments.koRound') }}</span>
            <span v-if="openMatchCount > 0" class="results-chip results-chip-open">{{ openMatchCount }} {{ $t('tournaments.statusOpen') }}</span>
            <span v-if="liveMatchCount > 0" class="results-chip results-chip-live">{{ liveMatchCount }} {{ $t('tournaments.statusLive') }}</span>
            <span v-if="finishedMatchCount > 0" class="results-chip">{{ finishedMatchCount }} {{ $t('tournaments.statusFinished') }}</span>
        </div>
        <div v-if="numberOfTables && (filteredGroupMatches.length || filteredKnockoutMatches.length)" class="distribute-tables-bar">
            <button @click="$emit('distribute-tables')" class="btn-primary">
                {{ $t('tournaments.distributeTables') }}
            </button>
        </div>
        <section v-if="filteredGroupMatches.length" class="group-matches">
            <div class="results-section-header">
                <h4>{{ $t('tournaments.groupMatches') }}</h4>
                <span class="results-chip">{{ filteredGroupMatches.length }}</span>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>{{ $t('tournaments.round') }}</th>
                        <th>{{ $t('tournaments.group') }}</th>
                        <th v-if="numberOfTables">{{ $t('tournaments.table') }}</th>
                        <th>{{ $t('tournaments.encounter') }}</th>
                        <th>{{ $t('tournaments.result') }}</th>
                        <th>{{ $t('tournaments.sets') }}</th>
                        <th>{{ $t('tournaments.action') }}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="m in filteredGroupMatches" :key="m.id" :data-match-id="m.id" :class="{ 'active-match': activeMatchId === m.id, 'match-finished': m.isFinished, 'match-live': m.isActive }" @click="$emit('update:activeMatchId', m.id)">
                        <td>{{ m.groupRound }}</td>
                        <td>
                            <template v-if="getGroupClassName(m.groupId)">
                                {{ getGroupClassName(m.groupId) }} - {{ $t('tournaments.groupNumber') }} {{ m.groupNumber }}
                            </template>
                            <template v-else>
                                {{ $t('tournaments.groupNumber') }} {{ m.groupNumber }}
                            </template>
                        </td>
                        <td v-if="numberOfTables">
                            <select
                                :value="m.tableNumber || ''"
                                @change="$emit('set-match-table', m, $event.target.value === '' ? null : parseInt($event.target.value))"
                                class="table-select"
                                :disabled="m.isFinished"
                            >
                                <option value="">–</option>
                                <option
                                    v-for="t in numberOfTables"
                                    :key="t"
                                    :value="t"
                                    :disabled="occupiedTables.has(t) && m.tableNumber !== t"
                                >{{ t }}{{ occupiedTables.has(t) && m.tableNumber !== t ? ' ●' : '' }}</option>
                            </select>
                        </td>
                        <td>
                            <template v-if="m.isFinished">
                                <span v-if="winnerIsPlayer1(m)">
                                    <strong>{{ getMatchPlayerNames(m).name1 }}</strong> – {{ getMatchPlayerNames(m).name2 }}
                                </span>
                                <span v-else>
                                    {{ getMatchPlayerNames(m).name1 }} – <strong>{{ getMatchPlayerNames(m).name2 }}</strong>
                                </span>
                            </template>
                            <template v-else>
                                {{ getMatchPlayerNames(m).name1 }} – {{ getMatchPlayerNames(m).name2 }}
                            </template>
                        </td>
                        <td>
                            <template v-if="m.result === 'BYE'">
                                BYE
                            </template>
                            <template v-else-if="matchHasGaveUp(m)">
                                <span class="result-text gave-up-result">{{ formatResult(m) }}</span>
                                <span v-if="m.player1?.gaveUp && m.player2?.gaveUp" class="gave-up-badge-small">({{ $t('tournaments.gaveUp') }})</span>
                            </template>
                            <template v-else-if="!m.isFinished">
                                <template v-for="r in m.tournamentResults" :key="r.set">
                                    <template v-if="isEditing(m, r.set)">
                                        <input 
                                            :value="editingResult.value"
                                            @input="$emit('update:editingResult', { ...editingResult, value: $event.target.value })"
                                            @keyup.enter="$emit('save-edited-result', m)"
                                            @blur="$emit('save-edited-result', m)"
                                            @keyup.escape="$emit('cancel-edit')"
                                            class="inline-input"
                                            ref="editInput"
                                        />
                                    </template>
                                    <template v-else>
                                        <span @click="$emit('start-edit-result', m, r)" class="result-text clickable">
                                            {{ r.pointsPlayer1 }}:{{ r.pointsPlayer2 }}
                                        </span>
                                        <span v-if="!isLastResult(m, r)">, </span>
                                    </template>
                                </template>
                                <div class="new-set-line">
                                    <input 
                                        v-model="m.resultInput" 
                                        :placeholder="$t('tournaments.newSetPlaceholder')"
                                        @keyup.enter="$emit('save-match-result', m, m.resultInput)"
                                        @blur="$emit('save-match-result', m, m.resultInput)" 
                                        class="inline-input" 
                                    />
                                </div>
                            </template>
                            <template v-else>
                                {{ formatResult(m) }}
                            </template>
                        </td>
                        <td>
                            {{ getSetsString(m) }}
                        </td>
                        <td>
                            <span :class="['status-badge', getMatchStateClass(m)]">{{ getMatchStateLabel(m) }}</span>
                            <template v-if="matchHasGaveUp(m)">
                                <span class="no-edit-hint">{{ $t('tournaments.gaveUp') }}</span>
                            </template>
                            <template v-else>
                                <div class="action-row">
                                    <button v-if="!m.isFinished" @click="$emit('finish-match', m)">{{ $t('tournaments.finishMatch') }}</button>
                                    <button v-else @click="$emit('reopen-match', m)" class="btn-correct">{{ $t('tournaments.correctMatch') }}</button>
                                    <button v-if="!m.isFinished && !m.isActive" @click.stop="$emit('set-match-active', m, true)" class="btn-live" :title="$t('tournaments.markMatchLive')">▶️</button>
                                    <button v-if="!m.isFinished && m.isActive" @click.stop="$emit('set-match-active', m, false)" class="btn-live active" :title="$t('tournaments.unmarkMatchLive')">⏸️</button>
                                </div>
                            </template>
                        </td>
                    </tr>
                </tbody>
            </table>
        </section>
        <div v-if="participants.length > 1 && !filteredGroupMatches.length && !filteredKnockoutMatches.length" class="results-next-step">
            <button @click="$emit('start-matches')" class="btn-primary">
                {{ $t('tournaments.createMatches') }}
            </button>
        </div>
        <div v-if="canStartKnockout && !showKnockout && numberOfGroupsForSelectedClass > 1" class="results-next-step">
            <button @click="$emit('start-knockout')" class="btn-primary">
                {{ $t('tournaments.startKORound') }}
            </button>
        </div>
        <div v-if="showKnockout && canResetKnockout && numberOfGroupsForSelectedClass > 1" class="results-next-step results-next-step-muted">
            <button @click="$emit('reset-knockout')" class="trash-btn">
                🗑️ {{ $t('tournaments.deleteKORound') }}
            </button>
        </div>
        <section v-if="showKnockout && numberOfGroupsForSelectedClass > 1 && filteredKnockoutMatches.length" class="ko-round">
            <div class="results-section-header">
                <h4>{{ $t('tournaments.koRound') }}</h4>
                <span class="results-chip">{{ filteredKnockoutMatches.length }}</span>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>{{ $t('tournaments.class') }}</th>
                        <th>{{ $t('tournaments.round') }}</th>
                        <th v-if="numberOfTables">{{ $t('tournaments.table') }}</th>
                        <th>{{ $t('tournaments.encounter') }}</th>
                        <th>{{ $t('tournaments.result') }}</th>
                        <th>{{ $t('tournaments.sets') }}</th>
                        <th>{{ $t('tournaments.action') }}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="m in filteredKnockoutMatches" :key="m.id" :class="{ 'active-match': activeMatchId === m.id, 'match-finished': m.isFinished, 'match-live': m.isActive }" @click="$emit('update:activeMatchId', m.id)">
                        <td>{{ getKnockoutMatchClassName(m) }}</td>
                        <td>{{ m.round }}</td>
                        <td v-if="numberOfTables">
                            <select
                                :value="m.tableNumber || ''"
                                @change="$emit('set-match-table', m, $event.target.value === '' ? null : parseInt($event.target.value))"
                                class="table-select"
                                :disabled="m.isFinished"
                            >
                                <option value="">–</option>
                                <option
                                    v-for="t in numberOfTables"
                                    :key="t"
                                    :value="t"
                                    :disabled="occupiedTables.has(t) && m.tableNumber !== t"
                                >{{ t }}{{ occupiedTables.has(t) && m.tableNumber !== t ? ' ●' : '' }}</option>
                            </select>
                        </td>
                        <td>
                            <template v-if="m.isFinished">
                                <span v-if="winnerIsPlayer1(m)">
                                    <strong>{{ getMatchPlayerNames(m).name1 }}</strong> – {{ getMatchPlayerNames(m).name2 }}
                                </span>
                                <span v-else>
                                    {{ getMatchPlayerNames(m).name1 }} – <strong>{{ getMatchPlayerNames(m).name2 }}</strong>
                                </span>
                            </template>
                            <template v-else>
                                {{ getMatchPlayerNames(m).name1 }} – {{ getMatchPlayerNames(m).name2 }}
                            </template>
                        </td>
                        <td>
                            <template v-if="!m.isFinished">
                                <template v-for="r in m.tournamentResults" :key="r.set">
                                    <template v-if="isEditing(m, r.set)">
                                        <input 
                                            :value="editingResult.value"
                                            @input="$emit('update:editingResult', { ...editingResult, value: $event.target.value })"
                                            @keyup.enter="$emit('save-edited-result', m)"
                                            @blur="$emit('save-edited-result', m)"
                                            @keyup.escape="$emit('cancel-edit')"
                                            class="inline-input"
                                            ref="editInput"
                                        />
                                    </template>
                                    <template v-else>
                                        <span @click="$emit('start-edit-result', m, r)" class="result-text clickable">
                                            {{ r.pointsPlayer1 }}:{{ r.pointsPlayer2 }}
                                        </span>
                                        <span v-if="!isLastResult(m, r)">, </span>
                                    </template>
                                </template>
                                <div class="new-set-line">
                                    <input 
                                        v-model="m.resultInput" 
                                        :placeholder="$t('tournaments.newSetPlaceholder')"
                                        @keyup.enter="$emit('save-match-result', m, m.resultInput)"
                                        @blur="$emit('save-match-result', m, m.resultInput)" 
                                        class="inline-input" 
                                    />
                                </div>
                            </template>
                            <template v-else>
                                {{ formatResult(m) }}
                            </template>
                        </td>
                        <td>
                            {{ getSetsString(m) }}
                        </td>
                        <td>
                            <span :class="['status-badge', getMatchStateClass(m)]">{{ getMatchStateLabel(m) }}</span>
                            <div class="action-row">
                                <button v-if="!m.isFinished" @click="$emit('finish-match', m)">{{ $t('tournaments.finishMatch') }}</button>
                                <button v-else @click="$emit('reopen-match', m)" class="btn-correct">{{ $t('tournaments.correctMatch') }}</button>
                                <button v-if="!m.isFinished && !m.isActive" @click.stop="$emit('set-match-active', m, true)" class="btn-live" :title="$t('tournaments.markMatchLive')">▶️</button>
                                <button v-if="!m.isFinished && m.isActive" @click.stop="$emit('set-match-active', m, false)" class="btn-live active" :title="$t('tournaments.unmarkMatchLive')">⏸️</button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </section>
        <section v-if="Object.keys(filteredGroupedRankingList).length > 0" class="ranking">
            <h4>{{ $t('tournaments.resultsRanking') }}</h4>
            <template v-for="(classKey, idx) in Object.keys(filteredGroupedRankingList).sort((a, b) => {
                const aNum = a === 'null' ? 999999 : parseInt(a);
                const bNum = b === 'null' ? 999999 : parseInt(b);
                return aNum - bNum;
            })" :key="`class-${classKey}`">
                <div v-if="idx > 0" class="ranking-class-gap"></div>
                <h5 v-if="getClassName(classKey)">{{ getClassName(classKey) }}</h5>
                <table>
                    <thead>
                        <tr>
                            <th>{{ $t('tournaments.position') }}</th>
                            <th>{{ $t('tournaments.player') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(entry, entryIdx) in filteredGroupedRankingList[classKey].filter(e => Number(e.position) <= 3)" :key="`${entry.member.id}-${entryIdx}`">
                            <td>{{ entry.position }}.</td>
                            <td>
                                {{ entry.member.firstName }}
                                {{ entry.member.lastName }}
                            </td>
                        </tr>
                    </tbody>
                </table>
            </template>
        </section>
    </div>
</template>

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

export default {
    name: 'TournamentResultsTab',
    components: {
        TournamentClassSelector
    },
    props: {
        selectedDate: {
            type: [String, Number],
            default: null
        },
        selectedViewClass: {
            type: [Number, String, null],
            default: null
        },
        tournamentClasses: {
            type: Array,
            required: true
        },
        groupMatches: {
            type: Array,
            required: true
        },
        knockoutMatches: {
            type: Array,
            required: true
        },
        activeMatchId: {
            type: [Number, null],
            default: null
        },
        editingResult: {
            type: Object,
            required: true
        },
        canStartKnockout: {
            type: Boolean,
            required: true
        },
        showKnockout: {
            type: Boolean,
            required: true
        },
        canResetKnockout: {
            type: Boolean,
            required: true
        },
        getTotalNumberOfGroups: {
            type: Number,
            required: true
        },
        groupedRankingList: {
            type: Object,
            required: true
        },
        participants: {
            type: Array,
            required: true
        },
        groups: {
            type: Array,
            required: true
        },
        pairings: {
            type: Array,
            required: true
        },
        numberOfTables: {
            type: [Number, null],
            default: null
        }
    },
    computed: {
        filteredGroupMatches() {
            return this.sortMatchesForDisplay(this.filterMatchesByClass(this.groupMatches));
        },
        filteredKnockoutMatches() {
            return this.sortMatchesForDisplay(this.filterMatchesByClass(this.knockoutMatches));
        },
        filteredGroupedRankingList() {
            // 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 this.groupedRankingList;
            }
            // Wenn "Ohne Klasse" ausgewählt ist
            if (this.selectedViewClass === '__none__' || this.selectedViewClass === 'null') {
                const result = {};
                if (this.groupedRankingList['null']) {
                    result['null'] = this.groupedRankingList['null'];
                }
                return result;
            }
            // Filtere nach der ausgewählten Klasse
            const selectedId = Number(this.selectedViewClass);
            if (Number.isNaN(selectedId)) {
                return this.groupedRankingList;
            }
            const result = {};
            const classKey = String(selectedId);
            if (this.groupedRankingList[classKey]) {
                result[classKey] = this.groupedRankingList[classKey];
            }
            return result;
        },
        occupiedTables() {
            // Tische, die von laufenden (nicht abgeschlossenen) Matches belegt sind
            const allMatches = [...this.groupMatches, ...this.knockoutMatches];
            const occupied = new Set();
            for (const m of allMatches) {
                if (m.tableNumber && !m.isFinished) {
                    occupied.add(m.tableNumber);
                }
            }
            return occupied;
        },
        numberOfGroupsForSelectedClass() {
            // Zähle direkt die Gruppen für die ausgewählte Klasse
            // Nur Stage 1 Gruppen (stageId null/undefined) zählen
            // Und nur Gruppen mit mindestens einem Teilnehmer
            let groupsToCount = this.groups.filter(g => 
                (!g.stageId || g.stageId === null || g.stageId === undefined) &&
                g.participants && Array.isArray(g.participants) && g.participants.length > 0
            );
            
            // Wenn keine Klasse ausgewählt ist, zähle alle Stage 1 Gruppen
            if (this.selectedViewClass === null || this.selectedViewClass === undefined || this.selectedViewClass === '' || this.selectedViewClass === '__all__' || this.selectedViewClass === 'all') {
                return groupsToCount.length;
            }
            
            // Wenn "Ohne Klasse" ausgewählt ist
            if (this.selectedViewClass === '__none__' || this.selectedViewClass === 'null') {
                return groupsToCount.filter(g => g.classId === null || g.classId === undefined).length;
            }
            
            // Filtere nach der ausgewählten Klasse
            const selectedId = Number(this.selectedViewClass);
            if (Number.isNaN(selectedId)) {
                return groupsToCount.length;
            }
            
            return groupsToCount.filter(g => {
                if (g.classId === null || g.classId === undefined) {
                    return false;
                }
                return Number(g.classId) === selectedId;
            }).length;
        },
        liveMatchCount() {
            return [...this.filteredGroupMatches, ...this.filteredKnockoutMatches].filter(m => m.isActive && !m.isFinished).length;
        },
        openMatchCount() {
            return [...this.filteredGroupMatches, ...this.filteredKnockoutMatches].filter(m => !m.isActive && !m.isFinished && !this.matchHasGaveUp(m)).length;
        },
        finishedMatchCount() {
            return [...this.filteredGroupMatches, ...this.filteredKnockoutMatches].filter(m => m.isFinished).length;
        }
    },
    emits: [
        'update:selectedViewClass',
        'update:activeMatchId',
        'update:editingResult',
        'save-edited-result',
        'cancel-edit',
        'start-edit-result',
        'save-match-result',
        'finish-match',
        'reopen-match',
        'set-match-active',
        'set-match-table',
        'distribute-tables',
        'start-matches',
        'start-knockout',
        'reset-knockout'
    ],
    methods: {
        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;
            });
        },
        sortMatchesForDisplay(matches) {
            const stateWeight = (match) => {
                if (match.isActive && !match.isFinished) return 0;
                if (!match.isFinished && !this.matchHasGaveUp(match)) return 1;
                if (this.matchHasGaveUp(match)) return 2;
                return 3;
            };
            return [...matches].sort((a, b) => {
                const byState = stateWeight(a) - stateWeight(b);
                if (byState !== 0) return byState;
                const roundA = Number(a.groupRound || 0);
                const roundB = Number(b.groupRound || 0);
                if (roundA !== roundB) return roundA - roundB;
                const groupA = Number(a.groupNumber || 0);
                const groupB = Number(b.groupNumber || 0);
                if (groupA !== groupB) return groupA - groupB;
                return Number(a.id || 0) - Number(b.id || 0);
            });
        },
        getGroupClassName(groupId) {
            if (!groupId) return '';
            const group = this.groups.find(g => g.groupId === groupId);
            if (!group || !group.classId) return '';
            return this.getClassName(group.classId);
        },
        getKnockoutMatchClassName(match) {
            if (!match) return '';
            if (match.classId) {
                return this.getClassName(match.classId);
            }
            return '';
        },
        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 '';
            }
        },
        getMatchPlayerNames(match) {
            const classId = match.classId;
            if (classId) {
                const tournamentClass = this.tournamentClasses.find(c => c.id === classId);
                if (tournamentClass && tournamentClass.isDoubles) {
                    const pairing1 = this.pairings.find(p => 
                        p.classId === classId &&
                        (p.member1Id === match.player1Id || p.external1Id === match.player1Id ||
                         p.member2Id === match.player1Id || p.external2Id === match.player1Id)
                    );
                    const pairing2 = this.pairings.find(p => 
                        p.classId === classId &&
                        (p.member1Id === match.player2Id || p.external1Id === match.player2Id ||
                         p.member2Id === match.player2Id || p.external2Id === match.player2Id)
                    );
                    
                    if (pairing1 && pairing2) {
                        const name1 = this.getPairingPlayerName(pairing1, 1) + ' / ' + this.getPairingPlayerName(pairing1, 2);
                        const name2 = this.getPairingPlayerName(pairing2, 1) + ' / ' + this.getPairingPlayerName(pairing2, 2);
                        return { name1, name2 };
                    }
                }
            }
            return {
                name1: this.getPlayerName(match.player1),
                name2: this.getPlayerName(match.player2)
            };
        },
        getPlayerName(p) {
            if (!p) return 'Freilos';
            if (p.member) {
                return p.member.firstName + ' ' + p.member.lastName;
            } else {
                return (p.firstName || '') + ' ' + (p.lastName || '');
            }
        },
        getPairingPlayerName(pairing, playerNumber) {
            if (playerNumber === 1) {
                if (pairing.member1 && pairing.member1.member) {
                    return `${pairing.member1.member.firstName} ${pairing.member1.member.lastName}`;
                } else if (pairing.external1) {
                    return `${pairing.external1.firstName} ${pairing.external1.lastName}`;
                }
            } else if (playerNumber === 2) {
                if (pairing.member2 && pairing.member2.member) {
                    return `${pairing.member2.member.firstName} ${pairing.member2.member.lastName}`;
                } else if (pairing.external2) {
                    return `${pairing.external2.firstName} ${pairing.external2.lastName}`;
                }
            }
            return this.$t('tournaments.unknown');
        },
        formatResult(match) {
            if (!match.tournamentResults?.length) return '-';
            return match.tournamentResults
                .sort((a, b) => a.set - b.set)
                .map(r => `${Math.abs(r.pointsPlayer1)}:${Math.abs(r.pointsPlayer2)}`)
                .join(', ');
        },
        getSetsString(match) {
            const results = match.tournamentResults || [];
            let win1 = 0, win2 = 0;
            for (const r of results) {
                if (r.pointsPlayer1 > r.pointsPlayer2) win1++;
                else if (r.pointsPlayer2 > r.pointsPlayer1) win2++;
            }
            return `${win1}:${win2}`;
        },
        winnerIsPlayer1(match) {
                if (match.result === 'BYE') {
                    // Gewinner ist der vorhandene Spieler
                    return !!match.player1 && !match.player2;
                }
                const [t, n] = this.getSetsString(match).split(':').map(Number);
                return t > n;
        },
        isEditing(match, set) {
            return (
                this.editingResult.matchId === match.id &&
                this.editingResult.set === set
            );
        },
        isLastResult(match, result) {
            const arr = match.tournamentResults || [];
            return arr.length > 0 && arr[arr.length - 1].set === result.set;
        },
        matchHasGaveUp(match) {
            return match.gaveUpMatch || match.player1?.gaveUp || match.player2?.gaveUp;
        },
        getMatchStateLabel(match) {
            if (this.matchHasGaveUp(match)) return this.$t('tournaments.gaveUp');
            if (match.isFinished) return this.$t('tournaments.statusFinished');
            if (match.isActive) return this.$t('tournaments.statusLive');
            return this.$t('tournaments.statusOpen');
        },
        getMatchStateClass(match) {
            if (this.matchHasGaveUp(match)) return 'status-gaveup';
            if (match.isFinished) return 'status-finished';
            if (match.isActive) return 'status-live';
            return 'status-open';
        }
    }
};
</script>

<style scoped>
.results-summary {
    display: flex;
    flex-wrap: wrap;
    gap: 0.6rem;
    margin-bottom: 1rem;
}

.results-chip {
    display: inline-flex;
    align-items: center;
    padding: 0.35rem 0.7rem;
    border-radius: 999px;
    background: var(--background-soft);
    color: var(--text-muted);
    font-size: 0.9rem;
    font-weight: 600;
}

.results-chip-live {
    background: rgba(46, 125, 50, 0.14);
    color: var(--success-color);
}

.results-chip-open {
    background: rgba(181, 106, 29, 0.14);
    color: #8f5316;
}

.results-section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
}

.results-section-header h4 {
    margin: 0 0 0.75rem 0;
}

/* Farbmarkierungen für Spiele */
.match-finished {
    background-color: var(--background-soft) !important;
}

.match-finished td {
    color: var(--text-muted) !important;
}

.match-live {
    background-color: rgba(46, 125, 50, 0.12) !important;
}

.match-live:not(.match-finished) td {
    color: var(--success-color) !important;
}

.match-finished.match-live {
    background-color: #e9ecef !important;
}

.match-finished.match-live td {
    color: #626262 !important;
}

/* Aktives Match hervorheben - auch wenn es abgeschlossen ist */
.active-match {
    background-color: rgba(181, 106, 29, 0.12) !important;
    border-left: 3px solid #b56a1d !important;
}

.active-match.match-finished {
    background-color: #fff3cd !important;
}

.active-match.match-finished td {
    color: #8f5316 !important;
}

.active-match.match-live {
    background-color: #fff3cd !important;
}

.active-match.match-live td {
    color: #8f5316 !important;
}

.gave-up-result {
    color: var(--text-muted);
}
.gave-up-badge-small {
    margin-left: 0.25rem;
    font-size: 0.8rem;
    color: var(--danger-color);
}
.no-edit-hint {
    font-size: 0.85rem;
    color: var(--text-muted);
}

.active-match:hover {
    background-color: rgba(181, 106, 29, 0.18) !important;
}

.distribute-tables-bar {
    margin-bottom: 1rem;
}

.results-next-step {
    display: flex;
    justify-content: flex-start;
    margin-top: 1rem;
    margin-bottom: 1rem;
    padding: 0.9rem 1rem;
    border: 1px solid var(--border-color);
    border-radius: 12px;
    background: var(--surface-color, #ffffff);
}

.results-next-step-muted {
    border-color: var(--border-color);
    background: var(--background-soft);
}

.ranking-class-gap {
    margin-top: 2rem;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 4.8rem;
    padding: 0.2rem 0.45rem;
    border-radius: 999px;
    font-size: 0.78rem;
    font-weight: 700;
    margin-right: 0.5rem;
    margin-bottom: 0.35rem;
}

.status-open {
    background: var(--background-soft);
    color: var(--text-muted);
}

.status-live {
    background: rgba(46, 125, 50, 0.14);
    color: var(--success-color);
}

.status-finished {
    background: var(--primary-soft);
    color: var(--primary-dark);
}

.status-gaveup {
    background: rgba(200, 76, 50, 0.14);
    color: var(--danger-color);
}

.action-row {
    display: flex;
    flex-wrap: wrap;
    gap: 0.35rem;
    align-items: center;
}

.table-select {
    width: 3.5rem;
    padding: 0.15rem 0.25rem;
    font-size: 0.85rem;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--surface-color, #ffffff);
    color: var(--text-color);
}
</style>
