import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
import { getAuth, signInWithEmailAndPassword, onAuthStateChanged, signOut, createUserWithEmailAndPassword, setPersistence, browserLocalPersistence } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
import { getFirestore, doc, setDoc, getDoc, getDocs, collection, deleteDoc, onSnapshot, addDoc, updateDoc, query, where, orderBy, writeBatch, serverTimestamp, Timestamp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";

// --- CONFIGURATION ---
const firebaseConfig = {
    apiKey: "AIzaSyBK8sp4ZVpPEcteLF-a12FO9_1TgzDPisA",
    authDomain: "evolve-health-app-9d8b8.firebaseapp.com",
    projectId: "evolve-health-app-9d8b8",
    storageBucket: "evolve-health-app-9d8b8.appspot.com",
    messagingSenderId: "461915477544",
    appId: "1:461915477544:web:d1f9c3e9a3b1b2c4d5e6f7"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);

// Set persistence to local to prevent session loss on refresh
setPersistence(auth, browserLocalPersistence)
  .catch((error) => {
    console.error("Error setting persistence:", error);
  });

// --- STATE ---
let members = [];
let professionals = [];
let schedule = [];
let payments = [];
let checkins = [];
let measurements = [];
let meals = [];
let professionalNotes = [];
let globalSettings = { monthlyRate: 0 };
let memberSearchTerm = '';
let memberSortOption = 'name';
let memberStatusFilter = 'active';
let currentUser = null;
let listeners = []; // To store unsubscribe functions

// --- CURRENCY FORMATTING ---
function formatCurrency(amount) {
    return `${Number(amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

// --- DOM ELEMENTS ---
const loginScreen = document.getElementById('login-screen');
const mainPortal = document.getElementById('main-portal');
const loginForm = document.getElementById('login-form');
const logoutBtn = document.getElementById('logout-btn');
const userDetails = document.getElementById('user-details');
// const viewTitle = document.getElementById('view-title'); // Removed
const viewsContainer = document.getElementById('views');
const bottomMenu = document.getElementById('bottom-menu');
const notificationBanner = document.getElementById('notification-banner');

// --- VIEWS & NAVIGATION ---
const appViews = {
    dashboard: { title: 'Dashboard', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z" /></svg>`, render: renderDashboard },
    schedule: { title: 'Schedule', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5m-9-6h.008v.008H12v-.008z" /></svg>`, render: renderSchedule },
    trainers: { title: 'Professionals', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m-7.5-2.962A3.375 3.375 0 019 12.25c0-1.03.394-1.983 1.047-2.721 1.046-.924 2.413-1.533 3.841-1.533 1.428 0 2.795.609 3.84 1.533.654.738 1.048 1.69 1.048 2.721 0 .407-.047.806-.133 1.187m-15.133 2.962a3.375 3.375 0 01-1.047-2.721c0-1.03.394-1.983 1.047-2.721 1.046-.924 2.413-1.533 3.841-1.533 1.428 0 2.795.609 3.84 1.533.654.738 1.048 1.69 1.048 2.721 0 .407-.047.806-.133 1.187m-4.86-6.333a3.375 3.375 0 01-3.375-3.375 3.375 3.375 0 013.375-3.375s3.375 1.51 3.375 3.375c0 1.862-1.51 3.375-3.375 3.375z" /></svg>`, render: renderTrainers },
    members: { title: 'Members', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-4.67c.12-.318.232-.654.335-1.003a4.5 4.5 0 00-4.5-4.5C7.83 8.433 6 10.233 6 12.5c0 .621.074 1.227.21 1.804a7.5 7.5 0 00-4.473 6.584l-.012.087a12.318 12.318 0 008.745 3.945z" /></svg>`, render: renderMembers },
    payments: { title: 'Payments', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 8.25h19.5M2.25 9h19.5m-16.5 5.25h6m-6 2.25h3m-3.75 3h15a2.25 2.25 0 002.25-2.25V6.75A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25v10.5A2.25 2.25 0 004.5 19.5z" /></svg>`, render: renderPayments },
    checkins: { title: 'Check-ins', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>`, render: renderCheckins },
    measurements: { title: 'Measurements', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" /></svg>`, render: renderMeasurements },
    meals: { title: 'Meals', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M11.35 3.836c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z" /></svg>`, render: renderMeals },
    consultations: { title: 'Consultations', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" /></svg>`, render: renderConsultations },
    reports: { title: 'Reports', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>`, render: renderReports },
    settings: { title: 'Settings', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-1.007 1.11-1.11h2.592c.55.101 1.02.567 1.11 1.11l.09 1.086a11.99 11.99 0 013.42 2.32l.807-1.036a1.125 1.125 0 011.58.288l1.84 3.185a1.125 1.125 0 01-.289 1.581l-1.036.806c.06.37.1.746.1 1.128s-.04.758-.1 1.128l1.036.806a1.125 1.125 0 01.289 1.581l-1.84 3.185a1.125 1.125 0 01-1.58-.288l-.807-1.036a11.99 11.99 0 01-3.42 2.32l-.09 1.086c-.09.542-.56 1.007-1.11 1.11h-2.592c-.55-.101-1.02-.567-1.11-1.11l-.09-1.086a11.99 11.99 0 01-3.42-2.32l-.807 1.036a1.125 1.125 0 01-1.58-.288l-1.84-3.185a1.125 1.125 0 01.289-1.581l1.036-.806c-.06-.37-.1-.746-.1-1.128s.04-.758.1-1.128L2.92 8.719a1.125 1.125 0 01-.289-1.581l1.84-3.185a1.125 1.125 0 011.58-.288l.807 1.036a11.99 11.99 0 013.42-2.32l.09-1.086zM12 15a3 3 0 100-6 3 3 0 000 6z" /></svg>`, render: renderSettings },
};

const measurementFields = {
    Male: [
        { id: 'weight', label: 'Weight (kg)' },
        { id: 'height', label: 'Height (in)' },
        { id: 'chest', label: 'Chest (in)' },
        { id: 'lArm', label: 'Left Arm (in)' },
        { id: 'rArm', label: 'Right Arm (in)' },
        { id: 'abdomen', label: 'Abdomen (in)' },
        { id: 'waist', label: 'Waist (in)' },
        { id: 'hips', label: 'Hips (in)' },
        { id: 'lThigh', label: 'Left Thigh (in)' },
        { id: 'rThigh', label: 'Right Thigh (in)' }
    ],
    Female: [
        { id: 'weight', label: 'Weight (kg)' },
        { id: 'height', label: 'Height (in)' },
        { id: 'bust', label: 'Bust (in)' },
        { id: 'lArm', label: 'Left Arm (in)' },
        { id: 'rArm', label: 'Right Arm (in)' },
        { id: 'abdomen', label: 'Abdomen (in)' },
        { id: 'waist', label: 'Waist (in)' },
        { id: 'hips', label: 'Hips (in)' },
        { id: 'lThigh', label: 'Left Thigh (in)' },
        { id: 'rThigh', label: 'Right Thigh (in)' }
    ]
};

function showView(viewKey) {
    const view = appViews[viewKey];
    if (!view) return;

    // viewTitle.textContent = view.title; // Removed
    viewsContainer.innerHTML = ''; // Clear previous view
    view.render(viewsContainer);

    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.toggle('active', item.dataset.view === viewKey);
    });
}

function setupNavigation() {
    bottomMenu.innerHTML = Object.keys(appViews).map(key => `
        <button class="nav-item ${key === 'dashboard' ? 'active' : ''}" data-view="${key}">
            ${appViews[key].icon}
            <span>${appViews[key].title}</span>
        </button>
    `).join('');

    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', () => showView(item.dataset.view));
    });
}

// --- AUTHENTICATION ---
onAuthStateChanged(auth, async (user) => {
    if (user) {
        // Prevent infinite loop by not checking if we already have a session
        if (currentUser && currentUser.uid === user.uid) {
            console.log("Session already active for", user.uid);
            return;
        }

        try {
            console.log("Checking admin privileges for", user.uid);
            const userDoc = await getDoc(doc(db, "users", user.uid));
            
            if (userDoc.exists() && userDoc.data().role === 'admin') {
                console.log("Admin login successful");
                currentUser = { uid: user.uid, email: user.email, ...userDoc.data() };
                loginScreen.style.display = 'none';
                mainPortal.style.display = 'block';
                bottomMenu.style.display = 'flex';
                userDetails.textContent = `Welcome, Admin`;
                initializeAppState();
            } else {
                console.warn("User is not an admin or document missing. Exists:", userDoc.exists(), "Data:", userDoc.data());
                alert("Access Denied: You do not have administrator privileges.");
                await signOut(auth);
            }
        } catch (error) {
            console.error("Auth verification failed:", error);
            alert("Login verification failed due to an error. See console for details.");
            // Do NOT sign out immediately on transient errors, but UI might remain locked
            // However, usually better to force re-login if state is indeterminate
            await signOut(auth);
        }
    } else {
        console.log("No user signed in");
        currentUser = null;
        loginScreen.style.display = 'flex';
        mainPortal.style.display = 'none';
        bottomMenu.style.display = 'none';
        userDetails.textContent = '';
        // Unsubscribe from all listeners when logged out
        listeners.forEach(unsubscribe => unsubscribe());
        listeners = [];
    }
});

loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const email = loginForm['login-username'].value;
    const password = loginForm['login-password'].value;
    const errorEl = document.getElementById('login-error');
    try {
        errorEl.textContent = '';
        await signInWithEmailAndPassword(auth, email, password);
    } catch (error) {
        console.error("Login failed:", error);
        errorEl.textContent = "Login failed. Please check your credentials.";
    }
});

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

