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

// Import only the functions we need from the Firestore and Auth SDKs
import { getAuth, signInWithEmailAndPassword, signOut, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
import { getFirestore, collection, addDoc, setDoc, doc, deleteDoc, onSnapshot, getDoc, getDocs, writeBatch } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";

// --- DOM elements ---
const loginPage = document.getElementById('login-page');
const dashboardPage = document.getElementById('dashboard-page');
const loginForm = document.getElementById('login-form');
const loginMessage = document.getElementById('login-message');
const logoutButton = document.getElementById('logout-button');
const tabButtons = document.querySelectorAll('.admin-tab-button');
const tabContents = document.querySelectorAll('.tab-content');

// Home Tab DOM elements
const menuItemCount = document.getElementById('menu-item-count');
const galleryItemCount = document.getElementById('gallery-item-count');
const faqItemCount = document.getElementById('faq-item-count');
const blogItemCount = document.getElementById('blog-item-count');

// Messages Tab DOM elements
const messagesList = document.getElementById('messages-list');

// Menu Management DOM elements
const menuItemForm = document.getElementById('menu-item-form');
const masterMenuTableBody = document.getElementById('master-menu-table');
const addFeedbackMessage = document.getElementById('add-feedback-message');
const menuSearchInput = document.getElementById('menu-search-input');
const menuCategoryFilter = document.getElementById('menu-category-filter');

// Gallery Management DOM elements
const galleryForm = document.getElementById('gallery-form');
const galleryList = document.getElementById('gallery-list');
const uploadComputerBtn = document.getElementById('upload-computer-btn');
const imageFileInput = document.getElementById('image-file-input');
const useCameraBtn = document.getElementById('use-camera-btn');
const previewContainer = document.getElementById('preview-container');
const imagePreview = document.getElementById('image-preview');
const videoPreview = document.getElementById('video-preview');
const imageCanvas = document.getElementById('image-canvas');
const cameraControls = document.getElementById('camera-controls');
const takePictureBtn = document.getElementById('take-picture-btn');
const cancelCameraBtn = document.getElementById('cancel-camera-btn');
const addImageBtn = document.getElementById('add-image-btn');
const addImageBtnText = document.getElementById('add-image-btn-text');
const uploadLoader = document.getElementById('upload-loader');
const galleryFeedback = document.getElementById('gallery-feedback');
const imageUrlInput = document.getElementById('image-url');
const imageAltInput = document.getElementById('image-alt');


// FAQ Management DOM elements
const faqForm = document.getElementById('faq-form');
const faqsList = document.getElementById('faqs-list');

// Blog Management DOM elements
const blogForm = document.getElementById('blog-form');
const blogList = document.getElementById('blog-list');
const blogCategoryInput = document.getElementById('blog-category');
const blogCategoriesDatalist = document.getElementById('blog-categories-datalist');
const recipeFields = document.getElementById('recipe-fields');


// Global state
let allMenuItems = [];
let allBlogPosts = [];
let cameraStream = null;


// --- Authentication ---
onAuthStateChanged(auth, (user) => {
    if (user) {
        loginPage.classList.add('hidden');
        dashboardPage.classList.remove('hidden');
        initializeDashboard();
    } else {
        loginPage.classList.remove('hidden');
        dashboardPage.classList.add('hidden');
    }
});

if (loginForm) {
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const email = loginForm.email.value;
        const password = loginForm.password.value;
        try {
            await signInWithEmailAndPassword(auth, email, password);
            loginMessage.classList.add('hidden');
        } catch (error) {
            loginMessage.textContent = 'Invalid email or password.';
            loginMessage.classList.remove('hidden');
            console.error("Login failed:", error);
        }
    });
}


if (logoutButton) {
    logoutButton.addEventListener('click', async () => {
        await signOut(auth);
    });
}


// --- Tab Management ---
const switchTab = (tabName) => {
    tabButtons.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.tab === tabName);
    });
    tabContents.forEach(content => {
        const isTargetContent = content.id === `${tabName}-tab-content`;
        content.classList.toggle('hidden', !isTargetContent);
        if (isTargetContent) {
            content.classList.remove('active');
            void content.offsetWidth;
            content.classList.add('active');
        }
    });
};

