// +++ THIS IS THE NEW CODE TO REPLACE IT WITH +++
// Import the ready-to-use db object from our central init file
import { db } from './firebase-init.php';

// Import only the functions we need from the Firestore SDK
import { getFirestore, collection, onSnapshot, addDoc, serverTimestamp, query, orderBy, limit } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";

// DOM elements
const galleryContainer = document.getElementById('gallery-container');
const galleryLoadingMessage = document.getElementById('gallery-loading-message');
const faqContainer = document.getElementById('faq-container');
const faqLoadingMessage = document.getElementById('faq-loading-message');
const blogContainer = document.getElementById('blog-container');
const blogLoadingMessage = document.getElementById('blog-loading-message');
const contactForm = document.getElementById('contact-form');
const formStatus = document.getElementById('form-status');
const counterSection = document.getElementById('counter-section');

// Function to render gallery
const renderGallery = (snapshot) => {
    if (!galleryContainer) return;
    galleryContainer.innerHTML = '';
    if (snapshot.docs.length === 0) {
        galleryContainer.innerHTML = `<p class="text-gray-400 text-center mt-8 col-span-full">No images available in the gallery yet.</p>`;
    }
    snapshot.docs.slice(0, 6).forEach(doc => { // Limit to 6 images on homepage
        const item = doc.data();
        const itemHtml = `
            <div class="relative w-full h-64 overflow-hidden rounded-lg shadow-lg transition-transform duration-300 hover:scale-105 hover:z-20">
                <img src="${item.url || 'https://placehold.co/400x300'}" alt="${item.altText || ''}" class="absolute inset-0 w-full h-full object-cover">
            </div>
        `;
        galleryContainer.innerHTML += itemHtml;
    });
};

// Function to render FAQs
const renderFaqs = (snapshot) => {
    if(!faqContainer) return;
    faqContainer.innerHTML = '';

    if (snapshot.empty) {
        faqContainer.innerHTML = `<p class="text-gray-400 text-center mt-8">No FAQs available yet.</p>`;
        return;
    }

    snapshot.forEach(doc => {
        const faq = { id: doc.id, ...doc.data() };
        const faqHtml = `
            <div class="rounded-lg bg-gray-800/50 p-4 shadow-lg cursor-pointer transition-transform transform hover:scale-[1.02] duration-300 faq-item">
                <div class="flex items-center justify-between">
                    <h3 class="text-xl sm:text-2xl text-amber-400 font-normal">${faq.question || 'N/A'}</h3>
                    <i class="fas fa-plus text-white faq-icon"></i>
                </div>
                <p class="text-gray-300 mt-2 faq-answer font-light">${faq.answer || 'N/A'}</p>
            </div>
        `;
        faqContainer.innerHTML += faqHtml;
    });
    
    document.querySelectorAll('.faq-item').forEach(item => {
        item.addEventListener('click', () => {
            item.querySelector('.faq-answer').classList.toggle('show');
            item.querySelector('.faq-icon').classList.toggle('rotate');
        });
    });
};

// Function to render blog posts
const renderBlog = (snapshot) => {
    if (!blogContainer) return;
    blogContainer.innerHTML = '';
    if (snapshot.docs.length === 0) {
        blogContainer.innerHTML = `<p class="text-gray-400 text-center mt-8 col-span-full">No blog posts available yet.</p>`;
    }
    snapshot.docs.slice(0, 3).forEach(doc => { // Limit to 3 blog posts
        const post = { id: doc.id, ...doc.data() };
        const content = post.content || '';
        const div = document.createElement('div');
        div.className = 'bg-gray-800/50 rounded-lg shadow-lg overflow-hidden transition-transform transform hover:scale-105 duration-300';
        div.innerHTML = `
            <a href="single-post.html?id=${post.id}" class="block">
                <img src="${post.image || 'https://placehold.co/400x300'}" alt="${post.title || ''}" class="w-full h-48 object-cover">
            </a>
            <div class="p-6 text-left">
                <h3 class="text-xl font-semibold text-amber-400 mb-2">${post.title || 'N/A'}</h3>
                <p class="text-gray-300 text-sm mb-4 font-light">
                    ${content.length > 100 ? content.substring(0, 100) + '...' : content}
                </p>
                <a href="single-post.html?id=${post.id}" class="text-amber-400 hover:text-amber-300 transition-colors text-sm font-normal">Read More <i class="fas fa-arrow-right ml-1"></i></a>
            </div>
        `;
        blogContainer.appendChild(div);
    });
};


// --- Contact Form Submission ---
if(contactForm) {
    contactForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = {
            name: contactForm.name.value,
            email: contactForm.email.value,
            phone: contactForm.phone.value,
            message: contactForm.message.value,
            timestamp: serverTimestamp(),
            status: 'new'
        };

        try {
            await addDoc(collection(db, 'contact_messages'), formData);
            formStatus.textContent = 'Your message has been sent successfully!';
            formStatus.classList.remove('hidden', 'text-red-400');
            formStatus.classList.add('text-green-400');
            contactForm.reset();
        } catch (error) {
            console.error('Error sending message:', error);
            formStatus.textContent = 'Failed to send message. Please try again later.';
            formStatus.classList.remove('hidden', 'text-green-400');
            formStatus.classList.add('text-red-400');
        } finally {
            formStatus.classList.remove('hidden');
            setTimeout(() => formStatus.classList.add('hidden'), 5000);
        }
    });
}

// --- Counter Animation ---
const startCounterAnimation = () => {
    const counters = document.querySelectorAll('.counter-value');
    const speed = 200; // The lower the slower

    counters.forEach(counter => {
        const animate = () => {
            const target = +counter.getAttribute('data-target');
            const count = +counter.innerText;
            const increment = target / speed;

            if (count < target) {
                counter.innerText = Math.ceil(count + increment);
                setTimeout(animate, 1);
            } else {
                counter.innerText = target;
            }
        };
        animate();
    });
};

// --- Intersection Observer for Counter ---
let observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            startCounterAnimation();
            observer.unobserve(entry.target);
        }
    });
}, { threshold: 0.5 });


// --- Real-time Listeners for all sections ---
const initializeWebsite = () => {
    if(galleryLoadingMessage) galleryLoadingMessage.classList.remove('hidden');
    if(faqLoadingMessage) faqLoadingMessage.classList.remove('hidden');
    if(blogLoadingMessage) blogLoadingMessage.classList.remove('hidden');

    if (counterSection) {
        observer.observe(counterSection);
    }
    
    onSnapshot(collection(db, 'gallery'), (snapshot) => {
        renderGallery(snapshot);
        if(galleryLoadingMessage) galleryLoadingMessage.classList.add('hidden');
    });

    const faqsQuery = query(collection(db, 'faqs'), limit(5));
    onSnapshot(faqsQuery, (snapshot) => {
        renderFaqs(snapshot);
        if(faqLoadingMessage) faqLoadingMessage.classList.add('hidden');
    });

    const blogsQuery = query(collection(db, 'blogs'), orderBy('timestamp', 'desc'));
    onSnapshot(blogsQuery, (snapshot) => {
        renderBlog(snapshot);
        if(blogLoadingMessage) blogLoadingMessage.classList.add('hidden');
    });
};

window.addEventListener('DOMContentLoaded', initializeWebsite);

