/**
 * Valentine's Day Web App - Main JavaScript
 */

// ============================================
// UTILITY FUNCTIONS
// ============================================

/**
 * Create floating heart animation
 */
function createHeart() {
    const container = document.querySelector('.hearts-container');
    if (!container) return;

    const heart = document.createElement('div');
    heart.className = 'heart';
    heart.innerHTML = '❤️';
    
    const startX = Math.random() * window.innerWidth;
    heart.style.left = startX + 'px';
    heart.style.top = window.innerHeight + 'px';
    heart.style.fontSize = (Math.random() * 1.5 + 1) + 'rem';
    heart.style.animationDuration = (Math.random() * 3 + 4) + 's';
    heart.style.animationDelay = Math.random() * 0.5 + 's';
    
    container.appendChild(heart);
    
    setTimeout(() => heart.remove(), 8000);
}

/**
 * Create falling particle effect
 */
function createParticles(x, y, count = 5) {
    for (let i = 0; i < count; i++) {
        const particle = document.createElement('div');
        particle.className = 'heart';
        particle.innerHTML = '✨';
        particle.style.left = x + 'px';
        particle.style.top = y + 'px';
        particle.style.position = 'fixed';
        particle.style.fontSize = '1.2rem';
        
        const angle = (i / count) * Math.PI * 2;
        const velocity = 3;
        const tx = Math.cos(angle) * velocity * 100;
        const ty = Math.sin(angle) * velocity * 100;
        
        particle.style.setProperty('--tx', tx + 'px');
        particle.style.setProperty('--ty', ty + 'px');
        particle.style.animation = 'particleFloat 1.5s ease-out forwards';
        
        document.body.appendChild(particle);
        
        setTimeout(() => particle.remove(), 1500);
    }
}

/**
 * Smooth page transition
 */
function transitionToPage(url) {
    const page = document.querySelector('.page');
    if (page) {
        page.classList.add('fade-out');
        setTimeout(() => {
            window.location.href = url;
        }, 500);
    } else {
        window.location.href = url;
    }
}

/**
 * Play sound (if audio element exists)
 */
function playSound(audioId) {
    const audio = document.getElementById(audioId);
    if (audio) {
        audio.play().catch(e => console.log('Audio play prevented:', e));
    }
}

/**
 * Detect if user is on mobile
 */
function isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

/**
 * Add heart cursor trail effect
 */
function initHeartCursorTrail() {
    if (isMobile()) return; // Skip on mobile
    
    let mouseX = 0;
    let mouseY = 0;
    
    document.addEventListener('mousemove', (e) => {
        mouseX = e.clientX;
        mouseY = e.clientY;
    });
    
    setInterval(() => {
        if (Math.random() > 0.7) {
            const trail = document.createElement('span');
            trail.innerHTML = '❤️';
            trail.style.position = 'fixed';
            trail.style.left = mouseX + 'px';
            trail.style.top = mouseY + 'px';
            trail.style.pointerEvents = 'none';
            trail.style.fontSize = '0.8rem';
            trail.style.opacity = '0.7';
            trail.style.animation = 'fadeOut 1s ease-out forwards';
            trail.style.zIndex = '1000';
            
            document.body.appendChild(trail);
            
            setTimeout(() => trail.remove(), 1000);
        }
    }, 50);
}

/**
 * Animate text with typewriter effect
 */
function typewriterEffect(element, text, speed = 50, callback = null) {
    if (!element) return;
    
    element.textContent = '';
    let index = 0;
    
    function type() {
        if (index < text.length) {
            element.textContent += text.charAt(index);
            index++;
            setTimeout(type, speed);
        } else if (callback) {
            callback();
        }
    }
    
    type();
}

/**
 * Create confetti animation
 */
function createConfetti(count = 50) {
    for (let i = 0; i < count; i++) {
        const confetti = document.createElement('div');
        confetti.className = 'confetti-piece';
        confetti.innerHTML = ['❤️', '💖', '✨', '🎉', '💕'][Math.floor(Math.random() * 5)];
        confetti.style.left = Math.random() * window.innerWidth + 'px';
        confetti.style.top = '-20px';
        confetti.style.fontSize = (Math.random() * 2 + 1) + 'rem';
        confetti.style.position = 'fixed';
        confetti.style.zIndex = '100';
        confetti.style.animation = `confetti ${(Math.random() * 2 + 2)}s linear forwards`;
        
        document.body.appendChild(confetti);
        
        setTimeout(() => confetti.remove(), 4000);
    }
}

/**
 * Create fireworks effect
 */
