import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
import { getAuth, signInWithEmailAndPassword, onAuthStateChanged, signOut, createUserWithEmailAndPassword } 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 } 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);

// --- STATE ---
let members = [];
let professionals = [];
let schedule = [];
let payments = [];
let checkins = [];
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');
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 },
    notifications: { title: 'Notifications', 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="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" /></svg>`, render: renderNotifications },
    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 },
};

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

    viewTitle.textContent = view.title;
    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) {
        const userDoc = await getDoc(doc(db, "users", user.uid));
        if (userDoc.exists() && userDoc.data().role === 'admin') {
            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 {
            await signOut(auth);
        }
    } else {
        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,
        professionals: (data) => professionals = data,
        schedule: (data) => schedule = data,
        payments: (data) => payments = data,
        checkins: (data) => checkins = data,
    };

    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);
    }
}

// --- 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-xl font-semibold text-center text-white">Total Members</h3><p class="text-4xl font-extrabold text-center mt-2">${members.length}</p></div>
                <div class="vibrant-card"><h3 class="text-xl font-semibold text-center text-white">Total Professionals</h3><p class="text-4xl font-extrabold text-center mt-2">${professionals.length}</p></div>
                <div class="vibrant-card"><h3 class="text-xl font-semibold text-center text-white">Total Dues (TZS)</h3><p class="text-4xl font-extrabold text-center mt-2">${formatCurrency(totalDues)}</p></div>
                <div class="vibrant-card"><h3 class="text-xl font-semibold text-center text-white">Paid This Month (TZS)</h3><p class="text-4xl font-extrabold text-center mt-2">${formatCurrency(totalPaidThisMonth)}</p></div>
            </div>
            <div>
                <h3 class="text-2xl font-bold text-teal-400 mt-6">Schedule for Today</h3>
                <div id="schedule-today-list" class="space-y-2 mt-2">
                    ${scheduleToday.length > 0 ? scheduleToday.map(s => `
                        <div class="bg-gray-700/50 p-3 rounded-lg flex justify-between items-center">
                            <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>
            </div>
        </div>
    `;
}

function renderSchedule(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <h3 class="text-2xl font-bold text-teal-400 mb-4">Book a New Session</h3>
                <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>
            <h3 class="text-2xl font-bold text-teal-400 mt-6">All Bookings</h3>
            <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-700/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" data-id="${s.id}">Delete</button>
                    </div>
                `).join('')}
            </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">
                <h3 class="text-2xl font-bold text-teal-400 mb-4">Add/Edit Professional</h3>
                <form id="trainer-form" class="space-y-4">
                    <input type="hidden" id="trainer-id-input">
                    <div><label for="trainer-category" class="block text-sm font-medium text-gray-400 mb-1">Category</label><select id="trainer-category" class="input-field"><option value="Trainer">Trainer</option><option value="Consultant">Consultant</option></select></div>
                    <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"></div>
                    <div><label for="trainer-gender" class="block text-sm font-medium text-gray-400 mb-1">Gender</label><input type="text" id="trainer-gender" placeholder="Gender" class="input-field"></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"></div>
                    <button type="submit" class="btn-primary w-full">Save Professional</button>
                </form>
            </div>
            <h3 class="text-2xl font-bold text-teal-400 mt-6">Professional List</h3>
            <ul id="trainer-list" class="space-y-2">
                ${professionals.map(p => `
                    <li class="bg-gray-700/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.category}</span></p>
                            <p class="text-sm text-gray-300">${p.phone}</p>
                        </div>
                        <div class="space-x-2">
                            <button class="btn-secondary edit-trainer-btn" data-id="${p.id}">Edit</button>
                            <button class="btn-danger delete-trainer-btn" data-id="${p.id}">Delete</button>
                        </div>
                    </li>
                `).join('')}
            </ul>
        </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')));
}

