<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Budget Allocation System</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--bg: #070b14;
--bg-elevated: #0d1320;
--card: #111827;
--border: #1e293b;
--fg: #f1f5f9;
--muted: #64748b;
--accent: #00d4aa;
--accent-dim: rgba(0, 212, 170, 0.15);
--danger: #f43f5e;
--warning: #f59e0b;
--info: #3b82f6;
}
* {
box-sizing: border-box;
}
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
}
.font-mono {
font-family: 'JetBrains Mono', monospace;
}
/* Background atmosphere */
.bg-atmosphere {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 0;
background:
radial-gradient(ellipse 80% 50% at 20% 0%, rgba(0, 212, 170, 0.08) 0%, transparent 50%),
radial-gradient(ellipse 60% 40% at 80% 100%, rgba(59, 130, 246, 0.06) 0%, transparent 50%),
linear-gradient(180deg, var(--bg) 0%, #0a0f1a 100%);
}
.grid-pattern {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 0;
opacity: 0.03;
background-image:
linear-gradient(var(--muted) 1px, transparent 1px),
linear-gradient(90deg, var(--muted) 1px, transparent 1px);
background-size: 60px 60px;
}
/* Cards */
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 16px;
overflow: hidden;
}
.card-glow {
position: relative;
}
.card-glow::before {
content: '';
position: absolute;
inset: -1px;
border-radius: 17px;
padding: 1px;
background: linear-gradient(135deg, rgba(0, 212, 170, 0.3), transparent 50%);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
}
/* Custom range slider */
input[type="range"] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 6px;
background: var(--border);
border-radius: 3px;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 18px;
height: 18px;
background: var(--accent);
border-radius: 50%;
cursor: grab;
transition: transform 0.15s, box-shadow 0.15s;
box-shadow: 0 0 0 4px rgba(0, 212, 170, 0.2);
}
input[type="range"]::-webkit-slider-thumb:hover {
transform: scale(1.1);
box-shadow: 0 0 0 6px rgba(0, 212, 170, 0.3);
}
input[type="range"]::-webkit-slider-thumb:active {
cursor: grabbing;
}
input[type="range"]:focus {
outline: none;
}
input[type="range"]:focus-visible::-webkit-slider-thumb {
box-shadow: 0 0 0 6px rgba(0, 212, 170, 0.4);
}
/* Animations */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes scaleIn {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes pulse-glow {
0%, 100% { opacity: 0.5; }
50% { opacity: 1; }
}
.animate-in {
animation: fadeInUp 0.6s ease-out forwards;
opacity: 0;
}
.delay-1 { animation-delay: 0.1s; }
.delay-2 { animation-delay: 0.2s; }
.delay-3 { animation-delay: 0.3s; }
.delay-4 { animation-delay: 0.4s; }
.delay-5 { animation-delay: 0.5s; }
@media (prefers-reduced-motion: reduce) {
.animate-in {
animation: none;
opacity: 1;
}
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--muted);
}
/* Button styles */
.btn-primary {
background: var(--accent);
color: var(--bg);
font-weight: 600;
padding: 12px 24px;
border-radius: 10px;
transition: all 0.2s;
border: none;
cursor: pointer;
}
.btn-primary:hover {
filter: brightness(1.1);
transform: translateY(-1px);
}
.btn-primary:active {
transform: translateY(0);
}
.btn-primary:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.btn-secondary {
background: transparent;
color: var(--fg);
font-weight: 500;
padding: 12px 24px;
border-radius: 10px;
transition: all 0.2s;
border: 1px solid var(--border);
cursor: pointer;
}
.btn-secondary:hover {
background: var(--border);
border-color: var(--muted);
}
/* Tag styles */
.tag {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 4px 10px;
border-radius: 6px;
font-size: 12px;
font-weight: 500;
}
.tag-success {
background: rgba(0, 212, 170, 0.15);
color: var(--accent);
}
.tag-warning {
background: rgba(245, 158, 11, 0.15);
color: var(--warning);
}
.tag-danger {
background: rgba(244, 63, 94, 0.15);
color: var(--danger);
}
.tag-info {
background: rgba(59, 130, 246, 0.15);
color: var(--info);
}
/* Canvas container */
.chart-container {
position: relative;
}
canvas {
display: block;
}
/* Tooltip */
.tooltip {
position: absolute;
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
font-size: 13px;
pointer-events: none;
opacity: 0;
transition: opacity 0.15s;
z-index: 100;
white-space: nowrap;
}
.tooltip.visible {
opacity: 1;
}
/* Category indicator */
.category-dot {
width: 10px;
height: 10px;
border-radius: 50%;
flex-shrink: 0;
}
</style>
</head>
<body class="antialiased">
<div class="bg-atmosphere"></div>
<div class="grid-pattern"></div>
<div class="relative z-10 min-h-screen">
<!-- Header -->
<header class="border-b border-[var(--border)] bg-[var(--bg)]/80 backdrop-blur-xl sticky top-0 z-50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between h-16">
<div class="flex items-center gap-3">
<div class="w-9 h-9 rounded-lg bg-gradient-to-br from-[var(--accent)] to-[#00a080] flex items-center justify-center">
<svg class="w-5 h-5 text-[var(--bg)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
</svg>
</div>
<span class="font-semibold text-lg">BudgetFlow</span>
</div>
<nav class="hidden md:flex items-center gap-6">
<a href="#" class="text-[var(--fg)] font-medium">Dashboard</a>
<a href="#" class="text-[var(--muted)] hover:text-[var(--fg)] transition-colors">Analytics</a>
<a href="#" class="text-[var(--muted)] hover:text-[var(--fg)] transition-colors">Reports</a>
</nav>
<div class="flex items-center gap-3">
<button class="btn-secondary text-sm py-2 px-4">Export</button>
<button class="btn-primary text-sm py-2 px-4">Save Plan</button>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<!-- Page Header -->
<div class="mb-8 animate-in">
<h1 class="text-3xl md:text-4xl font-bold mb-2">Budget Allocation</h1>
<p class="text-[var(--muted)] text-lg">Plan and predict your financial distribution for Q4 2025</p>
</div>
<!-- Summary Cards -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
<div class="card p-5 animate-in delay-1">
<p class="text-[var(--muted)] text-sm mb-1">Total Budget</p>
<p class="text-2xl font-bold font-mono">$125,000</p>
<p class="text-xs text-[var(--muted)] mt-2">Annual allocation</p>
</div>
<div class="card p-5 animate-in delay-2">
<p class="text-[var(--muted)] text-sm mb-1">Allocated</p>
<p class="text-2xl font-bold font-mono" id="allocated-amount">$0</p>
<p class="text-xs text-[var(--accent)] mt-2" id="allocated-percent">0% of total</p>
</div>
<div class="card p-5 animate-in delay-3">
<p class="text-[var(--muted)] text-sm mb-1">Predicted Spend</p>
<p class="text-2xl font-bold font-mono" id="predicted-spend">$0</p>
<p class="text-xs text-[var(--warning)] mt-2" id="prediction-variance">Based on trends</p>
</div>
<div class="card p-5 animate-in delay-4">
<p class="text-[var(--muted)] text-sm mb-1">Health Score</p>
<p class="text-2xl font-bold font-mono text-[var(--accent)]" id="health-score">--</p>
<p class="text-xs text-[var(--muted)] mt-2" id="health-label">Calculating...</p>
</div>
</div>
<!-- Main Grid -->
<div class="grid lg:grid-cols-3 gap-6">
<!-- Left Column - Allocation -->
<div class="lg:col-span-2 space-y-6">
<!-- Allocation Chart -->
<div class="card card-glow p-6 animate-in delay-2">
<div class="flex items-center justify-between mb-6">
<div>
<h2 class="text-xl font-semibold">Current Allocation</h2>
<p class="text-[var(--muted)] text-sm mt-1">Drag sliders to adjust budget distribution</p>
</div>
<div class="flex gap-2">
<button class="tag tag-info cursor-pointer hover:opacity-80" onclick="resetAllocation()">Reset</button>
<button class="tag tag-success cursor-pointer hover:opacity-80" onclick="optimizeAllocation()">Auto-optimize</button>
</div>
</div>
<div class="grid md:grid-cols-2 gap-8">
<!-- Donut Chart -->
<div class="chart-container flex items-center justify-center">
<canvas id="allocationChart" width="240" height="240"></canvas>
<div id="chartTooltip" class="tooltip"></div>
</div>
<!-- Sliders -->
<div class="space-y-5" id="category-sliders">
<!-- Generated by JS -->
</div>
</div>
</div>
<!-- Prediction Chart -->
<div class="card p-6 animate-in delay-3">
<div class="flex items-center justify-between mb-6">
<div>
<h2 class="text-xl font-semibold">Spending Prediction</h2>
<p class="text-[var(--muted)] text-sm mt-1">6-month forecast based on historical trends</p>
</div>
<div class="flex gap-2">
<button class="time-btn px-3 py-1.5 rounded-lg text-sm font-medium bg-[var(--accent-dim)] text-[var(--accent)]" data-months="6">6M</button>
<button class="time-btn px-3 py-1.5 rounded-lg text-sm font-medium text-[var(--muted)] hover:bg-[var(--border)]" data-months="12">12M</button>
</div>
</div>
<div class="chart-container h-64">
<canvas id="predictionChart"></canvas>
</div>
</div>
</div>
<!-- Right Column - Insights -->
<div class="space-y-6">
<!-- AI Recommendations -->
<div class="card card-glow p-6 animate-in delay-4">
<div class="flex items-center gap-2 mb-4">
<div class="w-8 h-8 rounded-lg bg-[var(--accent-dim)] flex items-center justify-center">
<svg class="w-4 h-4 text-[var(--accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
</svg>
</div>
<h2 class="text-lg font-semibold">AI Recommendations</h2>
</div>
<div class="space-y-3" id="recommendations">
<!-- Generated by JS -->
</div>
</div>
<!-- Category Breakdown -->
<div class="card p-6 animate-in delay-5">
<h2 class="text-lg font-semibold mb-4">Category Analysis</h2>
<div class="space-y-4" id="category-analysis">
<!-- Generated by JS -->
</div>
</div>
<!-- Risk Assessment -->
<div class="card p-6 animate-in delay-5">
<h2 class="text-lg font-semibold mb-4">Risk Assessment</h2>
<div class="space-y-3">
<div class="flex items-center justify-between">
<span class="text-sm text-[var(--muted)]">Overspend Risk</span>
<span class="tag tag-warning" id="overspend-risk">Low</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-[var(--muted)]">Budget Variance</span>
<span class="tag tag-info" id="budget-variance">Stable</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-[var(--muted)]">Forecast Accuracy</span>
<span class="tag tag-success" id="forecast-accuracy">94%</span>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<script>
// Budget Data
const TOTAL_BUDGET = 125000;
const EPS = 0.001;
const categories = [
{ id: 'marketing', name: 'Marketing', color: '#00d4aa', budget: 30000, trend: 1.08 },
{ id: 'engineering', name: 'Engineering', color: '#3b82f6', budget: 40000, trend: 1.12 },
{ id: 'operations', name: 'Operations', color: '#f59e0b', budget: 20000, trend: 0.95 },
{ id: 'hr', name: 'Human Resources', color: '#8b5cf6', budget: 15000, trend: 1.02 },
{ id: 'rd', name: 'R&D', color: '#ec4899', budget: 15000, trend: 1.15 },
{ id: 'misc', name: 'Miscellaneous', color: '#64748b', budget: 5000, trend: 0.90 }
];
// Historical spending data (last 6 months)
const historicalData = {
marketing: [22000, 24500, 26000, 28000, 29000, 31000],
engineering: [32000, 34000, 36000, 37000, 39000, 41000],
operations: [18000, 17500, 19000, 18500, 18000, 19500],
hr: [12000, 12500, 13000, 13500, 14000, 14500],
rd: [10000, 12000, 14000, 16000, 17500, 18000],
misc: [4500, 4800, 4200, 5000, 4600, 4800]
};
// Simple linear regression for prediction
function linearRegression(data) {
const n = data.length;
let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0;
for (let i = 0; i < n; i++) {
sumX += i;
sumY += data[i];
sumXY += i * data[i];
sumXX += i * i;
}
const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
const intercept = (sumY - slope * sumX) / n;
return { slope, intercept };
}
// Predict future values
function predictFuture(categoryId, months) {
const data = historicalData[categoryId];
const { slope, intercept } = linearRegression(data);
const predictions = [];
for (let i = data.length; i < data.length + months; i++) {
predictions.push(Math.max(0, slope * i + intercept));
}
return predictions;
}
// Initialize UI
function init() {
renderSliders();
updateAllocation();
renderPredictions(6);
renderRecommendations();
renderCategoryAnalysis();
setupEventListeners();
}
// Render category sliders
function renderSliders() {
const container = document.getElementById('category-sliders');
container.innerHTML = categories.map(cat => `
<div class="slider-group" data-category="${cat.id}">
<div class="flex items-center justify-between mb-2">
<div class="flex items-center gap-2">
<div class="category-dot" style="background: ${cat.color}"></div>
<span class="text-sm font-medium">${cat.name}</span>
</div>
<span class="font-mono text-sm budget-value">$${cat.budget.toLocaleString()}</span>
</div>
<input
type="range"
min="0"
max="${TOTAL_BUDGET / 2}"
value="${cat.budget}"
step="1000"
data-category="${cat.id}"
aria-label="${cat.name} budget"
>
<div class="flex justify-between text-xs text-[var(--muted)] mt-1">
<span>$0</span>
<span class="percent-value">${((cat.budget / TOTAL_BUDGET) * 100).toFixed(1)}%</span>
</div>
</div>
`).join('');
// Add event listeners to sliders
container.querySelectorAll('input[type="range"]').forEach(slider => {
slider.addEventListener('input', handleSliderChange);
});
}
// Handle slider change
function handleSliderChange(e) {
const categoryId = e.target.dataset.category;
const value = parseInt(e.target.value);
const category = categories.find(c => c.id === categoryId);
if (category) {
category.budget = value;
// Update display values
const group = e.target.closest('.slider-group');
group.querySelector('.budget-value').textContent = `$${value.toLocaleString()}`;
group.querySelector('.percent-value').textContent = `${((value / TOTAL_BUDGET) * 100).toFixed(1)}%`;
updateAllocation();
}
}
// Update allocation display and charts
function updateAllocation() {
const allocated = categories.reduce((sum, c) => sum + c.budget, 0);
const percent = (allocated / TOTAL_BUDGET) * 100;
document.getElementById('allocated-amount').textContent = `$${allocated.toLocaleString()}`;
document.getElementById('allocated-percent').textContent = `${percent.toFixed(1)}% of total`;
// Calculate predicted spend
const predictedSpend = categories.reduce((sum, c) => {
const predictions = predictFuture(c.id, 1);
return sum + (predictions[0] || c.budget);
}, 0);
document.getElementById('predicted-spend').textContent = `$${Math.round(predictedSpend).toLocaleString()}`;
const variance = ((predictedSpend - allocated) / allocated * 100).toFixed(1);
const varianceEl = document.getElementById('prediction-variance');
if (parseFloat(variance) > 5) {
varianceEl.textContent = `${variance}% over budget`;
varianceEl.className = 'text-xs text-[var(--danger)]';
} else if (parseFloat(variance) < -5) {
varianceEl.textContent = `${Math.abs(variance)}% under budget`;
varianceEl.className = 'text-xs text-[var(--accent)]';
} else {
varianceEl.textContent = 'Within target';
varianceEl.className = 'text-xs text-[var(--muted)]';
}
// Calculate health score
const balanceScore = calculateBalanceScore();
const healthScore = Math.round(balanceScore * 100);
document.getElementById('health-score').textContent = `${healthScore}`;
const healthLabel = document.getElementById('health-label');
if (healthScore >= 80) {
healthLabel.textContent = 'Excellent balance';
} else if (healthScore >= 60) {
healthLabel.textContent = 'Good allocation';
} else {
healthLabel.textContent = 'Needs adjustment';
}
// Update risk assessment
updateRiskAssessment(allocated, predictedSpend);
// Draw charts
drawAllocationChart();
}
// Calculate balance score (how evenly distributed)
function calculateBalanceScore() {
const total = categories.reduce((sum, c) => sum + c.budget, 0);
if (total === 0) return 0;
const idealPercent = 1 / categories.length;
let score = 0;
categories.forEach(c => {
const actualPercent = c.budget / total;
// Score based on how close to ideal (not too concentrated)
score += Math.min(actualPercent, idealPercent * 2);
});
return score / 2;
}
// Draw donut chart
function drawAllocationChart() {
const canvas = document.getElementById('allocationChart');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const outerRadius = Math.max(EPS, Math.min(centerX, centerY) - 20);
const innerRadius = Math.max(EPS, outerRadius * 0.65);
ctx.clearRect(0, 0, canvas.width, canvas.height);
const total = Math.max(EPS, categories.reduce((sum, c) => sum + c.budget, 0));
let startAngle = -Math.PI / 2;
categories.forEach((cat, i) => {
const sliceAngle = Math.max(0, (cat.budget / total) * Math.PI * 2);
if (sliceAngle > 0) {
ctx.beginPath();
ctx.arc(centerX, centerY, outerRadius, startAngle, startAngle + sliceAngle);
ctx.arc(centerX, centerY, innerRadius, startAngle + sliceAngle, startAngle, true);
ctx.closePath();
ctx.fillStyle = cat.color;
ctx.fill();
startAngle += sliceAngle;
}
});
// Center text
ctx.fillStyle = '#f1f5f9';
ctx.font = 'bold 24px Space Grotesk';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(`$${Math.round(total / 1000)}K`, centerX, centerY - 10);
ctx.fillStyle = '#64748b';
ctx.font = '13px Space Grotesk';
ctx.fillText('Allocated', centerX, centerY + 15);
}
// Render prediction chart
function renderPredictions(months) {
const canvas = document.getElementById('predictionChart');
const ctx = canvas.getContext('2d');
const rect = canvas.parentElement.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const padding = { top: 20, right: 20, bottom: 40, left: 60 };
const chartWidth = canvas.width - padding.left - padding.right;
const chartHeight = canvas.height - padding.top - padding.bottom;
// Calculate total predictions per month
const totalHistorical = [];
for (let i = 0; i < 6; i++) {
let sum = 0;
categories.forEach(cat => {
sum += historicalData[cat.id][i];
});
totalHistorical.push(sum);
}
const totalPredictions = [];
for (let i = 0; i < months; i++) {
let sum = 0;
categories.forEach(cat => {
const preds = predictFuture(cat.id, months);
sum += preds[i];
});
totalPredictions.push(sum);
}
const allData = [...totalHistorical, ...totalPredictions];
const maxVal = Math.max(...allData) * 1.1;
const minVal = Math.min(...allData) * 0.9;
// Draw grid
ctx.strokeStyle = 'rgba(30, 41, 59, 0.5)';
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = padding.top + (chartHeight / 4) * i;
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(padding.left + chartWidth, y);
ctx.stroke();
const val = maxVal - ((maxVal - minVal) / 4) * i;
ctx.fillStyle = '#64748b';
ctx.font = '11px JetBrains Mono';
ctx.textAlign = 'right';
ctx.fillText(`$${Math.round(val / 1000)}K`, padding.left - 10, y + 4);
}
// Month labels
const monthLabels = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
ctx.textAlign = 'center';
allData.forEach((_, i) => {
const x = padding.left + (chartWidth / (allData.length - 1)) * i;
ctx.fillText(monthLabels[i], x, canvas.height - 15);
});
// Draw budget line
const allocated = categories.reduce((sum, c) => sum + c.budget, 0);
const budgetY = padding.top + chartHeight - ((allocated - minVal) / (maxVal - minVal)) * chartHeight;
ctx.strokeStyle = 'rgba(244, 63, 94, 0.5)';
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.moveTo(padding.left, budgetY);
ctx.lineTo(padding.left + chartWidth, budgetY);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = '#f43f5e';
ctx.font = '10px Space Grotesk';
ctx.textAlign = 'left';
ctx.fillText('Budget', padding.left + chartWidth + 5, budgetY + 3);
// Draw historical line
ctx.strokeStyle = '#64748b';
ctx.lineWidth = 2;
ctx.beginPath();
totalHistorical.forEach((val, i) => {
const x = padding.left + (chartWidth / (allData.length - 1)) * i;
const y = padding.top + chartHeight - ((val - minVal) / (maxVal - minVal)) * chartHeight;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
});
ctx.stroke();
// Draw prediction line
ctx.strokeStyle = '#00d4aa';
ctx.lineWidth = 2;
ctx.beginPath();
const lastHistoricalX = padding.left + (chartWidth / (allData.length - 1)) * (totalHistorical.length - 1);
const lastHistoricalY = padding.top + chartHeight - ((totalHistorical[totalHistorical.length - 1] - minVal) / (maxVal - minVal)) * chartHeight;
ctx.moveTo(lastHistoricalX, lastHistoricalY);
totalPredictions.forEach((val, i) => {
const x = padding.left + (chartWidth / (allData.length - 1)) * (totalHistorical.length + i);
const y = padding.top + chartHeight - ((val - minVal) / (maxVal - minVal)) * chartHeight;
ctx.lineTo(x, y);
});
ctx.stroke();
// Draw confidence area
ctx.fillStyle = 'rgba(0, 212, 170, 0.1)';
ctx.beginPath();
const firstPredX = padding.left + (chartWidth / (allData.length - 1)) * totalHistorical.length;
const firstPredY = padding.top + chartHeight - ((totalPredictions[0] - minVal) / (maxVal - minVal)) * chartHeight;
ctx.moveTo(lastHistoricalX, lastHistoricalY);
totalPredictions.forEach((val, i) => {
const x = padding.left + (chartWidth / (allData.length - 1)) * (totalHistorical.length + i);
const y = padding.top + chartHeight - ((val * 1.05 - minVal) / (maxVal - minVal)) * chartHeight;
ctx.lineTo(x, y);
});
for (let i = totalPredictions.length - 1; i >= 0; i--) {
const val = totalPredictions[i];
const x = padding.left + (chartWidth / (allData.length - 1)) * (totalHistorical.length + i);
const y = padding.top + chartHeight - ((val * 0.95 - minVal) / (maxVal - minVal)) * chartHeight;
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.fill();
}
// Render AI recommendations
function renderRecommendations() {
const container = document.getElementById('recommendations');
const recommendations = [
{
type: 'warning',
title: 'R&D underspend detected',
desc: 'Consider increasing R&D budget to match growth trajectory'
},
{
type: 'success',
title: 'Operations optimized',
desc: 'Current allocation aligns with efficiency trends'
},
{
type: 'info',
title: 'Marketing ROI potential',
desc: '12% growth trend suggests room for increased investment'
}
];
container.innerHTML = recommendations.map(rec => `
<div class="p-3 rounded-lg bg-[var(--bg-elevated)] border border-[var(--border)] hover:border-[var(--muted)] transition-colors cursor-pointer">
<div class="flex items-start gap-2">
<span class="tag tag-${rec.type} shrink-0">${rec.type === 'success' ? '+' : rec.type === 'warning' ? '!' 'i'}</span>
<div>
<p class="text-sm font-medium">${rec.title}</p>
<p class="text-xs text-[var(--muted)] mt-0.5">${rec.desc}</p>
</div>
</div>
</div>
`).join('');
}
// Render category analysis
function renderCategoryAnalysis() {
const container = document.getElementById('category-analysis');
container.innerHTML = categories.map(cat => {
const predictions = predictFuture(cat.id, 3);
const avgPredicted = predictions.reduce((a, b) => a + b, 0) / predictions.length;
const variance = ((avgPredicted - cat.budget) / cat.budget * 100).toFixed(1);
const isOver = parseFloat(variance) > 0;
return `
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<div class="category-dot" style="background: ${cat.color}"></div>
<span class="text-sm">${cat.name}</span>
</div>
<div class="flex items-center gap-2">
<span class="font-mono text-sm">${cat.trend > 1 ? '+' : ''}${((cat.trend - 1) * 100).toFixed(0)}%</span>
<span class="tag ${isOver ? 'tag-danger' : 'tag-success'}">${isOver ? '↑' : '↓'}${Math.abs(variance)}%</span>
</div>
</div>
`;
}).join('');
}
// Update risk assessment
function updateRiskAssessment(allocated, predicted) {
const variance = Math.abs((predicted - allocated) / allocated * 100);
const riskEl = document.getElementById('overspend-risk');
if (variance > 15) {
riskEl.textContent = 'High';
riskEl.className = 'tag tag-danger';
} else if (variance > 8) {
riskEl.textContent = 'Medium';
riskEl.className = 'tag tag-warning';
} else {
riskEl.textContent = 'Low';
riskEl.className = 'tag tag-success';
}
const varianceEl = document.getElementById('budget-variance');
if (predicted > allocated * 1.1) {
varianceEl.textContent = 'Over budget';
varianceEl.className = 'tag tag-danger';
} else if (predicted < allocated * 0.9) {
varianceEl.textContent = 'Under budget';
varianceEl.className = 'tag tag-info';
} else {
varianceEl.textContent = 'Stable';
varianceEl.className = 'tag tag-success';
}
}
// Reset allocation to defaults
function resetAllocation() {
const defaults = [30000, 40000, 20000, 15000, 15000, 5000];
categories.forEach((cat, i) => {
cat.budget = defaults[i];
});
renderSliders();
updateAllocation();
}
// Auto-optimize allocation
function optimizeAllocation() {
// Simple optimization: allocate based on growth trends
const totalTrend = categories.reduce((sum, c) => sum + c.trend, 0);
categories.forEach(cat => {
cat.budget = Math.round((cat.trend / totalTrend) * TOTAL_BUDGET);
});
renderSliders();
updateAllocation();
}
// Setup event listeners
function setupEventListeners() {
// Time range buttons
document.querySelectorAll('.time-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('.time-btn').forEach(b => {
b.classList.remove('bg-[var(--accent-dim)]', 'text-[var(--accent)]');
b.classList.add('text-[var(--muted)]');
});
e.target.classList.add('bg-[var(--accent-dim)]', 'text-[var(--accent)]');
e.target.classList.remove('text-[var(--muted)]');
const months = parseInt(e.target.dataset.months);
renderPredictions(months);
});
});
// Resize handler
let resizeTimeout;
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
renderPredictions(6);
}, 100);
});
}
// Initialize on load
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>