// 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, onSnapshot, doc, getDocs, query, orderBy } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";


// --- PRIVATE SANITIZER FUNCTIONS (for this file only) ---
function sanitizeHTML(str) {
    if (!str) return '';
    const temp = document.createElement('div');
    temp.textContent = str;
    return temp.innerHTML.replace(/\n/g, '<br>');
}

function sanitizeAndListify(str) {
    if (!str) return '';
    return str.split('\n')
        .filter(line => line.trim() !== '')
        .map(line => {
            const temp = document.createElement('div');
            temp.textContent = line;
            return `<li>${temp.innerHTML}</li>`;
        })
        .join('');
}
// --- END OF SANITIZER FUNCTIONS ---


// DOM Elements
const postLoadingMessage = document.getElementById('post-loading-message');
const postContentWrapper = document.getElementById('post-content-wrapper');
const postImage = document.getElementById('post-image');
const postTitle = document.getElementById('post-title');
const postDate = document.getElementById('post-date');
const postCategory = document.getElementById('post-category');
const postBody = document.getElementById('post-body');
const decreaseFontBtn = document.getElementById('decrease-font');
const increaseFontBtn = document.getElementById('increase-font');
const shareFacebookBtn = document.getElementById('share-facebook');
const shareTwitterBtn = document.getElementById('share-twitter');
const categoriesContainer = document.getElementById('categories-container');
const recentPostsContainer = document.getElementById('recent-posts-container');
const prevPostLink = document.getElementById('prev-post');
const prevPostTitle = document.getElementById('prev-post-title');
const nextPostLink = document.getElementById('next-post');
const nextPostTitle = document.getElementById('next-post-title');

// Recipe Display DOM Elements
const recipeDisplay = document.getElementById('recipe-display');
const recipePrepTimeDisplay = document.getElementById('recipe-preptime-display');
const recipeCookTimeDisplay = document.getElementById('recipe-cooktime-display');
const recipeYieldDisplay = document.getElementById('recipe-yield-display');
const recipeIngredientsList = document.getElementById('recipe-ingredients-list');
const recipeInstructionsList = document.getElementById('recipe-instructions-list');

// Font size state
let currentFontSize = 18;
const MIN_FONT_SIZE = 12;
const MAX_FONT_SIZE = 28;

const updateFontSize = () => {
    if (postBody) postBody.style.fontSize = `${currentFontSize}px`;
};

// --- SEO Helper Functions ---
const updateMetaTag = (selector, value) => {
    let element = document.querySelector(selector);
    if (element && value) {
        if (selector.startsWith('link')) {
            element.setAttribute('href', value);
        } else {
            element.setAttribute('content', value);
        }
    }
};

const updateAllMetaTags = (post, postUrl) => {
    const excerpt = post.content ? (post.content.substring(0, 155) + '...') : 'Read the latest from 168 Green Cabin.';
    document.title = `${post.title || 'Blog Post'} - 168 Green Cabin`;
    updateMetaTag("meta[name='description']", excerpt);
    updateMetaTag("link[rel='canonical']", postUrl);
    updateMetaTag("meta[property='og:title']", `${post.title} - 168 Green Cabin`);
    updateMetaTag("meta[property='og:description']", excerpt);
    updateMetaTag("meta[property='og:url']", postUrl);
    updateMetaTag("meta[property='og:image']", post.image || 'https://www.168greencabin.com.au/assets/images/logo.webp');
    updateMetaTag("meta[name='twitter:title']", `${post.title} - 168 Green Cabin`);
    updateMetaTag("meta[name='twitter:description']", excerpt);
    updateMetaTag("meta[name='twitter:image']", post.image || 'https://www.168greencabin.com.au/assets/images/logo.webp');
};

const injectSchema = (post) => {
    const existingSchema = document.querySelector('script[type="application/ld+json"]');
    if (existingSchema) existingSchema.remove();
    
    let schema;
    const isRecipe = (post.category || '').trim().toLowerCase() === 'recipes' && post.recipe;

    if (isRecipe) {
        schema = {
            "@context": "https://schema.org/",
            "@type": "Recipe",
            name: post.title,
            image: [post.image],
            author: { "@type": "Organization", name: "168 Green Cabin" },
            datePublished: post.timestamp ? new Date(post.timestamp).toISOString() : new Date().toISOString(),
            description: (post.content || '').substring(0, 200),
            prepTime: post.recipe.prepTime,
            cookTime: post.recipe.cookTime,
            recipeYield: post.recipe.recipeYield,
            recipeIngredient: (post.recipe.recipeIngredient || '').split('\n').filter(line => line.trim() !== ''),
            recipeInstructions: (post.recipe.recipeInstructions || '').split('\n').filter(line => line.trim() !== '').map((step) => ({ "@type": "HowToStep", text: step }))
        };
    } else {
        schema = {
            "@context": "https://schema.org",
            "@type": "BlogPosting",
            headline: post.title,
            image: post.image || 'https://www.168greencabin.com.au/assets/images/logo.webp',
            datePublished: post.timestamp ? new Date(post.timestamp).toISOString() : new Date().toISOString(),
            dateModified: post.timestamp ? new Date(post.timestamp).toISOString() : new Date().toISOString(),
            author: { "@type": "Organization", name: "168 Green Cabin", url: "https://www.168greencabin.com.au" },
            publisher: { "@type": "Organization", name: "168 Green Cabin", logo: { "@type": "ImageObject", url: "https://www.168greencabin.com.au/assets/images/logo.webp" }},
            description: post.content ? (post.content.substring(0, 155) + '...') : 'A blog post from 168 Green Cabin.',
            mainEntityOfPage: { "@type": "WebPage", "@id": window.location.href }
        };
    }

    const script = document.createElement('script');
    script.type = 'application/ld+json';
    script.textContent = JSON.stringify(schema);
    document.head.appendChild(script);
};