tabButtons.forEach(button => {
    button.addEventListener('click', () => {
        const tab = button.dataset.tab;
        switchTab(tab);
    });
});

document.querySelectorAll('.quick-action-btn').forEach(button => {
    button.addEventListener('click', (e) => {
        const tabLink = e.currentTarget.dataset.tabLink;
        switchTab(tabLink);
        if(tabLink === 'menu') {
            document.getElementById('item-name').focus();
        } else if (tabLink === 'gallery') {
            document.getElementById('image-alt').focus();
        } else if (tabLink === 'blogs') {
             document.getElementById('blog-title').focus();
        }
    });
});


// --- Dashboard Initialization and Real-time Listeners ---
const initializeDashboard = () => {
    onSnapshot(collection(db, 'menu_items'), (snapshot) => {
        allMenuItems = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        menuItemCount.textContent = allMenuItems.length;
        populateCategoryFilter();
        applyFiltersAndRender();
    });
    onSnapshot(collection(db, 'gallery'), (snapshot) => {
        renderGallery(snapshot);
        galleryItemCount.textContent = snapshot.size;
    });
    onSnapshot(collection(db, 'faqs'), (snapshot) => {
        renderFaqs(snapshot);
        faqItemCount.textContent = snapshot.size;
    });
    onSnapshot(collection(db, 'blogs'), (snapshot) => {
        allBlogPosts = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        renderBlogs(allBlogPosts);
        populateBlogCategoryDatalist();
        blogItemCount.textContent = allBlogPosts.length;
    });
    onSnapshot(collection(db, 'contact_messages'), (snapshot) => {
        renderMessages(snapshot);
    });
};

// --- Menu Filtering and Search ---
const populateCategoryFilter = () => {
    if (!menuCategoryFilter) return;
    const categories = [...new Set(allMenuItems.map(item => item.category))].sort();
    
    const currentValue = menuCategoryFilter.value;

    menuCategoryFilter.innerHTML = '<option value="all">All Categories</option>'; // Reset
    categories.forEach(category => {
        if (category) {
            const option = document.createElement('option');
            option.value = category;
            option.textContent = category;
            menuCategoryFilter.appendChild(option);
        }
    });
    menuCategoryFilter.value = currentValue;
};

const applyFiltersAndRender = () => {
    if (!menuSearchInput || !menuCategoryFilter) return;

    const searchTerm = menuSearchInput.value.toLowerCase();
    const selectedCategory = menuCategoryFilter.value;

    let filteredItems = allMenuItems;

    if (selectedCategory !== 'all') {
        filteredItems = filteredItems.filter(item => item.category === selectedCategory);
    }

    if (searchTerm) {
        filteredItems = filteredItems.filter(item => 
            item.name && item.name.toLowerCase().includes(searchTerm)
        );
    }
    
    renderMasterMenu(filteredItems);
};

if (menuSearchInput) {
    menuSearchInput.addEventListener('input', applyFiltersAndRender);
}
if (menuCategoryFilter) {
    menuCategoryFilter.addEventListener('change', applyFiltersAndRender);
}



// --- SVG Icons ---
const editIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z" /><path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" clip-rule="evenodd" /></svg>`;
const deleteIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm4 0a1 1 0 012 0v6a1 1 0 11-2 0V8z" clip-rule="evenodd" /></svg>`;
const deleteIconWhiteSVG = `<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-white" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm4 0a1 1 0 012 0v6a1 1 0 11-2 0V8z" clip-rule="evenodd" /></svg>`;


// --- CRUD Functions ---

