import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
import { getAuth, signInWithEmailAndPassword, onAuthStateChanged, signOut, setPersistence, browserLocalPersistence } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
import { getFirestore, doc, getDoc, collection, onSnapshot, addDoc, query, where, orderBy, serverTimestamp, updateDoc } 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
setPersistence(auth, browserLocalPersistence)
  .catch((error) => {
    console.error("Error setting persistence:", error);
  });

// --- STATE ---
let currentUser = null;
let memberDetails = {};
let schedule = [];
let payments = [];
let checkins = [];
let measurements = [];
let meals = [];
let professionalNotes = [];
let professionals = [];
let listeners = [];
let activeCheckinId = null;
let currentChartDate = new Date();
let chartInstance = null;

// --- 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 },
    history: { title: 'History', 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 12c0-1.232-.046-2.453-.138-3.662a4.006 4.006 0 00-3.7-3.7 48.678 48.678 0 00-7.324 0 4.006 4.006 0 00-3.7 3.7c-.092 1.21-.138 2.43-.138 3.662v.513a5.25 5.25 0 005.25 5.25h1.5a5.25 5.25 0 005.25-5.25v-.513z" /></svg>`, render: renderHistory },
    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 },
    rules: { title: 'Rules', 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="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /></svg>`, render: renderRules },
    profile: { title: 'Profile', 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.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" /></svg>`, render: renderProfile },
};

function showView(viewKey) {
    const view = appViews[viewKey];
    if (!view) return;
    // viewTitle.textContent = view.title; // Removed
    viewsContainer.innerHTML = '';
    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) {
        const userDoc = await getDoc(doc(db, "users", user.uid));
        if (userDoc.exists() && userDoc.data().role === 'member') {
            currentUser = { uid: user.uid, email: user.email, ...userDoc.data() };
            loginScreen.style.display = 'none';
            mainPortal.style.display = 'block';
            bottomMenu.style.display = 'flex';
            initializeAppState();
        } else {
            await signOut(auth);
        }
    } else {
        currentUser = null;
        loginScreen.style.display = 'flex';
        mainPortal.style.display = 'none';
        bottomMenu.style.display = 'none';
        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) {
        errorEl.textContent = "Login failed. Check credentials.";
    }
});

logoutBtn.addEventListener('click', () => signOut(auth));

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

function listenToDataChanges() {
    listeners.forEach(unsubscribe => unsubscribe());
    listeners = [];

    // Listen to member's own details
    const memberUnsub = onSnapshot(doc(db, "members", currentUser.uid), (doc) => {
        memberDetails = { id: doc.id, ...doc.data() };
        userDetails.textContent = `Hi, ${memberDetails.name?.split(' ')[0] || ''}`;
        refreshCurrentView();
    });
    listeners.push(memberUnsub);

    // Listen to member's schedule
    const scheduleQuery = query(collection(db, "schedule"), where("memberId", "==", currentUser.uid));
    const scheduleUnsub = onSnapshot(scheduleQuery, (snapshot) => {
        schedule = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        refreshCurrentView();
    });
    listeners.push(scheduleUnsub);

    // Listen to member's payments
    const paymentsQuery = query(collection(db, "payments"), where("memberId", "==", currentUser.uid));
    const paymentsUnsub = onSnapshot(paymentsQuery, (snapshot) => {
        payments = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        refreshCurrentView();
    });
    listeners.push(paymentsUnsub);
    // Listen to member's checkins
    const checkinsQuery = query(collection(db, "checkins"), where("memberId", "==", currentUser.uid));
    const checkinsUnsub = onSnapshot(checkinsQuery, (snapshot) => {
        checkins = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        
        // Restore active check-in state
        const active = checkins.find(c => !c.checkOut);
        activeCheckinId = active ? active.id : null;

        refreshCurrentView();
    });
    listeners.push(checkinsUnsub);

    // Listen to member's measurements
    const measurementsQuery = query(collection(db, "measurements"), where("memberId", "==", currentUser.uid));
    const measurementsUnsub = onSnapshot(measurementsQuery, (snapshot) => {
        measurements = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        refreshCurrentView();
    });
    listeners.push(measurementsUnsub);

    // Listen to member's meals
    const mealsQuery = query(collection(db, "meals"), where("memberId", "==", currentUser.uid));
    const mealsUnsub = onSnapshot(mealsQuery, (snapshot) => {
        meals = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        refreshCurrentView();
    });
    listeners.push(mealsUnsub);

    // Listen to professional notes
    const notesQuery = query(collection(db, "professional_notes"), where("memberId", "==", currentUser.uid));
    const notesUnsub = onSnapshot(notesQuery, (snapshot) => {
        professionalNotes = snapshot.docs.map(doc => ({ id: doc.id, type: 'note', ...doc.data() }));
        refreshCurrentView();
    });
    listeners.push(notesUnsub);

    // Listen to professionals (for names)
    const proUnsub = onSnapshot(collection(db, "professionals"), (snapshot) => {
        professionals = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        refreshCurrentView();
    });
    listeners.push(proUnsub);
}

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]) {
        appViews[activeViewKey].render(viewsContainer);
    }
}

