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

// --- THIS IS THE MISSING LINE ---
// Import the specific functions we need from the Firestore SDK
import { collection, onSnapshot } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";

// DOM elements
const galleryContainer = document.getElementById('full-gallery-container');
const galleryLoadingMessage = document.getElementById('gallery-loading-message');

// Function to render the full gallery
const renderFullGallery = (snapshot) => {
    if (!galleryContainer) return;

    if (snapshot.empty) {
        galleryContainer.innerHTML = `<p class="text-gray-400 text-center mt-8 col-span-full">No images available in the gallery yet.</p>`;
        return;
    }

    let galleryHtml = '';
    snapshot.forEach(doc => {
        const item = doc.data();
        galleryHtml += `
            <div class="relative w-full h-64 overflow-hidden rounded-lg shadow-lg transition-transform duration-300 hover:scale-105 hover:z-10">
                <img src="${item.url || 'https://placehold.co/400x300'}" alt="${item.altText || ''}" class="absolute inset-0 w-full h-full object-cover">
                <div class="absolute inset-0 bg-black/50 opacity-0 hover:opacity-100 transition-opacity duration-300 flex items-end p-4">
                    <p class="text-white text-sm font-light">${item.altText || ''}</p>
                </div>
            </div>
        `;
    });
    galleryContainer.innerHTML = galleryHtml;
};

// --- Real-time Listener for the gallery ---
const initializeGalleryPage = () => {
    if (galleryLoadingMessage) galleryLoadingMessage.classList.remove('hidden');

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

window.addEventListener('DOMContentLoaded', initializeGalleryPage);