import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
import { getAuth, signInWithEmailAndPassword, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
import { getFirestore, doc, getDoc, collection, onSnapshot, query, where, getDocs, addDoc, serverTimestamp, orderBy } 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);

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

// --- STATE ---
let currentUser = null;
let professionalDetails = {};
let schedule = [];
let members = []; // To store member names
let myConsultations = []; // To store consultations/notes
let listeners = [];

// --- 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');

// --- 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 },
    consultations: { title: 'Consultations', icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" /></svg>`, render: renderConsultations },
    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="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" /></svg>`, render: renderMeasurements },
    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 === 'professional') {
            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.";
    }
});

function renderMeasurements(container) {
    container.innerHTML = `
        <div class="space-y-6">
             <div class="bg-gray-700/50 p-6 rounded-lg">
                <h3 class="text-2xl font-bold text-amber-400 mb-4">Add Member Measurements</h3>
                <form id="measurements-form" class="space-y-4">
                    <div>
                        <label for="measure-member" class="block text-sm font-medium text-gray-400 mb-1">Select Member</label>
                        <select id="measure-member" class="input-field">
                            <option value="">Select a member...</option>
                            ${members.map(m => `<option value="${m.id}">${m.name}</option>`).join('')}
                        </select>
                    </div>
                    <div>
                        <label for="measure-date" class="block text-sm font-medium text-gray-400 mb-1">Date</label>
                        <input type="date" id="measure-date" class="input-field" value="${new Date().toISOString().split('T')[0]}">
                    </div>
                    <div id="dynamic-fields" class="grid grid-cols-2 gap-4">
                        <!-- Fields injected via JS -->
                    </div>
                    <button type="submit" class="btn-primary w-full">Save Measurements</button>
                </form>
            </div>
        </div>
    `;

    const form = document.getElementById('measurements-form');
    const memberSelect = document.getElementById('measure-member');
    const dynamicFields = document.getElementById('dynamic-fields');

    memberSelect.addEventListener('change', (e) => {
        const memberId = e.target.value;
        if (!memberId) {
            dynamicFields.innerHTML = '';
            return;
        }
        const member = members.find(m => m.id === memberId);
        const gender = member?.gender || 'Male';
        const genderKey = gender.charAt(0).toUpperCase() + gender.slice(1).toLowerCase();
        // Fallback if gender is not exactly Male/Female or defined
        const fields = measurementFields[genderKey] || measurementFields['Male'];

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

    form.addEventListener('submit', handleSaveMeasurements);
}

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

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

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

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

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

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

// --- NOTES LOGIC ---
const noteModal = document.getElementById('note-modal');
const noteForm = document.getElementById('note-form');
const cancelNoteBtn = document.getElementById('cancel-note-btn');

function openNoteModal(memberId, date) {
    document.getElementById('note-member-id').value = memberId;
    document.getElementById('note-date').value = date;
    const memberName = members.find(m => m.id === memberId)?.name || 'Member';
    document.getElementById('note-modal-title').textContent = `Add Note for ${memberName} on ${date}`;
    noteModal.classList.remove('hidden');
}

cancelNoteBtn.addEventListener('click', () => {
    noteModal.classList.add('hidden');
    noteForm.reset();
});

noteForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const memberId = document.getElementById('note-member-id').value;
    const date = document.getElementById('note-date').value;
    const content = document.getElementById('note-content').value;

    if (!content) {
        alert("Note cannot be empty.");
        return;
    }

    try {
        await addDoc(collection(db, "professional_notes"), {
            memberId,
            professionalId: currentUser.uid,
            professionalName: professionalDetails.name || currentUser.email,
            date,
            note: content,
            timestamp: serverTimestamp()
        });
        alert("Note saved successfully!");
        noteModal.classList.add('hidden');
        noteForm.reset();
    } catch (error) {
        console.error("Error saving note:", error);
        alert("Failed to save note.");
    }
});

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

// --- INITIALIZATION ---
async function initializeAppState() {
    setupNavigation();
    showView('dashboard');
    // Fetch all members once for name mapping
    const memberSnapshot = await getDocs(collection(db, "members"));
    members = memberSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    listenToDataChanges();
}

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

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

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

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

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 today = new Date().toISOString().split('T')[0];
    const scheduleToday = schedule
        .filter(s => s.date === today)
        .sort((a, b) => a.time.localeCompare(b.time));

    container.innerHTML = `
        <div class="space-y-6">
            <div class="p-6 rounded-lg bg-gray-700/50 text-center">
                <h3 class="text-xl font-semibold text-amber-400">Sessions Today</h3>
                <p class="text-5xl font-extrabold mt-2">${scheduleToday.length}</p>
            </div>
            <div>
                <h3 class="text-2xl font-bold text-amber-400 mb-4">Today's Agenda</h3>
                <div class="space-y-3">
                    ${scheduleToday.length > 0 ? scheduleToday.map(s => `
                        <div class="bg-gray-900/50 p-4 rounded-lg">
                            <div class="flex justify-between items-center mb-2">
                                <span class="font-bold text-lg">${s.time}</span>
                                <span class="text-gray-300">${members.find(m => m.id === s.memberId)?.name || 'Unknown Member'}</span>
                            </div>
                            <button class="btn-secondary text-xs w-full add-note-btn flex justify-center items-center gap-2 p-2" data-member-id="${s.memberId}" data-date="${s.date}" title="Add Note">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" /></svg>
                            </button>
                        </div>
                    `).join('') : '<p class="text-gray-400">No sessions scheduled for today.</p>'}
                </div>
            </div>
        </div>
    `;

    container.querySelectorAll('.add-note-btn').forEach(btn => {
        btn.addEventListener('click', () => openNoteModal(btn.dataset.memberId, btn.dataset.date));
    });
}

function renderSchedule(container) {
    const sortedSchedule = [...schedule].sort((a, b) => new Date(b.date + 'T' + b.time) - new Date(a.date + 'T' + a.time));

    container.innerHTML = `
        <h3 class="text-2xl font-bold text-amber-400 mb-4">All Your Sessions</h3>
        <div class="space-y-3">
            ${sortedSchedule.length > 0 ? sortedSchedule.map(s => `
                <div class="bg-gray-700/50 p-4 rounded-lg">
                    <div class="flex justify-between items-start mb-2">
                        <div>
                            <p class="font-bold text-lg">${new Date(s.date + 'T00:00:00').toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })} at ${s.time}</p>
                            <p class="text-amber-300">With: ${members.find(m => m.id === s.memberId)?.name || 'Unknown Member'}</p>
                        </div>
                        <button class="btn-secondary text-xs add-note-btn flex justify-center items-center gap-2 p-2" data-member-id="${s.memberId}" data-date="${s.date}" title="Add Note">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" /></svg>
                        </button>
                    </div>
                </div>
            `).join('') : '<p class="text-gray-400">You have no sessions scheduled.</p>'}
        </div>
    `;

    container.querySelectorAll('.add-note-btn').forEach(btn => {
        btn.addEventListener('click', () => openNoteModal(btn.dataset.memberId, btn.dataset.date));
    });
}

function renderConsultations(container) {
    // Get unique members who have notes
    const uniqueMemberIds = [...new Set(myConsultations.map(n => n.memberId))];
    const consultedMembers = members.filter(m => uniqueMemberIds.includes(m.id));
    
    // Sort notes by date descending
    const sortedNotes = [...myConsultations].sort((a, b) => new Date(b.date) - new Date(a.date));

    // Helper to render the list HTML
    const getListHtml = (notes) => {
        if (notes.length === 0) return '<p class="text-gray-400">No consultation notes found.</p>';
        return notes.map(note => `
            <div class="bg-gray-700/50 p-4 rounded-lg border-l-4 border-amber-400">
                <div class="flex justify-between items-start mb-2">
                    <div>
                        <p class="font-bold text-lg text-white">${members.find(m => m.id === note.memberId)?.name || 'Unknown Member'}</p>
                        <p class="text-xs text-gray-400">${new Date(note.date).toLocaleDateString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}</p>
                    </div>
                </div>
                <div class="text-gray-300 mt-2 text-sm whitespace-pre-wrap bg-gray-800/50 p-3 rounded">${note.note}</div>
            </div>
        `).join('');
    };

    container.innerHTML = `
        <h3 class="text-2xl font-bold text-amber-400 mb-4">Consultation History</h3>
        
        <div class="mb-6">
             <label class="block text-sm font-medium text-gray-400 mb-2">Filter by Member</label>
             <select id="consultation-filter" class="input-field bg-gray-800 border-gray-600 text-white w-full p-2 rounded">
                <option value="all">All Members</option>
                ${consultedMembers.map(m => `<option value="${m.id}">${m.name}</option>`).join('')}
             </select>
        </div>

        <div id="consultation-list" class="space-y-4">
            ${getListHtml(sortedNotes)}
        </div>
    `;

    document.getElementById('consultation-filter').addEventListener('change', (e) => {
        const memberId = e.target.value;
        const filteredNotes = memberId === 'all' 
            ? sortedNotes 
            : sortedNotes.filter(n => n.memberId === memberId);
        document.getElementById('consultation-list').innerHTML = getListHtml(filteredNotes);
    });
}

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">${professionalDetails.name || 'N/A'}</span></p>
            <p><span class="font-bold text-gray-400">Category:</span> <span class="text-white">${professionalDetails.category || 'N/A'}</span></p>
            <p><span class="font-bold text-gray-400">Phone:</span> <span class="text-white">${professionalDetails.phone || 'N/A'}</span></p>
            <p><span class="font-bold text-gray-400">Gender:</span> <span class="text-white">${professionalDetails.gender || 'N/A'}</span></p>
            <p><span class="font-bold text-gray-400">Email:</span> <span class="text-white">${currentUser.email || 'N/A'}</span></p>
        </div>
    `;
}