function createFireworks(x, y, particleCount = 30) {
    for (let i = 0; i < particleCount; i++) {
        const angle = (i / particleCount) * Math.PI * 2;
        const velocity = Math.random() * 5 + 3;
        const vx = Math.cos(angle) * velocity;
        const vy = Math.sin(angle) * velocity;
        
        const spark = document.createElement('div');
        spark.style.position = 'fixed';
        spark.style.left = x + 'px';
        spark.style.top = y + 'px';
        spark.style.width = '8px';
        spark.style.height = '8px';
        spark.style.borderRadius = '50%';
        spark.style.background = ['#ff4d6d', '#ffb6c1', '#c9184a', '#fff5f7'][Math.floor(Math.random() * 4)];
        spark.style.zIndex = '100';
        spark.style.boxShadow = '0 0 8px rgba(255, 77, 109, 0.8)';
        
        document.body.appendChild(spark);
        
        let px = x;
        let py = y;
        let gx = vx;
        let gy = vy + 0.2; // gravity
        
        const animate = () => {
            px += gx;
            py += gy;
            spark.style.left = px + 'px';
            spark.style.top = py + 'px';
            
            if (py < window.innerHeight) {
                requestAnimationFrame(animate);
            } else {
                spark.remove();
            }
        };
        
        animate();
    }
}

/**
 * Create heart rain effect
 */
function createHeartRain(count = 30) {
    for (let i = 0; i < count; i++) {
        const heartRain = document.createElement('div');
        heartRain.className = 'heart-rain';
        heartRain.innerHTML = '❤️';
        heartRain.style.left = Math.random() * window.innerWidth + 'px';
        heartRain.style.top = '-50px';
        heartRain.style.animationDuration = (Math.random() * 2 + 2) + 's';
        
        document.body.appendChild(heartRain);
        
        setTimeout(() => heartRain.remove(), 4000);
    }
}

/**
 * Initialize continuous heart floating
 */
function initContinuousHearts(interval = 1000) {
    setInterval(() => {
        createHeart();
    }, interval);
}

/**
 * Easter egg - press specific key sequence
 */
function initEasterEgg() {
    const sequence = [];
    const targetSequence = ['i', 'l', 'o', 'v', 'e', 'y', 'o', 'u'];
    
    document.addEventListener('keypress', (e) => {
        sequence.push(e.key.toLowerCase());
        
        if (sequence.length > targetSequence.length) {
            sequence.shift();
        }
        
        if (sequence.join('') === targetSequence.join('')) {
            triggerEasterEgg();
            sequence.length = 0;
        }
    });
}

function triggerEasterEgg() {
    // Big celebration
    createConfetti(100);
    createHeartRain(50);
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            createFireworks(
                Math.random() * window.innerWidth,
                Math.random() * window.innerHeight * 0.5,
                40
            );
        }, i * 300);
    }
    
    // Show message
    const message = document.createElement('div');
    message.style.position = 'fixed';
    message.style.top = '50%';
    message.style.left = '50%';
    message.style.transform = 'translate(-50%, -50%)';
    message.style.background = 'rgba(255, 77, 109, 0.95)';
    message.style.color = 'white';
    message.style.padding = '30px 50px';
    message.style.borderRadius = '20px';
    message.style.fontSize = '1.5rem';
    message.style.fontFamily = "'Dancing Script', cursive";
    message.style.zIndex = '1000';
    message.style.textAlign = 'center';
    message.style.animation = 'fadeInUp 0.5s ease';
    message.innerHTML = '💕 You found the secret! 💕<br>I love you even more! 💖';
    
    document.body.appendChild(message);
    
    setTimeout(() => {
        message.style.animation = 'fadeOut 0.5s ease forwards';
        setTimeout(() => message.remove(), 500);
    }, 3000);
}

/**
 * Enable button no-escape functionality
 */
function makeButtonEscapeOnHover(button, options = {}) {
    if (!button) return;
    
    let isHovered = false;
    
    button.addEventListener('mouseenter', () => {
        isHovered = true;
    });
    
    button.addEventListener('mousemove', (e) => {
        if (!isHovered) return;
        
        const rect = button.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;
        
        const distance = Math.hypot(e.clientX - centerX, e.clientY - centerY);
        
        if (distance < 100) {
            const angle = Math.atan2(e.clientY - centerY, e.clientX - centerX);
            const moveDistance = 80;
            const newX = Math.cos(angle + Math.PI) * moveDistance;
            const newY = Math.sin(angle + Math.PI) * moveDistance;
            
            button.style.transform = `translate(${newX}px, ${newY}px)`;
        }
    });
    
    button.addEventListener('mouseleave', () => {
        isHovered = false;
        button.style.transform = 'translate(0, 0)';
    });
}

/**
 * Initialize all page features on load
 */
