// Load and display all blog posts
async function loadBlogPosts() {
    try {
        const response = await fetch('blog-posts.json');
        const posts = await response.json();
        const container = document.getElementById("blogPostsContainer");
        
        // Sort posts by date (newest first)
        const sortedPosts = posts.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        sortedPosts.forEach(post => {
            const postElement = document.createElement('div');
            postElement.className = 'blog-post';
            postElement.id = `post-${post.id}`;
            
            // Convert content newlines to paragraphs
            const contentParagraphs = post.content.split('\n\n').filter(p => p.trim().length > 0);
            const formattedContent = contentParagraphs.map(p => `<p>${p.trim()}</p>`).join('');
            
            postElement.innerHTML = `
                <h2 class="blog-post-title">${post.title}</h2>
                <p class="blog-post-date">${post.date}</p>
                <p class="blog-post-excerpt">${post.excerpt}</p>
                <div class="blog-post-content">${formattedContent}</div>
                <p class="blog-post-signature">-- Author --</p>
            `;
            
            container.appendChild(postElement);
        });
        
        // Scroll to post if hash is present
        if (window.location.hash) {
            setTimeout(() => {
                const targetPost = document.querySelector(window.location.hash);
                if (targetPost) {
                    targetPost.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            }, 100);
        }
    } catch (error) {
        console.error('Error loading blog posts:', error);
        document.getElementById("blogPostsContainer").innerHTML = 
            '<p class="error">Error loading blog posts. Please try again later.</p>';
    }
}

// Load posts when page loads
window.addEventListener('load', loadBlogPosts);