// --- RENDER FUNCTIONS ---
function renderDashboard(container) {
    const dueAmount = memberDetails.dueAmount || 0;
    const isCheckedIn = !!activeCheckinId;

    // Calculate next session
    const now = new Date();
    const upcomingSessions = schedule
        .filter(s => {
            const sessionDate = new Date(s.date + 'T' + (s.time || '00:00'));
            return sessionDate >= now;
        })
        .sort((a, b) => new Date(a.date + 'T' + a.time) - new Date(b.date + 'T' + b.time));
    
    const nextSession = upcomingSessions.length > 0 ? upcomingSessions[0] : null;
    const nextSessionText = nextSession 
        ? `${new Date(nextSession.date).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })} at ${nextSession.time}`
        : 'No upcoming sessions';

    // Alert Logic for Long Checkout
    let alertHtml = '';
    if (isCheckedIn) {
            const activeCheckin = checkins.find(c => c.id === activeCheckinId);
            if (activeCheckin && activeCheckin.checkIn) {
                const durationMs = new Date() - activeCheckin.checkIn.toDate();
                const durationHrs = durationMs / (1000 * 60 * 60);
                if (durationHrs > 1) {
                    alertHtml = `
                    <div class="bg-red-900/50 border border-red-500 text-red-100 p-4 rounded-lg mb-6 flex items-start space-x-3 animate-pulse text-left">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mt-0.5 flex-shrink-0 text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                        <div>
                            <h4 class="font-bold text-red-400">Forget to checkout?</h4>
                            <p class="text-sm text-gray-300">You have been checked in for over 1 hour. Please tap "Check Out" if you're done.</p>
                        </div>
                    </div>
                    `;
                }
            }
    }

    container.innerHTML = `
        <div class="space-y-8 text-center">
            ${alertHtml}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="p-6 rounded-lg bg-gray-700/50">
                    <h3 class="text-sm font-semibold text-amber-400">Outstanding Dues</h3>
                    <p class="text-xl font-extrabold mt-2 ${dueAmount > 0 ? 'text-red-400' : 'text-green-400'}">TZS ${dueAmount.toFixed(2)}</p>
                </div>
                <div class="p-6 rounded-lg bg-gray-700/50">
                    <h3 class="text-sm font-semibold text-amber-400">Next Session</h3>
                    <p class="text-lg font-bold mt-2 text-white">${nextSessionText}</p>
                </div>
            </div>

            <div class="p-6">
                <button id="check-in-btn" class="rounded-full w-48 h-48 flex flex-col items-center justify-center text-3xl font-bold shadow-2xl mx-auto transform hover:scale-105 transition-transform ${isCheckedIn ? 'bg-green-500' : 'btn-primary'}">
                    ${isCheckedIn ? 
                        `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-16 h-16 mb-2"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75" /></svg>Check Out` : 
                        `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-16 h-16 mb-2"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9" /></svg>Check In`}
                </button>
                <p id="check-in-status" class="mt-4 text-gray-400 h-6"></p>
            </div>

            <div class="p-6 rounded-lg bg-gray-700/50">
                <div class="flex justify-between items-center mb-4">
                    <button id="prev-month-btn" class="text-amber-400 hover:text-amber-300 font-bold text-xl">&lt;</button>
                    <h3 id="chart-title" class="text-xl font-semibold text-amber-400">Check-in Activity</h3>
                    <button id="next-month-btn" class="text-amber-400 hover:text-amber-300 font-bold text-xl">&gt;</button>
                </div>
                <div style="height: 300px;">
                    <canvas id="checkinChart"></canvas>
                </div>
            </div>
        </div>
    `;
    document.getElementById('check-in-btn').addEventListener('click', isCheckedIn ? handleCheckOut : handleCheckIn);
    
    document.getElementById('prev-month-btn').addEventListener('click', () => {
        currentChartDate.setMonth(currentChartDate.getMonth() - 1);
        renderCheckinChart();
    });
    
    document.getElementById('next-month-btn').addEventListener('click', () => {
        currentChartDate.setMonth(currentChartDate.getMonth() + 1);
        renderCheckinChart();
    });

    renderCheckinChart();
}