// --- INITIALIZATION ---
function initializeAppState() {
    setupNavigation();
    showView('dashboard');
    listenToDataChanges();
    listenToNotifications();
}

function listenToDataChanges() {
    // Clear existing listeners to prevent duplicates on re-login
    listeners.forEach(unsubscribe => unsubscribe());
    listeners = [];

    const collections = {
        members: (data) => {
            members = data;
            // Run cycle check logic (debounced/throttled handled by Firestore updates mostly)
            if(data.length > 0) checkMembershipCycles(data);
        },
        professionals: (data) => professionals = data,
        schedule: (data) => schedule = data,
        payments: (data) => payments = data,
        checkins: (data) => checkins = data,
        measurements: (data) => measurements = data,
        meals: (data) => meals = data,
        professional_notes: (data) => professionalNotes = data,
    };

    // Listen to Settings
    const settingsUnsub = onSnapshot(doc(db, "settings", "general"), (doc) => {
        if (doc.exists()) {
            globalSettings = doc.data();
        }
    });
    listeners.push(settingsUnsub);

   for (const [name, setter] of Object.entries(collections)) {
        const q = query(collection(db, name));
        const unsubscribe = onSnapshot(q, (snapshot) => {
            const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
            setter(data);
            refreshCurrentView();
        });
        listeners.push(unsubscribe);
    }
}

function listenToNotifications() {
    const q = query(collection(db, "notifications"), where("endDate", ">=", new Date().toISOString().split('T')[0]));
    const unsubscribe = onSnapshot(q, (snapshot) => {
        const activeNotifications = snapshot.docs.map(doc => doc.data().message);
        if (activeNotifications.length > 0) {
            notificationBanner.querySelector('p').textContent = activeNotifications.join(' | ');
            notificationBanner.classList.remove('hidden');
        } else {
            notificationBanner.classList.add('hidden');
        }
    });
    listeners.push(unsubscribe);
}

function refreshCurrentView() {
    const activeViewKey = document.querySelector('.nav-item.active')?.dataset.view;
    if (activeViewKey && appViews[activeViewKey]) {
        const currentScroll = { x: window.scrollX, y: window.scrollY };
        appViews[activeViewKey].render(viewsContainer);
        window.scrollTo(currentScroll.x, currentScroll.y);
    }
}

// --- MEMBERSHIP CYCLE LOGIC ---
async function checkMembershipCycles(membersList) {
    if (!membersList || membersList.length === 0) return;

    try {
        const settingsSnap = await getDoc(doc(db, "settings", "general"));
        if (!settingsSnap.exists()) return;
        const rate = Number(settingsSnap.data().monthlyRate) || 0;
        if (rate <= 0) return;

        const batch = writeBatch(db);
        let updateCount = 0;
        const today = new Date();
        today.setHours(0,0,0,0);

        for (const m of membersList) {
            if (m.status === 'inactive') continue;

            // Initialize nextCycleDate logic for existing members if missing but startDate present
            let cycleDateStr = m.nextCycleDate;
            let cycleDate;

            if (!cycleDateStr && m.startDate) {
                // Determine current cycle end based on startDate
                let loopDate = new Date(m.startDate);
                // Advance in 28-day steps until > today
                // Wait, if nextCycleDate is missing, maybe we should set it to startDate + 28 days?
                // Or if startDate was long ago, we need to catch up.
                // Simple init: just set it to startDate + 28 days. 
                // If that date is already passed, logic below will catch it and add dueAmount.
                // This might perform retro-active billing for ALL missed months? 
                // That might be dangerous: "amount due... updated as soon as the new cycle starts"
                // Let's assume we just want to track from now on.
                // But to be consistent with "4 Fridays" logic:
                
                // Let's just set nextCycleDate = startDate + 28 days if missing. 
                // The loop below will then handle billing if that date is past.
                cycleDate = new Date(m.startDate);
                cycleDate.setDate(cycleDate.getDate() + 28);
                cycleDateStr = cycleDate.toISOString().split('T')[0];
                
                // We must set this initial date or the loop below fails.
                // But we can't update doc inside this loop to init unless we batch it.
                // Let's treat cycleDate from calc.
            } else if (cycleDateStr) {
                cycleDate = new Date(cycleDateStr);
            } else {
                continue; // No data to work with
            }
            
            // Check if cycle date (Renewal Date) has arrived or passed
            if (cycleDate <= today) {
                // Calculate new Date (Next 4 Fridays / 28 Days)
                const newDate = new Date(cycleDate);
                newDate.setDate(newDate.getDate() + 28);
                const newCycleDateStr = newDate.toISOString().split('T')[0];
                
                // Update Dues
                const currentDue = Number(m.dueAmount) || 0;
                const newDue = currentDue + rate;
                const totalAmount = (Number(m.totalAmount) || 0) + rate;
                // Assuming 'months' tracks cycles
                const totalMonths = (Number(m.months) || 0) + 1;

                const memberRef = doc(db, "members", m.id);
                batch.update(memberRef, {
                    nextCycleDate: newCycleDateStr,
                    dueAmount: newDue,
                    totalAmount: totalAmount,
                    months: totalMonths
                });
                updateCount++;
            }
        }

        if (updateCount > 0) {
            await batch.commit();
            console.log(`Updated membership cycles for ${updateCount} members.`);
        }
    } catch (error) {
        console.error("Error checking membership cycles:", error);
    }
}

// --- RENDER FUNCTIONS ---

function renderDashboard(container) {
    const totalDues = members.reduce((sum, m) => sum + (Number(m.dueAmount) || 0), 0);
    const totalPaidThisMonth = payments
        .filter(p => new Date(p.date).getMonth() === new Date().getMonth())
        .reduce((sum, p) => sum + (Number(p.amount) || 0), 0);

    const today = new Date().toISOString().split('T')[0];
    const scheduleToday = schedule.filter(s => s.date === today);

    container.innerHTML = `
        <div class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div class="vibrant-card"><h3 class="text-lg font-semibold text-center text-white">Total Members</h3><p class="text-3xl font-extrabold text-center mt-2">${members.length}</p></div>
                <div class="vibrant-card"><h3 class="text-lg font-semibold text-center text-white">Total Professionals</h3><p class="text-3xl font-extrabold text-center mt-2">${professionals.length}</p></div>
                <div class="vibrant-card"><h3 class="text-lg font-semibold text-center text-white">Total Dues (TZS)</h3><p class="text-3xl font-extrabold text-center mt-2">${formatCurrency(totalDues)}</p></div>
                <div class="vibrant-card"><h3 class="text-lg font-semibold text-center text-white">Paid This Month (TZS)</h3><p class="text-3xl font-extrabold text-center mt-2">${formatCurrency(totalPaidThisMonth)}</p></div>
            </div>
            
            <details class="group bg-gray-700/50 rounded-lg p-4" open>
                <summary class="flex justify-between items-center font-medium cursor-pointer list-none">
                    <h3 class="text-lg font-bold text-teal-400">Schedule for Today</h3>
                    <span class="transition-transform duration-300 group-open:rotate-180 text-teal-400">
                        <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                    </span>
                </summary>
                <div id="schedule-today-list" class="space-y-2 mt-4 group-open:animate-fadeIn">
                    ${scheduleToday.length > 0 ? scheduleToday.map(s => `
                        <div class="bg-gray-800/50 p-3 rounded-lg flex justify-between items-center text-white">
                            <span>${s.time} - ${members.find(m=>m.id===s.memberId)?.name || 'N/A'} with ${professionals.find(p=>p.id===s.trainerId)?.name || 'N/A'}</span>
                        </div>
                    `).join('') : '<p class="text-gray-400">No sessions scheduled for today.</p>'}
                </div>
            </details>
        </div>
    `;
}

