// Navigation Scroll Effect
window.addEventListener('scroll', () => {
    const navbar = document.getElementById('navbar');
    if (window.scrollY > 50) {
        navbar.classList.add('scrolled');
    } else {
        navbar.classList.remove('scrolled');
    }
});

// Mobile Menu Toggle
const mobileToggle = document.getElementById('mobileToggle');
const navMenu = document.getElementById('navMenu');

if (mobileToggle && navMenu) {
    mobileToggle.addEventListener('click', () => {
        navMenu.classList.toggle('active');
    });
}

// Close mobile menu when clicking a link
document.querySelectorAll('.nav-link').forEach(link => {
    link.addEventListener('click', () => {
        if (navMenu) {
            navMenu.classList.remove('active');
        }
    });
});

// Smooth Scroll Function
function scrollToSection(sectionId) {
    const element = document.getElementById(sectionId);
    if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
        if (navMenu) {
            navMenu.classList.remove('active');
        }
    }
}

// WhatsApp Contact Function
function openWhatsApp() {
    const message = encodeURIComponent(
        "Bonjour ECOLUX BTP, je souhaite obtenir une consultation gratuite pour mon projet de construction."
    );
    // Remplacez +221XXXXXXXXX par votre vrai numéro WhatsApp
    window.open(`https://wa.me/221XXXXXXXXX?text=${message}`, '_blank');
}

// Contact Form Submission
function handleSubmit(event) {
    event.preventDefault();
    
    // Récupérer les données du formulaire
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData);
    
    console.log('Form Data:', data);
    
    // Ici, vous pouvez envoyer les données à votre backend Django
    // Exemple avec fetch:
    /*
    fetch('/votre-endpoint-django/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken') // Pour Django CSRF
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        alert('Message envoyé avec succès!');
        event.target.reset();
    })
    .catch(error => {
        console.error('Erreur:', error);
        alert('Erreur lors de l\'envoi du message');
    });
    */
    
    // Pour l'instant, juste une alerte
    alert('Message envoyé avec succès! Nous vous contacterons bientôt.');
    event.target.reset();
}

// Fonction helper pour Django CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// Intersection Observer pour les animations au scroll
const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -100px 0px'
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
        }
    });
}, observerOptions);

// Observer tous les éléments avec la classe 'animate-on-scroll'
document.addEventListener('DOMContentLoaded', () => {
    const animatedElements = document.querySelectorAll('.service-card, .realisation-card, .blog-card');
    animatedElements.forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        el.style.transition = 'opacity 0.6s ease-out, transform 0.6s ease-out';
        observer.observe(el);
    });
});

// Blog Functions
function loadMorePosts() {
    const loadButton = document.getElementById('loadMorePosts');
    const blogGrid = document.querySelector('.blog-grid');
    
    if (!blogGrid) return;
    
    const currentPosts = blogGrid.querySelectorAll('.blog-card').length;
    
    fetch(`/api/load-more-posts/?offset=${currentPosts}`)
        .then(response => response.json())
        .then(data => {
            if (data.posts && data.posts.length > 0) {
                data.posts.forEach(post => {
                    const postElement = createBlogCard(post);
                    blogGrid.appendChild(postElement);
                });
                
                if (!data.has_more) {
                    loadButton.style.display = 'none';
                }
            } else {
                loadButton.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Erreur lors du chargement des articles:', error);
        });
}

function createBlogCard(post) {
    const div = document.createElement('div');
    div.className = 'blog-card';
    div.innerHTML = `
        <div class="blog-image" style="background-image: url('${post.featured_image || ''}');"></div>
        <div class="blog-content">
            <span class="blog-date">${post.created_at}</span>
            <h3>${post.title}</h3>
            <p>${post.excerpt}</p>
            <a href="/blog/${post.slug}/" class="read-more">Lire la suite →</a>
        </div>
    `;
    return div;
}

// Project Functions
function loadMoreProjects() {
    const loadButton = document.getElementById('loadMoreProjects');
    const projectsGrid = document.querySelector('.realisations-grid');
    
    if (!projectsGrid) return;
    
    const currentProjects = projectsGrid.querySelectorAll('.realisation-card').length;
    
    fetch(`/api/load-more-projects/?offset=${currentProjects}`)
        .then(response => response.json())
        .then(data => {
            if (data.projects && data.projects.length > 0) {
                data.projects.forEach(project => {
                    const projectElement = createProjectCard(project);
                    projectsGrid.appendChild(projectElement);
                });
                
                if (!data.has_more) {
                    loadButton.style.display = 'none';
                }
            } else {
                loadButton.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Erreur lors du chargement des projets:', error);
        });
}

function createProjectCard(project) {
    const div = document.createElement('div');
    div.className = 'realisation-card';
    div.innerHTML = `
        <div class="realisation-image" style="background-image: url('${project.featured_image || ''}');"></div>
        <div class="realisation-content">
            <h3>${project.title}</h3>
            <p>${project.description}</p>
            <span class="tag">${project.category}</span>
            <a href="/realisations/${project.slug}/" class="btn-outline" style="margin-top: 1rem;">Voir le projet</a>
        </div>
    `;
    return div;
}

// Search functionality
function searchContent(query, type = 'all') {
    const searchResults = document.getElementById('searchResults');
    if (!searchResults) return;
    
    if (query.length < 3) {
        searchResults.innerHTML = '';
        searchResults.style.display = 'none';
        return;
    }
    
    fetch(`/api/search/?q=${encodeURIComponent(query)}&type=${type}`)
        .then(response => response.json())
        .then(data => {
            displaySearchResults(data, searchResults);
        })
        .catch(error => {
            console.error('Erreur lors de la recherche:', error);
        });
}

function displaySearchResults(data, container) {
    if (!data.results || data.results.length === 0) {
        container.innerHTML = '<p>Aucun résultat trouvé</p>';
        container.style.display = 'block';
        return;
    }
    
    const resultsHTML = data.results.map(result => `
        <div class="search-result">
            <h4><a href="${result.url}">${result.title}</a></h4>
            <p>${result.excerpt}</p>
            <span class="search-type">${result.type}</span>
        </div>
    `).join('');
    
    container.innerHTML = resultsHTML;
    container.style.display = 'block';
}

// Utility functions
function formatDate(dateString) {
    const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
    };
    return new Date(dateString).toLocaleDateString('fr-FR', options);
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}
