<template>
    <section class="tournament-classes">
        <h4>{{ $t('tournaments.classes') }}</h4>
        <div class="classes-content">
            <div v-if="tournamentClasses.length === 0" class="no-classes-message">
                <p>{{ $t('tournaments.noClassesYet') }}</p>
            </div>
            <div v-else class="classes-list">
                <div v-for="classItem in tournamentClasses" :key="classItem.id" class="class-item">
                    <template v-if="editingClassId === classItem.id">
                        <!-- Bearbeitungsfelder werden weiter unten verwendet -->
                    </template>
                    <template v-else>
                        <span class="class-name-label">
                            {{ classItem.name }}
                            <span class="class-type-inline" :class="{ 'doubles': classItem.isDoubles }">
                                ({{ classItem.isDoubles ? $t('tournaments.doubles') : $t('tournaments.singles') }})
                            </span>
                        </span>
                        <span v-if="classItem.gender" class="class-gender-badge" :class="'gender-' + classItem.gender">
                            {{ classItem.gender === 'male' ? $t('members.genderMale') : classItem.gender === 'female' ? $t('members.genderFemale') : $t('tournaments.genderMixed') }}
                        </span>
                        <span v-if="classItem.minBirthYear || classItem.maxBirthYear" class="class-birth-year-badge">
                            <template v-if="classItem.minBirthYear && classItem.maxBirthYear">
                                {{ classItem.minBirthYear }}–{{ classItem.maxBirthYear }}
                            </template>
                            <template v-else-if="classItem.maxBirthYear">
                                ≤ {{ classItem.maxBirthYear }}
                            </template>
                            <template v-else>
                                ≥ {{ classItem.minBirthYear }}
                            </template>
                        </span>
                        <button @click.stop="editClass(classItem)" class="btn-edit-small" :title="$t('tournaments.edit')">✏️</button>
                        <button @click.stop="deleteClass(classItem)" class="trash-btn-small" :title="$t('tournaments.delete')">🗑️</button>
                    </template>
                </div>
            </div>
            <!-- Gemeinsame Eingabefelder für Hinzufügen und Bearbeiten -->
            <div class="add-class" :class="{ 'editing': editingClassId !== null }">
                <input 
                    type="text" 
                    :value="isEditing ? localEditingClassName : localNewClassName" 
                    @input="handleNameInput($event)"
                    :placeholder="$t('tournaments.className')" 
                    class="class-name-input" 
                    @keyup.enter="isEditing ? saveClassEdit(getEditingClassItem()) : addClass()"
                    @keyup.esc="isEditing ? cancelClassEdit() : null"
                    ref="classInput"
                />
                <label class="class-doubles-checkbox" @mousedown.prevent>
                    <input 
                        type="checkbox" 
                        :checked="isEditing ? localEditingClassIsDoubles : localNewClassIsDoubles" 
                        @change="handleDoublesChange($event)"
                        @mousedown.stop 
                    />
                    <span>{{ $t('tournaments.doubles') }}</span>
                </label>
                <select 
                    :value="isEditing ? localEditingClassGender : localNewClassGender" 
                    @change="handleGenderChange($event)"
                    class="class-gender-select"
                    @mousedown.stop
                >
                    <option :value="null">{{ $t('tournaments.genderAll') }}</option>
                    <option value="male">{{ $t('members.genderMale') }}</option>
                    <option value="female">{{ $t('members.genderFemale') }}</option>
                    <option value="mixed">{{ $t('tournaments.genderMixed') }}</option>
                </select>
                <input 
                    type="number" 
                    :value="isEditing ? localEditingClassMaxBirthYear : localNewClassMaxBirthYear" 
                    @input="handleMaxBirthYearInput($event)"
                    :min="currentYear - 18" 
                    :max="currentYear - 6"
                    :placeholder="$t('tournaments.minBirthYear')" 
                    class="class-birth-year-input" 
                    @mousedown.stop
                />
                <button 
                    v-if="isEditing" 
                    @click="saveClassEdit(getEditingClassItem())" 
                    class="btn-save-small" 
                    :title="$t('tournaments.save')"
                >✓</button>
                <button 
                    v-if="isEditing" 
                    @click="cancelClassEdit" 
                    class="btn-cancel-small" 
                    :title="$t('tournaments.cancel')"
                >✕</button>
                <button 
                    v-else 
                    @click="addClass" 
                    class="btn-add"
                >{{ $t('tournaments.addClass') }}</button>
            </div>
        </div>
    </section>