function renderSchedule(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Book a New Session</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                            <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <form id="add-session-form" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div><label for="session-member" class="block text-sm font-medium text-gray-400 mb-1">Member</label><select id="session-member" class="input-field">${members.map(m => `<option value="${m.id}">${m.name}</option>`).join('')}</select></div>
                            <div><label for="session-trainer" class="block text-sm font-medium text-gray-400 mb-1">Professional</label><select id="session-trainer" class="input-field">${professionals.map(p => `<option value="${p.id}">${p.name}</option>`).join('')}</select></div>
                            <div><label for="session-date" class="block text-sm font-medium text-gray-400 mb-1">Date</label><input type="date" id="session-date" class="input-field"></div>
                            <div><label for="session-time" class="block text-sm font-medium text-gray-400 mb-1">Time</label><input type="time" id="session-time" class="input-field"></div>
                            <button type="submit" class="btn-primary md:col-span-2">Book Session</button>
                        </form>
                    </div>
                </details>
            </div>
            
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">All Bookings</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                            <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <div id="schedule-list" class="space-y-2">
                            ${schedule.sort((a,b) => new Date(b.date + 'T' + b.time) - new Date(a.date + 'T' + a.time)).map(s => `
                                <div class="bg-gray-800/50 p-3 rounded-lg flex justify-between items-center">
                                    <div>
                                        <p class="font-bold">${new Date(s.date + 'T00:00:00').toLocaleDateString()} at ${s.time}</p>
                                        <p class="text-sm text-gray-300">${members.find(m=>m.id===s.memberId)?.name || 'N/A'} with ${professionals.find(p=>p.id===s.trainerId)?.name || 'N/A'}</p>
                                    </div>
                                    <button class="btn-danger delete-session-btn p-2" data-id="${s.id}" title="Delete"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" /></svg></button>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </details>
            </div>
        </div>
    `;
    document.getElementById('add-session-form').addEventListener('submit', handleAddSession);
    document.querySelectorAll('.delete-session-btn').forEach(btn => btn.addEventListener('click', (e) => deleteItem('schedule', e.target.dataset.id, 'Session')));
}

function renderTrainers(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Add/Edit Professional</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                            <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <form id="trainer-form" class="space-y-4">
                            <input type="hidden" id="trainer-id-input">
                            <div><label for="trainer-name" class="block text-sm font-medium text-gray-400 mb-1">Name</label><input type="text" id="trainer-name" placeholder="Name" class="input-field" required></div>
                            <div><label for="trainer-gender" class="block text-sm font-medium text-gray-400 mb-1">Gender</label><select id="trainer-gender" class="input-field" required><option value="">Select Gender...</option><option value="Male">Male</option><option value="Female">Female</option></select></div>
                            <div><label for="trainer-specialization" class="block text-sm font-medium text-gray-400 mb-1">Specialization</label><input type="text" id="trainer-specialization" placeholder="e.g. Yoga, Weights" class="input-field"></div>
                            <div><label for="trainer-charges" class="block text-sm font-medium text-gray-400 mb-1">Charges (TZS)</label><input type="number" id="trainer-charges" placeholder="0.00" class="input-field" step="0.01"></div>
                            <div><label for="trainer-phone" class="block text-sm font-medium text-gray-400 mb-1">Phone Number</label><input type="text" id="trainer-phone" placeholder="Phone Number" class="input-field" required></div>
                            <div><label for="trainer-email" class="block text-sm font-medium text-gray-400 mb-1">Email</label><input type="email" id="trainer-email" placeholder="Email" class="input-field" required></div>
                            <button type="submit" class="btn-primary w-full">Save Professional</button>
                        </form>
                    </div>
                </details>
            </div>
            
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Professional List</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                            <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <ul id="trainer-list" class="space-y-2">
                            ${professionals.map(p => `
                                <li class="bg-gray-800/50 p-3 rounded-lg flex justify-between items-center">
                                    <div>
                                        <p class="font-bold">${p.name} <span class="text-xs bg-purple-600 px-2 py-1 rounded-full">${p.specialization || p.category || 'N/A'}</span></p>
                                        <p class="text-sm text-gray-300">
                                            ${p.phone} | ${p.email || 'No Email'}
                                            | <span class="${!p.status || p.status === 'active' ? 'text-green-400' : 'text-red-400'} capitalize">${p.status || 'active'}</span>
                                        </p>
                                        ${p.charges ? `<p class="text-sm text-teal-400">Charges: TZS ${formatCurrency(p.charges)}</p>` : ''}
                                    </div>
                                    <div class="space-x-2 flex">
                                        <button class="btn-secondary toggle-prop-btn p-2" data-id="${p.id}" data-status="${p.status || 'active'}" title="${p.status === 'inactive' ? 'Activate' : 'Deactivate'}">
                                            ${p.status === 'inactive' ? 
                                                `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 text-green-400"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>` : 
                                                `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 text-red-400"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" /></svg>`
                                            }
                                        </button>
                                        <button class="btn-secondary edit-trainer-btn p-2" data-id="${p.id}" title="Edit"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 pointer-events-none"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" /></svg></button>
                                        <button class="btn-danger delete-trainer-btn p-2" data-id="${p.id}" title="Delete"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 pointer-events-none"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" /></svg></button>
                                    </div>
                                </li>
                            `).join('')}
                        </ul>
                    </div>
                </details>
            </div>
        </div>
    `;
    document.getElementById('trainer-form').addEventListener('submit', handleTrainerForm);
    document.querySelectorAll('.edit-trainer-btn').forEach(btn => btn.addEventListener('click', (e) => editTrainer(e.target.dataset.id)));
    document.querySelectorAll('.delete-trainer-btn').forEach(btn => btn.addEventListener('click', (e) => deleteItem('professionals', e.target.dataset.id, 'Professional')));
    document.querySelectorAll('.toggle-prop-btn').forEach(btn => btn.addEventListener('click', async (e) => {
        const id = e.currentTarget.dataset.id;
        const currentStatus = e.currentTarget.dataset.status;
        const newStatus = currentStatus === 'inactive' ? 'active' : 'inactive';
        
        if(confirm(`Are you sure you want to ${newStatus === 'inactive' ? 'deactivate' : 'activate'} this professional?`)) {
             try {
                await updateDoc(doc(db, "professionals", id), { status: newStatus });
            } catch (err) {
                console.error("Error updating status:", err);
                alert("Failed to update status.");
            }
        }
    }));
}

function renderMembers(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Add/Edit Member</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                            <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <form id="member-form" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <input type="hidden" id="member-id-input">
                            <div><label for="member-name" class="block text-sm font-medium text-gray-400 mb-1">Name</label><input type="text" id="member-name" class="input-field" required></div>
                            <div><label for="member-contact" class="block text-sm font-medium text-gray-400 mb-1">Contact</label><input type="text" id="member-contact" class="input-field"></div>
                            <div><label for="member-email" class="block text-sm font-medium text-gray-400 mb-1">Email</label><input type="email" id="member-email" class="input-field" required></div>
                            <div><label for="member-dob" class="block text-sm font-medium text-gray-400 mb-1">Date of Birth</label><input type="date" id="member-dob" class="input-field" required></div>
                            <div><label for="member-gender" class="block text-sm font-medium text-gray-400 mb-1">Gender</label><select id="member-gender" class="input-field"><option value="Male">Male</option><option value="Female">Female</option><option value="Other">Other</option></select></div>
                            
                            <div><label for="member-rate" class="block text-sm font-medium text-gray-400 mb-1">Rate (TZS)</label><input type="number" id="member-rate" class="input-field" required></div>
                            <div><label for="member-start-date" class="block text-sm font-medium text-gray-400 mb-1">Start Date</label><input type="date" id="member-start-date" class="input-field" required></div>
                            
                            <div class="md:col-span-2"><label for="member-due-amount" class="block text-sm font-medium text-gray-400 mb-1">Due Amount / Past Due</label><input type="number" id="member-due-amount" class="input-field" placeholder="0">
                                <p class="text-xs text-gray-400 mt-1">For new members, enter any past due amount. The current month's rate will be added automatically.</p>
                            </div>

                            <div class="md:col-span-2"><label for="member-notes" class="block text-sm font-medium text-gray-400 mb-1">Notes</label><textarea id="member-notes" rows="3" class="input-field"></textarea></div>
                            <button type="submit" class="btn-primary md:col-span-2">Save Member</button>
                        </form>
                    </div>
                </details>
            </div>

            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Member List</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                            <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                            <div>
                                <input type="text" id="member-search" placeholder="Search members..." class="input-field" value="${memberSearchTerm}">
                            </div>
                            <div>
                                <select id="member-sort" class="input-field">
                                    <option value="name" ${memberSortOption === 'name' ? 'selected' : ''}>Sort by Name</option>
                                    <option value="date" ${memberSortOption === 'date' ? 'selected' : ''}>Sort by Start Date</option>
                                </select>
                            </div>
                            <div>
                                <select id="member-status-filter" class="input-field">
                                    <option value="active" ${memberStatusFilter === 'active' ? 'selected' : ''}>Active Only</option>
                                    <option value="inactive" ${memberStatusFilter === 'inactive' ? 'selected' : ''}>Inactive Only</option>
                                    <option value="all" ${memberStatusFilter === 'all' ? 'selected' : ''}>All Statuses</option>
                                </select>
                            </div>
                        </div>

                        <ul id="member-list" class="space-y-2">
                            <!-- Populated by JS -->
                        </ul>
                    </div>
                </details>
            </div>
        </div>
        <div id="change-password-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75">
            <div class="bg-gray-800 p-6 rounded-lg shadow-xl w-full max-w-sm">
                <h4 id="password-modal-title" class="text-lg font-bold text-teal-400 mb-4">Change Password</h4>
                <form id="change-password-form" class="space-y-4">
                    <input type="hidden" id="password-member-id">
                    <div><label for="new-password" class="block text-sm font-medium text-gray-400 mb-1">New Password</label><input type="password" id="new-password" placeholder="New Password" class="input-field"></div>
                    <div class="flex justify-end space-x-2">
                        <button type="button" id="cancel-password-btn" class="btn-secondary">Cancel</button>
                        <button type="submit" class="btn-primary">Save</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    
    // Set default values for new member
    document.getElementById('member-rate').value = globalSettings.monthlyRate || 0;
    document.getElementById('member-start-date').value = new Date().toISOString().split('T')[0];

    const memberForm = document.getElementById('member-form');
    memberForm.addEventListener('submit', handleMemberForm);
    
    document.getElementById('cancel-password-btn').addEventListener('click', closeChangePasswordModal);
    document.getElementById('change-password-form').addEventListener('submit', handleChangePassword);

    // List Logic
    const updateList = () => {
        // Update Globals from DOM
        memberSearchTerm = document.getElementById('member-search').value.toLowerCase();
        memberSortOption = document.getElementById('member-sort').value;
        memberStatusFilter = document.getElementById('member-status-filter').value;
        
        let filtered = members.filter(m => {
            const matchesSearch = (m.name || '').toLowerCase().includes(memberSearchTerm) || (m.email || '').toLowerCase().includes(memberSearchTerm);
            const matchesStatus = memberStatusFilter === 'all' || (memberStatusFilter === 'active' ? (m.status !== 'inactive') : (m.status === 'inactive'));
            return matchesSearch && matchesStatus;
        });

        if (memberSortOption === 'name') {
            filtered.sort((a,b) => a.name.localeCompare(b.name));
        } else if (memberSortOption === 'date') {
            filtered.sort((a,b) => new Date(b.startDate || 0) - new Date(a.startDate || 0));
        }

        document.getElementById('member-list').innerHTML = filtered.map(m => `
            <li class="bg-gray-700/50 p-3 rounded-lg">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="font-bold">${m.name}</p>
                        <p class="text-sm text-gray-300">
                            ${m.email} | Rate: ${formatCurrency(m.rate || 0)} | 
                            <span class="${!m.status || m.status === 'active' ? 'text-green-400' : 'text-red-400'} capitalize">${m.status || 'active'}</span>
                        </p>
                    </div>
                    <div class="space-x-2 flex">
                        <button class="btn-secondary toggle-status-btn p-2" data-id="${m.id}" data-status="${m.status || 'active'}" title="${m.status === 'inactive' ? 'Activate' : 'Deactivate'}">
                            ${m.status === 'inactive' ? 
                                `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 text-green-400"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>` : 
                                `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 text-red-400"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" /></svg>`
                            }
                        </button>
                        <button class="btn-secondary edit-member-btn p-2" data-id="${m.id}" title="Edit"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 pointer-events-none"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" /></svg></button>
                        <button class="btn-secondary change-password-btn p-2" data-id="${m.id}" data-name="${m.name}" title="Change Password"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 pointer-events-none"><path stroke-linecap="round" stroke-linejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z" /></svg></button>
                    </div>
                </div>
                <div class="text-xs mt-2 grid grid-cols-2 gap-2">
                    <span class="${m.dueAmount > 0 ? 'text-red-400 font-bold' : 'text-green-400'}">Due: TZS ${formatCurrency(m.dueAmount || 0)}</span>
                    <span class="text-gray-400">Next Cycle: ${m.nextCycleDate ? new Date(m.nextCycleDate).toLocaleDateString() : 'N/A'}</span>
                </div>
            </li>
        `).join('');

        document.querySelectorAll('.edit-member-btn').forEach(btn => btn.addEventListener('click', (e) => editMember(e.target.dataset.id)));
        document.querySelectorAll('.change-password-btn').forEach(btn => btn.addEventListener('click', openChangePasswordModal));
        document.querySelectorAll('.toggle-status-btn').forEach(btn => btn.addEventListener('click', async (e) => {
            const id = e.currentTarget.dataset.id;
            const currentStatus = e.currentTarget.dataset.status;
            const newStatus = currentStatus === 'inactive' ? 'active' : 'inactive';
            
            if(confirm(`Are you sure you want to ${newStatus === 'inactive' ? 'deactivate' : 'activate'} this member?`)) {
                 try {
                    await updateDoc(doc(db, "members", id), { status: newStatus });
                } catch (err) {
                    console.error("Error updating status:", err);
                    alert("Failed to update status.");
                }
            }
        }));
    };

    document.getElementById('member-search').addEventListener('input', updateList);
    document.getElementById('member-sort').addEventListener('change', updateList);
    document.getElementById('member-status-filter').addEventListener('change', updateList);
    
    updateList();
}

function renderPayments(container) {
    const membersWithDues = members.filter(m => m.dueAmount > 0);
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Members with Outstanding Dues</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                            <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <ul id="dues-list" class="space-y-2">
                            ${membersWithDues.length > 0 ? membersWithDues.map(m => `
                                <li class="bg-gray-800/50 p-3 rounded-lg flex justify-between items-center">
                                    <div>
                                        <p class="font-bold">${m.name}</p>
                                        <p class="text-sm text-red-400">Due: TZS ${formatCurrency(m.dueAmount)}</p>
                                    </div>
                                    <button class="btn-primary record-payment-btn" data-id="${m.id}" data-name="${m.name}" data-due="${m.dueAmount}">Record Payment</button>
                                </li>
                            `).join('') : '<p class="text-gray-400">No outstanding dues.</p>'}
                        </ul>
                    </div>
                </details>
            </div>
        </div>
        <div id="add-payment-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75">
            <div class="bg-gray-800 p-6 rounded-lg shadow-xl w-full max-w-sm">
                <h4 id="payment-modal-title" class="text-lg font-bold text-teal-400 mb-4">Record Payment</h4>
                <form id="add-payment-form" class="space-y-4">
                    <input type="hidden" id="payment-member-id">
                    <div><label for="payment-amount" class="block text-sm font-medium text-gray-400 mb-1">Amount</label><input type="number" id="payment-amount" placeholder="Amount" class="input-field"></div>
                    <div class="flex justify-end space-x-2">
                        <button type="button" id="cancel-payment-btn" class="btn-secondary">Cancel</button>
                        <button type="submit" class="btn-primary">Record</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    document.querySelectorAll('.record-payment-btn').forEach(btn => btn.addEventListener('click', openPaymentModal));
    document.getElementById('cancel-payment-btn').addEventListener('click', closePaymentModal);
    document.getElementById('add-payment-form').addEventListener('submit', handleAddPayment);
}

function renderCheckins(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Recent Member Check-ins</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <ul id="checkins-list" class="space-y-3">
                            ${checkins.sort((a,b) => (b.checkIn?.toMillis() || 0) - (a.checkIn?.toMillis() || 0)).map(c => `
                                <li class="bg-gray-800/50 p-4 rounded-lg flex flex-col md:flex-row justify-between items-start md:items-center space-y-3 md:space-y-0">
                                    <div>
                                        <p class="font-bold text-lg">${members.find(m=>m.id===c.memberId)?.name || 'Unknown Member'}</p>
                                        <div class="text-sm text-gray-300 mt-1 space-y-1">
                                            <p><span class="text-gray-500 w-20 inline-block">Check-in:</span> ${c.checkIn ? new Date(c.checkIn.toDate()).toLocaleString() : 'N/A'}</p>
                                            <p><span class="text-gray-500 w-20 inline-block">Check-out:</span> ${c.checkOut ? new Date(c.checkOut.toDate()).toLocaleString() : '<span class="text-teal-400">Active</span>'}</p>
                                        </div>
                                    </div>
                                    <button class="btn-secondary text-xs px-2 py-2 edit-checkin-btn" data-id="${c.id}" title="Edit Times">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" /></svg>
                                    </button>
                                </li>
                            `).join('')}
                        </ul>
                    </div>
                </details>
            </div>
        </div>

        <!-- Modal -->
        <div id="checkin-modal" class="fixed inset-0 bg-black/80 hidden flex items-center justify-center p-4 z-50">
            <div class="bg-gray-800 p-6 rounded-lg w-full max-w-md">
                <h3 class="text-xl font-bold text-white mb-4">Edit Check-in</h3>
                <form id="edit-checkin-form" class="space-y-4">
                    <input type="hidden" id="edit-checkin-id">
                    <div>
                        <label class="block text-sm text-gray-400 mb-1">Check-in Time</label>
                        <input type="datetime-local" id="edit-checkin-in" class="input-field w-full step-1">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-400 mb-1">Check-out Time</label>
                        <input type="datetime-local" id="edit-checkin-out" class="input-field w-full step-1">
                        <p class="text-xs text-gray-500 mt-1">Leave empty if session is still active</p>
                    </div>
                    <div class="flex justify-end space-x-3 mt-6">
                        <button type="button" id="cancel-checkin-edit" class="btn-secondary">Cancel</button>
                        <button type="submit" class="btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    `;

    // Event Listeners
    document.querySelectorAll('.edit-checkin-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = e.target.dataset.id;
            const checkin = checkins.find(c => c.id === id);
            if (!checkin) return;
            
            document.getElementById('edit-checkin-id').value = id;
            
            // Format for datetime-local: YYYY-MM-DDThh:mm:ss
            const formatForInput = (timestamp) => {
                if (!timestamp) return '';
                const d = timestamp.toDate();
                d.setMinutes(d.getMinutes() - d.getTimezoneOffset()); 
                return d.toISOString().slice(0, 16);
            };

            document.getElementById('edit-checkin-in').value = formatForInput(checkin.checkIn);
            document.getElementById('edit-checkin-out').value = formatForInput(checkin.checkOut);
            
            document.getElementById('checkin-modal').classList.remove('hidden');
        });
    });

    document.getElementById('cancel-checkin-edit').addEventListener('click', () => {
        document.getElementById('checkin-modal').classList.add('hidden');
    });

    document.getElementById('edit-checkin-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const id = document.getElementById('edit-checkin-id').value;
        const inVal = document.getElementById('edit-checkin-in').value;
        const outVal = document.getElementById('edit-checkin-out').value;
        
        if (!inVal) {
            alert("Check-in time is required");
            return;
        }

        try {
            const dataToUpdate = {
                checkIn: Timestamp.fromDate(new Date(inVal)),
                checkOut: outVal ? Timestamp.fromDate(new Date(outVal)) : null
            };
            
            await updateDoc(doc(db, "checkins", id), dataToUpdate);
            alert("Check-in updated successfully");
            document.getElementById('checkin-modal').classList.add('hidden');
        } catch (error) {
            console.error("Error updating checkin:", error);
            alert("Failed to update checkin");
        }
    });
}

