// Animación de contadores
function animateCounter(element, target, duration = 2000) {
    let start = 0;
    const increment = target / (duration / 16);
    
    const timer = setInterval(() => {
        start += increment;
        if (start >= target) {
            element.textContent = Math.floor(target);
            clearInterval(timer);
        } else {
            element.textContent = Math.floor(start);
        }
    }, 16);
}

// Inicializar contadores cuando sean visibles
const observerOptions = {
    threshold: 0.5
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const userCount = document.getElementById('userCount');
            const interactionCount = document.getElementById('interactionCount');
            
            // NO animar si ya tienen la clase 'animated' (ya fueron actualizados por loadLandingContent)
            if (userCount && !userCount.classList.contains('animated')) {
                animateCounter(userCount, 0); // Valor por defecto 0
                userCount.classList.add('animated');
            }
            
            if (interactionCount && !interactionCount.classList.contains('animated')) {
                animateCounter(interactionCount, 0); // Valor por defecto 0
                interactionCount.classList.add('animated');
            }
        }
    });
}, observerOptions);

document.addEventListener('DOMContentLoaded', () => {
    const heroStats = document.querySelector('.hero-stats');
    if (heroStats) {
        observer.observe(heroStats);
    }
    
    // Animación de scroll suave
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
});

// Modal de login
function showLogin() {
    document.getElementById('loginModal').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function hideLogin() {
    document.getElementById('loginModal').classList.remove('active');
    document.body.style.overflow = 'auto';
}

// Cerrar modal al hacer click fuera
document.getElementById('loginModal')?.addEventListener('click', (e) => {
    if (e.target.id === 'loginModal') {
        hideLogin();
    }
});

// Manejar login
async function handleLogin(event) {
    event.preventDefault();
    
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const username = usernameInput.value.trim();
    const password = passwordInput.value;
    
    // Validación
    if (!username) {
        showNotification('Por favor ingresa tu usuario', 'error');
        usernameInput.focus();
        return;
    }
    
    if (!password) {
        showNotification('Por favor ingresa tu contraseña', 'error');
        passwordInput.focus();
        return;
    }
    
    if (password.length < 6) {
        showNotification('La contraseña debe tener al menos 6 caracteres', 'error');
        passwordInput.focus();
        return;
    }
    
    const btn = event.target.querySelector('.btn-submit');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verificando...';
    btn.disabled = true;
    
    try {
        const response = await fetch('api/auth.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'login',
                username,
                password,
                remember: false
            })
        });
        
        if (!response.ok) {
            throw new Error('Error en la respuesta del servidor');
        }
        
        const data = await response.json();
        
        if (data.success) {
            localStorage.setItem('auth_token', data.token);
            localStorage.setItem('user_data', JSON.stringify(data.user));
            
            showNotification('¡Acceso concedido!', 'success');
            
            setTimeout(() => {
                window.location.href = 'index.html';
            }, 500);
        } else {
            showNotification(data.message || 'Credenciales incorrectas', 'error');
            btn.innerHTML = originalText;
            btn.disabled = false;
            passwordInput.value = '';
            passwordInput.focus();
        }
    } catch (error) {
        console.error('Error:', error);
        showNotification('Error de conexión con el servidor', 'error');
        btn.innerHTML = originalText;
        btn.disabled = false;
    }
}

// Notificaciones
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
        <span>${message}</span>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.classList.add('show');
    }, 100);
    
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// Estilos para notificaciones (agregar dinámicamente)
const style = document.createElement('style');
style.textContent = `
    .notification {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 25px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        gap: 12px;
        font-weight: 600;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        transform: translateX(400px);
        transition: transform 0.3s;
        z-index: 10000;
    }
    
    .notification.show {
        transform: translateX(0);
    }
    
    .notification-success {
        background: #10b981;
        color: white;
    }
    
    .notification-error {
        background: #ef4444;
        color: white;
    }
    
    .notification i {
        font-size: 1.2rem;
    }
`;
document.head.appendChild(style);


// Cargar contenido dinámico del landing
async function loadLandingContent() {
    try {
        const response = await fetch('api/landing.php');
        
        if (!response.ok) {
            console.error('Error en respuesta:', response.status);
            return;
        }
        
        const data = await response.json();
        
        if (data.success) {
            // Stats - Actualizar TODOS los elementos
            const stats = data.stats;
            const userCountEl = document.getElementById('userCount');
            const interactionCountEl = document.getElementById('interactionCount');
            const navUserCountEl = document.getElementById('navUserCount');
            const navInteractionCountEl = document.getElementById('navInteractionCount');
            
            // Actualizar directamente sin animación
            if (userCountEl) {
                userCountEl.textContent = stats.total_users || 0;
                userCountEl.classList.add('animated'); // Marcar como actualizado
            }
            if (interactionCountEl) {
                interactionCountEl.textContent = stats.total_conversations || 0;
                interactionCountEl.classList.add('animated'); // Marcar como actualizado
            }
            if (navUserCountEl) navUserCountEl.textContent = stats.total_users || 0;
            if (navInteractionCountEl) navInteractionCountEl.textContent = stats.total_conversations || 0;
            
            // Hero Section
            if (data.data.hero) {
                const hero = data.data.hero;
                document.querySelector('.hero-title .gradient-text').textContent = hero.title || 'Cler';
                document.querySelector('.hero-subtitle').textContent = hero.content.description || '';
                const downloadBtn = document.querySelector('.btn-download');
                if (downloadBtn) {
                    downloadBtn.innerHTML = `<i class="fab fa-google-play"></i> ${hero.content.cta_text || 'Descargar'}`;
                    downloadBtn.href = hero.content.cta_link || '#';
                }
            }
            
            // Features
            if (data.data.features && data.data.features.content) {
                const grid = document.querySelector('.features-grid');
                grid.innerHTML = data.data.features.content.map(f => `
                    <div class="feature-card">
                        <div class="feature-icon ${f.color}">
                            <i class="fas ${f.icon}"></i>
                        </div>
                        <h3>${f.title}</h3>
                        <p>${f.description}</p>
                    </div>
                `).join('');
            }
            
            // Technology
            if (data.data.technology && data.data.technology.content) {
                const grid = document.querySelector('.tech-grid');
                grid.innerHTML = data.data.technology.content.map(t => `
                    <div class="tech-item">
                        <i class="fas ${t.icon}"></i>
                        <h4>${t.title}</h4>
                        <p>${t.description}</p>
                    </div>
                `).join('');
            }
            
            // Experience
            if (data.data.experience && data.data.experience.content) {
                const container = document.querySelector('.preview-features');
                container.innerHTML = data.data.experience.content.map(e => `
                    <div class="preview-item">
                        <i class="fas ${e.icon}"></i>
                        <div>
                            <h4>${e.title}</h4>
                            <p>${e.description}</p>
                        </div>
                    </div>
                `).join('');
            }
        }
    } catch (error) {
        console.error('Error cargando contenido:', error);
    }
}

// Cargar contenido al iniciar
document.addEventListener('DOMContentLoaded', () => {
    loadLandingContent();
});
