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 listeners = [];
let activeCheckinId = 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 },
    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() }));
        refreshCurrentView();
    });
    listeners.push(checkinsUnsub);
}

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

    container.innerHTML = `
        <div class="space-y-8 text-center">
            <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-xl font-semibold text-amber-400">Outstanding Dues</h3>
                    <p class="text-4xl 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-xl font-semibold text-amber-400">Next Session</h3>
                    <p class="text-2xl 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 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 ? 'Check Out' : '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">
                <h3 class="text-xl font-semibold text-amber-400 mb-4">Check-in Activity (This Month)</h3>
                <canvas id="checkinChart"></canvas>
            </div>
        </div>
    `;
    document.getElementById('check-in-btn').addEventListener('click', isCheckedIn ? handleCheckOut : handleCheckIn);
    renderCheckinChart();
}

function renderCheckinChart() {
    const ctx = document.getElementById('checkinChart').getContext('2d');
    
    // Process data
    const currentMonth = new Date().getMonth();
    const currentYear = new Date().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
    const checkinsByDate = {};
    monthCheckins.forEach(c => {
        const d = c.checkIn.toDate();
        const dateKey = d.getDate(); // 1-31
        if (!checkinsByDate[dateKey]) checkinsByDate[dateKey] = [];
        
        let duration = 0;
        if (c.checkOut) {
            duration = (c.checkOut.toDate() - c.checkIn.toDate()) / (1000 * 60); // minutes
        } else {
             duration = (new Date() - c.checkIn.toDate()) / (1000 * 60);
        }
        checkinsByDate[dateKey].push(duration);
    });

    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    const labels = Array.from({length: daysInMonth}, (_, i) => i + 1);
    
    // Find max number of checkins in a day
    let maxCheckins = 0;
    Object.values(checkinsByDate).forEach(arr => {
        if (arr.length > maxCheckins) maxCheckins = arr.length;
    });

    const datasets = [];
    const colors = ['rgba(255, 99, 132, 0.7)', 'rgba(54, 162, 235, 0.7)', 'rgba(255, 206, 86, 0.7)', 'rgba(75, 192, 192, 0.7)'];

    for (let i = 0; i < maxCheckins; i++) {
        const data = labels.map(day => {
            const dayCheckins = checkinsByDate[day] || [];
            return dayCheckins[i] ? dayCheckins[i].toFixed(0) : 0;
        });

        datasets.push({
            label: `Session ${i + 1}`,
            data: data,
            backgroundColor: colors[i % colors.length],
            stack: 'Stack 0',
        });
    }

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: datasets
        },
        options: {
            responsive: true,
            scales: {
                x: {
                    title: { display: true, text: 'Date' },
                    stacked: true
                },
                y: {
                    title: { display: true, text: 'Duration (mins)' },
                    stacked: true,
                    beginAtZero: true
                }
            },
            plugins: {
                legend: { display: datasets.length > 1 }
            }
        }
    });
}

function renderSchedule(container) {
    const upcoming = schedule
        .filter(s => new Date(s.date) >= new Date(new Date().toDateString()))
        .sort((a, b) => new Date(a.date + 'T' + a.time) - new Date(b.date + 'T' + b.time));

    container.innerHTML = `
        <h3 class="text-2xl font-bold text-amber-400 mb-4">Upcoming Sessions</h3>
        <div class="space-y-3">
            ${upcoming.length > 0 ? upcoming.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' })}</p>
                    <p class="text-amber-300 text-xl">${s.time}</p>
                </div>
            `).join('') : '<p class="text-gray-400">No upcoming sessions.</p>'}
        </div>
    `;
}

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-2xl 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-2xl 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 renderRules(container) {
    container.innerHTML = `
        <div class="bg-gray-700/50 p-4 rounded-lg">
            <img src="../Images/Evolve Rules.jpg" alt="Evolve Entry Rules" class="w-full rounded-md">
        </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">${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">Package:</span> <span class="text-white">${memberDetails.package || '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>
    `;
}

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