// Fetch posts immediately and then every 3 seconds document.addEventListener('DOMContentLoaded', () => { fetchPosts(); setInterval(fetchPosts, 3000); }); async function fetchPosts() { try { const response = await fetch('/api/posts'); const posts = await response.json(); renderPosts(posts); } catch (error) { console.error('Error fetching posts:', error); } } function renderPosts(posts) { const container = document.getElementById('posts-container'); const existingIds = new Set(Array.from(container.children).map(child => parseInt(child.dataset.id))); // We want to prepend new posts, but preserving order. // The API returns sorted by newest first. // If empty, just render all if (container.children.length === 0) { container.innerHTML = posts.map(createPostHTML).join(''); return; } // Check for new posts at the top of the list const newPosts = posts.filter(p => !existingIds.has(p.id)); if (newPosts.length > 0) { // Insert new posts at the top // Since 'posts' is sorted newest first, we iterate backwards through newPosts // to insert them in the correct order at the top (topmost is newest) // Wait, if posts is [10, 9, 8] and we have [9, 8], new is [10]. // We just prepend 10. // Actually simplest is to re-render if there are changes to avoid complex DOM manipulation for this demo // But to make it smooth, let's try to just prepend. // Let's keep it simple: if count changes, re-render. // In a real app we'd diff, but this is a prototype. if (newPosts.length > 0) { container.innerHTML = posts.map(createPostHTML).join(''); } } } function createPostHTML(post) { const verifiedIcon = post.isVerifiedAI ? `` : ''; return `