// Interactive Pet Feature - Theme-based Pets
document.addEventListener('DOMContentLoaded', function() {
    'use strict';

    // Get current theme
    function getCurrentTheme() {
        return localStorage.getItem('theme') || 'green';
    }

    // Pet sprites (detailed pixelated SVG matching provided images)
    const petSprites = {
        // Green Frog - detailed pixelated
        green: `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cg%3E%3Crect x='12' y='32' width='40' height='16' fill='%23a4d65e'/%3E%3Crect x='8' y='36' width='4' height='8' fill='%23a4d65e'/%3E%3Crect x='52' y='36' width='4' height='8' fill='%23a4d65e'/%3E%3Crect x='16' y='24' width='12' height='8' fill='%23a4d65e'/%3E%3Crect x='36' y='24' width='12' height='8' fill='%23a4d65e'/%3E%3Crect x='20' y='28' width='4' height='4' fill='%23fff'/%3E%3Crect x='40' y='28' width='4' height='4' fill='%23fff'/%3E%3Crect x='22' y='30' width='2' height='2' fill='%23000'/%3E%3Crect x='42' y='30' width='2' height='2' fill='%23000'/%3E%3Crect x='28' y='40' width='8' height='2' fill='%2388aa44'/%3E%3Crect x='20' y='40' width='24' height='8' fill='%23d4e896'/%3E%3Crect x='8' y='48' width='8' height='4' fill='%23a4d65e'/%3E%3Crect x='48' y='48' width='8' height='4' fill='%23a4d65e'/%3E%3Crect x='16' y='48' width='8' height='8' fill='%2388aa44'/%3E%3Crect x='40' y='48' width='8' height='8' fill='%2388aa44'/%3E%3C/g%3E%3C/svg%3E`,

        // Pink Pig - detailed pixelated
        pink: `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cg%3E%3Crect x='16' y='24' width='32' height='24' fill='%23ffb3d9'/%3E%3Crect x='12' y='28' width='4' height='16' fill='%23ffb3d9'/%3E%3Crect x='48' y='28' width='4' height='16' fill='%23ffb3d9'/%3E%3Crect x='20' y='16' width='8' height='8' fill='%23ffb3d9'/%3E%3Crect x='36' y='16' width='8' height='8' fill='%23ffb3d9'/%3E%3Crect x='22' y='18' width='4' height='4' fill='%23ff9ec7'/%3E%3Crect x='38' y='18' width='4' height='4' fill='%23ff9ec7'/%3E%3Crect x='24' y='32' width='4' height='4' fill='%23000'/%3E%3Crect x='36' y='32' width='4' height='4' fill='%23000'/%3E%3Crect x='24' y='40' width='16' height='4' fill='%23ff69b4'/%3E%3Crect x='28' y='44' width='8' height='2' fill='%23ff69b4'/%3E%3Crect x='30' y='46' width='4' height='2' fill='%23ff69b4'/%3E%3Crect x='16' y='48' width='8' height='8' fill='%23ffb3d9'/%3E%3Crect x='40' y='48' width='8' height='8' fill='%23ffb3d9'/%3E%3Crect x='32' y='20' width='4' height='4' fill='%23ff69b4'/%3E%3C/g%3E%3C/svg%3E`,

        // Blue Axolotl - with frills
        blue: `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cg%3E%3Crect x='16' y='28' width='32' height='16' fill='%2387ceeb'/%3E%3Crect x='12' y='32' width='4' height='8' fill='%2387ceeb'/%3E%3Crect x='48' y='32' width='4' height='8' fill='%2387ceeb'/%3E%3Crect x='8' y='24' width='12' height='4' fill='%235f9ed1'/%3E%3Crect x='44' y='24' width='12' height='4' fill='%235f9ed1'/%3E%3Crect x='4' y='20' width='8' height='4' fill='%235f9ed1'/%3E%3Crect x='52' y='20' width='8' height='4' fill='%235f9ed1'/%3E%3Crect x='6' y='16' width='6' height='4' fill='%235f9ed1'/%3E%3Crect x='52' y='16' width='6' height='4' fill='%235f9ed1'/%3E%3Crect x='20' y='32' width='4' height='4' fill='%23000'/%3E%3Crect x='40' y='32' width='4' height='4' fill='%23000'/%3E%3Crect x='22' y='34' width='2' height='2' fill='%23fff'/%3E%3Crect x='42' y='34' width='2' height='2' fill='%23fff'/%3E%3Crect x='28' y='38' width='8' height='2' fill='%23000'/%3E%3Crect x='16' y='44' width='32' height='4' fill='%2387ceeb'/%3E%3Crect x='12' y='40' width='4' height='4' fill='%2387ceeb'/%3E%3Crect x='48' y='40' width='4' height='4' fill='%2387ceeb'/%3E%3Crect x='20' y='48' width='8' height='4' fill='%235f9ed1'/%3E%3Crect x='36' y='48' width='8' height='4' fill='%235f9ed1'/%3E%3C/g%3E%3C/svg%3E`,

        // Red Larva - with antennae
        red: `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cg%3E%3Crect x='24' y='16' width='16' height='32' fill='%23ff6b6b'/%3E%3Crect x='20' y='20' width='4' height='24' fill='%23ff6b6b'/%3E%3Crect x='40' y='20' width='4' height='24' fill='%23ff6b6b'/%3E%3Crect x='16' y='12' width='8' height='4' fill='%23ff4444'/%3E%3Crect x='40' y='12' width='8' height='4' fill='%23ff4444'/%3E%3Crect x='20' y='8' width='4' height='4' fill='%23ff4444'/%3E%3Crect x='40' y='8' width='4' height='4' fill='%23ff4444'/%3E%3Crect x='18' y='4' width='4' height='4' fill='%23ff4444'/%3E%3Crect x='42' y='4' width='4' height='4' fill='%23ff4444'/%3E%3Crect x='28' y='24' width='4' height='4' fill='%23000'/%3E%3Crect x='32' y='24' width='4' height='4' fill='%23000'/%3E%3Crect x='28' y='32' width='8' height='2' fill='%23000'/%3E%3Crect x='24' y='48' width='16' height='4' fill='%23ff6b6b'/%3E%3Crect x='22' y='44' width='4' height='4' fill='%23ff6b6b'/%3E%3Crect x='38' y='44' width='4' height='4' fill='%23ff6b6b'/%3E%3Crect x='26' y='36' width='12' height='8' fill='%23ff9999'/%3E%3C/g%3E%3C/svg%3E`
    };

    // Pet names
    const petNames = {
        green: 'Frog',
        pink: 'Pig',
        blue: 'Axolotl',
        red: 'Larva'
    };

    // Pet emojis
    const petEmojis = {
        green: '🐸',
        pink: '🐷',
        blue: '🦎',
        red: '🐛'
    };

    // Positive messages for the pet
    const positiveMessages = [
        "You're doing great! 💪",
        "Keep coding! 🚀",
        "You got this! ⭐",
        "Awesome work! 🎉",
        "Don't give up! 💯",
        "You're amazing! ✨",
        "Keep learning! 📚",
        "Great job! 👏",
        "Stay focused! 🎯",
        "You're a star! 🌟",
        "Believe in yourself! 💖",
        "Keep pushing! 🔥",
        "You're brilliant! 🧠",
        "Never stop learning! 📖",
        "You can do it! 💪",
        "Success is near! 🏆",
        "Stay positive! 😊",
        "Keep going! 🎊",
        "You're unstoppable! 🚀",
        "Dream big! 🌈"
    ];

    // Pet settings
    const petSettings = {
        enabled: localStorage.getItem('petEnabled') !== 'false',
        speed: 0.8,
        idleTime: 2000,
        walkTime: 6000,
        messageInterval: 10000 // Show message every 10 seconds
    };

    let pet, petX, petRotation;
    let isWalking = false;
    let isDragging = false;
    let dragOffsetX;
    let direction = 1;
    let currentTheme = getCurrentTheme();

    // Create pet element
    function createPet() {
        if (!petSettings.enabled) return;

        const theme = getCurrentTheme();

        pet = document.createElement('div');
        pet.className = 'interactive-pet';
        pet.setAttribute('data-pet-theme', theme);
        pet.innerHTML = `
            <div class="pet-body">
                <img src="${petSprites[theme]}" alt="${petNames[theme]} Pet" class="pet-sprite">
                <div class="pet-shadow"></div>
                <div class="pet-speech-bubble" id="pet-speech"></div>
            </div>
        `;
        document.body.appendChild(pet);

        petX = Math.random() * (window.innerWidth - 100);
        petRotation = 0;
        updatePetPosition();

        pet.addEventListener('mousedown', startDrag);
        pet.addEventListener('click', petClick);
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', endDrag);

        pet.addEventListener('touchstart', startDragTouch);
        document.addEventListener('touchmove', dragTouch);
        document.addEventListener('touchend', endDrag);

        startPetBehavior();
    }

    function updatePetPosition() {
        if (pet) {
            pet.style.left = petX + 'px';
            pet.style.bottom = '20px';
            pet.style.transform = `rotate(${petRotation}deg)`;
        }
    }

    function startPetBehavior() {
        setInterval(() => {
            if (!isDragging && !isWalking) {
                if (Math.random() > 0.3) {
                    startWalking();
                } else {
                    doIdle();
                }
            }
        }, petSettings.idleTime);

        function animate() {
            if (isWalking && !isDragging) {
                movePet();
            }
            requestAnimationFrame(animate);
        }
        animate();
    }

    function startWalking() {
        isWalking = true;
        pet.classList.add('walking');

        direction = Math.random() > 0.5 ? 1 : -1;

        if (direction < 0) {
            petRotation = -15;
        } else {
            petRotation = 15;
        }

        updatePetPosition();

        setTimeout(() => {
            stopWalking();
        }, petSettings.walkTime);
    }

    function stopWalking() {
        isWalking = false;
        pet.classList.remove('walking');
        petRotation = 0;
        updatePetPosition();
    }

    function doIdle() {
        pet.classList.remove('walking');

        const idles = ['bounce', 'blink'];
        const randomIdle = idles[Math.floor(Math.random() * idles.length)];

        pet.classList.add(randomIdle);
        setTimeout(() => {
            pet.classList.remove(randomIdle);
        }, 800);
    }

    function movePet() {
        petX += petSettings.speed * direction;

        const maxX = window.innerWidth - 100;

        if (petX < -80) {
            petX = maxX;
        }
        if (petX > maxX) {
            petX = -80;
        }

        updatePetPosition();
    }

    function startDrag(e) {
        e.preventDefault();
        isDragging = true;
        isWalking = false;
        pet.classList.remove('walking');
        pet.classList.add('dragging');

        const rect = pet.getBoundingClientRect();
        dragOffsetX = e.clientX - rect.left;
    }

    function drag(e) {
        if (isDragging) {
            petX = e.clientX - dragOffsetX;
            updatePetPosition();
        }
    }

    function endDrag() {
        if (isDragging) {
            isDragging = false;
            pet.classList.remove('dragging');
            petRotation = 0;
            updatePetPosition();
        }
    }

    function startDragTouch(e) {
        const touch = e.touches[0];
        isDragging = true;
        isWalking = false;
        pet.classList.remove('walking');
        pet.classList.add('dragging');

        const rect = pet.getBoundingClientRect();
        dragOffsetX = touch.clientX - rect.left;
    }

    function dragTouch(e) {
        if (isDragging) {
            const touch = e.touches[0];
            petX = touch.clientX - dragOffsetX;
            updatePetPosition();
        }
    }

    function petClick(e) {
        if (!isDragging) {
            e.stopPropagation();

            pet.classList.add('jump');

            setTimeout(() => {
                pet.classList.remove('jump');
            }, 600);

            // Show random message when clicked
            showRandomMessage();
        }
    }

    function showRandomMessage() {
        const speechBubble = document.getElementById('pet-speech');
        if (!speechBubble) return;

        // Get random message
        const randomMsg = positiveMessages[Math.floor(Math.random() * positiveMessages.length)];

        // Show message
        speechBubble.textContent = randomMsg;
        speechBubble.classList.add('show');

        // Hide after 3 seconds
        setTimeout(() => {
            speechBubble.classList.remove('show');
        }, 3000);
    }

    // Show random messages periodically
    function startRandomMessages() {
        setInterval(() => {
            if (petSettings.enabled && !isDragging) {
                showRandomMessage();
            }
        }, petSettings.messageInterval);
    }

    window.togglePet = function() {
        petSettings.enabled = !petSettings.enabled;
        localStorage.setItem('petEnabled', petSettings.enabled);

        if (petSettings.enabled) {
            createPet();
            updateControlButton();
        } else {
            if (pet) {
                pet.remove();
                pet = null;
            }
            updateControlButton();
        }
    };

    function updateControlButton() {
        const btn = document.querySelector('.pet-control-btn');
        if (btn) {
            const theme = getCurrentTheme();
            btn.innerHTML = petSettings.enabled ? petEmojis[theme] : '🚫';
            btn.title = `Toggle ${petNames[theme]} Pet`;
        }
    }

    function createPetControl() {
        const theme = getCurrentTheme();
        const controlBtn = document.createElement('button');
        controlBtn.className = 'pet-control-btn';
        controlBtn.innerHTML = petSettings.enabled ? petEmojis[theme] : '🚫';
        controlBtn.title = `Toggle ${petNames[theme]} Pet`;
        controlBtn.onclick = function() {
            togglePet();
        };
        document.body.appendChild(controlBtn);
    }

    // Theme change detection
    function handleThemeChange() {
        const newTheme = getCurrentTheme();
        if (newTheme !== currentTheme) {
            currentTheme = newTheme;

            if (pet) {
                pet.remove();
                pet = null;
            }

            if (petSettings.enabled) {
                createPet();
            }

            updateControlButton();
        }
    }

    // Listen for theme changes via custom event
    window.addEventListener('themeChanged', handleThemeChange);

    // Also check periodically
    setInterval(handleThemeChange, 1000);

    createPet();
    createPetControl();
    startRandomMessages();
});