function renderMeasurements(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Record Measurements</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <form id="measurements-form" class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div><label for="measure-member" class="block text-sm font-medium text-gray-400 mb-1">Member</label><select id="measure-member" class="input-field" required><option value="">Select Member</option>${members.map(m => `<option value="${m.id}">${m.name}</option>`).join('')}</select></div>
                                <div><label for="measure-date" class="block text-sm font-medium text-gray-400 mb-1">Date</label><input type="date" id="measure-date" class="input-field" required value="${new Date().toISOString().split('T')[0]}"></div>
                            </div>
                            
                            <div id="dynamic-measurement-fields" class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                <!-- Fields will be injected here based on member gender -->
                                <p class="text-gray-400 col-span-full">Select a member to see measurement fields.</p>
                            </div>

                            <button type="submit" class="btn-primary w-full">Save Measurements</button>
                        </form>
                    </div>
                </details>
            </div>

            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Measurement History</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <div class="mb-4">
                            <select id="filter-measure-member" class="input-field w-full md:w-1/3"><option value="">Select Member to View History</option>${members.map(m => `<option value="${m.id}">${m.name}</option>`).join('')}</select>
                        </div>
                        <div id="view-mode-container" class="flex space-x-4 bg-gray-800 p-1 rounded-lg mb-4 hidden w-fit">
                            <label class="inline-flex items-center px-3 py-1 rounded cursor-pointer hover:bg-gray-700 transition-colors">
                                <input type="radio" name="viewMode" value="text" checked class="hidden peer">
                                <span class="text-gray-400 peer-checked:text-teal-400 font-medium">Text</span>
                            </label>
                            <label class="inline-flex items-center px-3 py-1 rounded cursor-pointer hover:bg-gray-700 transition-colors">
                                <input type="radio" name="viewMode" value="graph" class="hidden peer">
                                <span class="text-gray-400 peer-checked:text-teal-400 font-medium">Graph</span>
                            </label>
                        </div>
                        <div id="measurements-content" class="hidden">
                            <div id="measurements-list" class="space-y-2">
                                <!-- List populated by JS -->
                            </div>
                            <div id="measurements-chart-container" class="hidden" style="height: 400px;">
                                <canvas id="measurementsChart"></canvas>
                            </div>
                        </div>
                    </div>
                </details>
            </div>
        </div>
    `;

    const form = document.getElementById('measurements-form');
    form.addEventListener('submit', handleSaveMeasurements);

    const memberSelect = document.getElementById('measure-member');
    memberSelect.addEventListener('change', (e) => {
        const memberId = e.target.value;
        const fieldsContainer = document.getElementById('dynamic-measurement-fields');
        
        if (!memberId) {
            fieldsContainer.innerHTML = '<p class="text-gray-400 col-span-full">Select a member to see measurement fields.</p>';
            return;
        }

        const member = members.find(m => m.id === memberId);
        const gender = member?.gender || 'Male'; // Default to Male if not specified
        // Normalize gender string to match keys (Male/Female)
        const genderKey = gender.charAt(0).toUpperCase() + gender.slice(1).toLowerCase();
        const fields = measurementFields[genderKey] || measurementFields['Male'];

        fieldsContainer.innerHTML = fields.map(field => `
            <div>
                <label class="block text-sm font-medium text-gray-400 mb-1">${field.label}</label>
                <input type="number" step="0.1" id="measure-${field.id}" class="input-field" data-field-id="${field.id}">
            </div>
        `).join('');
    });

    const filterSelect = document.getElementById('filter-measure-member');
    filterSelect.addEventListener('change', () => updateMeasurementsList(filterSelect.value));
    
    document.getElementsByName('viewMode').forEach(radio => {
        radio.addEventListener('change', () => updateMeasurementsList(filterSelect.value));
    });

    updateMeasurementsList('');
}

function updateMeasurementsList(memberId) {
    const listContainer = document.getElementById('measurements-list');
    const chartContainer = document.getElementById('measurements-chart-container');
    const viewModeContainer = document.getElementById('view-mode-container');
    const contentContainer = document.getElementById('measurements-content');
    const viewMode = document.querySelector('input[name="viewMode"]:checked').value;

    if (!memberId) {
        viewModeContainer.classList.add('hidden');
        contentContainer.classList.add('hidden');
        return;
    }

    viewModeContainer.classList.remove('hidden');
    contentContainer.classList.remove('hidden');

    let filtered = measurements.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    if (memberId) {
        filtered = filtered.filter(m => m.memberId === memberId);
    }

    const fieldOrder = ['weight', 'height', 'chest', 'bust', 'lArm', 'rArm', 'abdomen', 'waist', 'hips', 'lThigh', 'rThigh'];

    if (viewMode === 'graph') {
        listContainer.classList.add('hidden');
        chartContainer.classList.remove('hidden');

        if (filtered.length === 0) {
            chartContainer.innerHTML = '<p class="text-gray-400 flex items-center justify-center h-full">No measurements found for this member.</p>';
            return;
        }

        // Ensure canvas exists
        if (!chartContainer.querySelector('canvas')) {
             chartContainer.innerHTML = '<canvas id="measurementsChart"></canvas>';
        }

        // Sort ascending for chart
        const chartData = [...filtered].sort((a, b) => new Date(a.date) - new Date(b.date));
        renderMeasurementsChart(chartData, fieldOrder);

    } else {
        // Text Mode
        listContainer.classList.remove('hidden');
        chartContainer.classList.add('hidden');

        if (filtered.length === 0) {
            listContainer.innerHTML = '<p class="text-gray-400">No measurements found.</p>';
            return;
        }

        listContainer.innerHTML = filtered.map(m => {
            const member = members.find(mem => mem.id === m.memberId);
            const gender = member?.gender || 'Male';
            const genderKey = gender.charAt(0).toUpperCase() + gender.slice(1).toLowerCase();
            const fields = measurementFields[genderKey] || measurementFields['Male'];

            // Filter fields that have values in this measurement record
            let displayFields = fields.filter(f => m[f.id] !== undefined && m[f.id] !== '');
            
            // Sort display fields
            displayFields.sort((a, b) => {
                return fieldOrder.indexOf(a.id) - fieldOrder.indexOf(b.id);
            });

            
            // Calculate BMI for display
            const heightM = m.height ? m.height * 0.0254 : 0;
            const bmi = (m.weight && heightM) ? parseFloat((m.weight / (heightM * heightM)).toFixed(2)) : '-';

            return `
            <details class="bg-gray-800/50 rounded-lg group">
                <summary class="p-4 flex justify-between items-start cursor-pointer list-none">
                    <div>
                        <p class="font-bold text-lg text-teal-400">${member?.name || 'Unknown Member'}</p>
                        <p class="text-sm text-gray-400">${new Date(m.date).toLocaleDateString()}</p>
                    </div>
                    <div class="flex items-center space-x-2">
                        <button class="btn-danger text-xs px-2 py-2 delete-measure-btn z-10 relative" data-id="${m.id}" title="Delete"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" /></svg></button>
                        <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </div>
                </summary>
                <div class="p-4 pt-0 border-t border-gray-700/50 text-sm mt-2">
                    <div class="grid grid-cols-3 gap-2 mb-3 pb-3 border-b border-gray-700/50 font-semibold text-white text-center">
                        <p>Height: <span class="text-teal-400">${m.height || '-'}</span> in</p>
                        <p>Weight: <span class="text-teal-400">${m.weight || '-'}</span> kg</p>
                        <p>BMI: <span class="text-teal-400">${bmi}</span></p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
                        ${displayFields.filter(f => !['weight', 'height'].includes(f.id)).map(f => `<p><span class="text-gray-400">${f.label.split('(')[0]}:</span> ${m[f.id]} ${f.id === 'weight' ? 'kg' : 'in'}</p>`).join('')}
                    </div>
                </div>
            </details>
        `}).join('');

        document.querySelectorAll('.delete-measure-btn').forEach(btn => {
            btn.addEventListener('click', (e) => deleteItem('measurements', e.target.dataset.id, 'Measurement'));
        });
    }
}

function renderMeasurementsChart(data, fieldOrder) {
    const ctx = document.getElementById('measurementsChart').getContext('2d');
    
    // Sort data
    const sortedData = [...data].sort((a,b) => new Date(a.date) - new Date(b.date));
    const labels = sortedData.map(m => new Date(m.date).toLocaleDateString());

    // 1. Filter keys excluding weight/height/BMI if in main graph
    // But we need to support switching views.
    // Let's modify the previous setup or add buttons to toggle.
    // For now, implementing the requested logic: Main graph EXCLUDES Weight.
    // We also need to Calculate BMI.
    
    // Calculate BMI for each record if possible
    sortedData.forEach(m => {
        if (m.weight && m.height) {
            // BMI = weight(kg) / (height(m))^2
            // Height is in inches. 1 inch = 0.0254 m
            const heightM = m.height * 0.0254;
            m.bmi = parseFloat((m.weight / (heightM * heightM)).toFixed(2));
        }
    });

    const chartContainer = document.getElementById('measurements-chart-container');
    
    // Create Mode Switcher if not exists
    if (!document.getElementById('chart-mode-switcher')) {
        const switcher = document.createElement('div');
        switcher.id = 'chart-mode-switcher';
        switcher.className = 'flex space-x-2 mb-4 justify-center flex-wrap';
        switcher.innerHTML = `
            <button class="px-3 py-1 bg-gray-600 rounded text-sm hover:bg-gray-500 chart-mode-btn active" data-mode="main">Body</button>
            <button class="px-3 py-1 bg-gray-600 rounded text-sm hover:bg-gray-500 chart-mode-btn" data-mode="height">Height</button>
            <button class="px-3 py-1 bg-gray-600 rounded text-sm hover:bg-gray-500 chart-mode-btn" data-mode="weight">Weight</button>
            <button class="px-3 py-1 bg-gray-600 rounded text-sm hover:bg-gray-500 chart-mode-btn" data-mode="bmi">BMI</button>
        `;
        chartContainer.insertBefore(switcher, chartContainer.firstChild);
        
        // Add click handlers
        switcher.querySelectorAll('.chart-mode-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                switcher.querySelectorAll('.chart-mode-btn').forEach(b => b.classList.remove('bg-teal-600', 'active'));
                e.target.classList.add('bg-teal-600', 'active');
                updateChart(e.target.dataset.mode);
            });
        });
        // Set Request Mode active (Main)
        switcher.querySelector('[data-mode="main"]').classList.add('bg-teal-600');
    }

    let chartInstance = window.measurementsChartInstance;

    function updateChart(mode) {
        let datasets = [];

        if (mode === 'height') {
            const hue = 240; // Blue
             datasets.push({
                label: 'Height (in)',
                data: sortedData.map(m => m.height || null),
                borderColor: `hsl(${hue}, 70%, 60%)`,
                backgroundColor: `hsl(${hue}, 70%, 60%)`,
                tension: 0.1,
                spanGaps: true
            });
        } else if (mode === 'weight') {
            const hue = 0; // Red
             datasets.push({
                label: 'Weight (kg)',
                data: sortedData.map(m => m.weight || null),
                borderColor: `hsl(${hue}, 70%, 60%)`,
                backgroundColor: `hsl(${hue}, 70%, 60%)`,
                tension: 0.1,
                spanGaps: true
            });
        } else if (mode === 'bmi') {
             const hue = 120; // Green
             datasets.push({
                label: 'BMI',
                data: sortedData.map(m => m.bmi || null),
                borderColor: `hsl(${hue}, 70%, 60%)`,
                backgroundColor: `hsl(${hue}, 70%, 60%)`,
                tension: 0.1,
                spanGaps: true
            });
        } else {
             // Main: All except Weight, Height, BMI
             const allKeys = new Set();
             sortedData.forEach(m => {
                Object.keys(m).forEach(key => {
                    if (!['id', 'memberId', 'date', 'timestamp', 'weight', 'height', 'bmi'].includes(key)) {
                        allKeys.add(key);
                    }
                });
            });
            const sortedKeys = Array.from(allKeys).sort((a, b) => {
                return fieldOrder.indexOf(a) - fieldOrder.indexOf(b);
            });

             datasets = sortedKeys.map((key, index) => {
                const hue = (index * 137.508) % 360; 
                const color = `hsl(${hue}, 70%, 60%)`;
                return {
                    label: key.replace(/([A-Z])/g, ' $1').trim().replace(/^./, str => str.toUpperCase()),
                    data: sortedData.map(m => m[key] || null),
                    borderColor: color,
                    backgroundColor: color,
                    tension: 0.1,
                    spanGaps: true
                };
            });
        }

        if (chartInstance) {
            chartInstance.destroy();
        }

        chartInstance = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: datasets
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        labels: { color: '#9CA3AF' }
                    }
                },
                scales: {
                    x: {
                        ticks: { color: '#9CA3AF' },
                        grid: { color: '#374151' }
                    },
                    y: {
                        ticks: { color: '#9CA3AF' },
                        grid: { color: '#374151' }
                    }
                }
            }
        });
        window.measurementsChartInstance = chartInstance;
    }
    
    // Initial Render
    const activeMode = document.querySelector('.chart-mode-btn.active')?.dataset.mode || 'main';
    updateChart(activeMode);
}

async function handleSaveMeasurements(e) {
    e.preventDefault();
    const form = e.target;
    const memberId = form['measure-member'].value;
    const date = form['measure-date'].value;

    if (!memberId || !date) {
        alert("Member and Date are required.");
        return;
    }

    const member = members.find(m => m.id === memberId);
    const gender = member?.gender || 'Male';
    const genderKey = gender.charAt(0).toUpperCase() + gender.slice(1).toLowerCase();
    const fields = measurementFields[genderKey] || measurementFields['Male'];

    const data = {
        memberId,
        date,
        timestamp: serverTimestamp()
    };

    // Collect data from dynamic fields
    fields.forEach(field => {
        const input = document.getElementById(`measure-${field.id}`);
        if (input && input.value) {
            data[field.id] = Number(input.value);
        }
    });

    try {
        await addDoc(collection(db, "measurements"), data);
        alert("Measurements saved successfully!");
        form.reset();
        form['measure-date'].value = new Date().toISOString().split('T')[0]; // Reset date to today
        // Trigger change event to clear fields or re-render empty ones
        document.getElementById('measure-member').dispatchEvent(new Event('change'));
    } catch (error) {
        console.error("Error saving measurements:", error);
        alert("Failed to save measurements.");
    }
}

function renderMeals(container) {
    const memberOptions = members.sort((a,b) => a.name.localeCompare(b.name)).map(m => `<option value="${m.id}">${m.name}</option>`).join('');

    container.innerHTML = `
        <div class="space-y-6">
             <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">View Member Meals</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-400 mb-1">Select Member</label>
                                <select id="meals-member-select" class="input-field w-full">
                                    <option value="">-- Select Member --</option>
                                    ${memberOptions}
                                </select>
                            </div>
                        </div>
                        
                        <!-- Filter Section -->
                        <div id="meals-filter-section" class="hidden grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-gray-600 pt-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-400 mb-1">Start Date</label>
                                <input type="date" id="meals-start-date" class="input-field w-full">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-400 mb-1">End Date</label>
                                <input type="date" id="meals-end-date" class="input-field w-full">
                            </div>
                        </div>

                        <div id="meals-results-area" class="space-y-4 mt-4">
                            <p class="text-gray-400 text-center">Select a member to view their meals.</p>
                        </div>
                    </div>
                </details>
            </div>
        </div>
    `;

    // Event listeners
    const memberSelect = document.getElementById('meals-member-select');
    const startDateInput = document.getElementById('meals-start-date');
    const endDateInput = document.getElementById('meals-end-date');

    const updateView = () => {
        const memberId = memberSelect.value;
        const resultArea = document.getElementById('meals-results-area');
        const filterSection = document.getElementById('meals-filter-section');

        if (!memberId) {
            resultArea.innerHTML = '<p class="text-gray-400 text-center">Select a member to view their meals.</p>';
            filterSection.classList.add('hidden');
            return;
        }
        
        filterSection.classList.remove('hidden');

        const startDate = startDateInput.value;
        const endDate = endDateInput.value;

        let filtered = meals.filter(m => m.memberId === memberId).sort((a,b) => new Date(b.date) - new Date(a.date));
        
        if (startDate) filtered = filtered.filter(m => m.date >= startDate);
        if (endDate) filtered = filtered.filter(m => m.date <= endDate);

        if (filtered.length === 0) {
            resultArea.innerHTML = '<p class="text-gray-400 text-center">No meal entries found for this member.</p>';
            return;
        }

        resultArea.innerHTML = filtered.map(m => `
            <div class="bg-gray-800/50 p-4 rounded-lg">
                <div class="flex flex-col md:flex-row justify-between md:items-center border-b border-gray-600 pb-2 mb-2">
                    <span class="font-bold text-lg text-white">${new Date(m.date).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' })}</span>
                    <span class="text-teal-400 font-semibold mt-1 md:mt-0">Water: ${m.waterIntake} L</span>
                </div>
                <div class="text-gray-300">
                    <p class="font-semibold text-xs text-gray-500 uppercase tracking-widest mb-1">Food Intake</p>
                    <p class="whitespace-pre-wrap">${m.foodIntake || 'No details.'}</p>
                </div>
            </div>
        `).join('');
    };

    memberSelect.addEventListener('change', updateView);
    startDateInput.addEventListener('change', updateView);
    endDateInput.addEventListener('change', updateView);
}

function renderConsultations(container) {
    // Sort members for the dropdown
    const sortedMembers = [...members].sort((a, b) => a.name.localeCompare(b.name));

    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Consultation History</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <div class="mb-4">
                             <label class="block text-sm font-medium text-gray-400 mb-2">Select Member to View History</label>
                             <select id="consultation-admin-filter" class="input-field w-full md:w-1/2">
                                <option value="">-- Select Member --</option>
                                ${sortedMembers.map(m => `<option value="${m.id}">${m.name}</option>`).join('')}
                             </select>
                        </div>
                        <div id="consultation-admin-list" class="space-y-4">
                            <p class="text-gray-400">Please select a member to view their consultation history.</p>
                        </div>
                    </div>
                </details>
            </div>
        </div>
    `;

    document.getElementById('consultation-admin-filter').addEventListener('change', (e) => {
        const memberId = e.target.value;
        const listContainer = document.getElementById('consultation-admin-list');
        
        if (!memberId) {
            listContainer.innerHTML = '<p class="text-gray-400">Please select a member to view their consultation history.</p>';
            return;
        }

        const memberNotes = professionalNotes
            .filter(n => n.memberId === memberId)
            .sort((a, b) => new Date(b.date) - new Date(a.date));

        if (memberNotes.length === 0) {
            listContainer.innerHTML = '<p class="text-gray-400">No consultation notes found for this member.</p>';
            return;
        }

        listContainer.innerHTML = memberNotes.map(note => {
            // Try to find professional name from cached list, fallback to stored name in note, or Unknown
            const profName = professionals.find(p => p.id === note.professionalId)?.name || note.professionalName || 'Unknown Professional';
            
            return `
            <div class="bg-gray-800/50 p-4 rounded-lg border-l-4 border-teal-400">
                <div class="flex justify-between items-start mb-2">
                    <div>
                        <p class="font-bold text-lg text-white">By: ${profName}</p>
                        <p class="text-xs text-gray-400">${new Date(note.date).toLocaleDateString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}</p>
                    </div>
                </div>
                <div class="text-gray-300 mt-2 text-sm whitespace-pre-wrap bg-gray-900/30 p-3 rounded">${note.note}</div>
            </div>
            `;
        }).join('');
    });
}

function renderReports(container) {
    container.innerHTML = `
        <div class="space-y-8">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <details class="group" open>
                    <summary class="flex justify-between items-center cursor-pointer list-none mb-4">
                        <h3 class="text-lg font-bold text-teal-400">Member Payment Report</h3>
                        <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="group-open:animate-fadeIn">
                        <form id="payment-report-form" class="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                            <div><label for="report-month" class="block text-sm font-medium text-gray-400 mb-1">Month</label><input type="month" id="report-month" class="input-field"></div>
                            <div><label for="report-member" class="block text-sm font-medium text-gray-400 mb-1">Member (Optional)</label><select id="report-member" class="input-field"><option value="">All Members</option>${members.map(m => `<option value="${m.id}">${m.name}</option>`).join('')}</select></div>
                            <button type="submit" class="btn-primary">Generate Report</button>
                        </form>
                        <div id="payment-report-results" class="mt-4"></div>
                    </div>
                </details>
            </div>
        </div>
    `;
    document.getElementById('payment-report-form').addEventListener('submit', generatePaymentReport);
}

function renderSettings(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-6 rounded-lg space-y-3">
                <h3 class="text-lg font-bold text-teal-400 mb-4">Admin Profile</h3>
                <p><span class="font-bold text-gray-400">User ID:</span> <span class="text-white">${currentUser.uid}</span></p>
                <p><span class="font-bold text-gray-400">Email:</span> <span class="text-white">${currentUser.email}</span></p>
                <p><span class="font-bold text-gray-400">Role:</span> <span class="text-white capitalize">${currentUser.role}</span></p>
            </div>

            <div class="bg-gray-700/50 p-6 rounded-lg">
                <details class="group">
                    <summary class="flex justify-between items-center font-medium cursor-pointer list-none">
                        <h3 class="text-lg font-bold text-teal-400">Notifications</h3>
                         <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="text-neutral-600 mt-3 group-open:animate-fadeIn">
                         <form id="notification-form" class="space-y-4 mt-4">
                            <div><label for="notification-message" class="block text-sm font-medium text-gray-400 mb-1">Message</label><input type="text" id="notification-message" placeholder="Notification message" class="input-field"></div>
                            <div><label for="notification-start-date" class="block text-sm font-medium text-gray-400 mb-1">Start Date</label><input type="date" id="notification-start-date" class="input-field"></div>
                            <div><label for="notification-end-date" class="block text-sm font-medium text-gray-400 mb-1">End Date</label><input type="date" id="notification-end-date" class="input-field"></div>
                            <button type="submit" class="btn-primary w-full">Save Notification</button>
                        </form>
                    </div>
                </details>
            </div>

            <div class="bg-gray-700/50 p-6 rounded-lg">
                <details class="group">
                    <summary class="flex justify-between items-center font-medium cursor-pointer list-none">
                        <h3 class="text-lg font-bold text-teal-400">Membership Settings</h3>
                         <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="text-neutral-600 mt-3 group-open:animate-fadeIn">
                        <form id="membership-settings-form" class="space-y-4 mt-4">
                            <div>
                                <label for="monthly-rate" class="block text-sm font-medium text-gray-400 mb-1">Monthly Membership Rate (TZS)</label>
                                <input type="number" id="monthly-rate" placeholder="0.00" class="input-field" step="0.01">
                            </div>
                            <button type="submit" class="btn-primary">Save Settings</button>
                        </form>
                    </div>
                </details>
            </div>

            <div class="bg-gray-700/50 p-6 rounded-lg">
                <details class="group">
                    <summary class="flex justify-between items-center font-medium cursor-pointer list-none">
                        <h3 class="text-lg font-bold text-teal-400">Gym Rules</h3>
                         <span class="transition group-open:rotate-180 text-teal-400">
                             <svg fill="none" height="24" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="24"><path d="M6 9l6 6 6-6"></path></svg>
                        </span>
                    </summary>
                    <div class="text-neutral-600 mt-3 group-open:animate-fadeIn">
                        <form id="rules-form" class="space-y-4 mt-4">
                            <div>
                                <label for="gym-rules" class="block text-sm font-medium text-gray-400 mb-1">Edit Rules (Numbered List)</label>
                                <textarea id="gym-rules" rows="10" class="input-field" placeholder="1. Rule one..."></textarea>
                            </div>
                            <button type="submit" class="btn-primary">Save Rules</button>
                        </form>
                    </div>
                </details>
            </div>
        </div>
    `;

    // Membership Settings Logic
    const membershipForm = document.getElementById('membership-settings-form');
    const monthlyRateInput = document.getElementById('monthly-rate');

    getDoc(doc(db, "settings", "general")).then(docSnap => {
        if (docSnap.exists()) {
            monthlyRateInput.value = docSnap.data().monthlyRate || '';
        }
    });

    membershipForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        try {
            await setDoc(doc(db, "settings", "general"), {
                monthlyRate: parseFloat(monthlyRateInput.value) || 0,
                updatedAt: serverTimestamp()
            }, { merge: true });
            alert("Membership settings saved successfully!");
        } catch (error) {
            console.error("Error saving membership settings:", error);
            alert("Failed to save settings.");
        }
    });

    // Notifications Logic
    document.getElementById('notification-form').addEventListener('submit', handleNotificationForm);

    // Rules Logic
    const rulesForm = document.getElementById('rules-form');
    const rulesInput = document.getElementById('gym-rules');

    // Fetch existing rules
    getDoc(doc(db, "settings", "rules")).then(docSnap => {
        if (docSnap.exists()) {
            rulesInput.value = docSnap.data().content || '';
        }
    });

    rulesForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        try {
            await setDoc(doc(db, "settings", "rules"), {
                content: rulesInput.value,
                updatedAt: serverTimestamp()
            });
            alert("Rules saved successfully!");
        } catch (error) {
            console.error("Error saving rules:", error);
            alert("Failed to save rules.");
        }
    });
}

// --- DATA MANIPULATION & EVENT HANDLERS ---

async function deleteItem(collectionName, id, itemName) {
    if (confirm(`Are you sure you want to delete this ${itemName}?`)) {
        try {
            await deleteDoc(doc(db, collectionName, id));
            alert(`${itemName} deleted successfully.`);
        } catch (error) {
            console.error(`Error deleting ${itemName}:`, error);
            alert(`Failed to delete ${itemName}.`);
        }
    }
}

async function handleAddSession(e) {
    e.preventDefault();
    const form = e.target;
    const sessionData = {
        memberId: form['session-member'].value,
        trainerId: form['session-trainer'].value,
        date: form['session-date'].value,
        time: form['session-time'].value,
    };
    if (!sessionData.date || !sessionData.time) {
        alert("Please select a date and time.");
        return;
    }
    try {
        await addDoc(collection(db, "schedule"), sessionData);
        form.reset();
        alert("Session booked successfully!");
    } catch (error) {
        console.error("Error booking session:", error);
        alert("Failed to book session.");
    }
}

async function handleTrainerForm(e) {
    e.preventDefault();
    const form = e.target;
    const id = form['trainer-id-input'].value;
    const data = {
        name: form['trainer-name'].value,
        gender: form['trainer-gender'].value,
        specialization: form['trainer-specialization'].value,
        category: form['trainer-specialization'].value, // Keep category for backward compat if needed
        charges: Number(form['trainer-charges'].value),
        phone: form['trainer-phone'].value,
        email: form['trainer-email'].value,
    };

    try {
        if (id) {
            // Updating existing professional
            await updateDoc(doc(db, "professionals", id), data);
            alert("Professional updated successfully!");
        } else {
            // Creating new professional
            // 1. Generate password
            const firstName = data.name.split(' ')[0];
            if (!firstName || !data.email) {
                alert("Name and Email are required to create a professional account.");
                return;
            }
            const formattedFirstName = firstName.charAt(0).toUpperCase() + firstName.slice(1).toLowerCase();
            const generatedPassword = `${formattedFirstName}@${new Date().getFullYear()}`;

            // 2. Create user in Firebase Auth
            const secondaryApp = initializeApp(firebaseConfig, `secondary-auth-prof-${Date.now()}`);
            const secondaryAuth = getAuth(secondaryApp);

            const userCredential = await createUserWithEmailAndPassword(secondaryAuth, data.email, generatedPassword);
            const newUid = userCredential.user.uid;

            // 3. Save to Firestore
            const batch = writeBatch(db);
            
            // Professional document
            const profRef = doc(db, "professionals", newUid);
            batch.set(profRef, data);

            // User role document
            const userRef = doc(db, "users", newUid);
            batch.set(userRef, {
                email: data.email,
                role: 'professional',
                username: data.email
            });

            await batch.commit();
            await signOut(secondaryAuth);

            alert(`Professional created successfully! Their password is: ${generatedPassword}`);
        }
        form.reset();
    } catch (error) {
        console.error("Error saving professional:", error);
         if (error.code === 'auth/email-already-in-use') {
            alert("Failed to save. The email address is already in use.");
        } else {
            alert("Failed to save professional. See console for details.");
        }
    }
}

function editTrainer(id) {
    const trainer = professionals.find(p => p.id === id);
    if (!trainer) return;
    const form = document.getElementById('trainer-form');
    form['trainer-id-input'].value = trainer.id;
    form['trainer-name'].value = trainer.name;
    form['trainer-gender'].value = trainer.gender;
    form['trainer-specialization'].value = trainer.specialization || trainer.category || '';
    form['trainer-charges'].value = trainer.charges || '';
    form['trainer-phone'].value = trainer.phone;
    form['trainer-email'].value = trainer.email || '';
    
    // Handle gender dropdown if value doesn't match options (e.g. text from old data)
    const genderSelect = form['trainer-gender'];
    if (!['Male', 'Female'].includes(trainer.gender) && trainer.gender) {
        // If gender is something else, maybe just default or leave empty?
        // Or adding 'Other' option temporarily? 
        // For now, let's assume standard data or user will update it.
    }

    form.scrollIntoView({ behavior: 'smooth' });
}

async function handleMemberForm(e) {
    e.preventDefault();
    const form = e.target;
    const id = form['member-id-input'].value;
    
    // Validate Start Date
    const startDateVal = form['member-start-date'].value;
    if (!startDateVal) {
        alert("Start Date is required.");
        return;
    }

    const data = {
        name: form['member-name'].value,
        contact: form['member-contact'].value,
        email: form['member-email'].value,
        dob: form['member-dob'].value,
        gender: form['member-gender'].value,
        rate: Number(form['member-rate'].value),
        startDate: startDateVal,
        dueAmount: Number(form['member-due-amount'].value) || 0,
        notes: form['member-notes'].value,
    };

    try {
        if (id) {
            // Update existing member
            await updateDoc(doc(db, "members", id), data);
            alert("Member updated successfully!");
        } else {
            // Create New Member
            const firstName = data.name.split(' ')[0];
            if (!firstName || !data.dob) {
                alert("Full Name and Date of Birth are required.");
                return;
            }
            
            // Password Generation
            const birthYear = new Date(data.dob).getFullYear();
            const formattedFirstName = firstName.charAt(0).toUpperCase() + firstName.slice(1).toLowerCase();
            const generatedPassword = `${formattedFirstName}@${birthYear}`;

            // Calculate Initial Dues & Cycle
            // Cycle Logic: Cycle starts on Start Date.
            // First payment of 'Rate' is due immediately (or at end of cycle? Usually start).
            // Plus any 'Past Due' entered in the `dueAmount` field.
            
            // The value currently in data.dueAmount is the "Past Due" entered by user.
            const pastDue = data.dueAmount;
            const currentPeriodFee = data.rate;
            
            data.dueAmount = pastDue + currentPeriodFee;
            data.totalMonths = 0;
            data.totalAmount = 0;
            data.paidAmount = 0;
            
            // Set Next Cycle Date (Start Date + 28 Days)
            const sDate = new Date(data.startDate);
            sDate.setDate(sDate.getDate() + 28);
            data.nextCycleDate = sDate.toISOString().split('T')[0];
            
            data.status = 'active';

            // Create Auth User
            const secondaryApp = initializeApp(firebaseConfig, `secondary-auth-${Date.now()}`);
            const secondaryAuth = getAuth(secondaryApp);
            
            const userCredential = await createUserWithEmailAndPassword(secondaryAuth, data.email, generatedPassword);
            const newUid = userCredential.user.uid;
            
            const batch = writeBatch(db);
            batch.set(doc(db, "members", newUid), data);
            batch.set(doc(db, "users", newUid), {
                email: data.email,
                role: 'member',
                username: data.email
            });

            await batch.commit();
            await signOut(secondaryAuth);

            alert(`Member created successfully! Password: ${generatedPassword}`);
        }
        form.reset();
        // Reset defaults for next entry
        document.getElementById('member-rate').value = globalSettings.monthlyRate || 0;
        document.getElementById('member-start-date').value = new Date().toISOString().split('T')[0];
    } catch (error) {
        console.error("Error saving member:", error);
        alert(error.code === 'auth/email-already-in-use' ? "Email already in use." : "Failed to save member.");
    }
}

function editMember(id) {
    const member = members.find(m => m.id === id);
    if (!member) return;
    const form = document.getElementById('member-form');
    
    // Map fields
    form['member-id-input'].value = member.id;
    form['member-name'].value = member.name;
    form['member-contact'].value = member.contact || '';
    form['member-email'].value = member.email;
    form['member-dob'].value = member.dob;
    form['member-gender'].value = member.gender;
    form['member-rate'].value = member.rate;
    form['member-start-date'].value = member.startDate;
    form['member-due-amount'].value = member.dueAmount;
    form['member-notes'].value = member.notes || '';

    form.scrollIntoView({ behavior: 'smooth' });
}

function openChangePasswordModal(e) {
    const { id, name } = e.target.dataset;
    document.getElementById('password-modal-title').textContent = `Change Password for ${name}`;
    document.getElementById('password-member-id').value = id;
    document.getElementById('change-password-modal').classList.remove('hidden');
}

function closeChangePasswordModal() {
    document.getElementById('change-password-modal').classList.add('hidden');
    document.getElementById('change-password-form').reset();
}

async function handleChangePassword(e) {
    e.preventDefault();
    const memberId = document.getElementById('password-member-id').value;
    const newPassword = document.getElementById('new-password').value;

    if (!newPassword || newPassword.length < 6) {
        alert("Password must be at least 6 characters long.");
        return;
    }

    // This is a placeholder for a secure backend function call
    // In a real app, you would call a Cloud Function that uses the Firebase Admin SDK
    // to update the user's password, as this is a privileged operation.
    try {
        // The following is NOT secure and will NOT work from the client-side
        // It is a placeholder to demonstrate the flow.
        // await updatePassword(user, newPassword); // This is a client-side SDK function that requires re-authentication.
        
        // SIMULATING a backend call
        console.log(`Request to change password for user ${memberId} to "${newPassword}"`);
        alert("Password change request sent. In a real app, this would be handled by a secure backend function.");
        
        closeChangePasswordModal();
    } catch (error) {
        console.error("Error changing password:", error);
        alert("Failed to change password. This requires a secure backend implementation.");
    }
}

function openPaymentModal(e) {
    const { id, name, due } = e.target.dataset;
    document.getElementById('payment-modal-title').textContent = `Record Payment for ${name}`;
    document.getElementById('payment-member-id').value = id;
    document.getElementById('payment-amount').value = due;
    document.getElementById('add-payment-modal').classList.remove('hidden');
}

function closePaymentModal() {
    document.getElementById('add-payment-modal').classList.add('hidden');
}

async function handleAddPayment(e) {
    e.preventDefault();
    const memberId = document.getElementById('payment-member-id').value;
    const amount = Number(document.getElementById('payment-amount').value);
    const member = members.find(m => m.id === memberId);

    if (!member || !amount) {
        alert("Invalid data.");
        return;
    }

    const batch = writeBatch(db);

    // 1. Add to payments collection
    const paymentRef = doc(collection(db, "payments"));
    batch.set(paymentRef, {
        memberId,
        amount,
        date: new Date().toISOString().split('T')[0],
        timestamp: serverTimestamp()
    });

    // 2. Update member's paid and due amounts
    const memberRef = doc(db, "members", memberId);
    const newPaidAmount = (member.paidAmount || 0) + amount;
    const newDueAmount = member.totalAmount - newPaidAmount;
    batch.update(memberRef, {
        paidAmount: newPaidAmount,
        dueAmount: newDueAmount
    });

    try {
        await batch.commit();
        alert("Payment recorded successfully!");
        closePaymentModal();
    } catch (error) {
        console.error("Error recording payment:", error);
        alert("Failed to record payment.");
    }
}

async function handleNotificationForm(e) {
    e.preventDefault();
    const form = e.target;
    const data = {
        message: form['notification-message'].value,
        startDate: form['notification-start-date'].value,
        endDate: form['notification-end-date'].value,
    };
    if (!data.message || !data.startDate || !data.endDate) {
        alert("All fields are required.");
        return;
    }
    try {
        // Using a fixed ID 'active-banner' to ensure only one banner config exists
        await setDoc(doc(db, "notifications", "active-banner"), data);
        alert("Notification saved successfully!");
        form.reset();
    } catch (error) {
        console.error("Error saving notification:", error);
        alert("Failed to save notification.");
    }
}

function generatePaymentReport(e) {
    e.preventDefault();
    const month = document.getElementById('report-month').value;
    const memberId = document.getElementById('report-member').value;
    const resultsContainer = document.getElementById('payment-report-results');

    if (!month) {
        resultsContainer.innerHTML = `<p class="text-red-400">Please select a month.</p>`;
        return;
    }

    const [year, monthNum] = month.split('-');
    
    let filteredPayments = payments.filter(p => {
        const paymentDate = new Date(p.date);
        return paymentDate.getFullYear() == year && (paymentDate.getMonth() + 1) == monthNum;
    });

    if (memberId) {
        filteredPayments = filteredPayments.filter(p => p.memberId === memberId);
    }

    if (filteredPayments.length === 0) {
        resultsContainer.innerHTML = `<p class="text-gray-400">No payments found for the selected criteria.</p>`;
        return;
    }

    const total = filteredPayments.reduce((sum, p) => sum + p.amount, 0);

    resultsContainer.innerHTML = `
        <h4 class="text-xl font-bold text-teal-400 mt-4">Report for ${month}</h4>
        <p class="mb-2">Total Payments: $${total.toFixed(2)}</p>
        <ul class="space-y-2">
            ${filteredPayments.map(p => `
                <li class="bg-gray-900/50 p-2 rounded-lg">
                    ${members.find(m => m.id === p.memberId)?.name || 'N/A'} - $${p.amount.toFixed(2)} on ${p.date}
                </li>
            `).join('')}
        </ul>
    `;
}

// --- INITIAL LOAD ---
document.addEventListener('DOMContentLoaded', () => {
    // The onAuthStateChanged listener will handle the initial setup
});