function renderCheckinChart() {
    const ctx = document.getElementById('checkinChart').getContext('2d');
    
    // Update Title
    const monthName = currentChartDate.toLocaleString('default', { month: 'long', year: 'numeric' });
    document.getElementById('chart-title').textContent = `Check-in Activity (${monthName})`;

    // Process data
    const currentMonth = currentChartDate.getMonth();
    const currentYear = currentChartDate.getFullYear();
    
    const monthCheckins = checkins.filter(c => {
        if (!c.checkIn) return false;
        const d = c.checkIn.toDate();
        return d.getMonth() === currentMonth && d.getFullYear() === currentYear;
    });

    // Group by date and Sum Duration
    const checkinsByDate = {};
    monthCheckins.forEach(c => {
        const d = c.checkIn.toDate();
        const dateKey = d.getDate(); // 1-31
        
        let duration = 0;
        if (c.checkOut) {
            duration = (c.checkOut.toDate() - c.checkIn.toDate()) / (1000 * 60); // minutes
        } else {
             // For active checkins, calculate duration until now
             duration = (new Date() - c.checkIn.toDate()) / (1000 * 60);
        }
        
        if (!checkinsByDate[dateKey]) checkinsByDate[dateKey] = 0;
        checkinsByDate[dateKey] += duration;
    });

    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    const labels = Array.from({length: daysInMonth}, (_, i) => i + 1);
    
    const data = labels.map(day => {
        return checkinsByDate[day] ? checkinsByDate[day].toFixed(0) : 0;
    });

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

    chartInstance = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Total Duration (mins)',
                data: data,
                borderColor: '#14B8A6', // Teal-500
                backgroundColor: 'rgba(20, 184, 166, 0.2)', // Teal-500 with opacity
                borderWidth: 2,
                tension: 0.4, // Smooth curves
                fill: true,
                pointBackgroundColor: '#F59E0B', // Amber-500
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: '#F59E0B'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    title: { display: true, text: 'Date', color: '#9CA3AF' },
                    ticks: { color: '#F9FAFB' },
                    grid: { color: '#374151' }
                },
                y: {
                    title: { display: true, text: 'Duration (mins)', color: '#9CA3AF' },
                    beginAtZero: true,
                    ticks: { color: '#F9FAFB' },
                    grid: { color: '#374151' }
                }
            },
            plugins: {
                legend: { display: false },
                tooltip: {
                    intersect: false,
                    mode: 'index',
                    callbacks: {
                         label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += context.parsed.y + ' mins';
                            }
                            return label;
                        }
                    }
                }
            }
        }
    });
}

