<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>MoonDuck - Das Original!</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        @keyframes twinkle {
            0%, 100% { opacity: 0; }
            50% { opacity: 1; }
        }

        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
        }

        @keyframes walking {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-5px) rotate(-5deg); }
        }

        .star {
            position: absolute;
            background: white;
            border-radius: 50%;
            animation: twinkle 3s infinite;
        }

        .floating-duck {
            animation: float 3s infinite ease-in-out;
        }

        .walking-duck {
            animation: walking 1s infinite ease-in-out;
        }

        .glass-effect {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        /* Achievement Styles */
        .achievement-popup {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 15px;
            border-radius: 10px;
            z-index: 1000;
            transform: translateX(120%);
            transition: transform 0.5s ease;
            max-width: 90%;
        }

        .achievement-popup.show {
            transform: translateX(0);
        }

        #duck {
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            transition: transform 0.2s ease;
        }

        .pet-count {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 0.8rem;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            padding: 2px 8px;
            border-radius: 12px;
            white-space: nowrap;
            z-index: 1000;
        }

        .love-particle {
            position: absolute;
            font-size: 1.5rem;
            pointer-events: none;
            animation: float 1s ease-out forwards;
            opacity: 1;
        }

        .day-theme { 
            background: linear-gradient(to bottom right, #1a365d, #2c5282); 
        }
        .night-theme { 
            background: linear-gradient(to bottom right, #000428, #004e92); 
        }
        .sunset-theme { 
            background: linear-gradient(to bottom right, #1a365d, #742a2a); 
        }
        .sunrise-theme { 
            background: linear-gradient(to bottom right, #1a365d, #2b6cb0); 
        }

        /* Wetter-Effekte */
        .rain-drop {
            position: absolute;
            top: -10px;
            width: 2px;
            height: 10px;
            background: blue;
            opacity: 0.5;
            animation: rain-fall 1s linear infinite;
        }

        @keyframes rain-fall {
            to {
                transform: translateY(100vh);
                opacity: 0;
            }
        }

        .snow-flake {
            position: absolute;
            top: -10px;
            font-size: 1rem;
            animation: snow-fall 5s linear infinite;
        }

        @keyframes snow-fall {
            to {
                transform: translateY(100vh) translateX(var(--wind-offset));
                opacity: 0;
            }
        }

        /* Erweiterte Statistiken Styles */
        .extended-stat {
            text-align: center;
            color: rgb(147, 197, 253);
        }

        /* Modale Anpassungen */
        @media (max-width: 640px) {
            .achievement-popup {
                right: 10px;
                bottom: 10px;
                padding: 10px;
            }
        }
    </style>
</head>
<body class="night-theme min-h-screen text-gray-100 p-4" id="mainBody">
    <!-- Sternenhintergrund -->
    <div id="stars" class="fixed top-0 left-0 w-full h-full -z-10"></div>

    <!-- Achievement Container -->
    <div id="achievementContainer"></div>

    <div class="max-w-4xl mx-auto">
        <h1 class="text-4xl md:text-5xl lg:text-6xl font-bold text-center mb-8 text-transparent bg-clip-text bg-gradient-to-r from-purple-400 via-blue-300 to-indigo-400">
            🌙 MoonDuck 🦆
        </h1>
        
        <!-- Wetter-Effekte Container -->
        <div class="weather-container" id="weatherContainer"></div>
        
        <!-- Enten-Container -->
        <div class="glass-effect rounded-xl p-4 mb-6 relative h-48 md:h-64 lg:h-80 overflow-hidden">
            <div class="absolute inset-0 bg-gradient-to-b from-[#1a237e]/30 to-[#0d47a1]/30"></div>
            <div id="duckFamily" class="relative w-full h-full">
                <div id="duck" class="floating-duck absolute text-5xl md:text-6xl lg:text-7xl transition-all duration-1000 cursor-pointer">🦆</div>
                <!-- Baby-Enten werden hier dynamisch eingefügt -->
            </div>
        </div>

        <!-- Anpassungs-Button -->
        <div class="text-center mb-6">
            <button id="customizeButton" 
                    class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 md:py-3 md:px-6 lg:py-4 lg:px-8 rounded">
                Enten anpassen 🎨
            </button>
        </div>

        <!-- Personalisierung Panel -->
        <div id="customizationPanel" class="duck-customization hidden mb-6">
            <div class="text-center mb-2 text-lg md:text-xl">Enten-Skins</div>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
                <div class="duck-skin cursor-pointer p-2 bg-gray-800 rounded flex items-center justify-center" onclick="changeDuckSkin('🦆')">🦆 Klassisch</div>
                <div class="duck-skin cursor-pointer p-2 bg-gray-800 rounded flex items-center justify-center" onclick="changeDuckSkin('🦢')">🦢 Schwan</div>
                <div class="duck-skin cursor-pointer p-2 bg-gray-800 rounded flex items-center justify-center" onclick="changeDuckSkin('🐧')">🐧 Pinguin</div>
            </div>
        </div>

        <!-- Status & Timer -->
        <div class="glass-effect rounded-xl p-4 mb-6">
            <div id="walkStatus" class="text-center text-xl md:text-2xl font-semibold mb-2">
                Status wird geladen...
            </div>
            <div id="timer" class="text-center text-lg md:text-xl text-blue-300">
                Prüfe Boost-Verfügbarkeit...
            </div>
        </div>

        <!-- Button -->
        <button onclick="boostDuck()" id="boostButton" 
                class="w-full mb-6 bg-blue-500 hover:bg-blue-600 disabled:bg-gray-500 
                       disabled:cursor-not-allowed transition-all duration-300 text-white 
                       font-bold py-3 px-6 md:py-4 md:px-8 lg:py-5 lg:px-10 rounded-xl transform hover:scale-105 active:scale-95"
                disabled>
            Ente anschieben! 🚀
        </button>

        <!-- Erweiterte Statistiken -->
        <div class="glass-effect rounded-xl p-6 mb-6">
            <h2 class="text-2xl md:text-3xl font-bold mb-4 text-center">Statistiken</h2>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <div class="text-center">
                    <div class="text-3xl md:text-4xl font-bold text-blue-300" id="totalDistance">0</div>
                    <div class="text-sm md:text-base text-gray-300">Meter zurückgelegt</div>
                </div>
                <div class="text-center">
                    <div class="text-3xl md:text-4xl font-bold text-blue-300" id="totalBoosts">0</div>
                    <div class="text-sm md:text-base text-gray-300">Anschübe insgesamt</div>
                </div>
                <!-- Hinzugefügte erweiterte Statistiken -->
                <div class="text-center">
                    <div class="text-3xl md:text-4xl font-bold text-blue-300" id="avgDistance">0</div>
                    <div class="text-sm md:text-base text-gray-300">Durchschnittliche Distanz pro Boost</div>
                </div>
                <div class="text-center">
                    <div class="text-3xl md:text-4xl font-bold text-blue-300" id="maxBoostsDay">0</div>
                    <div class="text-sm md:text-base text-gray-300">Maximale Boosts pro Tag</div>
                </div>
                <div class="text-center">
                    <div class="text-3xl md:text-4xl font-bold text-blue-300" id="totalTime">0h</div>
                    <div class="text-sm md:text-base text-gray-300">Gesamtlaufzeit</div>
                </div>
            </div>
        </div>

        <!-- Enten-Fakten -->
        <div class="glass-effect rounded-xl p-6 mb-6">
            <h3 class="text-2xl md:text-3xl font-semibold mb-4 text-center">Wusstest du schon?</h3>
            <p id="duckFact" class="text-lg md:text-xl text-center text-gray-200 transition-opacity duration-500"></p>
        </div>

        <!-- Achievements Modal -->
        <div id="achievementsModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50">
            <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 
                        w-11/12 max-w-2xl glass-effect rounded-xl p-6 sm:p-8 lg:p-10">
                <h2 class="text-2xl md:text-3xl font-bold mb-4">Achievements 🏆</h2>
                <div id="achievementsList" class="grid grid-cols-1 sm:grid-cols-2 gap-4 max-h-[60vh] overflow-y-auto"></div>
                <button onclick="closeAchievements()" 
                        class="mt-4 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">
                    Schließen
                </button>
            </div>
        </div>
    </div>

    <!-- Floating Buttons -->
    <button id="showAchievements" 
            class="fixed bottom-4 right-4 bg-blue-500 hover:bg-blue-600 text-white p-3 md:p-4 lg:p-5 rounded-full shadow-lg transform hover:scale-110 transition-all">
        🏆
    </button>

    <script>
        // Globale Variable für stats
        let stats = {};

        // Basis-Konfiguration
        let userId = localStorage.getItem('userId') || 'user_' + Math.random().toString(36).substr(2, 9);
        localStorage.setItem('userId', userId);
        let petCount = parseInt(localStorage.getItem('duckPetCount') || '0');

        // Enten-Fakten
        const duckFacts = [
            "Enten haben eine eingebaute Taucherbrille - eine spezielle Nickhaut schützt ihre Augen unter Wasser",
            "Eine Ente schläft mit einer Gehirnhälfte, während die andere wach bleibt",
            "Entenbabys können direkt nach dem Schlüpfen schwimmen und tauchen",
            "Das Gefieder von Enten enthält eine natürliche Fettschicht, die es wasserabweisend macht",
            "Enten haben keine Nerven oder Blutgefäße in ihren Füßen, deswegen frieren sie im Winter nicht",
            "Eine Ente kann bis zu 25 Jahre alt werden",
            "Enten haben einen exzellenten Orientierungssinn dank eines eingebauten Kompasses",
            "Stockenten können bis zu 100 km/h im Flug erreichen",
            "Enten verbringen bis zu 6 Stunden am Tag mit der Gefiederpflege",
            "Enten können ihren Hals um 180 Grad drehen",
            "Die Körpertemperatur einer Ente liegt bei etwa 41°C",
            "Baby-Enten prägen sich die Stimme ihrer Mutter schon vor dem Schlüpfen ein",
            "Eine Ente hat etwa 12.000 Federn",
            "Enten können bis zu 6 Meter tief tauchen"
        ];

        function showRandomDuckFact() {
            const factElement = document.getElementById('duckFact');
            factElement.style.opacity = '0';
            
            setTimeout(() => {
                const randomFact = duckFacts[Math.floor(Math.random() * duckFacts.length)];
                factElement.textContent = randomFact;
                factElement.style.opacity = '1';
            }, 500);
        }

        const achievements = {
            firstPet: { id: 'firstPet', title: 'Erster Kontakt', description: 'Streichle die Ente zum ersten Mal', icon: '🤝', unlocked: false, unlockedAt: null },
            tenPets: { id: 'tenPets', title: 'Enten-Freund', description: 'Streichle die Ente 10 Mal', icon: '💝', unlocked: false, unlockedAt: null },
            hundredMeters: { id: 'hundredMeters', title: 'Marathon-Ente', description: '100 Meter zurückgelegt', icon: '🏃', unlocked: false, unlockedAt: null },
            nightOwl: { id: 'nightOwl', title: 'Nachteule', description: 'Boost zwischen 22-6 Uhr', icon: '🌙', unlocked: false, unlockedAt: null },
            weekendWarrior: { 
                id: 'weekendWarrior', 
                title: 'Weekend Warrior', 
                description: 'Boost am Wochenende', 
                icon: '🎉', 
                unlocked: false, 
                unlockedAt: null 
            },
            weatherMaster: { 
                id: 'weatherMaster', 
                title: 'Wetterfest', 
                description: 'Boost bei jedem Wetter', 
                icon: '🌈', 
                unlocked: false, 
                unlockedAt: null 
            },
            duckFamily: { 
                id: 'duckFamily', 
                title: 'Entenfamilie', 
                description: 'Erste Baby-Ente erscheint', 
                icon: '👨‍👩‍👦', 
                unlocked: false, 
                unlockedAt: null 
            },
            customizer: { 
                id: 'customizer', 
                title: 'Stylist', 
                description: 'Ändere den Enten-Skin', 
                icon: '🎨', 
                unlocked: false, 
                unlockedAt: null 
            }
        };

        // Lade gespeicherte Achievements
        const savedAchievements = JSON.parse(localStorage.getItem('achievements') || '{}');
        Object.keys(savedAchievements).forEach(key => {
            if (achievements[key]) {
                achievements[key].unlocked = savedAchievements[key].unlocked;
                achievements[key].unlockedAt = savedAchievements[key].unlockedAt;
            }
        });

        function createStars() {
            const starsContainer = document.getElementById('stars');
            const numberOfStars = 100;
            
            for (let i = 0; i < numberOfStars; i++) {
                const star = document.createElement('div');
                star.className = 'star';
                star.style.width = Math.random() * 3 + 'px';
                star.style.height = star.style.width;
                star.style.left = Math.random() * 100 + '%';
                star.style.top = Math.random() * 100 + '%';
                star.style.animationDelay = Math.random() * 3 + 's';
                starsContainer.appendChild(star);
            }
        }

        function updateDuck(statsData) {
            const duck = document.getElementById('duck');
            
            // Position basierend auf Gesamtdistanz
            const container = duck.parentElement;
            const progress = (statsData.total_distance % 1000) / 1000;
            const position = progress * (container.offsetWidth - 80);
            duck.style.left = `${position}px`;
            
            // Animation basierend auf Status
            if (statsData.is_walking) {
                duck.classList.remove('floating-duck');
                duck.classList.add('walking-duck');
            } else {
                duck.classList.remove('walking-duck');
                duck.classList.add('floating-duck');
            }
        }

        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
        }

        function updatePetCount() {
            const duck = document.getElementById('duck');
            let countElement = duck.querySelector('.pet-count');
            if (petCount > 0) {
                if (!countElement) {
                    countElement = document.createElement('div');
                    countElement.className = 'pet-count';
                    duck.appendChild(countElement);
                }
                countElement.textContent = `${petCount}x gestreichelt`;
            } else if (countElement) {
                countElement.remove();
            }
        }

        function updateUI() {
            $.ajax({
                url: 'controller/duck-stats.php',
                method: 'GET',
                success: function(response) {
                    if(response.success) {
                        stats = response.stats; // Globale Variable setzen
                        
                        // Update Statistiken
                        $('#totalDistance').text(stats.total_distance);
                        $('#totalBoosts').text(stats.total_boosts);
                        
                        // Update Status
                        if (stats.is_walking) {
                            $('#walkStatus').html(`
                                <span class="text-green-400">Die Ente läuft!</span><br>
                                <span class="text-sm">Noch ${formatTime(stats.remaining_walk_time)} Minuten</span>
                            `);
                        } else {
                            $('#walkStatus').text('Die Ente wartet auf einen Anschub!');
                        }
                        
                        // Update Duck animation und Position
                        updateDuck(stats);
                        
                        // Prüfe Achievements
                        checkAchievements();
                        // Update erweiterte Statistiken
                        updateExtendedStats(stats);
                    }
                }
            });

            // Prüfe Boost-Verfügbarkeit
            $.ajax({
                url: 'controller/check-boost.php',
                method: 'POST',
                data: { user_id: userId },
                success: function(response) {
                    if(response.can_boost) {
                        $('#timer').text('Du kannst die Ente anschieben!');
                        $('#boostButton').prop('disabled', false);
                    } else {
                        $('#timer').text(
                            `Nächster Anschub in: ${formatTime(response.next_boost_in)}`
                        );
                        $('#boostButton').prop('disabled', true);
                    }
                }
            });
        }

        function boostDuck() {
            $('#boostButton').prop('disabled', true);
            
            // Audio abspielen
            playBoostSound();
            
            $.ajax({
                url: 'controller/boost-duck.php',
                method: 'POST',
                data: { user_id: userId },
                success: function(response) {
                    console.log('Server Antwort:', response);
                    
                    if(response.success || (response.stats && response.stats.total_boosts)) {
                        $('#walkStatus').html('<span class="text-green-400">Boost erfolgreich!</span>');
                        setTimeout(() => {
                            updateUI();
                        }, 1000);
                    } else {
                        handleBoostError(response);
                    }
                },
                error: function(xhr, status, error) {
                    console.log('XHR Status:', xhr.status);
                    console.log('XHR Response:', xhr.responseText);
                    console.log('Error:', error);
                    
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if(response.stats || response.success) {
                            $('#walkStatus').html('<span class="text-green-400">Boost erfolgreich!</span>');
                            setTimeout(() => {
                                updateUI();
                            }, 1000);
                            return;
                        }
                    } catch(e) {
                        console.log('Parse error:', e);
                    }
                    
                    handleBoostError({
                        error: 'Boost wird verarbeitet...'
                    });
                }
            });
        }

        function handleBoostError(response) {
            $('#walkStatus').html(
                `<span class="text-yellow-400">${response.error || 'Boost wird verarbeitet...'}</span>`
            );
            setTimeout(() => {
                updateUI();
                $('#boostButton').prop('disabled', false);
            }, 2000);
        }

        // Achievement Funktionen
        function showAchievementPopup(achievement) {
            const popup = document.createElement('div');
            popup.className = 'achievement-popup';
            popup.innerHTML = `
                <div class="flex items-center">
                    <span class="text-2xl mr-3">${achievement.icon}</span>
                    <div>
                        <div class="font-bold">${achievement.title}</div>
                        <div class="text-sm">${achievement.description}</div>
                    </div>
                </div>
            `;
            document.getElementById('achievementContainer').appendChild(popup);
            setTimeout(() => popup.classList.add('show'), 100);
            setTimeout(() => {
                popup.classList.remove('show');
                setTimeout(() => popup.remove(), 500);
            }, 3000);
        }

        function unlockAchievement(achievementId) {
            const achievement = achievements[achievementId];
            if (achievement && !achievement.unlocked) {
                achievement.unlocked = true;
                achievement.unlockedAt = new Date().toISOString();
                localStorage.setItem('achievements', JSON.stringify(achievements));
                showAchievementPopup(achievement);
            }
        }

        function checkAchievements() {
            // Erster Kontakt
            if (petCount >= 1 && !achievements.firstPet.unlocked) {
                unlockAchievement('firstPet');
            }

            // Enten-Freund
            if (petCount >= 10 && !achievements.tenPets.unlocked) {
                unlockAchievement('tenPets');
            }

            // Marathon-Ente
            if (stats.total_distance >= 100 && !achievements.hundredMeters.unlocked) {
                unlockAchievement('hundredMeters');
            }

            // Nachteule
            const currentHour = new Date().getHours();
            if ((currentHour >= 22 || currentHour < 6) && !achievements.nightOwl.unlocked) {
                unlockAchievement('nightOwl');
            }

            // Weekend Warrior
            const now = new Date();
            const isWeekend = now.getDay() === 0 || now.getDay() === 6;
            if (isWeekend && !achievements.weekendWarrior.unlocked) {
                unlockAchievement('weekendWarrior');
            }

            // Wetterfest
            if (stats.total_boosts >= 1 && !achievements.weatherMaster.unlocked) {
                unlockAchievement('weatherMaster');
            }

            // Entenfamilie
            if (babyDucks.length > 0 && !achievements.duckFamily.unlocked) {
                unlockAchievement('duckFamily');
            }

            // Stylist
            if (localStorage.getItem('duckSkin') && !achievements.customizer.unlocked) {
                unlockAchievement('customizer');
            }
        }

        function showAchievements() {
            const modal = document.getElementById('achievementsModal');
            const list = document.getElementById('achievementsList');
            list.innerHTML = '';
            
            Object.values(achievements).forEach(achievement => {
                const div = document.createElement('div');
                div.className = `p-4 glass-effect rounded-lg ${achievement.unlocked ? 'text-green-300' : 'text-gray-400'}`;
                div.innerHTML = `
                    <div class="flex items-center">
                        <span class="text-2xl mr-3">${achievement.icon}</span>
                        <div>
                            <div class="font-bold">${achievement.title}</div>
                            <div class="text-sm">${achievement.description}</div>
                            ${achievement.unlocked ? `<div class="text-xs mt-1">Freigeschaltet: ${new Date(achievement.unlockedAt).toLocaleString()}</div>` : ''}
                        </div>
                    </div>
                `;
                list.appendChild(div);
            });
            
            modal.classList.remove('hidden');
        }

        function closeAchievements() {
            document.getElementById('achievementsModal').classList.add('hidden');
        }

        const weatherTypes = {
            CLEAR: 'clear',
            RAIN: 'rain',
            SNOW: 'snow'
        };

        let currentWeather = weatherTypes.CLEAR;
        let weatherParticles = [];

        function setWeather(type) {
            currentWeather = type;
            const container = document.getElementById('weatherContainer');
            container.innerHTML = '';
            weatherParticles = [];

            if (type === weatherTypes.RAIN) {
                for (let i = 0; i < 50; i++) {
                    createRaindrop();
                }
            } else if (type === weatherTypes.SNOW) {
                for (let i = 0; i < 30; i++) {
                    createSnowflake();
                }
            }

            // Ändere Duck-Aussehen basierend auf Wetter
            const duck = document.getElementById('duck');
            if (type === weatherTypes.RAIN) {
                duck.textContent = '☔'; // Ente mit Regenschirm
            } else if (type === weatherTypes.SNOW) {
                duck.textContent = '🧊'; // Winterente
            } else {
                duck.textContent = localStorage.getItem('duckSkin') || '🦆';
            }
        }

        function createRaindrop() {
            const drop = document.createElement('div');
            drop.className = 'rain-drop';
            drop.style.left = Math.random() * 100 + '%';
            drop.style.animationDuration = (0.5 + Math.random() * 0.5) + 's';
            container = document.getElementById('weatherContainer');
            container.appendChild(drop);

            drop.addEventListener('animationend', () => {
                drop.remove();
                if (currentWeather === weatherTypes.RAIN) {
                    createRaindrop();
                }
            });
        }

        function createSnowflake() {
            const flake = document.createElement('div');
            flake.className = 'snow-flake';
            flake.textContent = '❄';
            flake.style.left = Math.random() * 100 + '%';
            flake.style.animationDuration = (3 + Math.random() * 2) + 's';
            flake.style.setProperty('--wind-offset', (Math.random() * 100 - 50) + 'px');
            container = document.getElementById('weatherContainer');
            container.appendChild(flake);

            flake.addEventListener('animationend', () => {
                flake.remove();
                if (currentWeather === weatherTypes.SNOW) {
                    createSnowflake();
                }
            });
        }

        // Entenfamilie-System
        let babyDucks = [];
        const maxBabyDucks = 5;

        function addBabyDuck() {
            if (babyDucks.length >= maxBabyDucks) return;

            const babyDuck = document.createElement('div');
            babyDuck.className = 'baby-duck floating';
            babyDuck.textContent = '🦆';
            babyDuck.style.transform = 'scale(0.6)';
            babyDuck.style.position = 'absolute';
            babyDuck.style.bottom = '10px';
            babyDuck.style.left = '50%';
            babyDuck.style.transition = 'left 0.5s';
            document.getElementById('duckFamily').appendChild(babyDuck);

            babyDucks.push(babyDuck);
            updateBabyDuckPositions();
        }

        function updateBabyDuckPositions() {
            const mainDuck = document.getElementById('duck');
            const mainDuckRect = mainDuck.getBoundingClientRect();
            
            babyDucks.forEach((baby, index) => {
                const offset = 40 * (index + 1);
                baby.style.left = `calc(50% - ${offset}px)`;
                baby.style.top = '60%';
            });
        }

        // Personalisierung
        function changeDuckSkin(skin) {
            localStorage.setItem('duckSkin', skin);
            if (currentWeather === weatherTypes.CLEAR) {
                document.getElementById('duck').textContent = skin;
            }
            unlockAchievement('customizer');
        }

        function toggleCustomization() {
            const panel = document.getElementById('customizationPanel');
            panel.classList.toggle('hidden');
        }

        // Erweiterte Statistiken
        function updateExtendedStats(stats) {
            // Durchschnittliche Distanz pro Boost
            const avgDist = stats.total_distance / stats.total_boosts || 0;
            document.getElementById('avgDistance').textContent = avgDist.toFixed(1);
            // Maximale Boosts pro Tag berechnen
            const maxBoosts = Math.max(stats.boosts_today || 0, parseInt(localStorage.getItem('maxBoostsDay') || '0'));
            if (stats.boosts_today > maxBoosts) {
                localStorage.setItem('maxBoostsDay', stats.boosts_today);
                document.getElementById('maxBoostsDay').textContent = stats.boosts_today;
            }
            // Gesamtlaufzeit
            const totalHours = (stats.total_walk_time || 0) / 3600;
            document.getElementById('totalTime').textContent = totalHours.toFixed(1) + 'h';
        }

        // Event-basierte Features
        function checkForSpecialEvents() {
            const now = new Date();
            const isWeekend = now.getDay() === 0 || now.getDay() === 6;
            const isNightTime = now.getHours() >= 22 || now.getHours() < 6;

            if (isWeekend && !achievements.weekendWarrior.unlocked) {
                unlockAchievement('weekendWarrior');
            }

            if (isNightTime && !achievements.nightOwl.unlocked) {
                setWeather(weatherTypes.CLEAR);
                document.getElementById('duck').textContent = '😴';
            }
        }

        // Erweiterte Initialisierung und Updates
        function extendedInit() {
            // Lade gespeicherten Skin
            const savedSkin = localStorage.getItem('duckSkin');
            if (savedSkin) {
                document.getElementById('duck').textContent = savedSkin;
            }

            // Wetter-System starten
            setWeather(weatherTypes.CLEAR);

            // Zufälliges Wetter alle 5 Minuten
            setInterval(() => {
                const random = Math.random();
                if (random < 0.7) {
                    setWeather(weatherTypes.CLEAR);
                } else if (random < 0.85) {
                    setWeather(weatherTypes.RAIN);
                } else {
                    setWeather(weatherTypes.SNOW);
                }
            }, 300000);

            // Baby-Enten Check (nach UpdateUI)
            if (stats.total_distance > 1000 && babyDucks.length === 0) {
                addBabyDuck();
            }
            if (stats.total_distance > 2000 && babyDucks.length === 1) {
                addBabyDuck();
            }
            // Weitere Baby-Enten bei höheren Meilensteinen
        }

        // Erweiterte Update-Funktion
        function extendedUpdate() {
            updateExtendedStats(stats);
            checkForSpecialEvents();
            updateBabyDuckPositions();
        }

        // Event Listeners für neue Features
        document.getElementById('customizeButton').addEventListener('click', toggleCustomization);

        // Initialisierung erweitern
        const originalInit = window.onload;
        window.onload = function() {
            if (originalInit) originalInit();
            extendedInit();
        };

        // Update-Intervall erweitern
        setInterval(extendedUpdate, 5000);        // Wetter-System

        // Event Listeners
        document.getElementById('showAchievements').addEventListener('click', showAchievements);
        document.getElementById('duck').addEventListener('click', petDuck);
        
        // Initialisierung
        let lastPetTime = 0;
        createStars();
        updateUI();
        updatePetCount();
        updateDayNightCycle();
        showRandomDuckFact();
        
        // Automatische Updates
        setInterval(updateUI, 5000);
        setInterval(updateDayNightCycle, 60000); // Prüft jede Minute die Tageszeit
        setInterval(showRandomDuckFact, 12000); // Neue Fakten alle 12 Sekunden
        
        // Responsive Updates
        window.addEventListener('resize', updateUI);

        // Tag/Nacht System
        function updateDayNightCycle() {
            const hour = new Date().getHours();
            const mainBody = document.getElementById('mainBody');
            
            if (hour >= 6 && hour < 8) { // Sonnenaufgang
                mainBody.className = 'min-h-screen text-gray-100 p-4 sunrise-theme';
            } else if (hour >= 8 && hour < 18) { // Tag
                mainBody.className = 'min-h-screen text-gray-100 p-4 day-theme';
            } else if (hour >= 18 && hour < 20) { // Sonnenuntergang
                mainBody.className = 'min-h-screen text-gray-100 p-4 sunset-theme';
            } else { // Nacht
                mainBody.className = 'min-h-screen text-gray-100 p-4 night-theme';
            }
        }

        // Funktion zum Abspielen des Boost-Sounds
        function playBoostSound() {
            const audio = new Audio('assets/quack.mp3');
            audio.volume = 0.05;
            audio.play().catch(error => {
                console.error('Audio-Fehler:', error);
            });
        }

        // Implementierung der petDuck-Funktion (einzige Definition)
        function petDuck(event) {
            const now = Date.now();
            if (now - lastPetTime < 500) return; // Vermeidet zu schnelles Streicheln
            lastPetTime = now;
            
            petCount++;
            localStorage.setItem('duckPetCount', petCount);
            updatePetCount();

            // Sofortige Überprüfung der Achievements nach dem Streicheln
            checkAchievements();

            const duck = document.getElementById('duck');
            const heart = document.createElement('div');
            heart.className = 'love-particle';
            heart.textContent = '❤️';
            heart.style.left = (event.clientX - duck.getBoundingClientRect().left) + 'px';
            heart.style.top = (event.clientY - duck.getBoundingClientRect().top) + 'px';
            
            duck.parentElement.appendChild(heart);
            setTimeout(() => {
                heart.style.transform = 'translateY(-50px)';
                heart.style.opacity = '0';
            }, 50);
            setTimeout(() => heart.remove(), 1000);
        }
    </script>
</body>
</html>