function initPage() {
    // Add fade-in class to page
    const page = document.querySelector('.page');
    if (page && !page.classList.contains('fade-in')) {
        page.classList.add('fade-in');
    }
    
    // Initialize heart floating
    initContinuousHearts(1500);
    
    // Initialize heart cursor trail
    initHeartCursorTrail();
    
    // Initialize Easter egg
    initEasterEgg();
    
    // Unmute audio on first interaction
    const audioElements = document.querySelectorAll('audio');
    const unmuteAudio = () => {
        audioElements.forEach(audio => {
            audio.muted = false;
            audio.play().catch(e => console.log('Audio play prevented:', e));
        });
        document.removeEventListener('click', unmuteAudio);
        document.removeEventListener('touchstart', unmuteAudio);
    };
    
    document.addEventListener('click', unmuteAudio);
    document.addEventListener('touchstart', unmuteAudio);
}

/**
 * Google Font loader
 */
function loadGoogleFonts() {
    const link = document.createElement('link');
    link.href = 'https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400;700&family=Poppins:wght@400;600;700&display=swap';
    link.rel = 'stylesheet';
    document.head.appendChild(link);
}

// ============================================
// INITIALIZATION
// ============================================

document.addEventListener('DOMContentLoaded', () => {
    loadGoogleFonts();
    initPage();
});

// ============================================
// PAGE-SPECIFIC FUNCTIONS
// ============================================

/**
 * Initialize landing page (index.php)
 */
function initLandingPage() {
    const openBtn = document.getElementById('openBtn');
    if (openBtn) {
        openBtn.addEventListener('click', () => {
            createParticles(openBtn.offsetLeft + openBtn.offsetWidth / 2, openBtn.offsetTop + openBtn.offsetHeight / 2);
            setTimeout(() => {
                transitionToPage('page2.php');
            }, 300);
        });
    }
}

/**
 * Initialize slideshow (page2.php)
 */
function initSlideshow() {
    let currentSlide = 0;
    const slides = document.querySelectorAll('.slide');
    const totalSlides = slides.length;
    let autoAdvanceInterval;
    
    function showSlide(n) {
        slides.forEach(slide => slide.classList.remove('active'));
        if (n >= totalSlides) {
            currentSlide = totalSlides - 1;
            showSlideshowMessage();
            return;
        }
        if (n < 0) currentSlide = 0;
        
        slides[currentSlide].classList.add('active');
        
        const dots = document.querySelectorAll('.progress-dot');
        dots.forEach(dot => dot.classList.remove('active'));
        if (dots[currentSlide]) {
            dots[currentSlide].classList.add('active');
        }
    }
    
    function nextSlide() {
        currentSlide++;
        if (currentSlide >= totalSlides) {
            showSlideshowMessage();
            return;
        }
        showSlide(currentSlide);
        resetAutoAdvance();
    }
    
    function prevSlide() {
        currentSlide--;
        if (currentSlide < 0) currentSlide = 0;
        showSlide(currentSlide);
        resetAutoAdvance();
    }
    
    function resetAutoAdvance() {
        clearInterval(autoAdvanceInterval);
        autoAdvanceInterval = setInterval(nextSlide, 4000);
    }
    
    function showSlideshowMessage() {
        const message = document.querySelector('.slideshow-message');
        if (message) {
            message.style.display = 'block';
            message.classList.add('fade-in');
            
            const nextBtn = document.getElementById('nextSlideBtn');
            if (nextBtn) {
                nextBtn.textContent = '✨ One More Thing…';
                nextBtn.onclick = () => {
                    transitionToPage('page3.php');
                };
            }
        }
    }
    
    // Button event listeners
    const prevBtn = document.getElementById('prevSlideBtn');
    const nextBtn = document.getElementById('nextSlideBtn');
    
    if (prevBtn) prevBtn.addEventListener('click', prevSlide);
    if (nextBtn) nextBtn.addEventListener('click', nextSlide);
    
    // Dot click navigation
    const dots = document.querySelectorAll('.progress-dot');
    dots.forEach((dot, index) => {
        dot.addEventListener('click', () => {
            currentSlide = index;
            showSlide(currentSlide);
            resetAutoAdvance();
        });
    });
    
    // Initialize
    showSlide(currentSlide);
    autoAdvanceInterval = setInterval(nextSlide, 4000);
}

/**
 * Initialize funny trap page (page3.php)
 */
