// Import the ready-to-use db object from our central init file
import { db } from './firebase-init.php';

// Import the specific functions we need from the Firestore SDK
import { collection, query, orderBy, getDocs } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";

// DOM Elements
const postsLoadingMessage = document.getElementById('posts-loading-message');
const postsContainer = document.getElementById('posts-container');
const categoriesContainer = document.getElementById('categories-container');
const recentPostsContainer = document.getElementById('recent-posts-container');
const blogPageTitle = document.getElementById('blog-page-title');

// --- Main Function to Load Blog Page ---
const loadBlogPage = async () => {
    try {
        const params = new URLSearchParams(window.location.search);
        const categoryFilter = params.get('category');

        if (categoryFilter) {
            blogPageTitle.textContent = `Category: ${categoryFilter}`;
        }

        // Fetch all posts
        const postsQuery = query(collection(db, 'blogs'), orderBy('timestamp', 'desc'));
        const querySnapshot = await getDocs(postsQuery);
        
        const allPosts = [];
        querySnapshot.forEach(doc => {
            allPosts.push({ id: doc.id, ...doc.data() });
        });

        // Filter posts if a category is selected
        const postsToRender = categoryFilter 
            ? allPosts.filter(post => post.category === categoryFilter)
            : allPosts;

        renderPosts(postsToRender);
        renderRecentPosts(allPosts);
        renderCategories(allPosts);

        postsLoadingMessage.classList.add('hidden');

    } catch (error) {
        console.error("Error loading blog page:", error);
        postsLoadingMessage.textContent = "Failed to load posts. Please try again later.";
    }
};

const renderPosts = (posts) => {
    postsContainer.innerHTML = '';
    if (posts.length === 0) {
        postsContainer.innerHTML = '<p class="text-gray-400 md:col-span-2 text-center">No posts found in this category.</p>';
        return;
    }

    posts.forEach(post => {
        const postLink = `single-post.html?id=${post.id}`;
        const excerpt = post.content ? (post.content.substring(0, 100) + '...') : '';
        const postDate = post.timestamp ? new Date(post.timestamp).toLocaleDateString() : '';

        const div = document.createElement('div');
        div.className = 'bg-black/50 rounded-lg overflow-hidden flex flex-col group';
        div.innerHTML = `
            <a href="${postLink}" class="block">
                <img src="${post.image || 'https://placehold.co/600x400'}" alt="${post.title}" class="w-full h-56 object-cover transform group-hover:scale-105 transition-transform duration-300">
            </a>
            <div class="p-6 flex flex-col flex-grow">
                <div class="mb-3">
                    <a href="blog.html?category=${encodeURIComponent(post.category || 'Uncategorized')}" class="text-amber-400 text-sm font-semibold uppercase hover:underline">${post.category || 'Uncategorized'}</a>
                </div>
                <h3 class="text-2xl font-header text-white mb-2">
                    <a href="${postLink}" class="hover:text-amber-400 transition-colors">${post.title}</a>
                </h3>
                <p class="text-gray-400 text-sm mb-4">${postDate}</p>
                <p class="text-gray-300 font-light flex-grow">${excerpt}</p>
                <a href="${postLink}" class="inline-block mt-4 text-emerald-400 hover:text-emerald-300 font-semibold">Read More &rarr;</a>
            </div>
        `;
        postsContainer.appendChild(div);
    });
};

const renderRecentPosts = (posts) => {
    recentPostsContainer.innerHTML = '';
    posts.slice(0, 5).forEach(post => {
        const postLink = `single-post.html?id=${post.id}`;
        const div = document.createElement('div');
        div.innerHTML = `
            <a href="${postLink}" class="flex items-center space-x-3 group">
                <img src="${post.image || 'https://placehold.co/100x100'}" alt="${post.title}" class="w-16 h-16 object-cover rounded-md flex-shrink-0">
                <div>
                    <h4 class="text-base font-semibold text-white group-hover:text-amber-400 transition-colors">${post.title}</h4>
                    <p class="text-sm text-gray-400">${post.timestamp ? new Date(post.timestamp).toLocaleDateString() : ''}</p>
                </div>
            </a>
        `;
        recentPostsContainer.appendChild(div);
    });
};

const renderCategories = (posts) => {
    const categories = {};
    posts.forEach(post => {
        const category = post.category || 'Uncategorized';
        categories[category] = (categories[category] || 0) + 1;
    });

    categoriesContainer.innerHTML = '';
    const sortedCategories = Object.keys(categories).sort();

    // Add 'All Posts' link first
    const allLink = document.createElement('a');
    allLink.href = 'blog.html';
    allLink.className = "flex justify-between items-center text-gray-300 hover:text-amber-400 transition-colors";
    allLink.innerHTML = `
        <span>All Posts</span>
        <span class="text-sm text-gray-500">${posts.length}</span>
    `;
    categoriesContainer.appendChild(allLink);

    for (const category of sortedCategories) {
        const categoryLink = `blog.html?category=${encodeURIComponent(category)}`;
        const a = document.createElement('a');
        a.href = categoryLink;
        a.className = "flex justify-between items-center text-gray-300 hover:text-amber-400 transition-colors";
        a.innerHTML = `
            <span>${category}</span>
            <span class="text-sm text-gray-500">${categories[category]}</span>
        `;
        categoriesContainer.appendChild(a);
    }
};

window.addEventListener('DOMContentLoaded', loadBlogPage);