// Messages
const renderMessages = (snapshot) => {
    if (!messagesList) return;
    messagesList.innerHTML = '';
    if (snapshot.empty) {
        messagesList.innerHTML = `<li class="text-center text-gray-400 py-4">No messages yet.</li>`;
        return;
    }
    const messages = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    messages.sort((a, b) => (b.timestamp?.toDate() || 0) - (a.timestamp?.toDate() || 0));

    messages.forEach(msg => {
        const li = document.createElement('li');
        const isNew = msg.status === 'new';
        li.className = `message-item ${isNew ? 'message-new' : ''}`;
        
        const date = msg.timestamp ? msg.timestamp.toDate().toLocaleString() : 'No date';

        li.innerHTML = `
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div>
                    <div class="flex items-center gap-3">
                        <h4 class="font-semibold text-white">${msg.name || 'Anonymous'}</h4>
                        <a href="mailto:${msg.email}" class="text-sm text-amber-400 hover:underline">${msg.email || ''}</a>
                    </div>
                    <p class="text-sm text-gray-500">${date}</p>
                    <p class="text-gray-300 mt-2">${msg.message || 'No content'}</p>
                </div>
                <div class="flex items-center space-x-2 flex-shrink-0">
                    ${isNew ? `<button data-id="${msg.id}" class="btn btn-secondary btn-sm mark-read-btn">Mark as Read</button>` : ''}
                    <button data-id="${msg.id}" class="delete-message-btn action-btn text-red-400">${deleteIconSVG}</button>
                </div>
            </div>
        `;
        messagesList.appendChild(li);
    });

    messagesList.querySelectorAll('.mark-read-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const id = e.currentTarget.dataset.id;
            await setDoc(doc(db, 'contact_messages', id), { status: 'read' }, { merge: true });
        });
    });
    messagesList.querySelectorAll('.delete-message-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const id = e.currentTarget.dataset.id;
            if(confirm('Are you sure you want to delete this message permanently?')) {
                await deleteDoc(doc(db, 'contact_messages', id));
            }
        });
    });
};


// Menu Items
if (menuItemForm) {
    menuItemForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const id = menuItemForm['menu-item-id'].value;
        const name = menuItemForm['item-name'].value;
        const price = menuItemForm['item-price'].value;
        const description = menuItemForm['item-description'].value;
        const img = menuItemForm['item-img'].value;
        const category = menuItemForm['item-category'].value;
        const status = menuItemForm['item-status'].value;
        const itemData = { name, price, description, img, category, status };

        try {
            if (id) {
                const docRef = doc(db, 'menu_items', id);
                await setDoc(docRef, itemData, { merge: true });
            } else {
                await addDoc(collection(db, 'menu_items'), itemData);
            }
            menuItemForm.reset();
            menuItemForm['menu-item-id'].value = '';
            addFeedbackMessage.textContent = "Item successfully saved!";
            addFeedbackMessage.classList.remove('hidden', 'text-red-400');
            addFeedbackMessage.classList.add('text-green-400');
        } catch (error) {
            console.error("Error saving menu item:", error);
            addFeedbackMessage.textContent = "Error saving item. Please try again.";
            addFeedbackMessage.classList.remove('hidden', 'text-green-400');
            addFeedbackMessage.classList.add('text-red-400');
        }
    });
}


const renderMasterMenu = (items) => {
    if (!masterMenuTableBody) return;
    masterMenuTableBody.innerHTML = '';
    if (!items || items.length === 0) {
        masterMenuTableBody.innerHTML = `<tr><td colspan="6" class="text-center py-4">No menu items found.</td></tr>`;
        return;
    }

    items.forEach(item => {
        const row = masterMenuTableBody.insertRow();
        row.className = `bg-transparent hover:bg-gray-700/50 ${item.status === 'unavailable' ? 'opacity-50' : ''}`;

        row.insertCell().innerHTML = `<div class="px-6 py-4"><img src="${item.img || 'https://placehold.co/100x100/334155/ffffff?text=Img'}" alt="${item.name || ''}" class="w-12 h-12 rounded-full object-cover"></div>`;
        row.insertCell().innerHTML = `<div class="px-6 py-4 font-medium text-white whitespace-nowrap">${item.name || 'N/A'}</div>`;
        row.insertCell().innerHTML = `<div class="px-6 py-4">${item.category || 'N/A'}</div>`;
        row.insertCell().innerHTML = `<div class="px-6 py-4">${item.price || 'N/A'}</div>`;
        row.insertCell().innerHTML = `
            <div class="px-6 py-4">
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" value="" class="sr-only peer status-toggle-checkbox" data-id="${item.id}" ${item.status === 'available' ? 'checked' : ''}>
                    <div class="w-11 h-6 bg-gray-600 rounded-full peer peer-focus:ring-2 peer-focus:ring-emerald-800 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-600"></div>
                </label>
            </div>`;
        row.insertCell().innerHTML = `
            <div class="px-6 py-4 flex justify-end space-x-2">
                <button data-id="${item.id}" class="edit-item-btn action-btn text-blue-400">${editIconSVG}</button>
                <button data-id="${item.id}" class="delete-item-btn action-btn text-red-400">${deleteIconSVG}</button>
            </div>`;
    });

    attachMenuActionListeners();
};