// --- Main Function to Load Post ---
const loadPostAndSidebar = async () => {
    const params = new URLSearchParams(window.location.search);
    const postId = params.get('id');

    if (!postId) {
        if (postLoadingMessage) postLoadingMessage.textContent = "Post not found. Please check the URL.";
        return;
    }

    try {
        const postsQuery = query(collection(db, 'blogs'), orderBy('timestamp', 'desc'));
        const querySnapshot = await getDocs(postsQuery);
        
        const allPosts = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        const currentPostIndex = allPosts.findIndex(post => post.id === postId);
        
        if (currentPostIndex === -1) {
            if (postLoadingMessage) postLoadingMessage.textContent = "Post not found.";
            return;
        }
        
        const post = allPosts[currentPostIndex];
        
        updateAllMetaTags(post, window.location.href);
        injectSchema(post);

        // --- POPULATE MAIN CONTENT ---
        if (postImage) { postImage.src = post.image || 'https://placehold.co/1200x800'; postImage.alt = post.title || 'Blog post image'; }
        if (postTitle) postTitle.textContent = post.title || 'Untitled Post';
        if (postDate) postDate.textContent = post.timestamp ? new Date(post.timestamp).toLocaleDateString() : 'No date';
        if (postCategory) postCategory.textContent = post.category || 'Uncategorized';
        
        // ** SECURITY FIX: Use the self-contained sanitizer function **
        if (postBody) postBody.innerHTML = sanitizeHTML(post.content);

        // --- POPULATE RECIPE SECTION ---
        const isRecipe = (post.category || '').trim().toLowerCase() === 'recipes' && post.recipe;
        if (recipeDisplay) {
            if (isRecipe) {
                recipeDisplay.classList.remove('hidden');
                if (recipePrepTimeDisplay) recipePrepTimeDisplay.textContent = post.recipe.prepTime || 'N/A';
                if (recipeCookTimeDisplay) recipeCookTimeDisplay.textContent = post.recipe.cookTime || 'N/A';
                if (recipeYieldDisplay) recipeYieldDisplay.textContent = post.recipe.recipeYield || 'N/A';
                
                // ** SECURITY FIX: Use the self-contained sanitizer functions **
                if (recipeIngredientsList) recipeIngredientsList.innerHTML = sanitizeAndListify(post.recipe.recipeIngredient);
                if (recipeInstructionsList) recipeInstructionsList.innerHTML = sanitizeAndListify(post.recipe.recipeInstructions);

            } else {
                recipeDisplay.classList.add('hidden');
            }
        }
        
        updateFontSize();

        if (shareFacebookBtn) shareFacebookBtn.href = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(window.location.href)}`;
        if (shareTwitterBtn) shareTwitterBtn.href = `https://twitter.com/intent/tweet?url=${encodeURIComponent(window.location.href)}&text=${encodeURIComponent(post.title)}`;

        renderRecentPosts(allPosts.filter(p => p.id !== postId));
        setupNavigation(allPosts, currentPostIndex);
        
        if (postLoadingMessage) postLoadingMessage.classList.add('hidden');
        if (postContentWrapper) postContentWrapper.classList.remove('hidden');

    } catch (error) {
        console.error("Error fetching post:", error);
        if (postLoadingMessage) postLoadingMessage.textContent = "Error loading post. Please try again later.";
    }
    
    renderCategories();
};

const renderRecentPosts = (posts) => {
    if (!recentPostsContainer) return;
    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 = () => {
    if (!categoriesContainer) return;
    onSnapshot(collection(db, 'blogs'), (snapshot) => {
        const categories = {};
        snapshot.forEach(doc => {
            const category = doc.data().category || 'Uncategorized';
            categories[category] = (categories[category] || 0) + 1;
        });
        categoriesContainer.innerHTML = '';
        Object.keys(categories).sort().forEach(category => {
            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);
        });
    });
};

const setupNavigation = (posts, currentIndex) => {
    if (nextPostLink && nextPostTitle) {
        if (currentIndex < posts.length - 1) {
            const nextPost = posts[currentIndex + 1];
            nextPostLink.href = `single-post.html?id=${nextPost.id}`;
            nextPostTitle.textContent = nextPost.title;
            nextPostLink.classList.remove('hidden');
            nextPostLink.style.display = 'flex';
        } else {
            nextPostLink.classList.add('hidden');
        }
    }
    if (prevPostLink && prevPostTitle) {
        if (currentIndex > 0) {
            const prevPost = posts[currentIndex - 1];
            prevPostLink.href = `single-post.html?id=${prevPost.id}`;
            prevPostTitle.textContent = prevPost.title;
            prevPostLink.classList.remove('hidden');
            prevPostLink.style.display = 'flex';
        } else {
            prevPostLink.classList.add('hidden');
        }
    }
};

// --- Event Listeners ---
if (increaseFontBtn) increaseFontBtn.addEventListener('click', () => {
    if (currentFontSize < MAX_FONT_SIZE) {
        currentFontSize += 2;
        updateFontSize();
    }
});

if (decreaseFontBtn) decreaseFontBtn.addEventListener('click', () => {
    if (currentFontSize > MIN_FONT_SIZE) {
        currentFontSize -= 2;
        updateFontSize();
    }
});

window.addEventListener('DOMContentLoaded', loadPostAndSidebar);