<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="Object.keys(finalPlacementsByClass).length > 0" class="final-placements">
            <h3>{{ $t('tournaments.finalPlacements') }}</h3>
            <template v-for="(classPlacements, classId) in finalPlacementsByClass" :key="`final-${classId}`">
                <div v-if="isAllSelected || shouldShowClass(classId==='null'?null:Number(classId))" class="class-section">
                    <h4 class="class-header">
                        {{ getClassName(classId) }}
                        <span class="class-type-badge" v-if="classId!==null" :class="{ doubles: isDoubles(classId), singles: !isDoubles(classId) }">
                            {{ isDoubles(classId) ? $t('tournaments.doubles') : $t('tournaments.singles') }}
                        </span>
                    </h4>
                    <table>
                        <thead>
                            <tr>
                                <th class="col-place">{{ labelPlace }}</th>
                                <th>{{ $t('tournaments.player') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(entry, entryIdx) in classPlacements" :key="`final-${classId}-${entryIdx}`">
                                <td class="col-place">{{ entry.position }}.</td>
                                <td>
                                    <span 
                                        class="player-name-clickable" 
                                        @click="openPlayerDialog(entry)"
                                        :title="$t('tournaments.showPlayerDetails')"
                                    >
                                        {{ getEntryPlayerName(entry) }}
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </template>
        </section>
        <section v-if="groupPlacements.length > 0" class="group-placements">
            <h3>{{ $t('tournaments.groupPlacements') }}</h3>
            <template v-for="(classGroups, classId) in groupPlacementsByClass" :key="`group-${classId}`">
                <div v-if="isAllSelected || shouldShowClass(classId==='null'?null:Number(classId))" class="class-section">
                    <h4 class="class-header">
                        {{ getClassName(classId) }}
                        <span class="class-type-badge" v-if="classId!==null" :class="{ doubles: isDoubles(classId), singles: !isDoubles(classId) }">
                            {{ isDoubles(classId) ? $t('tournaments.doubles') : $t('tournaments.singles') }}
                        </span>
                    </h4>
                    <div class="group-table" v-for="(g, gi) in classGroups" :key="`group-${classId}-${gi}`">
                        <h5>{{ g.groupLabel || ($t('tournaments.group') + ' ' + g.groupNumber) }}</h5>
                        <table>
                            <thead>
                                <tr>
                                    <th class="col-place">{{ labelPlace }}</th>
                                    <th>{{ $t('tournaments.player') }}</th>
                                    <th>{{ $t('tournaments.points') }}</th>
                                    <th>{{ $t('tournaments.sets') }}</th>
                                    <th>{{ $t('tournaments.setDiff') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(r, ri) in g.rankings" :key="`r-${g.groupId}-${ri}`">
                                    <td class="col-place">{{ r.position }}.</td>
                                    <td>
                                        <span 
                                            class="player-name-clickable" 
                                            @click="openPlayerDialogFromRanking(r)"
                                            :title="$t('tournaments.showPlayerDetails')"
                                        >
                                            {{ r.name }}
                                        </span>
                                    </td>
                                    <td>{{ r.points }}</td>
                                    <td>{{ r.setsWon }}:{{ r.setsLost }}</td>
                                    <td>{{ r.setDiff >= 0 ? '+' + r.setDiff : r.setDiff }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </template>
        </section>
        <div v-if="Object.keys(finalPlacementsByClass).length === 0 && groupPlacements.length === 0" class="no-placements">
            <p>{{ $t('tournaments.noPlacementsYet') }}</p>
        </div>
        
        <!-- Player Details Dialog -->
        <PlayerDetailsDialog
            v-model="showPlayerDialog"
            :player-id="selectedPlayerId"
            :is-external="selectedPlayerIsExternal"
            :tournament-id="selectedDate"
            :club-id="clubId"
            :player-name="selectedPlayerName"
        />
    </div>
</template>

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

export default {
    name: 'TournamentPlacementsTab',
    components: { 
        TournamentClassSelector,
        PlayerDetailsDialog
    },
    props: {
        selectedDate: { type: [String, Number], default: null },
        selectedViewClass: { type: [Number, String, null], default: null },
        tournamentClasses: { type: Array, required: true },
        participants: { type: Array, required: true },
        externalParticipants: { type: Array, required: true },
        pairings: { type: Array, required: true },
        groups: { type: Array, required: true },
        groupRankings: { type: Object, required: true },
        knockoutMatches: { type: Array, required: true },
        clubId: { type: [Number, String], required: true }
    },
    emits: ['update:selectedViewClass'],
    data() {
        return {
            showPlayerDialog: false,
            selectedPlayerId: null,
            selectedPlayerIsExternal: false,
            selectedPlayerName: ''
        };
    },
    watch: {
        showPlayerDialog(newVal) {
            console.log('[TournamentPlacementsTab] showPlayerDialog changed:', newVal);
        },
        selectedPlayerId(newVal) {
            console.log('[TournamentPlacementsTab] selectedPlayerId changed:', newVal);
        }
    },
    computed: {
        // Flag für 'Alle Klassen'
        isAllSelected() {
            const sel = this.selectedViewClass;
            if (sel === null || sel === undefined || sel === '') return true;
            if (typeof sel === 'string') {
                const norm = sel.trim();
                if (norm === '__none__') return false;
                const knownAll = ['__all__', 'all', 'ALL', '__allClasses__', '__ALL_CLASSES__'];
                if (knownAll.includes(norm)) return true;
                const parsed = parseInt(norm);
                return !Number.isFinite(parsed); // nicht-numerischer String => 'Alle Klassen'
            }
            return false;
        },
        labelPlace() {
            const t = this.$t && this.$t('tournaments.place');
            if (t && typeof t === 'string' && t.trim().length > 0 && t !== 'tournaments.place') return t;
            return 'Platz';
        },
        finalPlacementsByClass() {
            const byClass = {};
            const matchesByClass = {};
            (this.knockoutMatches || []).forEach(m => {
                const key = m.classId != null ? String(m.classId) : 'null';
                (matchesByClass[key] ||= []).push(m);
            });

                            const isClassDoubles = (classKey) => {
                                const cid = classKey === 'null' ? null : Number(classKey);
                                if (cid == null) return false;
                                const c = (this.tournamentClasses || []).find(x => x.id === cid);
                                return Boolean(c && c.isDoubles);
                            };

                            const getPairingName = (cid, playerId) => {
                                const classIdNum = cid == null ? null : Number(cid);
                                // Versuche zuerst: playerId ist die Pairing-ID
                                let pairing = (this.pairings || []).find(p => p.classId === classIdNum && p.id === playerId);
                                if (!pairing) {
                                    // Fallback: playerId ist Turnier-Mitglied-ID (member1Id/2Id oder external1Id/2Id)
                                    pairing = (this.pairings || []).find(p => 
                                        p.classId === classIdNum && (
                                            p.member1Id === playerId || p.member2Id === playerId ||
                                            p.external1Id === playerId || p.external2Id === playerId
                                        )
                                    );
                                }
                                if (!pairing) return null;
                                const n1 = pairing.member1?.member
                                    ? `${pairing.member1.member.firstName} ${pairing.member1.member.lastName}`
                                    : pairing.external1
                                        ? `${pairing.external1.firstName} ${pairing.external1.lastName}`
                                        : this.$t('tournaments.unknown');
                                const n2 = pairing.member2?.member
                                    ? `${pairing.member2.member.firstName} ${pairing.member2.member.lastName}`
                                    : pairing.external2
                                        ? `${pairing.external2.firstName} ${pairing.external2.lastName}`
                                        : this.$t('tournaments.unknown');
                                return `${n1} / ${n2}`;
                            };

                                    const addEntry = (classKey, position, participantOrPlayer, opts = {}) => {
                                const cid = classKey === 'null' ? null : Number(classKey);
                                (byClass[classKey] ||= []);
                                if (isClassDoubles(classKey)) {
                                    // Teilnehmer ist ein Player-Objekt aus Match: nutze dessen id zur Paarungssuche
                                            const playerId = opts.playerId != null
                                                ? opts.playerId
                                                : (participantOrPlayer?.id || participantOrPlayer?.member?.id || null);
                                    const displayName = playerId != null ? getPairingName(cid, playerId) : null;
                                    if (!displayName) return;
                                    const existing = byClass[classKey].find(e => e.displayName === displayName);
                                    if (!existing) {
                                        byClass[classKey].push({ position, displayName, classId: cid });
                                    } else if (Number(position) < Number(existing.position)) {
                                        existing.position = position;
                                    }
                                } else {
                                    // Einzel: wie zuvor mit member/direkten Namen
                                    const member = participantOrPlayer?.member
                                        ? participantOrPlayer.member
                                        : (participantOrPlayer && (participantOrPlayer.firstName || participantOrPlayer.lastName)
                                                ? { id: participantOrPlayer.id, firstName: participantOrPlayer.firstName, lastName: participantOrPlayer.lastName }
                                                : null);
                                    if (!member) return;
                                    const key = (member.id != null && Number.isFinite(Number(member.id)))
                                        ? `id:${Number(member.id)}`
                                        : `name:${(member.firstName || '').trim()}|${(member.lastName || '').trim()}`;
                                    const existing = byClass[classKey].find(e => {
                                        const ek = (e.member?.id != null && Number.isFinite(Number(e.member.id)))
                                            ? `id:${Number(e.member.id)}`
                                            : `name:${(e.member?.firstName || '').trim()}|${(e.member?.lastName || '').trim()}`;
                                        return ek === key;
                                    });
                                    if (!existing) {
                                        byClass[classKey].push({ position, member, classId: cid });
                                    } else if (Number(position) < Number(existing.position)) {
                                        existing.position = position;
                                    }
                                }
                            };

                            const parseWinnerLoser = (match) => {
                        if (!match || !match.isFinished) return { winner: null, loser: null };
                        // BYE-Fälle
                        if (String(match.result).toUpperCase() === 'BYE') {
                            const winner = match.player1 || match.player2 || null;
                            const loser = winner === match.player1 ? match.player2 : match.player1;
                                    const winnerSourceId = winner === match.player1 ? match.player1Id : match.player2Id;
                                    const loserSourceId = loser === match.player1 ? match.player1Id : match.player2Id;
                                    return { winner, loser, winnerSourceId, loserSourceId };
                        }
                        // Bevorzugt: aus tournamentResults die Satzgewinne ableiten
                        if (Array.isArray(match.tournamentResults) && match.tournamentResults.length > 0) {
                            let w1 = 0, w2 = 0;
                            for (const r of match.tournamentResults) {
                                const p1 = Number(r.pointsPlayer1);
                                const p2 = Number(r.pointsPlayer2);
                                if (Number.isFinite(p1) && Number.isFinite(p2)) {
                                    if (p1 > p2) w1++; else if (p2 > p1) w2++;
                                }
                            }
                            if (w1 !== w2) {
                                        const winP = w1 > w2 ? match.player1 : match.player2;
                                        const loseP = w1 > w2 ? match.player2 : match.player1;
                                        const winnerSourceId = w1 > w2 ? match.player1Id : match.player2Id;
                                        const loserSourceId = w1 > w2 ? match.player2Id : match.player1Id;
                                        return { winner: winP, loser: loseP, winnerSourceId, loserSourceId };
                            }
                        }
                        // Fallback: Ergebnis-String flexibel parsen (z.B. '5:11 0:1' -> nimm letztes 'a:b')
                        if (typeof match.result === 'string') {
                            const tokens = match.result.match(/-?\d+\s*:\s*-?\d+/g);
                            if (tokens && tokens.length > 0) {
                                const last = tokens[tokens.length - 1];
                                const parts = last.split(':');
                                const a = Number((parts[0] || '').trim());
                                const b = Number((parts[1] || '').trim());
                                if (Number.isFinite(a) && Number.isFinite(b)) {
                                            const winP = a > b ? match.player1 : match.player2;
                                            const loseP = a > b ? match.player2 : match.player1;
                                            const winnerSourceId = a > b ? match.player1Id : match.player2Id;
                                            const loserSourceId = a > b ? match.player2Id : match.player1Id;
                                            return { winner: winP, loser: loseP, winnerSourceId, loserSourceId };
                                }
                            }
                        }
                        return { winner: null, loser: null };
                    };

            Object.entries(matchesByClass).forEach(([classKey, classMatches]) => {
                if (!classMatches || classMatches.length === 0) return;
                const lower = (s) => (s || '').toLowerCase();
                const finalMatch = classMatches.find(m => lower(m.round) === 'finale');
                const thirdMatch = classMatches.find(m => lower(m.round).includes('platz 3'));
                const semifinals = classMatches.filter(m => lower(m.round).includes('halbfinale'));
                const quarterfinals = classMatches.filter(m => lower(m.round).includes('viertelfinale'));
                const round16 = classMatches.filter(m => lower(m.round).includes('achtelfinale'));

        const f = parseWinnerLoser(finalMatch);
        if (f.winner) addEntry(classKey, 1, f.winner, { playerId: f.winnerSourceId });
        if (f.loser) addEntry(classKey, 2, f.loser, { playerId: f.loserSourceId });

            const t = parseWinnerLoser(thirdMatch);
            if (t.winner) addEntry(classKey, 3, t.winner, { playerId: t.winnerSourceId });
            if (t.loser) addEntry(classKey, 4, t.loser, { playerId: t.loserSourceId });

                        if (!thirdMatch || !thirdMatch.isFinished) {
                                        semifinals.forEach(m => {
                                            const r = parseWinnerLoser(m);
                                            if (r.loser) addEntry(classKey, 3, r.loser, { playerId: r.loserSourceId });
                                        });
                        }
                                    quarterfinals.forEach(m => {
                                        const r = parseWinnerLoser(m);
                                        if (r.loser) addEntry(classKey, 5, r.loser, { playerId: r.loserSourceId });
                                    });
                                    round16.forEach(m => {
                                        const r = parseWinnerLoser(m);
                                        if (r.loser) addEntry(classKey, 9, r.loser, { playerId: r.loserSourceId });
                                    });

            byClass[classKey] = (byClass[classKey] || []).sort((a, b) => Number(a.position) - Number(b.position));
            });

            // Ergänze alle weiteren Teilnehmer der Klasse (auch wenn sie die KO-Runde nicht erreicht haben)
            // Baue Teilnehmerlisten pro Klasse aus participants und externalParticipants
            const participantsByClass = {};
            (this.participants || []).forEach(p => {
                const key = p.classId != null ? String(p.classId) : 'null';
                (participantsByClass[key] ||= []).push(p);
            });
            (this.externalParticipants || []).forEach(p => {
                const key = p.classId != null ? String(p.classId) : 'null';
                (participantsByClass[key] ||= []).push(p);
            });

            const getStableKeyForParticipant = (p) => {
                const member = p.member || p;
                if (member && member.id != null && Number.isFinite(Number(member.id))) {
                    return `id:${Number(member.id)}`;
                }
                const fn = (member?.firstName || '').trim();
                const ln = (member?.lastName || '').trim();
                if (!fn && !ln) return null;
                return `name:${fn}|${ln}`;
            };

                        Object.entries(participantsByClass).forEach(([classKey, plist]) => {
                const existingKeys = new Set((byClass[classKey] || []).map(e => {
                                        if (e.displayName) return `pair:${classKey}:${e.displayName}`;
                                        if (e.member?.id != null && Number.isFinite(Number(e.member.id))) return `id:${Number(e.member.id)}`;
                                        const fn = (e.member?.firstName || '').trim();
                                        const ln = (e.member?.lastName || '').trim();
                                        return `name:${fn}|${ln}`;
                }));

                const dedupSeen = new Set();
                const unique = [];
                for (const p of plist) {
                    const k = getStableKeyForParticipant(p);
                    if (!k || dedupSeen.has(k)) continue;
                    dedupSeen.add(k);
                    unique.push(p);
                }

                const maxPos = Math.max(0, ...(byClass[classKey] || []).map(e => Number(e.position) || 0));
                let nextPos = maxPos + 1;

                                if (isClassDoubles(classKey)) {
                                    // Für Doppel: ergänze fehlende Paarungen pro Klasse
                                    const cidNum = classKey === 'null' ? null : Number(classKey);
                                    const classPairings = (this.pairings || []).filter(p => p.classId === cidNum);
                                    classPairings.forEach(pairing => {
                                        // Bevorzuge direkte Pairing-ID
                                        const displayName = getPairingName(cidNum, pairing.id) || getPairingName(cidNum, pairing.member1Id || pairing.external1Id);
                                        if (!displayName) return;
                                        const key = `pair:${classKey}:${displayName}`;
                                        if (existingKeys.has(key)) return;
                                        (byClass[classKey] ||= []).push({ position: nextPos++, displayName, classId: cidNum });
                                        existingKeys.add(key);
                                    });
                                } else {
                                    unique.forEach(p => {
                                        const k = getStableKeyForParticipant(p);
                                        if (!k || existingKeys.has(k)) return;
                                        const memberLike = p.member ? p.member : {
                                            id: p.id,
                                            firstName: p.firstName,
                                            lastName: p.lastName
                                        };
                                        (byClass[classKey] ||= []).push({ position: nextPos++, member: memberLike, classId: classKey === 'null' ? null : Number(classKey) });
                                        existingKeys.add(k);
                                    });
                                }

                byClass[classKey] = (byClass[classKey] || []).sort((a, b) => Number(a.position) - Number(b.position));
            });

            const finalStageGroups = this.finalStageGroups;
            finalStageGroups.forEach(group => {
                const classKey = group.classId != null ? String(group.classId) : 'null';
                const cid = group.classId == null ? null : Number(group.classId);
                const rankings = this.groupRankings[group.groupId] || [];
                if (rankings.length === 0) return;
                byClass[classKey] = rankings.map(r => ({
                    position: r.position,
                    member: {
                        id: r.clubMemberId || r.memberId || r.id,
                        firstName: (r.name || '').split(' ').slice(0, -1).join(' '),
                        lastName: (r.name || '').split(' ').slice(-1).join(' '),
                    },
                    displayName: r.name,
                    classId: cid,
                    isExternal: r.isExternal || false,
                })).sort((a, b) => Number(a.position) - Number(b.position));
            });

            Object.keys(byClass).forEach(k => {
                if (!byClass[k] || byClass[k].length === 0) delete byClass[k];
            });

            return byClass;
        },
        finalStageGroups() {
            const stageGroups = (this.groups || []).filter(g => g.stageId !== null && g.stageId !== undefined);
            if (stageGroups.length === 0) return [];
            const maxStageIndex = Math.max(...stageGroups.map(g => Number(g.stageIndex || 0)));
            return stageGroups.filter(g => Number(g.stageIndex || 0) === maxStageIndex);
        },
        groupPlacements() {
            const placements = [];
            // Primär: aus groups + groupRankings
            if ((this.groups || []).length > 0) {
                this.groups
                    .filter(group => group.stageId === null || group.stageId === undefined)
                    .forEach(group => {
                    const rankings = this.groupRankings[group.groupId] || [];
                    if (rankings.length > 0) {
                        placements.push({
                            groupId: group.groupId,
                            groupNumber: group.groupNumber,
                            classId: group.classId,
                            groupLabel: group.groupLabel || null,
                            stageId: group.stageId || null,
                            stageIndex: group.stageIndex || null,
                            rankings: rankings.map(r => ({
                                id: r.id,
                                position: r.position,
                                name: r.name,
                                seeded: r.seeded,
                                points: r.points,
                                setsWon: r.setsWon,
                                setsLost: r.setsLost,
                                setDiff: r.setDiff,
                                isExternal: r.isExternal || false
                            }))
                        });
                    }
                });
            } else if (this.groupedRankingList && typeof this.groupedRankingList === 'object') {
                // Fallback: aus groupedRankingList (by classId -> groups)
                Object.entries(this.groupedRankingList).forEach(([classKey, groups]) => {
                    (groups || []).forEach((g, idx) => {
                        const rankings = Array.isArray(g.rankings) ? g.rankings : [];
                        if (rankings.length === 0) return;
                        placements.push({
                            groupId: g.groupId || `${classKey}-${idx}`,
                            groupNumber: g.groupNumber || (idx + 1),
                            classId: g.classId != null ? g.classId : (classKey === 'null' ? null : Number(classKey)),
                            rankings: rankings.map(r => ({
                                id: r.id,
                                position: r.position,
                                name: r.name,
                                seeded: r.seeded,
                                points: r.points,
                                setsWon: r.setsWon,
                                setsLost: r.setsLost,
                                setDiff: r.setDiff,
                                isExternal: r.isExternal || false
                            }))
                        });
                    });
                });
            }
            return placements.sort((a, b) => {
                if (a.classId !== b.classId) {
                    const aNum = a.classId || 999999;
                    const bNum = b.classId || 999999;
                    return aNum - bNum;
                }
                return a.groupNumber - b.groupNumber;
            });
        },
        groupPlacementsByClass() {
            const grouped = {};
            this.groupPlacements.forEach(p => {
                const key = p.classId || 'null';
                if (!grouped[key]) {
                    grouped[key] = [];
                }
                grouped[key].push(p);
            });
            return grouped;
        }
    },
    methods: {
        shouldShowClass(classId) {
            const sel = this.selectedViewClass;
            if (sel === null || sel === undefined || sel === '' || this.isAllSelected) return true;
            if (sel === '__none__') return true; // 'Ohne Klasse' zeigt alle
            const selectedId = typeof sel === 'string' ? parseInt(sel) : sel;
            return classId === selectedId;
        },
        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 '';
            }
        },
        getEntryPlayerName(entry) {
            // Doppel: displayName vorhanden
            if (entry && entry.displayName) return entry.displayName;
            // Einzel: Member-Name
            const m = entry.member || {};
            const fn = (m.firstName || '').trim();
            const ln = (m.lastName || '').trim();
            if (fn || ln) return `${fn} ${ln}`.trim();
            return this.$t('tournaments.unknown');
        },
        isDoubles(classId) {
            const cid = classId === 'null' ? null : (typeof classId === 'string' ? parseInt(classId) : classId);
            if (cid == null) return false;
            const c = (this.tournamentClasses || []).find(x => x.id === cid);
            return Boolean(c && c.isDoubles);
        },
        openPlayerDialog(entry) {
            console.log('[openPlayerDialog] entry:', entry);
            // Für Doppel-Paarungen können wir keine Details anzeigen
            if (entry.displayName) {
                console.log('[openPlayerDialog] Doppel-Paarung, keine Details');
                return;
            }
            
            if (!this.clubId) {
                console.warn('[openPlayerDialog] clubId fehlt');
                return;
            }
            
            const memberId = entry.member?.id;
            if (!memberId) {
                console.warn('[openPlayerDialog] Keine Member-ID:', {
                    hasMember: !!entry.member,
                    memberId: entry.member?.id
                });
                return;
            }
            
            // Prüfe zuerst in externalParticipants, ob es ein externer Teilnehmer ist
            const externalParticipant = this.externalParticipants.find(p => p.id === memberId);
            if (externalParticipant) {
                // Externer Teilnehmer gefunden
                console.log('[openPlayerDialog] Externer Teilnehmer, ID:', memberId);
                this.selectedPlayerId = memberId;
                this.selectedPlayerIsExternal = true;
                this.selectedPlayerName = this.getEntryPlayerName(entry);
                this.showPlayerDialog = true;
                return;
            }
            
            // Prüfe in participants, ob es ein interner Teilnehmer ist
            const participant = this.participants.find(p => {
                // Prüfe verschiedene mögliche ID-Felder
                return (p.member && p.member.id === memberId) || 
                       p.id === memberId || 
                       p.clubMemberId === memberId;
            });
            
            if (participant) {
                // Interner Teilnehmer gefunden
                const actualMemberId = participant.member?.id || participant.clubMemberId || memberId;
                console.log('[openPlayerDialog] Interner Teilnehmer, Member ID:', actualMemberId);
                this.selectedPlayerId = actualMemberId;
                this.selectedPlayerIsExternal = false;
                this.selectedPlayerName = this.getEntryPlayerName(entry);
                this.showPlayerDialog = true;
            } else {
                // Weder in participants noch in externalParticipants gefunden
                // Fallback: Versuche nochmal in externalParticipants mit firstName/lastName
                const entryName = this.getEntryPlayerName(entry);
                const nameParts = entryName.split(' ').filter(p => p);
                if (nameParts.length >= 2) {
                    const firstName = nameParts[0];
                    const lastName = nameParts.slice(1).join(' ');
                    const extByName = this.externalParticipants.find(p => 
                        p.firstName === firstName && p.lastName === lastName
                    );
                    if (extByName) {
                        console.log('[openPlayerDialog] Externer Teilnehmer (nach Name), ID:', extByName.id);
                        this.selectedPlayerId = extByName.id;
                        this.selectedPlayerIsExternal = true;
                        this.selectedPlayerName = entryName;
                        this.showPlayerDialog = true;
                        return;
                    }
                }
                
                console.warn('[openPlayerDialog] Teilnehmer nicht gefunden, versuche als intern:', {
                    memberId,
                    entryName
                });
                // Letzter Fallback: Annahme, dass es ein interner Member ist
                this.selectedPlayerId = memberId;
                this.selectedPlayerIsExternal = false;
                this.selectedPlayerName = this.getEntryPlayerName(entry);
                this.showPlayerDialog = true;
            }
        },
        openPlayerDialogFromRanking(ranking) {
            console.log('[openPlayerDialogFromRanking] ranking:', ranking);
            if (!this.clubId) {
                console.warn('[openPlayerDialogFromRanking] clubId nicht verfügbar');
                return;
            }
            
            // Prüfe, ob es ein interner oder externer Teilnehmer ist
            // ranking.id ist die TournamentMember.id oder ExternalTournamentParticipant.id
            if (ranking.isExternal === true) {
                // Externer Teilnehmer: ranking.id ist die ExternalTournamentParticipant.id
                console.log('[openPlayerDialogFromRanking] Externer Teilnehmer, ID:', ranking.id);
                this.selectedPlayerId = ranking.id;
                this.selectedPlayerIsExternal = true;
                this.selectedPlayerName = ranking.name;
                this.showPlayerDialog = true;
            } else {
                // Interner Teilnehmer: Finde den Participant, um die clubMemberId zu bekommen
                const participant = this.participants.find(p => p.id === ranking.id);
                console.log('[openPlayerDialogFromRanking] Interner Teilnehmer, participant:', participant);
                if (participant && participant.member && participant.member.id) {
                    console.log('[openPlayerDialogFromRanking] Öffne Dialog für Member ID:', participant.member.id);
                    this.selectedPlayerId = participant.member.id;
                    this.selectedPlayerIsExternal = false;
                    this.selectedPlayerName = ranking.name;
                    this.showPlayerDialog = true;
                } else if (participant && participant.clubMemberId) {
                    // Fallback: Verwende clubMemberId direkt
                    console.log('[openPlayerDialogFromRanking] Öffne Dialog für clubMemberId:', participant.clubMemberId);
                    this.selectedPlayerId = participant.clubMemberId;
                    this.selectedPlayerIsExternal = false;
                    this.selectedPlayerName = ranking.name;
                    this.showPlayerDialog = true;
                } else {
                    console.warn('[openPlayerDialogFromRanking] Teilnehmer nicht gefunden für ranking.id:', ranking.id);
                }
            }
        }
    }
};
</script>

<style scoped>
.final-placements,
.group-placements {
    margin-bottom: 2rem;
}

.class-section {
    margin-bottom: 2rem;
}

.class-header {
    margin-bottom: 1rem;
    color: #333;
    font-size: 1.1em;
}

.class-type-badge {
    display: inline-block;
    margin-left: 0.5rem;
    padding: 0.1rem 0.4rem;
    border-radius: 0.25rem;
    font-size: 0.85em;
    line-height: 1.2;
}

.class-type-badge.singles {
    background-color: #e3f2fd;
    color: #1565c0;
}

.class-type-badge.doubles {
    background-color: #e8f5e9;
    color: #2e7d32;
}

.group-table {
    margin-bottom: 1.5rem;
}

.group-table h5 {
    margin-bottom: 0.5rem;
    color: #666;
    font-size: 1em;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 1rem;
}

thead {
    background-color: #f5f5f5;
}

th, td {
    padding: 0.5rem;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

th {
    font-weight: 600;
}

/* Platz-Spalte kompakt */
.col-place {
    width: 4em;
}

.seeded-star {
    color: #ff9800;
    margin-right: 0.25rem;
}

.no-placements {
    text-align: center;
    padding: 2rem;
    color: #666;
}

.player-name-clickable {
    cursor: pointer;
    color: #1976d2;
    text-decoration: underline;
}

.player-name-clickable:hover {
    color: #1565c0;
}
</style>
/* Spaltenbreite für Platz: 4em */
table thead th:first-child,
table tbody td:first-child {
    width: 4em;
}


