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 } 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 currentUser = null;
let professionalDetails = {};
let schedule = [];
let members = []; // To store member names
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 },
    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;
    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.";
    }
});

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

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 flex justify-between items-center">
                            <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>
                    `).join('') : '<p class="text-gray-400">No sessions scheduled for today.</p>'}
                </div>
            </div>
        </div>
    `;
}

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">
                    <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>
            `).join('') : '<p class="text-gray-400">You have no sessions scheduled.</p>'}
        </div>
    `;
}

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