function renderMembers(container) {
    container.innerHTML = `
        <div class="space-y-6">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <h3 class="text-2xl font-bold text-teal-400 mb-4">Add/Edit Member</h3>
                <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"></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"></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-package" class="block text-sm font-medium text-gray-400 mb-1">Package</label><select id="member-package" class="input-field"><option value="Gold">Gold</option><option value="Silver">Silver</option><option value="Bronze">Bronze</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"></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"></div>
                    <div><label for="member-months" class="block text-sm font-medium text-gray-400 mb-1">Total Months</label><input type="number" id="member-months" class="input-field"></div>
                    <div><label for="member-total-amount" class="block text-sm font-medium text-gray-400 mb-1">Total Amount</label><input type="number" id="member-total-amount" class="input-field"></div>
                    <div><label for="member-paid-amount" class="block text-sm font-medium text-gray-400 mb-1">Paid Amount</label><input type="number" id="member-paid-amount" class="input-field"></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</label><input type="number" id="member-due-amount" class="input-field" disabled></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>
            <h3 class="text-2xl font-bold text-teal-400 mt-6">Member List</h3>
            <ul id="member-list" class="space-y-2">
                ${members.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} <span class="text-xs bg-yellow-500 px-2 py-1 rounded-full">${m.package}</span></p>
                                <p class="text-sm text-gray-300">${m.email}</p>
                            </div>
                            <div class="space-x-2">
                                <button class="btn-secondary edit-member-btn" data-id="${m.id}">Edit</button>
                                <button class="btn-secondary change-password-btn" data-id="${m.id}" data-name="${m.name}">Change Password</button>
                                <button class="btn-danger delete-member-btn" data-id="${m.id}">Delete</button>
                            </div>
                        </div>
                        <div class="text-xs mt-2 grid grid-cols-3 gap-2">
                            <span>Total: ${formatCurrency(m.totalAmount || 0)}</span>
                            <span>Paid: ${formatCurrency(m.paidAmount || 0)}</span>
                            <span class="font-bold ${m.dueAmount > 0 ? 'text-red-400' : 'text-green-400'}">Due: ${formatCurrency(m.dueAmount || 0)}</span>
                        </div>
                    </li>
                `).join('')}
            </ul>
        </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-xl 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>
    `;
    const memberForm = document.getElementById('member-form');
    memberForm.addEventListener('submit', handleMemberForm);
    ['member-total-amount', 'member-paid-amount'].forEach(id => {
        document.getElementById(id).addEventListener('input', calculateDueAmount);
    });
    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.getElementById('cancel-password-btn').addEventListener('click', closeChangePasswordModal);
    document.getElementById('change-password-form').addEventListener('submit', handleChangePassword);
    document.querySelectorAll('.delete-member-btn').forEach(btn => btn.addEventListener('click', (e) => deleteItem('members', e.target.dataset.id, 'Member')));
}

function renderPayments(container) {
    const membersWithDues = members.filter(m => m.dueAmount > 0);
    container.innerHTML = `
        <div class="space-y-6">
            <h3 class="text-2xl font-bold text-teal-400">Members with Outstanding Dues</h3>
            <ul id="dues-list" class="space-y-2">
                ${membersWithDues.length > 0 ? membersWithDues.map(m => `
                    <li class="bg-gray-700/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: ${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>
        <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-xl 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 = `
        <h3 class="text-2xl font-bold text-teal-400 mt-6">Recent Member Check-ins</h3>
        <ul id="checkins-list" class="space-y-2 mt-4">
            ${checkins.sort((a,b) => (b.checkIn?.toMillis() || 0) - (a.checkIn?.toMillis() || 0)).map(c => `
                <li class="bg-gray-700/50 p-3 rounded-lg">
                    <div class="flex justify-between items-center">
                        <p class="font-bold">${members.find(m=>m.id===c.memberId)?.name || 'Unknown Member'}</p>
                    </div>
                    <div class="text-sm text-gray-300 mt-1">
                        <p>Check-in: ${c.checkIn ? new Date(c.checkIn.toDate()).toLocaleString() : 'N/A'}</p>
                        <p>Check-out: ${c.checkOut ? new Date(c.checkOut.toDate()).toLocaleString() : 'Not yet'}</p>
                    </div>
                </li>
            `).join('')}
        </ul>
    `;
}

function renderNotifications(container) {
    container.innerHTML = `
        <div class="bg-gray-700/50 p-4 rounded-lg">
            <h3 class="text-2xl font-bold text-teal-400 mb-4">Configure Notification Banner</h3>
            <form id="notification-form" class="space-y-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>
    `;
    document.getElementById('notification-form').addEventListener('submit', handleNotificationForm);
}

function renderReports(container) {
    container.innerHTML = `
        <div class="space-y-8">
            <div class="bg-gray-700/50 p-4 rounded-lg">
                <h3 class="text-2xl font-bold text-teal-400 mb-4">Member Payment Report</h3>
                <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>
        </div>
    `;
    document.getElementById('payment-report-form').addEventListener('submit', generatePaymentReport);
}

function renderSettings(container) {
    container.innerHTML = `
        <div class="bg-gray-700/50 p-6 rounded-lg space-y-3">
            <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>
    `;
}

// --- 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,
        category: form['trainer-category'].value,
        gender: form['trainer-gender'].value,
        phone: form['trainer-phone'].value,
    };
    try {
        if (id) {
            await updateDoc(doc(db, "professionals", id), data);
        } else {
            await addDoc(collection(db, "professionals"), data);
        }
        form.reset();
        alert("Professional saved successfully!");
    } catch (error) {
        console.error("Error saving professional:", error);
        alert("Failed to save professional.");
    }
}

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-category'].value = trainer.category;
    form['trainer-gender'].value = trainer.gender;
    form['trainer-phone'].value = trainer.phone;
    form.scrollIntoView({ behavior: 'smooth' });
}

function calculateDueAmount() {
    const total = parseFloat(document.getElementById('member-total-amount').value) || 0;
    const paid = parseFloat(document.getElementById('member-paid-amount').value) || 0;
    document.getElementById('member-due-amount').value = (total - paid).toFixed(2);
}

async function handleMemberForm(e) {
    e.preventDefault();
    const form = e.target;
    const id = form['member-id-input'].value;
    const data = {
        name: form['member-name'].value,
        contact: form['member-contact'].value,
        email: form['member-email'].value,
        dob: form['member-dob'].value, // Added for password generation
        gender: form['member-gender'].value,
        package: form['member-package'].value,
        rate: Number(form['member-rate'].value),
        startDate: form['member-start-date'].value,
        totalMonths: Number(form['member-months'].value),
        totalAmount: Number(form['member-total-amount'].value),
        paidAmount: Number(form['member-paid-amount'].value),
        dueAmount: Number(form['member-due-amount'].value),
        notes: form['member-notes'].value,
    };

    try {
        if (id) {
            // This is an update to an existing member
            await updateDoc(doc(db, "members", id), data);
            alert("Member updated successfully!");
        } else {
            // This is a new member creation
            // 1. Generate the password
            const firstName = data.name.split(' ')[0];
            if (!firstName || !data.dob) {
                alert("Full Name and Date of Birth are required to create a new member.");
                return;
            }
            const birthYear = new Date(data.dob).getFullYear();
            const formattedFirstName = firstName.charAt(0).toUpperCase() + firstName.slice(1).toLowerCase();
            const generatedPassword = `${formattedFirstName}@${birthYear}`;

            // 2. Create user in Firebase Auth using a secondary app instance
            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;
            
            // 3. Save member and user data to Firestore in a batch
            const batch = writeBatch(db);
            
            // Member document
            const memberRef = doc(db, "members", newUid);
            batch.set(memberRef, data);

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

            await batch.commit();
            
            // Clean up secondary auth instance
            await signOut(secondaryAuth);

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

function editMember(id) {
    const member = members.find(m => m.id === id);
    if (!member) return;
    const form = document.getElementById('member-form');
    for (const key in member) {
        if (form[ `member-${key}`]) {
             form[`member-${key.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)}`].value = member[key];
        }
    }
    form['member-id-input'].value = member.id;
    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
});