// ============================================ // GLOBAL STATE // ============================================ let currentEpisodeId = null; let currentState = null; let currentPlan = null; let currentObservation = null; function getNumericInput(id, fallback) { const el = document.getElementById(id); if (!el) { return fallback; } const value = parseInt(el.value, 10); return Number.isFinite(value) ? value : fallback; } function getFormPayload() { const taskLevel = document.querySelector('input[name="difficulty"]:checked')?.value || 'easy'; const riskMode = document.querySelector('input[name="risk"]:checked')?.value || 'defensive'; const priorityMode = document.querySelector('input[name="priority"]:checked')?.value || 'balanced'; const goal = document.getElementById('goal-textarea')?.value?.trim() || 'maximize monthly stability while preserving emergency savings'; const income = getNumericInput('income-input', 75000); const expenses = getNumericInput('expenses-input', 45000); const savingsTarget = getNumericInput('savings-target-slider', 20); const focusAreas = Array.from(document.querySelectorAll('.focus-area:checked')).map((input) => input.value); return { taskLevel, goal, income, expenses, savingsTarget, priority: priorityMode, focusAreas: focusAreas.length ? focusAreas : ['all'], aiMode: riskMode === 'aggressive' ? 'Aggressive' : 'Conservative', }; } function sumValues(values) { return values.reduce((total, value) => total + (Number(value) || 0), 0); } function getAllocationMap(plan) { const fallback = { savings: 15000, rent: 12000, food: 5000, utilities: 2500, transport: 2000, discretionary: 2500, }; return { ...(plan?.allocations || fallback) }; } function getBudgetBuckets(plan, state, observation) { const allocations = getAllocationMap(plan); const income = Number(observation?.income ?? state?.income ?? 0); const expenses = Number(state?.expenses ?? Math.max(0, income - Number(observation?.remaining_budget ?? state?.remaining_budget ?? 0))); const remaining = Number(observation?.remaining_budget ?? state?.remaining_budget ?? Math.max(0, income - expenses)); const essentials = sumValues([ allocations.rent, allocations.food, allocations.utilities, allocations.transport, allocations.health, allocations.insurance, ]); const savings = Number(allocations.savings || 0); const debt = Number(allocations.debt || 0); const lifestyle = sumValues([allocations.entertainment, allocations.discretionary]); const allocatedFromRemaining = essentials + savings + debt + lifestyle; const residual = Math.max(0, remaining - allocatedFromRemaining); const buckets = [ { label: 'Fixed Expenses', value: Math.max(0, expenses), color: '#00FF88' }, { label: 'Planned Essentials', value: essentials, color: '#3DD6FF' }, { label: 'Savings', value: savings, color: '#66F2C5' }, { label: 'Debt', value: debt, color: '#FFB800' }, { label: 'Lifestyle', value: lifestyle, color: '#8B5CF6' }, { label: 'Unallocated', value: residual, color: '#262626' }, ].filter(item => item.value > 0.01); if (!buckets.length) { buckets.push({ label: 'Unallocated', value: Math.max(remaining, 1), color: '#00FF88' }); } return { buckets, allocations, income, expenses, remaining, essentials, savings, debt, lifestyle }; } function resizeCanvas(canvas) { const rect = canvas.getBoundingClientRect(); const dpr = window.devicePixelRatio || 1; const width = Math.max(1, Math.floor(rect.width)); const height = Math.max(1, Math.floor(rect.height)); if (canvas.width !== Math.floor(width * dpr) || canvas.height !== Math.floor(height * dpr)) { canvas.width = Math.floor(width * dpr); canvas.height = Math.floor(height * dpr); } const ctx = canvas.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); return { ctx, width, height }; } // ============================================ // API CALLS // ============================================ async function apiReset(taskLevel = 'easy', overrides = {}) { try { const payload = getFormPayload(); const response = await fetch('/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ task_level: taskLevel, goal: overrides.goal ?? payload.goal, ai_mode: overrides.aiMode ?? payload.aiMode, income: overrides.income ?? payload.income, expenses: overrides.expenses ?? payload.expenses, savings_target: overrides.savingsTarget ?? payload.savingsTarget, priority: overrides.priority ?? payload.priority, focus_areas: overrides.focusAreas ?? payload.focusAreas, }) }); const data = await response.json(); currentEpisodeId = data.state.episode_id; currentState = data.state; currentObservation = data.observation; updateUIFromState(data); return data; } catch (error) { console.error('Reset failed:', error); showError('Failed to reset environment'); } } async function apiStep(action) { if (!currentEpisodeId) { showError('No active episode. Click "Generate Plan" first.'); return; } try { const response = await fetch('/step', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ episode_id: currentEpisodeId, action: { episode_id: currentEpisodeId, ...action, } }) }); const data = await response.json(); currentState = data.state; currentObservation = data.observation; currentPlan = data.plan; updateUIFromState(data); return data; } catch (error) { console.error('Step failed:', error); showError('Failed to execute step'); } } async function apiGetState(episodeId = null) { try { const params = episodeId ? `?episode_id=${episodeId}` : ''; const response = await fetch(`/state${params}`); const data = await response.json(); currentState = data; currentObservation = data.observation || null; return data; } catch (error) { console.error('Get state failed:', error); } } // ============================================ // UI UPDATES // ============================================ function updateUIFromState(data) { const state = data.state || {}; const observation = data.observation || {}; const plan = data.plan || {}; currentObservation = observation; currentPlan = plan; // Update quick metrics const income = Number(observation.income ?? state.income ?? 75000); const expenses = Number(state.expenses ?? Math.max(0, income - Number(observation.remaining_budget ?? state.remaining_budget ?? 0))); const remaining = Number(observation.remaining_budget ?? state.remaining_budget ?? Math.max(0, income - expenses)); const plannedSavings = Number(plan?.allocations?.savings || 0); const savingsPct = income > 0 ? ((plannedSavings / income) * 100).toFixed(1) : '0.0'; document.getElementById('quick-income').textContent = `₹${formatNumber(income)}`; document.getElementById('quick-expenses').textContent = `₹${formatNumber(expenses)}`; document.getElementById('quick-remaining').textContent = `₹${formatNumber(remaining)}`; document.getElementById('quick-savings').textContent = `${savingsPct}%`; const incomeInput = document.getElementById('income-input'); const expensesInput = document.getElementById('expenses-input'); if (incomeInput) incomeInput.value = String(Math.round(income)); if (expensesInput) expensesInput.value = String(Math.round(expenses)); document.getElementById('income-display').textContent = `₹${formatNumber(income)}`; document.getElementById('expenses-display').textContent = `₹${formatNumber(expenses)}`; // Update key metrics const savingsTarget = getNumericInput('savings-target-slider', 20); document.querySelector('.key-metrics').innerHTML = `

