// Load and display a single blog post
async function loadBlogPost() {
    try {
        // Use relative path - this should work when post.js is loaded from /blog/post.html
        const apiPath = 'api/posts.php';
        
        const response = await fetch(apiPath);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const posts = await response.json();
        
        // Validate that we got an array
        if (!Array.isArray(posts)) {
            throw new Error('Invalid response format: expected array');
        }
        
        // Get post ID from URL query parameter
        const urlParams = new URLSearchParams(window.location.search);
        const postId = parseInt(urlParams.get('id'));
        
        if (isNaN(postId)) {
            document.getElementById('blogPostContainer').innerHTML = 
                '<p class="error">Invalid post ID. Please select a post from the sidebar.</p>';
            loadSidebarNavigation(posts);
            return;
        }
        
        // Find the post
        const post = posts.find(p => p.id === postId);
        
        if (!post) {
            document.getElementById('blogPostContainer').innerHTML = 
                '<p class="error">Post not found. Please select a post from the sidebar.</p>';
            loadSidebarNavigation(posts);
            return;
        }
        
        // Update page title
        const pageTitleEl = document.getElementById('pageTitle');
        if (pageTitleEl) {
            pageTitleEl.textContent = `${post.title} - Launch Pad`;
        }
        const blogPostTitleEl = document.getElementById('blogPostTitle');
        if (blogPostTitleEl) {
            blogPostTitleEl.textContent = `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('');
        
        const container = document.getElementById('blogPostContainer');
        container.innerHTML = `
            <div class="blog-post" id="post-${post.id}">
                <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>
                <div class="reactions-share-wrapper">
                    ${window.blogReactions ? window.blogReactions.createReactionButtons(post.id) : ''}
                    <p class="blog-post-signature">-- Author --</p>
                    ${window.blogReactions ? window.blogReactions.createShareButtons(post.id) : ''}
                </div>
            </div>
        `;
        
        // Load reactions for this post
        if (window.blogReactions) {
            window.blogReactions.loadReactions(post.id);
        }
        
        // Load sidebar navigation
        loadSidebarNavigation(posts, postId);
        
        // Align blog-sidebar top with blog-post-container top
        setTimeout(() => {
            const blogPostContainer = document.getElementById('blogPostContainer');
            const blogSidebar = document.getElementById('blogSidebar');
            if (blogPostContainer && blogSidebar) {
                const containerTop = blogPostContainer.getBoundingClientRect().top;
                const layoutTop = blogPostContainer.closest('.blog-layout').getBoundingClientRect().top;
                const offset = containerTop - layoutTop;
                blogSidebar.style.marginTop = offset + 'px';
            }
        }, 100);
        
    } catch (error) {
        console.error('Error loading blog post:', error);
        document.getElementById('blogPostContainer').innerHTML = 
            '<p class="error">Error loading blog post. Please try again later.</p>';
    }
}

// Load sidebar navigation with all posts
function loadSidebarNavigation(posts, currentPostId = null) {
    const sidebarNav = document.getElementById('sidebarNav');
    
    // Sort posts by date (newest first)
    const sortedPosts = [...posts].sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // Clear existing navigation
    sidebarNav.innerHTML = '';
    
    sortedPosts.forEach(post => {
        const navItem = document.createElement('a');
        navItem.href = `post.html?id=${post.id}`;
        navItem.className = 'sidebar-post-link';
        navItem.textContent = `Post-${post.id}`;
        
        // Highlight current post
        if (currentPostId !== null && post.id === currentPostId) {
            navItem.classList.add('active');
        }
        
        navItem.title = post.title;
        sidebarNav.appendChild(navItem);
    });
}

// Load post when page loads
window.addEventListener('load', loadBlogPost);