function renderSchedule(container) {
    const now = new Date();

    // Helper to get session Date object
    const getSessionDate = (session) => new Date(session.date + 'T' + (session.time || '00:00'));

    // Filter and sort upcoming
    const upcoming = schedule
        .filter(s => getSessionDate(s) > now)
        .sort((a, b) => getSessionDate(a) - getSessionDate(b));
    
    // Filter and sort past
    const past = schedule
        .filter(s => getSessionDate(s) <= now)
        .sort((a, b) => getSessionDate(b) - getSessionDate(a));

    // Get unique years and professionals for filters from past sessions
    const years = [...new Set(past.map(s => s.date.split('-')[0]))].sort().reverse();
    const pastTrainerIds = [...new Set(past.map(s => s.trainerId))];
    const pastTrainers = professionals.filter(p => pastTrainerIds.includes(p.id));

    container.innerHTML = `
        <!-- Upcoming Sessions -->
        <div class="mb-8">
            <h3 class="text-lg font-bold text-amber-400 mb-4">Upcoming Sessions</h3>
            <div class="space-y-3">
                ${upcoming.length > 0 ? upcoming.map(s => {
                    const trainer = professionals.find(p => p.id === s.trainerId);
                    const trainerName = trainer ? trainer.name : 'Unknown Professional';
                    const dateStr = new Date(s.date).toLocaleDateString('en-GB');
                    return `
                    <div class="bg-gray-700/50 p-4 rounded-lg flex flex-col md:flex-row justify-between md:items-center text-lg font-medium space-y-2 md:space-y-0">
                        <div>
                            <span class="text-white">${dateStr}</span>
                            <span class="hidden md:inline text-amber-400 mx-2">|</span>
                            <span class="text-amber-300 md:text-white">${s.time}</span>
                            <span class="hidden md:inline text-amber-400 mx-2">|</span>
                            <span class="text-gray-300 md:text-white">${trainerName}</span>
                        </div>
                    </div>
                    `;
                }).join('') : '<p class="text-gray-400">No upcoming sessions.</p>'}
            </div>
        </div>

        <!-- Previous Sessions -->
        <div>
            <h3 class="text-lg font-bold text-amber-400 mb-4">Previous Sessions</h3>
            
            <!-- Filters -->
            <div class="grid grid-cols-3 gap-4 mb-4">
                <select id="schedule-filter-month" class="input-field bg-gray-800 border-gray-600 text-white p-2 rounded focus:ring-amber-400 focus:border-amber-400">
                    <option value="">All Months</option>
                    ${Array.from({length: 12}, (_, i) => `<option value="${String(i+1).padStart(2, '0')}">${new Date(0, i).toLocaleString('default', {month:'long'})}</option>`).join('')}
                </select>
                <select id="schedule-filter-year" class="input-field bg-gray-800 border-gray-600 text-white p-2 rounded focus:ring-amber-400 focus:border-amber-400">
                    <option value="">All Years</option>
                    ${years.map(y => `<option value="${y}">${y}</option>`).join('')}
                </select>
                <select id="schedule-filter-prof" class="input-field bg-gray-800 border-gray-600 text-white p-2 rounded focus:ring-amber-400 focus:border-amber-400">
                    <option value="">All Professionals</option>
                    ${pastTrainers.map(p => `<option value="${p.id}">${p.name}</option>`).join('')}
                </select>
            </div>

            <div id="past-schedule-list" class="space-y-3">
                <!-- Populated by JS -->
            </div>
        </div>
    `;

    // Filter Logic
    const filterAndRender = () => {
        const month = document.getElementById('schedule-filter-month').value;
        const year = document.getElementById('schedule-filter-year').value;
        const profId = document.getElementById('schedule-filter-prof').value;

        const filtered = past.filter(s => {
            const [sYear, sMonth] = s.date.split('-');
            const matchesMonth = !month || sMonth === month;
            const matchesYear = !year || sYear === year;
            const matchesProf = !profId || s.trainerId === profId;
            return matchesMonth && matchesYear && matchesProf;
        });

        const listContainer = document.getElementById('past-schedule-list');
        if (filtered.length === 0) {
            listContainer.innerHTML = '<p class="text-gray-400">No previous sessions found matching filters.</p>';
            return;
        }

        listContainer.innerHTML = filtered.map(s => {
            const trainer = professionals.find(p => p.id === s.trainerId);
            const trainerName = trainer ? trainer.name : 'Unknown';
            const dateStr = new Date(s.date).toLocaleDateString('en-GB');
            
            // Find Note - Matching Date AND Professional
            const note = professionalNotes.find(n => n.date === s.date && n.professionalId === s.trainerId);
            
            if (note) {
                 return `
                <details class="bg-gray-700/50 rounded-lg group">
                    <summary class="p-4 flex justify-between items-center cursor-pointer list-none">
                        <div class="text-gray-200">
                            <p class="font-bold text-lg">${dateStr} <span class="text-amber-400 font-normal">at ${s.time}</span></p>
                            <p class="text-sm text-gray-400">with ${trainerName}</p>
                        </div>
                        <span class="text-amber-400 transition group-open:rotate-180">
                            <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="p-4 pt-0 border-t border-gray-600/50 text-gray-300 text-sm whitespace-pre-wrap">
                        <p class="font-semibold text-amber-400 mb-1">Session Note:</p>
                        ${note.note}
                    </div>
                </details>
                `;
            } else {
                 return `
                <div class="bg-gray-700/50 p-4 rounded-lg flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
                    <div class="text-gray-200">
                        <p class="font-bold text-lg">${dateStr} <span class="text-amber-400 font-normal">at ${s.time}</span></p>
                        <p class="text-sm text-gray-400">with ${trainerName}</p>
                    </div>
                </div>
                `;
            }
        }).join('');
    };

    // Attach Filter Listeners
    ['schedule-filter-month', 'schedule-filter-year', 'schedule-filter-prof'].forEach(id => {
        document.getElementById(id).addEventListener('change', filterAndRender);
    });

    // Initial Render of Past Sessions
    filterAndRender();
}

