<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-for="section in groupMatchSections" :key="section.key" class="group-matches">
            <div style="display:flex; align-items:center; justify-content:space-between;">
                <h4>{{ section.title }}</h4>
                <div>
                    <button v-if="numberOfTables" @click="onDistributeTables" class="btn-secondary">{{ $t('tournaments.distributeTables') }}</button>
                </div>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>{{ $t('tournaments.round') }}</th>
                        <th>{{ $t('tournaments.group') }}</th>
                        <th>{{ $t('tournaments.encounter') }}</th>
                        <th>Tisch</th>
                        <th>{{ $t('tournaments.result') }}</th>
                        <th>{{ $t('tournaments.sets') }}</th>
                        <th>{{ $t('tournaments.action') }}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="m in section.matches" :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) }} - {{ m.groupLabel || ($t('tournaments.groupNumber') + ' ' + m.groupNumber) }}
                            </template>
                            <template v-else>
                                {{ m.groupLabel || ($t('tournaments.groupNumber') + ' ' + m.groupNumber) }}
                            </template>
                        </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="numberOfTables">
                                <select @click.stop @change.stop="onSetMatchTable(m, $event.target.value)" :value="m.tableNumber || ''">
                                    <option value="">-</option>
                                    <option v-for="n in numberOfTables" :key="n" :value="n">{{ n }}</option>
                                </select>
                            </template>
                            <template v-else>
                                -
                            </template>
                        </td>
                        <td>
                            <template v-if="m.result === 'BYE'">
                                BYE
                            </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>
                                            <button v-if="!m.isFinished" @click.stop="onDeleteSet(m, r.set)" class="inline-delete" aria-label="Satz löschen">
                                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                    <path d="M18 6L6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                    <path d="M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                </svg>
                                            </button>
                                            <span v-if="!isLastResult(m, r)">, </span>
                                        </template>
                                </template>
                                <div class="new-set-line">
                                    <input 
                                        v-model="m.resultInput" 
                                        placeholder="Neuen Satz, z.B. 11:7"
                                        @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>
                            <button v-if="!m.isFinished" @click="$emit('finish-match', m)">Abschließen</button>
                            <button v-else @click="$emit('reopen-match', m)" class="btn-correct">Korrigieren</button>
                            <button v-if="!m.isFinished && !m.isActive" @click.stop="$emit('set-match-active', m, true)" class="btn-live" title="Als laufend markieren">▶️</button>
                            <button v-if="!m.isFinished && m.isActive" @click.stop="$emit('set-match-active', m, false)" class="btn-live active" title="Laufend-Markierung entfernen">⏸️</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </section>
        <div v-if="participants.length > 1 && !filteredGroupMatches.length && !filteredKnockoutMatches.length" class="start-matches" style="margin-top:1.5rem">
            <button @click="$emit('start-matches')">
                {{ $t('tournaments.createMatches') }}
            </button>
        </div>
        <div v-if="canStartKnockout && !showKnockout && numberOfGroupsForSelectedClass > 1" class="ko-start">
            <button @click="$emit('start-knockout')">
                {{ $t('tournaments.startFinalRound') }}
            </button>
        </div>
        <div v-if="showKnockout && canResetKnockout && numberOfGroupsForSelectedClass > 1" class="ko-reset" style="margin-top:1rem">
            <button @click="$emit('reset-knockout')" class="trash-btn">
                🗑️ {{ $t('tournaments.deleteFinalRound') }}
            </button>
        </div>
        <section v-if="showKnockout && numberOfGroupsForSelectedClass > 1 && filteredKnockoutMatches.length" class="ko-round">
            <h4>{{ $t('tournaments.koRound') }}</h4>
            <table>
                <thead>
                    <tr>
                        <th>{{ $t('tournaments.class') }}</th>
                        <th>{{ $t('tournaments.round') }}</th>
                        <th>{{ $t('tournaments.encounter') }}</th>
                        <th>Tisch</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>
                            <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="numberOfTables">
                                <select @click.stop @change.stop="onSetMatchTable(m, $event.target.value)" :value="m.tableNumber || ''">
                                    <option value="">-</option>
                                    <option v-for="n in numberOfTables" :key="n" :value="n">{{ n }}</option>
                                </select>
                            </template>
                            <template v-else>
                                -
                            </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>
                                            <button v-if="!m.isFinished" @click.stop="onDeleteSet(m, r.set)" class="inline-delete" aria-label="Satz löschen">
                                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                    <path d="M18 6L6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                    <path d="M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                </svg>
                                            </button>
                                            <span v-if="!isLastResult(m, r)">, </span>
                                        </template>
                                </template>
                                <div class="new-set-line">
                                    <input 
                                        v-model="m.resultInput" 
                                        placeholder="Neuen Satz, z.B. 11:7"
                                        @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>
                            <button v-if="!m.isFinished" @click="$emit('finish-match', m)">Fertig</button>
                            <button v-else @click="$emit('reopen-match', m)" class="btn-correct">Korrigieren</button>
                            <button v-if="!m.isFinished && !m.isActive" @click.stop="$emit('set-match-active', m, true)" class="btn-live" title="Als laufend markieren">▶️</button>
                            <button v-if="!m.isFinished && m.isActive" @click.stop="$emit('set-match-active', m, false)" class="btn-live active" title="Laufend-Markierung entfernen">⏸️</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </section>
        <section v-if="Object.keys(filteredGroupedRankingList).length > 0" class="ranking">
            <h4>Rangliste</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" style="margin-top: 2rem;"></div>
                <h5 v-if="getClassName(classKey)">{{ getClassName(classKey) }}</h5>
                <table>
                    <thead>
                        <tr>
                            <th>Platz</th>
                            <th>Spieler</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>
