// Application State let appState = { user: null, currentPage: 'dashboard', models: [], isTraining: false, trainingInterval: null }; // Initialize Application document.addEventListener('DOMContentLoaded', function() { initializeApp(); loadStoredData(); setupEventListeners(); checkAuthStatus(); }); function initializeApp() { // Load saved models const savedModels = localStorage.getItem('aiModels'); if (savedModels) { appState.models = JSON.parse(savedModels); } // Update UI updateModelsList(); updateStats(); } function loadStoredData() { // Check for saved user session const savedUser = localStorage.getItem('currentUser'); if (savedUser) { appState.user = JSON.parse(savedUser); updateUserUI(); } } function setupEventListeners() { // Navigation document.querySelectorAll('.nav-link').forEach(link => { link.addEventListener('click', function(e) { e.preventDefault(); const page = this.dataset.page; if (page) { navigateToPage(page); } }); }); // Action cards navigation document.querySelectorAll('.action-card').forEach(card => { card.addEventListener('click', function() { const page = this.dataset.page; if (page) { navigateToPage(page); } }); }); // User menu document.getElementById('userBtn').addEventListener('click', function() { document.getElementById('userDropdown').classList.toggle('show'); }); // Close dropdown when clicking outside document.addEventListener('click', function(e) { if (!e.target.closest('.user-menu')) { document.getElementById('userDropdown').classList.remove('show'); } }); // Modals document.getElementById('closeLoginModal').addEventListener('click', () => closeModal('loginModal')); document.getElementById('closeRegisterModal').addEventListener('click', () => closeModal('registerModal')); document.getElementById('closeTrainingModal').addEventListener('click', () => closeModal('trainingModal')); // Login/Register forms document.getElementById('loginForm').addEventListener('submit', handleLogin); document.getElementById('registerForm').addEventListener('submit', handleRegister); // Switch between login/register document.getElementById('showRegister').addEventListener('click', function(e) { e.preventDefault(); closeModal('loginModal'); openModal('registerModal'); }); document.getElementById('showLogin').addEventListener('click', function(e) { e.preventDefault(); closeModal('registerModal'); openModal('loginModal'); }); // Train form document.getElementById('trainForm').addEventListener('submit', handleTrainSubmit); // Logout document.getElementById('logoutBtn').addEventListener('click', handleLogout); // Profile navigation document.querySelectorAll('.dropdown-item').forEach(item => { item.addEventListener('click', function(e) { e.preventDefault(); const page = this.dataset.page; if (page) { navigateToPage(page); document.getElementById('userDropdown').classList.remove('show'); } }); }); // Model search and filter document.getElementById('modelSearch').addEventListener('input', filterModels); document.getElementById('modelFilter').addEventListener('change', filterModels); // Training controls document.getElementById('stopTraining').addEventListener('click', stopTraining); document.getElementById('pauseTraining').addEventListener('click', pauseTraining); } function checkAuthStatus() { if (!appState.user) { openModal('loginModal'); } } function navigateToPage(page) { // Hide all pages document.querySelectorAll('.page').forEach(p => { p.classList.add('hidden'); }); // Show selected page const pageElement = document.getElementById(page + 'Page'); if (pageElement) { pageElement.classList.remove('hidden'); } // Update nav active state document.querySelectorAll('.nav-link').forEach(link => { link.classList.remove('active'); if (link.dataset.page === page) { link.classList.add('active'); } }); appState.currentPage = page; // Page-specific actions if (page === 'models') { updateModelsList(); } } function openModal(modalId) { document.getElementById(modalId).classList.add('show'); } function closeModal(modalId) { document.getElementById(modalId).classList.remove('show'); } function handleLogin(e) { e.preventDefault(); const email = document.getElementById('email').value; const password = document.getElementById('password').value; // Simulate authentication const user = { id: Date.now(), email: email, name: email.split('@')[0], memberSince: new Date().toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) }; appState.user = user; localStorage.setItem('currentUser', JSON.stringify(user)); updateUserUI(); closeModal('loginModal'); showToast('Successfully logged in!'); } function handleRegister(e) { e.preventDefault(); const name = document.getElementById('regName').value; const email = document.getElementById('regEmail').value; const password = document.getElementById('regPassword').value; // Simulate registration const user = { id: Date.now(), email: email, name: name, memberSince: new Date().toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) }; appState.user = user; localStorage.setItem('currentUser', JSON.stringify(user)); updateUserUI(); closeModal('registerModal'); showToast('Account created successfully!'); } function handleLogout() { appState.user = null; localStorage.removeItem('currentUser'); updateUserUI(); openModal('loginModal'); showToast('Logged out successfully'); } function updateUserUI() { if (appState.user) { document.getElementById('username').textContent = appState.user.name; document.getElementById('dashboardUsername').textContent = appState.user.name; document.getElementById('profileName').textContent = appState.user.name; document.getElementById('profileEmail').textContent = appState.user.email; document.getElementById('memberSince').textContent = appState.user.memberSince; } else { document.getElementById('username').textContent = 'Guest'; document.getElementById('dashboardUsername').textContent = 'Guest'; } } function handleTrainSubmit(e) { e.preventDefault(); if (!appState.user) { showToast('Please login to train models'); openModal('loginModal'); return; } const formData = { modelName: document.getElementById('modelName').value, modelType: document.getElementById('modelType').value, datasetPath: document.getElementById('datasetPath').value, trainSplit: document.getElementById('trainSplit').value, valSplit: document.getElementById('valSplit').value, epochs: parseInt(document.getElementById('epochs').value), batchSize: parseInt(document.getElementById('batchSize').value), learningRate: parseFloat(document.getElementById('learningRate').value), autoSave: document.getElementById('autoSave').checked, generateConfig: document.getElementById('generateConfig').checked, useGPU: document.getElementById('useGPU').checked, userId: appState.user.id }; // Create new model entry const model = { id: Date.now(), ...formData, status: 'training', createdAt: new Date().toISOString(), metrics: { accuracy: 0, loss: 1.0, epochs: 0 } }; appState.models.unshift(model); localStorage.setItem('aiModels', JSON.stringify(appState.models)); // Start training simulation startTraining(model); } function startTraining(model) { appState.isTraining = true; // Show training modal document.getElementById('trainingModelName').textContent = model.modelName; document.getElementById('trainingDataset').textContent = model.datasetPath; document.getElementById('totalEpochs').textContent = model.epochs; openModal('trainingModal'); // Clear logs document.getElementById('logContainer').innerHTML = ''; // Simulate training progress let currentEpoch = 0; let progress = 0; let startTime = Date.now(); appState.trainingInterval = setInterval(() => { currentEpoch++; progress = (currentEpoch / model.epochs) * 100; // Update progress bar document.getElementById('progressFill').style.width = progress + '%'; document.getElementById('progressPercent').textContent = Math.round(progress); document.getElementById('currentEpoch').textContent = currentEpoch; // Simulate metrics const loss = Math.max(0.1, 1.0 - (currentEpoch / model.epochs) * 0.9 + Math.random() * 0.1); const accuracy = Math.min(99, (currentEpoch / model.epochs) * 95 + Math.random() * 5); document.getElementById('currentLoss').textContent = loss.toFixed(3); document.getElementById('currentAccuracy').textContent = accuracy.toFixed(2) + '%'; // Update time elapsed const elapsed = Math.floor((Date.now() - startTime) / 1000); const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; document.getElementById('timeElapsed').textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; // Add log entry addLogEntry(`Epoch ${currentEpoch}/${model.epochs} - Loss: ${loss.toFixed(3)}, Accuracy: ${accuracy.toFixed(2)}%`, 'info'); // Update model in storage const modelIndex = appState.models.findIndex(m => m.id === model.id); if (modelIndex !== -1) { appState.models[modelIndex].metrics = { accuracy: accuracy, loss: loss, epochs: currentEpoch }; localStorage.setItem('aiModels', JSON.stringify(appState.models)); } // Check if training is complete if (currentEpoch >= model.epochs) { completeTraining(model); } }, 1000); // Update every second for demo purposes } function completeTraining(model) { clearInterval(appState.trainingInterval); appState.isTraining = false; // Update model status const modelIndex = appState.models.findIndex(m => m.id === model.id); if (modelIndex !== -1) { appState.models[modelIndex].status = 'completed'; appState.models[modelIndex].completedAt = new Date().toISOString(); localStorage.setItem('aiModels', JSON.stringify(appState.models)); } addLogEntry('Training completed successfully!', 'success'); showToast('Model training completed!'); // Generate config files if requested if (model.generateConfig) { setTimeout(() => { addLogEntry('Configuration files generated and saved to your account', 'success'); }, 1000); } // Close modal after delay setTimeout(() => { closeModal('trainingModal'); navigateToPage('models'); updateModelsList(); updateStats(); }, 3000); } function stopTraining() { if (appState.isTraining) { clearInterval(appState.trainingInterval); appState.isTraining = false; // Find current training model const trainingModel = appState.models.find(m => m.status === 'training'); if (trainingModel) { trainingModel.status = 'failed'; localStorage.setItem('aiModels', JSON.stringify(appState.models)); } addLogEntry('Training stopped by user', 'error'); showToast('Training stopped'); setTimeout(() => { closeModal('trainingModal'); updateModelsList(); }, 1500); } } function pauseTraining() { // For demo purposes, pause just stops the interval if (appState.isTraining) { clearInterval(appState.trainingInterval); appState.isTraining = false; document.getElementById('pauseTraining').innerHTML = ' Resume'; addLogEntry('Training paused', 'info'); } else { // Resume logic would go here showToast('Resume functionality not implemented in demo'); } } function addLogEntry(message, type = 'info') { const logContainer = document.getElementById('logContainer'); const entry = document.createElement('div'); entry.className = `log-entry ${type}`; const timestamp = new Date().toLocaleTimeString(); entry.textContent = `[${timestamp}] ${message}`; logContainer.appendChild(entry); logContainer.scrollTop = logContainer.scrollHeight; } function updateModelsList() { const grid = document.getElementById('modelsGrid'); const userModels = appState.user ? appState.models.filter(m => m.userId === appState.user.id) : []; if (userModels.length === 0) { grid.innerHTML = `
Start training your first AI model
Accuracy
Loss
Epochs