function initTrapPage() {
    const clickBtn = document.getElementById('clickBtn');
    const responseDiv = document.getElementById('responseDiv');
    const yesBtn = document.getElementById('yesBtn');
    const noBtn = document.getElementById('noBtn');
    
    if (clickBtn) {
        clickBtn.addEventListener('click', () => {
            clickBtn.style.display = 'none';
            if (responseDiv) {
                responseDiv.style.display = 'flex';
                responseDiv.classList.add('fade-in');
                createParticles(window.innerWidth / 2, window.innerHeight / 2, 8);
            }
        });
    }
    
    if (yesBtn) {
        yesBtn.addEventListener('click', () => {
            createFireworks(yesBtn.offsetLeft + yesBtn.offsetWidth / 2, yesBtn.offsetTop + yesBtn.offsetHeight / 2);
            setTimeout(() => {
                transitionToPage('page4.php');
            }, 300);
        });
    }
    
    if (noBtn) {
        makeButtonEscapeOnHover(noBtn);
        
        // Fun messages on No button
        const funMessages = [
            'Are you sure?',
            'Try again 😌',
            "That's illegal",
            'Wrong answer',
            'Nice try!',
            'Not happening',
            'Keep trying!',
            'Nope!',
            'Click again 😊',
            'Not today'
        ];
        
        let clickCount = 0;
        noBtn.addEventListener('click', () => {
            clickCount++;
            const message = funMessages[Math.floor(Math.random() * funMessages.length)];
            noBtn.textContent = message;
            
            setTimeout(() => {
                noBtn.textContent = '😢 NO';
            }, 1000);
            
            createParticles(noBtn.offsetLeft + noBtn.offsetWidth / 2, noBtn.offsetTop + noBtn.offsetHeight / 2, 3);
        });
    }
}

/**
 * Initialize proposal page (page4.php)
 */
function initProposalPage() {
    const typewriterElement = document.getElementById('typewriterText');
    const questionElement = document.getElementById('bigQuestion');
    const finalButtonsDiv = document.getElementById('finalButtons');
    const yesBtn = document.getElementById('finalYesBtn');
    
    if (!typewriterElement) return;
    
    const messages = [
        'From the moment I met you…',
        'You\'ve made my world brighter.',
        'You make ordinary days extraordinary.',
        'You\'re my favorite person.',
        'I love everything about you.',
        'So…'
    ];
    
    let messageIndex = 0;
    
    function showNextMessage() {
        if (messageIndex < messages.length) {
            const message = messages[messageIndex];
            typewriterElement.textContent = '';
            typewriterEffect(typewriterElement, message, 40, () => {
                setTimeout(() => {
                    messageIndex++;
                    showNextMessage();
                }, messageIndex === messages.length - 1 ? 1000 : 1500);
            });
        } else {
            showQuestion();
        }
    }
    
    function showQuestion() {
        if (questionElement) {
            questionElement.style.display = 'block';
            questionElement.classList.add('fade-in');
            
            if (finalButtonsDiv) {
                finalButtonsDiv.style.display = 'flex';
                finalButtonsDiv.classList.add('fade-in');
            }
        }
    }
    
    // Start typewriter
    setTimeout(showNextMessage, 500);
    
    // Button handlers
    if (yesBtn) {
        yesBtn.addEventListener('click', () => {
            createConfetti(100);
            createHeartRain(50);
            createFireworks(window.innerWidth / 2, window.innerHeight / 2, 50);
            
            // Submit the form
            const form = document.getElementById('proposalForm');
            if (form) {
                setTimeout(() => form.submit(), 1000);
            }
        });
    }
}

/**
 * Initialize success page (success.php)
 */
function initSuccessPage() {
    // Continuous celebrations
    createConfetti(80);
    createHeartRain(60);
    
    for (let i = 0; i < 3; i++) {
        setTimeout(() => {
            createFireworks(
                Math.random() * window.innerWidth,
                Math.random() * window.innerHeight * 0.3,
                50
            );
        }, i * 500);
    }
    
    // Create confetti and fireworks periodically
    setInterval(() => {
        if (Math.random() > 0.6) {
            createConfetti(20);
            createFireworks(
                Math.random() * window.innerWidth,
                Math.random() * window.innerHeight * 0.4,
                30
            );
        }
    }, 2000);
}

/**
 * Initialize admin page (admin.php)
 */
function initAdminPage() {
    const deleteButtons = document.querySelectorAll('.delete-btn');
    
    deleteButtons.forEach(btn => {
        btn.addEventListener('click', (e) => {
            if (!confirm('Are you sure you want to delete this response?')) {
                e.preventDefault();
            }
        });
    });
}

/**
 * Initialize search/filter in admin (optional)
 */
function initAdminSearch() {
    const searchInput = document.getElementById('searchInput');
    const tableRows = document.querySelectorAll('tbody tr');
    
    if (searchInput) {
        searchInput.addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase();
            
            tableRows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(query) ? '' : 'none';
            });
        });
    }
}

// Expose functions globally for inline event handlers
window.initLandingPage = initLandingPage;
window.initSlideshow = initSlideshow;
window.initTrapPage = initTrapPage;
window.initProposalPage = initProposalPage;
window.initSuccessPage = initSuccessPage;
window.initAdminPage = initAdminPage;
window.createParticles = createParticles;
window.transitionToPage = transitionToPage;