function renderHistory(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <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-amber-400">Professional Session Notes</h3>
                    <span class="transition group-open:rotate-180">
                        <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 space-y-2">
                     ${professionalNotes.sort((a,b) => new Date(b.date) - new Date(a.date)).map(n => `
                        <div class="bg-gray-800/50 p-4 rounded-lg border-l-4 border-amber-500 text-white">
                             <p class="font-bold text-lg text-amber-400">Note by ${n.professionalName || 'Trainer'}</p>
                             <p class="text-sm text-gray-400 mb-2">${new Date(n.date).toLocaleDateString()}</p>
                             <p class="text-gray-200 italic">"${n.note}"</p>
                        </div>
                    `).join('') || '<p class="text-gray-400">No session notes.</p>'}
                </div>
            </details>

            <details class="group bg-gray-700/50 rounded-lg p-4">
                <summary class="flex justify-between items-center font-medium cursor-pointer list-none">
                    <h3 class="text-lg font-bold text-amber-400">Payment History</h3>
                    <span class="transition group-open:rotate-180">
                        <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 space-y-2">
                     ${payments.sort((a,b) => b.timestamp.toMillis() - a.timestamp.toMillis()).map(p => `
                        <div class="bg-gray-800/50 p-3 rounded-lg flex justify-between items-center text-white">
                            <span class="font-bold text-green-400">TZS ${p.amount.toFixed(2)}</span>
                            <span>${new Date(p.date).toLocaleDateString()}</span>
                        </div>
                    `).join('') || '<p class="text-gray-400">No payment history.</p>'}
                </div>
            </details>

            <details class="group bg-gray-700/50 rounded-lg p-4">
                <summary class="flex justify-between items-center font-medium cursor-pointer list-none">
                    <h3 class="text-lg font-bold text-amber-400">Check-in History</h3>
                    <span class="transition group-open:rotate-180">
                        <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 space-y-2">
                    ${checkins.sort((a,b) => (b.checkIn?.toMillis() || 0) - (a.checkIn?.toMillis() || 0)).map(c => `
                        <div class="bg-gray-800/50 p-3 rounded-lg text-white">
                            <div class="flex justify-between items-center">
                                <span class="font-bold">Check In:</span>
                                <span>${c.checkIn ? new Date(c.checkIn.toDate()).toLocaleString() : 'N/A'}</span>
                            </div>
                            <div class="flex justify-between items-center mt-1">
                                <span class="font-bold">Check Out:</span>
                                <span>${c.checkOut ? new Date(c.checkOut.toDate()).toLocaleString() : 'Not yet'}</span>
                            </div>
                        </div>
                    `).join('') || '<p class="text-gray-400">No check-in history.</p>'}
                </div>
            </details>
        </div>
    `;
}

function renderMeasurements(container) {
    const sortedMeasurements = measurements.sort((a, b) => new Date(a.date) - new Date(b.date)); // Sort ascending for chart
    const fieldOrder = ['weight', 'height', 'chest', 'bust', 'lArm', 'rArm', 'abdomen', 'waist', 'hips', 'lThigh', 'rThigh'];

    container.innerHTML = `
        <div class="space-y-6">
            <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-amber-400">Progress Chart</h3>
                    <span class="transition group-open:rotate-180">
                        <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="mt-4 group-open:animate-fadeIn">
                    <div id="chart-controls" class="mb-4"></div>
                    <div style="height: 400px;">
                        <canvas id="measurementsChart"></canvas>
                    </div>
                </div>
            </details>

            <details class="group bg-gray-700/50 rounded-lg p-4">
                <summary class="flex justify-between items-center font-medium cursor-pointer list-none">
                    <h3 class="text-lg font-bold text-amber-400">History</h3>
                    <span class="transition group-open:rotate-180">
                        <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="mt-4 space-y-4 group-open:animate-fadeIn">
                ${sortedMeasurements.length > 0 ? sortedMeasurements.slice().reverse().map(m => `
                    <details class="bg-gray-800/50 rounded-lg group/item">
                        <summary class="p-4 flex justify-between items-center cursor-pointer list-none font-bold text-lg text-amber-300">
                             <span>${new Date(m.date).toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</span>
                             <span class="transition group-open/item:rotate-180 text-amber-400">
                                <svg fill="none" height="20" shape-rendering="geometricPrecision" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" viewBox="0 0 24 24" width="20"><path d="M6 9l6 6 6-6"></path></svg>
                             </span>
                        </summary>
                        <div class="p-4 pt-0 border-t border-gray-700/50 text-sm">
                             <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-amber-400">${m.height || '-'}</span> in</p>
                                <p>Weight: <span class="text-amber-400">${m.weight || '-'}</span> kg</p>
                                <p>BMI: <span class="text-amber-400">${m.bmi || '-'}</span></p>
                             </div>
                             <div class="grid grid-cols-2 gap-2">
                                ${Object.entries(m)
                                    .filter(([key, value]) => !['id', 'memberId', 'date', 'timestamp', 'weight', 'height', 'bmi'].includes(key) && value)
                                    .sort((a, b) => fieldOrder.indexOf(a[0]) - fieldOrder.indexOf(b[0]))
                                    .map(([key, value]) => `
                                    <p><span class="text-gray-400 capitalize">${key.replace(/([A-Z])/g, ' $1').trim()}:</span> ${value} ${key === 'weight' ? 'kg' : 'in'}</p>
                                `).join('')}
                            </div>
                        </div>
                    </details>
                `).join('') : '<p class="text-gray-400">No measurements recorded yet.</p>'}
                </div>
            </details>
        </div>
    `;

    if (sortedMeasurements.length > 0) {
        renderMeasurementsChart(sortedMeasurements, fieldOrder);
    }
}

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());
    
    // Calculate BMI
    sortedData.forEach(m => {
        if (m.weight && m.height) {
            const heightM = m.height * 0.0254;
            m.bmi = parseFloat((m.weight / (heightM * heightM)).toFixed(2));
        }
    });

    const controlsContainer = document.getElementById('chart-controls');
    
    // 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 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>
        `;
        controlsContainer.appendChild(switcher);
        
        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);
            });
        });
        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;  
             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;
             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 {
                
             // Filter out Height from Main body measurements as it has its own tab
             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: '#F9FAFB' },
                        position: 'bottom'
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                scales: {
                    x: {
                        title: { display: true, text: 'Date', color: '#9CA3AF' },
                        ticks: { color: '#F9FAFB' },
                        grid: { color: '#374151' }
                    },
                    y: {
                        title: { display: true, text: 'Measurement', color: '#9CA3AF' },
                        ticks: { color: '#F9FAFB' },
                        grid: { color: '#374151' }
                    }
                }
            }
        });
        window.measurementsChartInstance = chartInstance;
    }
    
    // Initial Render
    const activeMode = document.querySelector('.chart-mode-btn.active')?.dataset.mode || 'main';
    updateChart(activeMode);
}