</template>

<script>
export default {
    name: 'TournamentClassList',
    props: {
        tournamentClasses: {
            type: Array,
            required: true
        },
        showClasses: {
            type: Boolean,
            default: false
        },
        editingClassId: {
            type: [Number, null],
            default: null
        },
        editingClassName: {
            type: String,
            default: ''
        },
        editingClassIsDoubles: {
            type: Boolean,
            default: false
        },
        editingClassGender: {
            type: [String, null],
            default: null
        },
        editingClassMaxBirthYear: {
            type: [Number, null],
            default: null
        },
        newClassName: {
            type: String,
            default: ''
        },
        newClassIsDoubles: {
            type: Boolean,
            default: false
        },
        newClassGender: {
            type: [String, null],
            default: null
        },
        newClassMaxBirthYear: {
            type: [Number, null],
            default: null
        }
    },
    emits: [
        'edit-class',
        'save-class-edit',
        'cancel-class-edit',
        'delete-class',
        'add-class',
        'add-class-error',
        'update:newClassName',
        'update:newClassIsDoubles',
        'update:newClassGender',
        'update:editingClassName',
        'update:editingClassIsDoubles',
        'update:editingClassGender',
        'update:editingClassMaxBirthYear',
        'update:newClassMaxBirthYear',
        'handle-class-input-blur'
    ],
    data() {
        return {
            localEditingClassName: '',
            localEditingClassIsDoubles: false,
            localEditingClassGender: null,
            localEditingClassMaxBirthYear: null,
            localNewClassName: '',
            localNewClassIsDoubles: false,
            localNewClassGender: null,
            localNewClassMaxBirthYear: null
        };
    },
    watch: {
        editingClassName(newVal) {
            this.localEditingClassName = newVal;
        },
        editingClassIsDoubles(newVal) {
            this.localEditingClassIsDoubles = newVal;
        },
        editingClassGender(newVal) {
            this.localEditingClassGender = newVal;
        },
        editingClassMaxBirthYear(newVal) {
            this.localEditingClassMaxBirthYear = newVal;
        },
        newClassName(newVal) {
            this.localNewClassName = newVal;
        },
        newClassIsDoubles(newVal) {
            this.localNewClassIsDoubles = newVal;
        },
        newClassGender(newVal) {
            this.localNewClassGender = newVal;
        },
        newClassMaxBirthYear(newVal) {
            this.localNewClassMaxBirthYear = newVal;
        },
        editingClassId(newVal) {
            // Wenn eine neue Klasse zum Bearbeiten ausgewählt wird, aktualisiere die lokalen Werte
            if (newVal !== null) {
                const classItem = this.tournamentClasses.find(c => c.id === newVal);
                if (classItem) {
                    this.localEditingClassName = classItem.name;
                    this.localEditingClassIsDoubles = Boolean(classItem.isDoubles);
                    this.localEditingClassGender = classItem.gender || null;
                    this.localEditingClassMaxBirthYear = classItem.minBirthYear || null;
                }
                // Bearbeitungsmodus: Fokussiere das Eingabefeld
                this.$nextTick(() => {
                    if (this.$refs.classInput) {
                        this.$refs.classInput.focus();
                        this.$refs.classInput.select();
                    }
                });
            } else {
                // Wenn Bearbeitung abgebrochen wird, setze die Werte zurück
                this.localEditingClassName = '';
                this.localEditingClassIsDoubles = false;
                this.localEditingClassGender = null;
                this.localEditingClassMaxBirthYear = null;
                // Felder für Hinzufügen zurücksetzen
                this.localNewClassName = '';
                this.localNewClassIsDoubles = false;
                this.localNewClassGender = null;
                this.localNewClassMaxBirthYear = null;
            }
        }
    },
    computed: {
        currentYear() {
            return new Date().getFullYear();
        },
        isEditing() {
            return this.editingClassId !== null;
        }
    },
    mounted() {
        // Initialisiere lokale Werte aus Props
        this.localEditingClassName = this.editingClassName;
        this.localEditingClassIsDoubles = this.editingClassIsDoubles;
        this.localEditingClassGender = this.editingClassGender;
        this.localEditingClassMaxBirthYear = this.editingClassMaxBirthYear;
        this.localNewClassName = this.newClassName;
        this.localNewClassIsDoubles = this.newClassIsDoubles;
        this.localNewClassGender = this.newClassGender;
        this.localNewClassMaxBirthYear = this.newClassMaxBirthYear;
    },
    methods: {
        editClass(classItem) {
            this.$emit('edit-class', classItem);
        },
        saveClassEdit(classItem) {
            this.$emit('save-class-edit', classItem);
        },
        cancelClassEdit() {
            this.$emit('cancel-class-edit');
        },
        deleteClass(classItem) {
            this.$emit('delete-class', classItem);
        },
        addClass() {
            // Validiere zuerst in der Komponente
            const className = this.localNewClassName;
            
            if (!className || !className.trim()) {
                // Emittiere ein Error-Event, damit der Parent die Fehlermeldung anzeigen kann
                this.$emit('add-class-error', 'Bitte geben Sie einen Klassennamen ein!');
                return;
            }
            
            // Stelle sicher, dass die Werte synchronisiert sind, bevor das Event emittiert wird
            this.$emit('update:newClassName', this.localNewClassName);
            this.$emit('update:newClassIsDoubles', this.localNewClassIsDoubles);
            this.$emit('update:newClassGender', this.localNewClassGender);
            this.$emit('update:newClassMaxBirthYear', this.localNewClassMaxBirthYear);
            
            const data = {
                name: this.localNewClassName,
                isDoubles: this.localNewClassIsDoubles,
                gender: this.localNewClassGender,
                minBirthYear: this.localNewClassMaxBirthYear
            };
            // Emittiere das Event mit den aktuellen Werten als Parameter
            this.$emit('add-class', data);
            
            // Felder zurücksetzen nach dem Hinzufügen
            this.localNewClassName = '';
            this.localNewClassIsDoubles = false;
            this.localNewClassGender = null;
            this.localNewClassMaxBirthYear = null;
        },
        getEditingClassItem() {
            return this.tournamentClasses.find(c => c.id === this.editingClassId);
        },
        handleNameInput(event) {
            const value = event.target.value;
            if (this.isEditing) {
                this.localEditingClassName = value;
                this.$emit('update:editingClassName', value);
            } else {
                this.localNewClassName = value;
                this.$emit('update:newClassName', value);
            }
        },
        handleDoublesChange(event) {
            const checked = event.target.checked;
            if (this.isEditing) {
                this.localEditingClassIsDoubles = checked;
                this.$emit('update:editingClassIsDoubles', checked);
            } else {
                this.localNewClassIsDoubles = checked;
                this.$emit('update:newClassIsDoubles', checked);
            }
        },
        handleGenderChange(event) {
            const value = event.target.value === 'null' ? null : event.target.value;
            if (this.isEditing) {
                this.localEditingClassGender = value;
                this.$emit('update:editingClassGender', value);
            } else {
                this.localNewClassGender = value;
                this.$emit('update:newClassGender', value);
            }
        },
        handleMaxBirthYearInput(event) {
            const value = event.target.value ? parseInt(event.target.value) : null;
            if (this.isEditing) {
                this.localEditingClassMaxBirthYear = value;
                this.$emit('update:editingClassMaxBirthYear', value);
            } else {
                this.localNewClassMaxBirthYear = value;
                this.$emit('update:newClassMaxBirthYear', value);
            }
        },
        handleClassInputBlur(event, classItem) {
            this.$emit('handle-class-input-blur', event, classItem);
        }
    }
};
</script>

<style scoped>
.class-type-inline {
    color: #4caf50;
    font-size: 0.75em;
    margin-left: 0.3rem;
    font-weight: 500;
}

.class-birth-year-input {
    padding: 0.4rem;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 0.9em;
    min-width: 120px;
    background-color: white;
}

.class-birth-year-badge {
    display: inline-block;
    padding: 0.2rem 0.5rem;
    border-radius: 4px;
    font-size: 0.85em;
    margin-left: 0.5rem;
    background-color: #e3f2fd;
    color: #1976d2;
    font-weight: 500;
}

.add-class.editing {
    background-color: #fff3cd;
    padding: 0.75rem;
    border-radius: 4px;
    border: 1px solid #ffc107;
}
</style>