const attachMenuActionListeners = () => {
    document.querySelectorAll('.edit-item-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const id = e.currentTarget.dataset.id;
            const docRef = doc(db, 'menu_items', id);
            const docSnap = await getDoc(docRef);
            if (docSnap.exists()) {
                const item = docSnap.data();
                menuItemForm['menu-item-id'].value = docSnap.id;
                menuItemForm['item-name'].value = item.name || '';
                menuItemForm['item-price'].value = item.price || '';
                menuItemForm['item-category'].value = item.category || '';
                menuItemForm['item-status'].value = item.status || 'available';
                menuItemForm['item-description'].value = item.description || '';
                menuItemForm['item-img'].value = item.img || '';
                menuItemForm.scrollIntoView({ behavior: 'smooth' });
            }
        });
    });

    document.querySelectorAll('.delete-item-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const id = e.currentTarget.dataset.id;
            if (confirm('Are you sure you want to delete this item?')) {
                try {
                    await deleteDoc(doc(db, 'menu_items', id));
                } catch (error) {
                    console.error("Error deleting menu item:", error);
                }
            }
        });
    });
    
    document.querySelectorAll('.status-toggle-checkbox').forEach(toggle => {
        toggle.addEventListener('change', async (e) => {
            const id = e.currentTarget.dataset.id;
            const newStatus = e.currentTarget.checked ? 'available' : 'unavailable';
            const docRef = doc(db, 'menu_items', id);
            try {
                await setDoc(docRef, { status: newStatus }, { merge: true });
            } catch (error) {
                console.error("Error updating status:", error);
                e.currentTarget.checked = !e.currentTarget.checked;
            }
        });
    });
};

const clearItemFormBtn = document.getElementById('clear-item-form-btn');
if (clearItemFormBtn) {
    clearItemFormBtn.addEventListener('click', () => {
        menuItemForm.reset();
        menuItemForm['menu-item-id'].value = '';
    });
}


// --- New Gallery Functions ---

const resetGalleryForm = () => {
    if (!galleryForm) return;
    galleryForm.reset();
    previewContainer.classList.add('hidden');
    imagePreview.src = '#';
    imagePreview.classList.add('hidden');
    videoPreview.classList.add('hidden');
    if (cameraStream) {
        cameraStream.getTracks().forEach(track => track.stop());
        cameraStream = null;
    }
    cameraControls.classList.add('hidden');
    hideGalleryFeedback();
    imageFileInput.value = '';
}

const showGalleryFeedback = (message, isError = false) => {
    if (!galleryFeedback) return;
    galleryFeedback.textContent = message;
    galleryFeedback.className = `text-sm mt-2 ${isError ? 'text-red-400' : 'text-green-400'}`;
    galleryFeedback.classList.remove('hidden');
}

const hideGalleryFeedback = () => {
    if (!galleryFeedback) return;
    galleryFeedback.classList.add('hidden');
}

const setUploadingState = (isUploading) => {
    if (!addImageBtn) return;
    addImageBtn.disabled = isUploading;
    if (isUploading) {
        addImageBtnText.classList.add('hidden');
        uploadLoader.classList.remove('hidden');
    } else {
        addImageBtnText.classList.remove('hidden');
        uploadLoader.classList.add('hidden');
    }
}

if (uploadComputerBtn) {
    uploadComputerBtn.addEventListener('click', () => {
        imageFileInput.removeAttribute('capture');
        imageFileInput.click();
    });
}


if (useCameraBtn) {
    useCameraBtn.addEventListener('click', () => {
        imageFileInput.setAttribute('capture', 'environment');
        imageFileInput.click();
    });
}