function renderRules(container) {
    container.innerHTML = `
        <div class="bg-gray-700/50 p-6 rounded-lg">
            <h3 class="text-lg font-bold text-amber-400 mb-4">Gym Rules</h3>
            <div id="rules-content" class="text-gray-300 space-y-2 whitespace-pre-wrap">Loading rules...</div>
        </div>
    `;

    getDoc(doc(db, "settings", "rules")).then(docSnap => {
        const contentDiv = document.getElementById('rules-content');
        if (docSnap.exists() && docSnap.data().content) {
            contentDiv.textContent = docSnap.data().content;
        } else {
            contentDiv.innerHTML = '<p>No rules have been set yet.</p>';
        }
    });
}

function renderProfile(container) {
    container.innerHTML = `
        <div class="bg-gray-700/50 p-6 rounded-lg space-y-3 text-lg">
            <p><span class="font-bold text-gray-400">Name:</span> <span class="text-white">${memberDetails.name || 'N/A'}</span></p>
            <p><span class="font-bold text-gray-400">Email:</span> <span class="text-white">${memberDetails.email || 'N/A'}</span></p>
            <p><span class="font-bold text-gray-400">Contact:</span> <span class="text-white">${memberDetails.contact || 'N/A'}</span></p>
            <p><span class="font-bold text-gray-400">Start Date:</span> <span class="text-white">${memberDetails.startDate ? new Date(memberDetails.startDate + 'T00:00:00').toLocaleDateString() : 'N/A'}</span></p>
        </div>
    `;
}