<style scoped>
.inline-delete{
    background: transparent;
    border: none;
    padding: 0 6px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    color: #d32f2f; /* warn red */
    font-size: 105%;
    line-height: 1;
}
.inline-delete svg{
    width: 1.05em;
    height: 1.05em;
    stroke: currentColor;
}
.inline-delete:focus{ outline: none; box-shadow: 0 0 0 3px rgba(211,47,47,0.12); border-radius:3px; }

/* Highlight for running matches (ensure high specificity) */
.match-live:not(.match-finished) td {
    background: #fff3cd !important;
    color: #5a3500 !important;
}
</style>

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

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
        },
        clubId: {
            type: [Number, String],
            required: false,
            default: null,
        },
        numberOfTables: {
            type: [Number, null],
            default: null,
        },
        pairings: {
            type: Array,
            required: true
        }
    },
    computed: {
        filteredGroupMatches() {
            return this.filterMatchesByClass(this.groupMatches);
        },
        preliminaryGroupMatches() {
            return this.filteredGroupMatches.filter(m => !this.isStageMatch(m));
        },
        finalGroupMatches() {
            return this.filteredGroupMatches.filter(m => this.isStageMatch(m));
        },
        groupMatchSections() {
            return [
                { key: 'preliminary', title: 'Vorrunde', matches: this.preliminaryGroupMatches },
                { key: 'final', title: 'Endrunde', matches: this.finalGroupMatches },
            ].filter(section => section.matches.length > 0);
        },
        filteredKnockoutMatches() {
            return this.filterMatchesByClass(this.knockoutMatches);
        },
        filteredGroupedRankingList() {
            // Wenn keine Klasse ausgewählt ist (null), zeige alle
            if (this.selectedViewClass === null || this.selectedViewClass === undefined) {
                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;
        },
        numberOfGroupsForSelectedClass() {
            // Zähle direkt die Vorrunden-Gruppen für die ausgewählte Klasse.
            // Endrunden-Gruppen dürfen den Start-Button nicht erneut aktivieren.
            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) {
                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;
        }
    },
    emits: [
        'update:selectedViewClass',
        'update:activeMatchId',
        'update:editingResult',
        'save-edited-result',
        'cancel-edit',
        'start-edit-result',
        'save-match-result',
        'delete-set',
        'finish-match',
        'reopen-match',
        'set-match-active',
        'start-matches',
        'start-knockout',
        'reset-knockout'
        ,'tables-distributed'
    ],
    methods: {
        // Simple HTML escape to avoid injecting unsafe markup into the dialog
        // We keep it minimal and safe for names/numbers
        
        escapeHtml(str) {
            if (str == null) return '';
            return String(str)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
        },

        async onDistributeTables() {
            if (!this.clubId || !this.selectedDate) return;
            try {
                const resp = await apiClient.post('/tournament/matches/distribute', { clubId: this.clubId, tournamentId: this.selectedDate });
                const updated = resp?.data?.updated || [];

                if (updated.length === 0) {
                    // Keine passenden Spiele gefunden
                    const msg = resp?.data?.message || (this.$t ? this.$t('tournaments.noAssignableMatches') : 'Keine Spiele verfügbar, bei denen beide Spieler frei sind.');
                    if (this.$root && this.$root.showInfo) this.$root.showInfo(this.$t('tournaments.distributeTablesResult') || 'Tischverteilung', msg);
                } else {
                    // Baue eine lesbare Liste der zugewiesenen Paarungen
                    // Generate an HTML table for better readability
                    const rows = updated.map(m => {
                        const local = (this.groupMatches || []).concat(this.knockoutMatches || []).find(x => x.id === m.id) || m;
                        const names = this.getMatchPlayerNames(local);
                        const tbl = m.tableNumber || (local.tableNumber || '-');
                        return `<tr><td>${this.escapeHtml(names.name1)}</td><td>–</td><td>${this.escapeHtml(names.name2)}</td><td style="text-align:right">${this.escapeHtml(String(tbl))}</td></tr>`;
                    }).join('');
                    const tableHtml = `
                        <table style="width:100%;border-collapse:collapse;">
                          <thead><tr><th style="text-align:left">Spieler A</th><th></th><th style="text-align:left">Spieler B</th><th style="text-align:right">Tisch</th></tr></thead>
                          <tbody>${rows}</tbody>
                        </table>
                    `;
                    if (this.$root && this.$root.showInfo) this.$root.showInfo(this.$t('tournaments.distributeTablesResult') || 'Tischverteilung', this.$t('tournaments.tablesDistributed') || 'Tische wurden verteilt.', tableHtml);
                }
                // Debug log and emit updated matches so parent can update UI immediately
                console.debug('[TournamentResultsTab.onDistributeTables] updatedCount=', Array.isArray(updated) ? updated.length : 0, 'updatedIds=', (updated || []).map(u => u.id));
                this.$emit('tables-distributed', updated);
            } catch (err) {
                const msg = err?.response?.data?.error || err.message || String(err);
                if (this.$root && this.$root.showInfo) {
                    this.$root.showInfo(this.$t('messages.error') || 'Fehler', msg, '', 'error');
                }
            }
        },
        async onSetMatchTable(match, value) {
            if (!this.clubId || !this.selectedDate || !match) return;
            const tableNumber = value === '' ? null : Number(value);
            try {
                await apiClient.put(`/tournament/match/${this.clubId}/${this.selectedDate}/${match.id}/table`, { tableNumber });
                this.$emit('tables-distributed');
            } catch (err) {
                const msg = err?.response?.data?.error || err.message || String(err);
                if (this.$root && this.$root.showInfo) {
                    this.$root.showInfo(this.$t('messages.error') || 'Fehler', msg, '', 'error');
                }
            }
        },
        async onDeleteSet(match, set) {
            const title = this.$t ? this.$t('tournaments.confirmDeleteSetTitle') : null;
            const message = this.$t ? this.$t('tournaments.confirmDeleteSet') : 'Satz wirklich löschen?';
            const confirmed = this.$root && this.$root.showConfirm ? await this.$root.showConfirm(title || '', message || '') : confirm(message);
            if (confirmed) this.$emit('delete-set', match, set);
        },
        isStageMatch(match) {
            return match && match.stageId !== null && match.stageId !== undefined;
        },
        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;
            });
        },
        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;
        }
    }
};
</script>