if (imageFileInput) {
    imageFileInput.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                resetGalleryForm();
                imagePreview.src = e.target.result;
                imagePreview.classList.remove('hidden');
                previewContainer.classList.remove('hidden');
                imageUrlInput.value = '';
            };
            reader.readAsDataURL(file);
        }
        imageFileInput.removeAttribute('capture');
    });
}



if (galleryForm) {
    galleryForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const altText = imageAltInput.value.trim();
        if (!altText) {
            showGalleryFeedback('Alt text is required for accessibility.', true);
            return;
        }

        const imageUrl = imageUrlInput.value.trim();
        const hasPreview = imagePreview.src && !imagePreview.src.endsWith('#');

        if (imageUrl && !hasPreview) {
            setUploadingState(true);
            try {
                await addDoc(collection(db, 'gallery'), { url: imageUrl, altText });
                showGalleryFeedback('Image added successfully from URL!');
                resetGalleryForm();
            } catch (error) {
                console.error("Error adding from URL:", error);
                showGalleryFeedback('Failed to add image from URL.', true);
            } finally {
                setUploadingState(false);
            }
            return;
        }

        if (hasPreview) {
            setUploadingState(true);
            const img = new Image();
            img.onload = async () => {
                const MAX_WIDTH = 1280;
                const MAX_HEIGHT = 1280;
                let width = img.width;
                let height = img.height;

                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height = height * (MAX_WIDTH / width);
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width = width * (MAX_HEIGHT / height);
                        height = MAX_HEIGHT;
                    }
                }

                const context = imageCanvas.getContext('2d');
                imageCanvas.width = width;
                imageCanvas.height = height;
                context.drawImage(img, 0, 0, width, height);
                
                const webpBase64 = imageCanvas.toDataURL('image/webp', 0.7);
                const base64Data = webpBase64.split(',')[1];

                const formData = new FormData();
                formData.append('image', base64Data);

                try {
                // We now send the data to our own proxy script
                const response = await fetch('assets/js/upload-proxy.php', {
                method: 'POST',
                headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                },
                // Send the image data in the body
                body: 'image=' + encodeURIComponent(base64Data)
                });
                const result = await response.json();

                    if (result.success) {
                        const uploadedUrl = result.data.url;
                        await addDoc(collection(db, 'gallery'), { url: uploadedUrl, altText });
                        showGalleryFeedback('Image uploaded and added successfully!');
                        resetGalleryForm();
                    } else {
                        throw new Error(result.error?.message || 'ImgBB upload failed.');
                    }
                } catch (error) {
                    console.error("Error uploading image:", error);
                    showGalleryFeedback(`Upload failed: ${error.message}`, true);
                } finally {
                    setUploadingState(false);
                }
            };
            img.onerror = () => {
                showGalleryFeedback('Failed to process image preview.', true);
                setUploadingState(false);
            }
            img.src = imagePreview.src;
            return;
        }

        showGalleryFeedback('Please select an image file, use the camera, or provide an image URL.', true);
    });
}



const renderGallery = (snapshot) => {
    if (!galleryList) return;
    galleryList.innerHTML = '';
    snapshot.forEach(doc => {
        const item = { id: doc.id, ...doc.data() };
        const div = document.createElement('div');
        div.className = 'relative group';
        div.innerHTML = `
            <img src="${item.url || 'https://placehold.co/400x300/334155/ffffff?text=Img'}" alt="${item.altText || ''}" class="w-full h-32 object-cover rounded-lg">
            <button data-id="${item.id}" class="delete-gallery-btn absolute top-2 right-2 p-1.5 bg-red-600 rounded-full text-white opacity-0 group-hover:opacity-100 transition-opacity action-btn">${deleteIconWhiteSVG}</button>
        `;
        galleryList.appendChild(div);
    });

    galleryList.querySelectorAll('.delete-gallery-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
             if (confirm('Are you sure you want to delete this image?')) {
                try {
                    await deleteDoc(doc(db, 'gallery', e.currentTarget.dataset.id));
                } catch (error) {
                    console.error("Error deleting gallery item:", error);
                }
            }
        });
    });
};