function renderMeals(container) {
    const today = new Date().toISOString().split('T')[0];
    
    container.innerHTML = `
        <div class="space-y-6">
            <!-- Add Meal Form -->
            <div class="bg-gray-700/50 p-6 rounded-lg">
                <h3 class="text-lg font-bold text-amber-400 mb-4">Add Daily Meal</h3>
                <form id="add-meal-form" class="space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-400 mb-1">Date</label>
                            <input type="date" id="meal-date" class="input-field w-full bg-gray-600 border-gray-500 rounded p-2 text-white" value="${today}" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-400 mb-1">Water Intake (Liters)</label>
                            <input type="number" id="meal-water" step="0.1" class="input-field w-full bg-gray-600 border-gray-500 rounded p-2 text-white" placeholder="e.g. 2.5" required>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-400 mb-1">Food Intake</label>
                        <textarea id="meal-food" rows="3" class="input-field w-full bg-gray-600 border-gray-500 rounded p-2 text-white" placeholder="Describe your meals (Breakfast, Lunch, Dinner, Snacks)..." required></textarea>
                    </div>
                    <button type="submit" class="btn-primary w-full py-2 rounded font-bold text-lg">Save Meal Entry</button>
                    <p id="meal-status" class="text-sm text-center mt-2 h-5 text-green-400"></p>
                </form>
            </div>

            <!-- Meal History -->
            <div class="space-y-4">
                <div class="flex justify-between items-center">
                    <h3 class="text-lg font-bold text-amber-400">Meal History</h3>
                </div>
                
                <div class="bg-gray-700/50 p-4 rounded-lg space-y-3">
                    <p class="text-sm font-bold text-gray-400 mb-2">Filter by Date Range</p>
                    <div class="grid grid-cols-2 gap-4">
                         <input type="date" id="history-start-date" class="bg-gray-600 border-gray-500 rounded p-2 text-white text-sm">
                         <input type="date" id="history-end-date" class="bg-gray-600 border-gray-500 rounded p-2 text-white text-sm">
                    </div>
                </div>

                <div id="meals-list" class="space-y-3">
                    <!-- Meals Populated Here -->
                </div>
            </div>
        </div>
    `;

    document.getElementById('add-meal-form').addEventListener('submit', handleAddMeal);
    document.getElementById('history-start-date').addEventListener('change', filterAndRenderMeals);
    document.getElementById('history-end-date').addEventListener('change', filterAndRenderMeals);

    filterAndRenderMeals();
}

function filterAndRenderMeals() {
    const listContainer = document.getElementById('meals-list');
    if (!listContainer) return;

    const startDateVal = document.getElementById('history-start-date').value;
    const endDateVal = document.getElementById('history-end-date').value;

    let filteredMeals = meals.sort((a, b) => new Date(b.date) - new Date(a.date));

    // Consolidate multiple entries for the same date if any? Requirements say "Add daily meal", implies one per day, or list of entries.
    // Requirement: "View Meals history, that displays the Date, and would expand to display Water and Food"
    // I'll show individual entries but if I wanted to group by date:
    
    if (startDateVal) {
        filteredMeals = filteredMeals.filter(m => m.date >= startDateVal);
    }
    if (endDateVal) {
        filteredMeals = filteredMeals.filter(m => m.date <= endDateVal);
    }

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

    listContainer.innerHTML = filteredMeals.map(m => `
        <details class="bg-gray-700/50 rounded-lg group">
            <summary class="p-4 flex justify-between items-center cursor-pointer list-none">
                <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="transition group-open:rotate-180 text-amber-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="p-4 pt-0 border-t border-gray-600/50 text-gray-300 text-sm space-y-2">
                <div>
                     <p class="font-semibold text-amber-400 mb-1">Water Intake:</p>
                     <p class="text-white text-lg">${m.waterIntake} Liters</p>
                </div>
                <div>
                     <p class="font-semibold text-amber-400 mb-1">Food Intake:</p>
                     <p class="whitespace-pre-wrap">${m.foodIntake || 'No food details.'}</p>
                </div>
            </div>
        </details>
    `).join('');
}