Monthly Income

₹${formatNumber(income)}

Total Expenses

₹${formatNumber(expenses)}

Max Savings Cap

${savingsTarget}%

Planned Savings

₹${formatNumber(plannedSavings)}

`; // Update AI reasoning if (typeof plan.confidence === 'number') { document.getElementById('confidence-score').textContent = `${Math.round(plan.confidence * 100)}%`; } document.getElementById('ai-reasoning-text').textContent = plan.rationale || 'The plan is balancing essentials, savings, and discretionary spending using the current budget state.'; const priorityMode = document.querySelector('input[name="priority"]:checked')?.value || 'balanced'; const primaryChip = document.querySelector('.target-chip'); const tertiaryChip = document.querySelector('.target-chip.tertiary'); if (primaryChip) { primaryChip.textContent = priorityMode === 'savings' ? 'SAVINGS FIRST' : 'BALANCED'; } if (tertiaryChip) { tertiaryChip.textContent = `MAX ${savingsTarget}% SAVINGS`; } renderAllocationTable(plan, state, observation); renderBreakdown(plan, state, observation); // Update JSON output updateJSONOutput(plan, state, observation); // Draw charts requestAnimationFrame(() => drawCharts(state, observation, plan)); } function updateJSONOutput(plan, state = {}, observation = {}) { const json = { episode_id: currentEpisodeId || state.episode_id || null, task_level: state.task_level || document.querySelector('input[name="difficulty"]:checked')?.value || 'easy', income: Number(observation.income ?? state.income ?? 0), expenses: Number(state.expenses ?? 0), remaining_budget: Number(observation.remaining_budget ?? state.remaining_budget ?? 0), allocation: getAllocationMap(plan), confidence: Number(plan.confidence ?? 0), rationale: plan.rationale || '', confidence_breakdown: plan.confidence_breakdown || {} }; document.getElementById('json-output').textContent = JSON.stringify(json, null, 2); } function renderAllocationTable(plan, state = {}, observation = {}) { const tbody = document.getElementById('allocation-tbody'); if (!tbody) { return; } const allocations = getAllocationMap(plan); const income = Number(observation.income ?? state.income ?? 0); const entries = Object.entries(allocations) .filter(([, value]) => Number(value) > 0) .sort((a, b) => b[1] - a[1]); tbody.innerHTML = entries.map(([category, value]) => { const pct = income > 0 ? ((Number(value) / income) * 100).toFixed(1) : '0.0'; const badge = category === 'savings' ? 'Protected' : category === 'debt' ? 'Debt cover' : 'Active'; return ` ${category.replace(/_/g, ' ')} ₹${formatNumber(value)} ${pct}% ${badge} `; }).join('') || ` No allocations available yet. `; } function renderBreakdown(plan, state = {}, observation = {}) { const container = document.getElementById('breakdown-content'); if (!container) { return; } const allocations = getAllocationMap(plan); const income = Number(observation.income ?? state.income ?? 0); const remaining = Number(observation.remaining_budget ?? state.remaining_budget ?? 0); const essentials = sumValues([ allocations.rent, allocations.food, allocations.utilities, allocations.transport, allocations.health, allocations.insurance, ]); container.innerHTML = `
Core essentials
₹${formatNumber(essentials)} — Rent, food, utilities, transport, health, insurance.
Savings reserve
₹${formatNumber(allocations.savings || 0)} protected as monthly reserve.
Remaining runway
₹${formatNumber(remaining)} budget left after fixed expenses.
Income coverage
${income > 0 ? Math.round(((income - remaining) / income) * 100) : 0}% of income is already committed.
`; } function drawCharts(state = {}, observation = {}, plan = {}) { const { buckets, allocations, income, remaining, savings } = getBudgetBuckets(plan, state, observation); // Pie Chart const pieCanvas = document.getElementById('pie-chart'); if (pieCanvas && pieCanvas.getContext) { const { ctx, width, height } = resizeCanvas(pieCanvas); ctx.clearRect(0, 0, width, height); const centerX = width / 2; const centerY = height / 2; const radius = Math.min(width, height) / 2 - 18; const total = buckets.reduce((sum, item) => sum + item.value, 0) || 1; // background ring ctx.fillStyle = '#141414'; ctx.beginPath(); ctx.arc(centerX, centerY, radius + 6, 0, Math.PI * 2); ctx.fill(); let angle = -Math.PI / 2; buckets.forEach((bucket) => { const sliceAngle = (bucket.value / total) * Math.PI * 2; ctx.fillStyle = bucket.color; ctx.beginPath(); ctx.moveTo(centerX, centerY); ctx.arc(centerX, centerY, radius, angle, angle + sliceAngle); ctx.closePath(); ctx.fill(); angle += sliceAngle; }); // Center circle ctx.fillStyle = '#0e0e0e'; ctx.beginPath(); ctx.arc(centerX, centerY, radius * 0.5, 0, 2 * Math.PI); ctx.fill(); // Center text ctx.fillStyle = '#FFFFFF'; ctx.font = '700 24px "JetBrains Mono", monospace'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(`₹${formatNumber(income)}`, centerX, centerY - 12); ctx.font = '600 12px "JetBrains Mono", monospace'; ctx.fillStyle = '#ADAAAA'; ctx.fillText('TOTAL INFLOW', centerX, centerY + 16); const legend = document.getElementById('pie-legend'); if (legend) { legend.innerHTML = buckets.map(bucket => `
${bucket.label} (${Math.round((bucket.value / total) * 100)}%)
`).join(''); } } // Bar Chart const barCanvas = document.getElementById('bar-chart'); if (barCanvas && barCanvas.getContext) { const { ctx, width, height } = resizeCanvas(barCanvas); ctx.clearRect(0, 0, width, height); const months = 12; const barWidth = (width - 24) / months; const maxHeight = height - 44; const monthlySavings = Number(savings || Math.max(remaining * 0.2, 1)); const taskLevel = String(state.task_level || 'easy'); const shockByMonth = taskLevel === 'hard' ? { 2: 0.5, 4: 0.85, 7: 0.65 } : taskLevel === 'medium' ? { 3: 0.7 } : {}; let runningReserve = 0; const values = Array.from({ length: months }, (_, index) => { const monthNumber = index + 1; const factor = shockByMonth[monthNumber] || 1; runningReserve += monthlySavings * factor; return Math.max(0, runningReserve); }); const maxValue = Math.max(...values, 1); ctx.fillStyle = '#0A0A0A'; ctx.fillRect(0, 0, width, height); // Grid ctx.strokeStyle = 'rgba(72, 72, 71, 0.1)'; ctx.lineWidth = 1; for (let i = 1; i < 5; i++) { const y = (height - 40) * (i / 5) + 20; ctx.beginPath(); ctx.moveTo(10, y); ctx.lineTo(width - 10, y); ctx.stroke(); } // Bars for (let i = 0; i < months; i++) { const value = values[i]; const barHeight = (value / maxValue) * maxHeight; const x = 12 + i * barWidth + barWidth * 0.12; const y = height - 20 - barHeight; const gradient = ctx.createLinearGradient(0, y, 0, height - 20); gradient.addColorStop(0, 'rgba(0, 255, 136, 0.95)'); gradient.addColorStop(1, 'rgba(0, 255, 136, 0.25)'); ctx.fillStyle = gradient; ctx.fillRect(x, y, barWidth * 0.74, barHeight); if (i === months - 1) { ctx.strokeStyle = '#00FF88'; ctx.lineWidth = 2; ctx.strokeRect(x, y, barWidth * 0.74, barHeight); } } // Axes ctx.strokeStyle = 'rgba(72, 72, 71, 0.3)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(10, height - 20); ctx.lineTo(width, height - 20); ctx.stroke(); ctx.beginPath(); ctx.moveTo(10, 20); ctx.lineTo(10, height - 20); ctx.stroke(); } } function formatNumber(num) { return Math.round(num).toLocaleString('en-IN'); } function showError(message) { alert(`Error: ${message}`); } // ============================================ // EVENT LISTENERS // ============================================ document.addEventListener('DOMContentLoaded', function() { // Income input const incomeInput = document.getElementById('income-input'); if (incomeInput) { incomeInput.addEventListener('input', function() { const value = parseInt(this.value); document.getElementById('income-display').textContent = `₹${formatNumber(value || 0)}`; }); } // Expenses input const expensesInput = document.getElementById('expenses-input'); if (expensesInput) { expensesInput.addEventListener('input', function() { const value = parseInt(this.value); document.getElementById('expenses-display').textContent = `₹${formatNumber(value || 0)}`; }); } // Savings target slider const savingsTargetSlider = document.getElementById('savings-target-slider'); if (savingsTargetSlider) { savingsTargetSlider.addEventListener('input', function() { const value = parseInt(this.value, 10) || 20; document.getElementById('savings-target-display').textContent = `${value}%`; }); } const focusAll = document.getElementById('focus-all'); const focusItems = document.querySelectorAll('.focus-area'); if (focusAll) { focusAll.addEventListener('change', function() { focusItems.forEach(item => { item.checked = this.checked; }); }); } focusItems.forEach(item => { item.addEventListener('change', function() { const selectedCount = Array.from(focusItems).filter(el => el.checked).length; if (focusAll) { focusAll.checked = selectedCount === focusItems.length; } if (selectedCount === 0) { this.checked = true; } }); }); // Difficulty selector document.querySelectorAll('input[name="difficulty"]').forEach(input => { input.addEventListener('change', function() { document.querySelectorAll('.difficulty-btn').forEach(btn => btn.classList.remove('selected')); this.closest('.difficulty-btn').classList.add('selected'); }); }); // Scenario selector (Alpha/Beta/Gamma) document.querySelectorAll('.scenario-card').forEach(card => { const activateScenario = async () => { document.querySelectorAll('.scenario-card').forEach(item => item.classList.remove('active')); card.classList.add('active'); const taskLevel = card.getAttribute('data-task-level') || 'easy'; const difficultyInput = document.querySelector(`input[name="difficulty"][value="${taskLevel}"]`); if (difficultyInput) { difficultyInput.checked = true; difficultyInput.dispatchEvent(new Event('change')); } const form = getFormPayload(); await apiReset(taskLevel, form); }; card.addEventListener('click', activateScenario); card.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); activateScenario(); } }); }); // Tabs document.querySelectorAll('.tab-btn').forEach(btn => { btn.addEventListener('click', function() { const tabName = this.getAttribute('data-tab'); // Remove active from all document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active')); // Add active to current this.classList.add('active'); document.getElementById(tabName + '-tab').classList.add('active'); }); }); // Generate button const generateBtn = document.getElementById('generate-btn'); if (generateBtn) { generateBtn.addEventListener('click', async function() { this.disabled = true; this.innerHTML = 'progress_activityGenerating...'; const form = getFormPayload(); await apiReset(form.taskLevel, form); this.disabled = false; this.innerHTML = 'auto_awesomeGenerate Plan'; }); } // JSON copy button document.querySelectorAll('.json-copy').forEach(btn => { btn.addEventListener('click', function() { const text = document.getElementById('json-output').textContent; navigator.clipboard.writeText(text).then(() => { this.textContent = 'COPIED!'; setTimeout(() => { this.textContent = 'COPY RAW'; }, 2000); }); }); }); // Material Symbols fallback for icon display setupMaterialSymbols(); // Initial load const initialForm = getFormPayload(); apiReset(initialForm.taskLevel, initialForm); }); // ============================================ // MATERIAL SYMBOLS SETUP // ============================================ function setupMaterialSymbols() { const style = document.createElement('style'); style.textContent = ` .material-symbols-outlined { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24; display: inline-block; line-height: 1; text-transform: none; letter-spacing: normal; word-wrap: normal; white-space: nowrap; direction: ltr; } `; document.head.appendChild(style); } // ============================================ // KEYBOARD SHORTCUTS // ============================================ document.addEventListener('keydown', function(e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { document.getElementById('generate-btn')?.click(); } }); // ============================================ // RESPONSIVE ADJUSTMENTS // ============================================ window.addEventListener('resize', function() { // Redraw charts on resize if (currentState) { drawCharts(currentState, currentObservation || {}, currentPlan || {}); } });