// FAQ Functions
if (faqForm) {
    faqForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const id = faqForm['faq-id'].value;
        const question = faqForm['faq-question'].value;
        const answer = faqForm['faq-answer'].value;
        const faq = { question, answer };
        try {
            if (id) {
                await setDoc(doc(db, 'faqs', id), faq);
            } else {
                await addDoc(collection(db, 'faqs'), faq);
            }
            faqForm.reset();
            faqForm['faq-id'].value = '';
        } catch (error) {
            console.error("Error saving FAQ:", error);
        }
    });
}


const renderFaqs = (snapshot) => {
    if (!faqsList) return;
    faqsList.innerHTML = '';
    snapshot.forEach(doc => {
        const faq = { id: doc.id, ...doc.data() };
        const li = document.createElement('li');
        li.className = 'bg-gray-700/50 p-4 rounded-lg flex items-center justify-between';
        li.innerHTML = `
            <div class="flex-grow">
                <h4 class="text-lg font-semibold text-white">${faq.question || 'N/A'}</h4>
                <p class="text-gray-400 text-sm mt-1">${faq.answer || 'N/A'}</p>
            </div>
            <div class="flex-shrink-0 flex items-center space-x-2 ml-4">
                <button data-id="${faq.id}" class="edit-faq-btn action-btn text-blue-400">${editIconSVG}</button>
                <button data-id="${faq.id}" class="delete-faq-btn action-btn text-red-400">${deleteIconSVG}</button>
            </div>
        `;
        faqsList.appendChild(li);
    });
    
    faqsList.querySelectorAll('.edit-faq-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const id = e.currentTarget.dataset.id;
            const docSnap = await getDoc(doc(db, 'faqs', id));
            if (docSnap.exists()) {
                const faq = docSnap.data();
                faqForm['faq-id'].value = docSnap.id;
                faqForm['faq-question'].value = faq.question || '';
                faqForm['faq-answer'].value = faq.answer || '';
                faqForm.scrollIntoView({ behavior: 'smooth' });
            }
        });
    });

    faqsList.querySelectorAll('.delete-faq-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            if (confirm('Are you sure you want to delete this FAQ?')) {
                try {
                    await deleteDoc(doc(db, 'faqs', e.currentTarget.dataset.id));
                } catch(error) {
                    console.error("Error deleting FAQ:", error);
                }
            }
        });
    });
};

const clearFaqFormBtn = document.getElementById('clear-faq-form-btn');
if (clearFaqFormBtn) {
    clearFaqFormBtn.addEventListener('click', () => {
        faqForm.reset();
        faqForm['faq-id'].value = '';
    });
}


// --- Blog Functions ---

// NEW: Show/hide recipe fields based on category
if (blogCategoryInput) {
    blogCategoryInput.addEventListener('input', () => {
        const isRecipe = blogCategoryInput.value.trim().toLowerCase() === 'recipes';
        recipeFields.classList.toggle('hidden', !isRecipe);
    });
}

// NEW: Populate blog category datalist for autocomplete
const populateBlogCategoryDatalist = () => {
    if (!blogCategoriesDatalist) return;
    const categories = [...new Set(allBlogPosts.map(post => post.category))].sort();
    blogCategoriesDatalist.innerHTML = '';
    categories.forEach(category => {
        if (category) {
            const option = document.createElement('option');
            option.value = category;
            blogCategoriesDatalist.appendChild(option);
        }
    });
};


if (blogForm) {
    blogForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const id = blogForm['blog-id'].value;
        
        // Base blog post data
        const blogPost = {
            title: blogForm['blog-title'].value,
            category: blogForm['blog-category'].value,
            image: blogForm['blog-image'].value,
            content: blogForm['blog-content'].value,
            timestamp: Date.now()
        };

        // If category is "Recipes", add recipe data
        if (blogPost.category.trim().toLowerCase() === 'recipes') {
            blogPost.recipe = {
                prepTime: blogForm['recipe-preptime'].value,
                cookTime: blogForm['recipe-cooktime'].value,
                recipeYield: blogForm['recipe-yield'].value,
                recipeIngredient: blogForm['recipe-ingredients'].value,
                recipeInstructions: blogForm['recipe-instructions'].value
            };
        } else {
            // Ensure no recipe object exists if it's not a recipe
            delete blogPost.recipe;
        }

        try {
            if (id) {
                await setDoc(doc(db, 'blogs', id), blogPost);
            } else {
                await addDoc(collection(db, 'blogs'), blogPost);
            }
            clearBlogForm();
        } catch (error) {
            console.error("Error saving blog post:", error);
        }
    });
}