async function handleAddMeal(e) {
    e.preventDefault();
    const statusEl = document.getElementById('meal-status');
    const btn = e.target.querySelector('button');
    
    const date = document.getElementById('meal-date').value;
    const water = document.getElementById('meal-water').value;
    const food = document.getElementById('meal-food').value;

    if (!date || !water || !food) {
        statusEl.textContent = 'Please fill all fields.';
        statusEl.className = 'text-center mt-2 h-5 text-red-400';
        return;
    }

    btn.disabled = true;
    statusEl.textContent = 'Saving...';
    statusEl.className = 'text-center mt-2 h-5 text-amber-400';

    try {
        await addDoc(collection(db, "meals"), {
            memberId: currentUser.uid,
            date: date,
            waterIntake: parseFloat(water),
            foodIntake: food,
            timestamp: serverTimestamp()
        });
        
        statusEl.textContent = 'Meal saved successfully!';
        statusEl.className = 'text-center mt-2 h-5 text-green-400';
        document.getElementById('add-meal-form').reset();
        document.getElementById('meal-date').value = new Date().toISOString().split('T')[0]; // Reset date to today
        
        // Refresh view manually just in case, though listener should handle it
        setTimeout(() => {
            statusEl.textContent = '';
            btn.disabled = false;
        }, 2000);
    } catch (error) {
        console.error("Error adding meal:", error);
        statusEl.textContent = 'Error saving meal. Try again.';
        statusEl.className = 'text-center mt-2 h-5 text-red-400';
        btn.disabled = false;
    }
}


// --- ACTIONS ---
function showAnimation(type) {
    const animationContainer = document.createElement('div');
    animationContainer.id = 'animation-container';
    let animationHtml = '';
    let text = '';

    if (type === 'happy') {
        text = 'Great to see you!';
        animationHtml = `<img src="../Images/Checkin.png" alt="Check-in successful" class="checkin-image">`;
    } else if (type === 'tired') {
        text = 'Great workout!';
        animationHtml = `<img src="../Images/Checkout.png" alt="Check-out successful" class="checkin-image">`;
    }

    animationContainer.innerHTML = `<p class="animation-text">${text}</p>${animationHtml}`;
    document.body.appendChild(animationContainer);

    setTimeout(() => {
        animationContainer.remove();
    }, 4800); // Animation lasts for just under 5 seconds
}

async function handleCheckIn() {
    const btn = document.getElementById('check-in-btn');
    const statusEl = document.getElementById('check-in-status');
    btn.disabled = true;
    statusEl.textContent = 'Checking in...';

    try {
        const docRef = await addDoc(collection(db, "checkins"), {
            memberId: currentUser.uid,
            checkIn: serverTimestamp(),
            checkOut: null
        });
        activeCheckinId = docRef.id;
        statusEl.textContent = 'Checked in successfully!';
        showAnimation('happy');
        refreshCurrentView();
    } catch (error) {
        console.error("Check-in failed:", error);
        statusEl.textContent = 'Check-in failed. Please try again.';
        btn.disabled = false;
    }
}

async function handleCheckOut() {
    const btn = document.getElementById('check-in-btn');
    const statusEl = document.getElementById('check-in-status');
    btn.disabled = true;
    statusEl.textContent = 'Checking out...';

    try {
        const checkinRef = doc(db, "checkins", activeCheckinId);
        await updateDoc(checkinRef, {
            checkOut: serverTimestamp()
        });
        activeCheckinId = null;
        statusEl.textContent = 'Checked out successfully!';
        showAnimation('tired');
        refreshCurrentView();
    } catch (error) {
        console.error("Check-out failed:", error);
        statusEl.textContent = 'Check-out failed. Please try again.';
        btn.disabled = false;
    }
}