// API Configuration const API_BASE = ''; // Auth State let currentUser = null; // Initialize on page load document.addEventListener('DOMContentLoaded', async () => { await checkAuth(); updateNavigation(); // Page-specific initialization const page = window.location.pathname; if (page.includes('dashboard')) await initDashboard(); if (page.includes('profile')) await initProfile(); if (page.includes('billing')) await initBilling(); if (page.includes('documentation')) initDocumentation(); }); // Authentication Check async function checkAuth() { const token = localStorage.getItem('token'); const publicPages = ['/', '/index.html', '/login.html', '/register.html', '/documentation.html']; const currentPath = window.location.pathname; if (token) { try { const response = await fetch(`${API_BASE}/api/me`, { headers: { 'Authorization': `Bearer ${token}` } }); if (response.ok) { currentUser = await response.json(); document.body.classList.add('authenticated'); } else { localStorage.removeItem('token'); currentUser = null; } } catch (error) { console.error('Auth check failed:', error); } } // Redirect if needed if (!currentUser && !publicPages.includes(currentPath)) { window.location.href = '/login.html'; } if (currentUser && (currentPath === '/login.html' || currentPath === '/register.html')) { window.location.href = '/dashboard.html'; } } // Update Navigation based on Auth State function updateNavigation() { const nav = document.querySelector('.navbar .d-flex'); if (!nav) return; if (currentUser) { nav.innerHTML = ` `; } else { nav.innerHTML = ` Login Sign Up `; } } // Logout async function logout() { const token = localStorage.getItem('token'); if (token) { await fetch(`${API_BASE}/api/logout`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } }); } localStorage.removeItem('token'); window.location.href = '/'; } // Show Notification function showNotification(message, type = 'success') { const notification = document.createElement('div'); notification.className = `alert alert-${type}`; notification.style.position = 'fixed'; notification.style.top = '20px'; notification.style.right = '20px'; notification.style.zIndex = '9999'; notification.style.minWidth = '300px'; notification.innerHTML = ` ${message} `; document.body.appendChild(notification); setTimeout(() => { notification.remove(); }, 5000); } // Format Currency function formatCurrency(amount) { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2 }).format(amount); } // Format Date function formatDate(dateString) { return new Date(dateString).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); }