// UPDATED renderBlogs to use the global allBlogPosts
const renderBlogs = (posts) => {
    if (!blogList) return;
    blogList.innerHTML = '';
    posts.forEach(post => {
        const content = post.content || '';
        const div = document.createElement('div');
        div.className = 'glass-panel p-4 rounded-lg shadow-lg flex flex-col justify-between';
        div.innerHTML = `
            <div>
                <img src="${post.image || 'https://placehold.co/400x300/334155/ffffff?text=Img'}" alt="${post.title || ''}" class="w-full h-40 object-cover rounded-lg mb-4">
                <h4 class="text-xl font-semibold text-white mb-2">${post.title || 'N/A'}</h4>
                <p class="text-gray-400 text-sm mb-4">${content.substring(0, 100)}...</p>
            </div>
            <div class="flex space-x-4 mt-auto pt-4 border-t border-gray-700">
                <button data-id="${post.id}" class="edit-blog-btn btn btn-secondary w-full justify-center">${editIconSVG} Edit</button>
                <button data-id="${post.id}" class="delete-blog-btn btn btn-secondary w-full justify-center">${deleteIconSVG} Delete</button>
            </div>
        `;
        blogList.appendChild(div);
    });
    
    blogList.querySelectorAll('.edit-blog-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const id = e.currentTarget.dataset.id;
            const docSnap = await getDoc(doc(db, 'blogs', id));
            if (docSnap.exists()) {
                const post = docSnap.data();
                blogForm['blog-id'].value = docSnap.id;
                blogForm['blog-title'].value = post.title || '';
                blogForm['blog-category'].value = post.category || '';
                blogForm['blog-image'].value = post.image || '';
                blogForm['blog-content'].value = post.content || '';

                const isRecipe = post.category && post.category.trim().toLowerCase() === 'recipes';

                // If it's a recipe, populate recipe fields
                if (isRecipe && post.recipe) {
                    blogForm['recipe-preptime'].value = post.recipe.prepTime || '';
                    blogForm['recipe-cooktime'].value = post.recipe.cookTime || '';
                    blogForm['recipe-yield'].value = post.recipe.recipeYield || '';
                    blogForm['recipe-ingredients'].value = post.recipe.recipeIngredient || '';
                    blogForm['recipe-instructions'].value = post.recipe.recipeInstructions || '';
                } else {
                    // Clear recipe fields if it's not a recipe
                    blogForm['recipe-preptime'].value = '';
                    blogForm['recipe-cooktime'].value = '';
                    blogForm['recipe-yield'].value = '';
                    blogForm['recipe-ingredients'].value = '';
                    blogForm['recipe-instructions'].value = '';
                }

                // Show/hide recipe fields based on the loaded category
                recipeFields.classList.toggle('hidden', !isRecipe);

                blogForm.scrollIntoView({ behavior: 'smooth' });
            }
        });
    });
    
    blogList.querySelectorAll('.delete-blog-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
             if (confirm('Are you sure you want to delete this blog post?')) {
                try {
                    await deleteDoc(doc(db, 'blogs', e.currentTarget.dataset.id));
                } catch (error) {
                    console.error("Error deleting blog post:", error);
                }
            }
        });
    });
};

// NEW clearBlogForm function
const clearBlogForm = () => {
    blogForm.reset();
    blogForm['blog-id'].value = '';
    // Also hide the recipe fields
    recipeFields.classList.add('hidden');
};

const clearBlogFormBtn = document.getElementById('clear-blog-form-btn');
if (clearBlogFormBtn) {
    clearBlogFormBtn.addEventListener('click', clearBlogForm);
}

