# Project export: OptiPanel

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 12.0
- Tagline: An AI engine that transforms business data into growth decisions — optimizing revenue streams before they dry out.
- Devpost: https://devpost.com/software/optipanel
- GitHub: https://github.com/aneshkondor/optipanelv2
- Demo: https://calhacks-optipanel.onrender.com/
- Video: https://www.youtube.com/embed/hjrsdwQvauw?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 2 GitHub contributor(s) — Aryan Khandelwal (3 commits), Claude (2 commits)

## Devpost submission (written by the team)

No Devpost description available.

## README (from the GitHub repository)

# 🚀 CalHacks Revenue Optimization Platform

> AI-powered revenue optimization platform with intelligent voice calling and real-time analytics

[![Deploy Backend](https://img.shields.io/badge/Deploy-Railway-blueviolet)](https://railway.app)
[![Deploy Frontend](https://img.shields.io/badge/Deploy-Vercel-black)](https://vercel.com)

## 📋 What Is This?

An intelligent B2B revenue optimization platform that:
- 📊 **Tracks user behavior** on your e-commerce site in real-time
- 🤖 **Uses Claude AI** to decide when to intervene with at-risk customers
- 📞 **Makes realistic voice calls** via Vapi with natural-sounding AI agents
- 💬 **AI Chat Interface** powered by Claude for instant business insights
- 📈 **Beautiful dashboards** with real-time metrics and analytics

## ⚡ Quick Start

### Prerequisites
- Node.js 18+
- API Keys: [Vapi](https://vapi.ai), [Anthropic Claude](https://anthropic.com), [OpenAI](https://openai.com)

### 1. Clone & Install
```bash
git clone https://github.com/a-khandel/calhacks-demo.git
cd calhacks-demo
npm install
cd frontend02 && npm install && cd ..
cd dummy_website && npm install && cd ..
```

### 2. Configure Environment
```bash
cp .env.example .env
# Add your API keys to .env
```

### 3. Start Everything
```bash
# Terminal 1 - Backend
node src/index.js

# Terminal 2 - Dashboard
cd frontend02 && npm run dev

# Terminal 3 - Demo E-commerce Site
cd dummy_website && npm run dev
```

📖 **Full Setup Guide**: [docs/setup/QUICKSTART.md](docs/setup/QUICKSTART.md)

---

## 📁 Project Structure

```
calhacks-demo/
├── 📂 src/                          # Backend (Node.js + Express)
│   ├── index.js                     # Main server
│   ├── services/
│   │   ├── aiChatService.js        # Claude AI chat integration
│   │   ├── claudeService.js        # AI decision engine
│   │   ├── vapiService.js          # Voice calling via Vapi
│   │   ├── engagementDetector.js   # User behavior analysis
│   │   └── metricsAggregator.js    # Real-time analytics
│   └── config/
│       └── vapi.config.js          # Voice agent configuration
│
├── 📂 frontend02/                   # Main Dashboard (React + Vite)
│   ├── src/
│   │   ├── components/
│   │   │   └── app/
│   │   │       ├── AIChatPanel.tsx     # Claude AI chat interface
│   │   │       └── EngagementMonitor.tsx # User monitoring
│   │   └── contexts/
│   │       └── MetricsContext.tsx       # Real-time metrics
│   └── package.json
│
├── 📂 dummy_website/                # Demo E-commerce Site (React + Vite)
│   ├── src/
│   │   ├── services/
│   │   │   └── analyticsTracker.js  # Sends metrics to backend
│   │   └── pages/                   # E-commerce pages
│   └── package.json
│
├── 📂 docs/                         # Documentation
│   ├── deployment/                  # Deployment guides
│   │   ├── QUICK_DEPLOY.md         # 15-min deploy guide
│   │   ├── DEPLOYMENT.md           # Full deployment docs
│   │   └── GITHUB_SETUP.md         # GitHub setup
│   ├── setup/                       # Setup instructions
│   │   ├── QUICKSTART.md           # Quick start guide
│   │   └── SETUP_INSTRUCTIONS.md   # Detailed setup
│   ├── guides/                      # Feature guides
│   │   ├── DEMO_GUIDE.md           # How to demo the app
│   │   └── AUTO_CALL_TRIGGER_GUIDE.md
│   ├── technical/                   # Technical docs
│   └── PROJECT_STRUCTURE.md         # Architecture details
│
├── 📂 scripts/                      # Utility scripts
│   ├── START_BACKEND.sh            # Quick backend starter
│   └── test-quick.js               # Test script
│
├── 📂 config/                       # Configuration files
│   └── railway.json                # Railway deployment config
│
├── .env.example                     # Environment variables template
├── package.json                     # Backend dependencies
└── README.md                        # This file
```

---

## 🎯 Key Features

### 1. Real-Time User Tracking
- Monitors user behavior on e-commerce site
- Tracks cart actions, page views, engagement
- Detects abandonment patterns

### 2. AI-Powered Decision Making
- Claude AI analyzes user behavior
- Intelligent intervention timing
- Personalized outreach strategies

### 3. Realistic Voice Calls
- Natural-sounding AI agent (Sarah)
- Office background sounds for realism
- Context-aware conversation scripts
- Handles objections and questions

### 4. AI Chat Interface (OptiPanel AI)
- Ask questions about your data
- Get instant insights and visualizations
- Generate charts automatically
- Save graphs to dashboard

### 5. Beautiful Dashboards
- Real-time metrics visualization
- User engagement monitoring
- Executive dashboard with custom widgets

---

## 🚀 Deployment

### Quick Deploy (15 minutes)

1. **Backend** → Deploy to Railway
2. **Frontend Dashboard** → Deploy to Vercel
3. **Demo Site** → Deploy to Vercel (separate project)

📖 **Step-by-Step**: [docs/deployment/QUICK_DEPLOY.md](docs/deployment/QUICK_DEPLOY.md)

### Cost: $0/month
- Railway: FREE ($5 credits)
- Vercel: FREE (unlimited for personal projects)

---

## 📚 Documentation

### Getting Started
- [Quick Start Guide](docs/setup/QUICKSTART.md) - Get running in 5 minutes
- [Setup Instructions](docs/setup/SETUP_INSTRUCTIONS.md) - Detailed setup
- [Demo Guide](docs/guides/DEMO_GUIDE.md) - How to demo the platform

### Deployment
- [Quick Deploy (15 min)](docs/deployment/QUICK_DEPLOY.md) - Fast deployment
- [Full Deployment Guide](docs/deployment/DEPLOYMENT.md) - All options
- [GitHub Setup](docs/deployment/GITHUB_SETUP.md) - Repository setup

### Technical
- [Project Structure](docs/PROJECT_STRUCTURE.md) - Architecture details
- [Frontend Integration](docs/technical/FRONTEND_INTEGRATION.md) - Frontend docs
- [What's New](docs/technical/WHATS_NEW.md) - Recent updates

---

## 🛠️ Tech Stack

### Backend
- **Runtime**: Node.js + Express
- **AI**: Claude 3.5 Sonnet (Anthropic)
- **Voice**: Vapi.ai + ElevenLabs + OpenAI GPT-4
- **Real-time**: WebSocket-like polling

### Frontend
- **Framework**: React + TypeScript + Vite
- **UI**: Tailwind CSS + Radix UI + shadcn/ui
- **Charts**: Recharts
- **State**: React Context API

### Deployment
- **Backend**: Railway
- **Frontend**: Vercel
- **Demo Site**: Vercel

---

## 🎬 How It Works

```
┌─────────────────────────────────────────────────────────┐
│ 1. User browses demo e-commerce site                    │
│    - Adds items to cart                                 │
│    - Removes items (showing hesitation)                 │
└─────────────┬───────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────┐
│ 2. Analytics tracker sends metrics to backend           │
│    - Cart actions, page views, engagement               │
└─────────────┬───────────────────────────────��───────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────┐
│ 3. Backend analyzes behavior with Claude AI             │
│    - Detects 3rd cart removal = critical risk           │
│    - AI decides: "Call now!"                            │
└─────────────┬───────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────┐
│ 4. Vapi makes realistic voice call                      │
│    - Natural AI agent with office background sounds     │
│    - Personalized script based on user behavior         │
│    - Offers help, discount, or assistance               │
└─────────────┬───────────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────────────────────┐
│ 5. Dashboard shows everything in real-time              │
│    - User metrics, call status, engagement trends       │
│    - AI chat for instant insights                       │
└─────────────────────────────────────────────────────────┘
```

---

## 🔑 Environment Variables

```bash
# Vapi (Voice Calling)
VAPI_API_KEY=your_vapi_api_key
VAPI_PHONE_NUMBER_

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 217 recognized source files, 1330 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- Express (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- React (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Docker (technology) — claimed on Devpost, not found in the code
- FastAPI (technology) — claimed on Devpost, not found in the code
- Python (language) — claimed on Devpost, not found in the code
- Redis (technology) — claimed on Devpost, not found in the code
- AI coding agent: Claude Code — evidence: commit authorship or trailers

## Codebase structure (from repository index)

### Files (120 of 227)

```
.env.example
.gitignore
build.sh
config/railway.json
docs/deployment/DEPLOYMENT.md
docs/deployment/GITHUB_SETUP.md
docs/deployment/QUICK_DEPLOY.md
docs/guides/AUTO_CALL_TRIGGER_GUIDE.md
docs/guides/DEMO_GUIDE.md
docs/guides/LENIENT_TRIGGER_GUIDE.md
docs/guides/REVENUE_RECOVERY_GUIDE.md
docs/guides/TEST_AUTO_TRIGGER.md
docs/PROJECT_OVERVIEW.txt
docs/PROJECT_STRUCTURE.md
docs/setup/QUICK_START.md
docs/setup/QUICKSTART.md
docs/setup/SETUP_INSTRUCTIONS.md
docs/setup/SIMPLE_GUIDE.md
docs/setup/START_HERE.md
docs/technical/ANALYTICS_ACCURACY_TEST.md
docs/technical/FIX_GUIDE.md
docs/technical/FIXED_ANALYTICS.md
docs/technical/FRONTEND_INTEGRATION.md
docs/technical/INTEGRATION_COMPLETE.md
docs/technical/STABLE_GRAPHS_FIX.md
docs/technical/WHATS_NEW.md
docs/technical/ZERO_AUTO_TRACKING.md
frontend-rev-opt/.env.production
frontend-rev-opt/index.html
frontend-rev-opt/package.json
frontend-rev-opt/README.md
frontend-rev-opt/src/App.tsx
frontend-rev-opt/src/Attributions.md
frontend-rev-opt/src/BACKEND_INTEGRATION.md
frontend-rev-opt/src/CLAUDE_HANDOVER_PROMPT.md
frontend-rev-opt/src/components/app/AIChatPanel.tsx
frontend-rev-opt/src/components/app/AlertsPage.tsx
frontend-rev-opt/src/components/app/AppShell.tsx
frontend-rev-opt/src/components/app/CohortsPage.tsx
frontend-rev-opt/src/components/app/DataCatalogPage.tsx
frontend-rev-opt/src/components/app/EngagementMonitor.tsx
frontend-rev-opt/src/components/app/ExecutiveDashboard.tsx
frontend-rev-opt/src/components/app/ExperimentsPage.tsx
frontend-rev-opt/src/components/app/ExplorePage.tsx
frontend-rev-opt/src/components/app/FloatingChat.tsx
frontend-rev-opt/src/components/app/FlowsPage.tsx
frontend-rev-opt/src/components/app/FunnelsPage.tsx
frontend-rev-opt/src/components/app/LiveMetricsPage.tsx
frontend-rev-opt/src/components/app/OnboardingFlow.tsx
frontend-rev-opt/src/components/app/ReportsPage.tsx
frontend-rev-opt/src/components/app/RetentionPage.tsx
frontend-rev-opt/src/components/app/RevenuePage.tsx
frontend-rev-opt/src/components/app/SettingsPage.tsx
frontend-rev-opt/src/components/app/utils/AI_ENGAGEMENT_README.md
frontend-rev-opt/src/components/app/utils/aiDataFormatter.ts
frontend-rev-opt/src/components/DashboardLoader.tsx
frontend-rev-opt/src/components/figma/ImageWithFallback.tsx
frontend-rev-opt/src/components/marketing/LandingPage.tsx
frontend-rev-opt/src/components/marketing/MarketingFooter.tsx
frontend-rev-opt/src/components/marketing/MarketingHeader.tsx
frontend-rev-opt/src/components/marketing/PricingPage.tsx
frontend-rev-opt/src/components/marketing/ProductPage.tsx
frontend-rev-opt/src/components/marketing/SecurityPage.tsx
frontend-rev-opt/src/components/marketing/SolutionsPage.tsx
frontend-rev-opt/src/components/ThemeProvider.tsx
frontend-rev-opt/src/components/ThemeToggle.tsx
frontend-rev-opt/src/components/ui/accordion.tsx
frontend-rev-opt/src/components/ui/alert-dialog.tsx
frontend-rev-opt/src/components/ui/alert.tsx
frontend-rev-opt/src/components/ui/aspect-ratio.tsx
frontend-rev-opt/src/components/ui/avatar.tsx
frontend-rev-opt/src/components/ui/badge.tsx
frontend-rev-opt/src/components/ui/breadcrumb.tsx
frontend-rev-opt/src/components/ui/button.tsx
frontend-rev-opt/src/components/ui/calendar.tsx
frontend-rev-opt/src/components/ui/card.tsx
frontend-rev-opt/src/components/ui/carousel.tsx
frontend-rev-opt/src/components/ui/chart.tsx
frontend-rev-opt/src/components/ui/checkbox.tsx
frontend-rev-opt/src/components/ui/collapsible.tsx
frontend-rev-opt/src/components/ui/command.tsx
frontend-rev-opt/src/components/ui/context-menu.tsx
frontend-rev-opt/src/components/ui/dialog.tsx
frontend-rev-opt/src/components/ui/drawer.tsx
frontend-rev-opt/src/components/ui/dropdown-menu.tsx
frontend-rev-opt/src/components/ui/form.tsx
frontend-rev-opt/src/components/ui/hover-card.tsx
frontend-rev-opt/src/components/ui/input-otp.tsx
frontend-rev-opt/src/components/ui/input.tsx
frontend-rev-opt/src/components/ui/label.tsx
frontend-rev-opt/src/components/ui/menubar.tsx
frontend-rev-opt/src/components/ui/navigation-menu.tsx
frontend-rev-opt/src/components/ui/pagination.tsx
frontend-rev-opt/src/components/ui/popover.tsx
frontend-rev-opt/src/components/ui/progress.tsx
frontend-rev-opt/src/components/ui/radio-group.tsx
frontend-rev-opt/src/components/ui/resizable.tsx
frontend-rev-opt/src/components/ui/scroll-area.tsx
frontend-rev-opt/src/components/ui/select.tsx
frontend-rev-opt/src/components/ui/separator.tsx
frontend-rev-opt/src/components/ui/sheet.tsx
frontend-rev-opt/src/components/ui/sidebar.tsx
frontend-rev-opt/src/components/ui/skeleton.tsx
frontend-rev-opt/src/components/ui/slider.tsx
frontend-rev-opt/src/components/ui/sonner.tsx
frontend-rev-opt/src/components/ui/switch.tsx
frontend-rev-opt/src/components/ui/table.tsx
frontend-rev-opt/src/components/ui/tabs.tsx
frontend-rev-opt/src/components/ui/textarea.tsx
frontend-rev-opt/src/components/ui/toggle-group.tsx
frontend-rev-opt/src/components/ui/toggle.tsx
frontend-rev-opt/src/components/ui/tooltip.tsx
frontend-rev-opt/src/components/ui/use-mobile.ts
frontend-rev-opt/src/components/ui/utils.ts
frontend-rev-opt/src/contexts/MetricsContext.tsx
frontend-rev-opt/src/examples/backend-server.js
frontend-rev-opt/src/examples/scraper-integration.js
frontend-rev-opt/src/guidelines/Guidelines.md
frontend-rev-opt/src/index.css
frontend-rev-opt/src/INTEGRATION_GUIDE.md
[107 more files omitted for size]
```

### Dependencies

- frontend-rev-opt/package.json: @radix-ui/react-accordion@^1.2.3, @radix-ui/react-alert-dialog@^1.1.6, @radix-ui/react-aspect-ratio@^1.1.2, @radix-ui/react-avatar@^1.1.3, @radix-ui/react-checkbox@^1.1.4, @radix-ui/react-collapsible@^1.1.3, @radix-ui/react-context-menu@^2.2.6, @radix-ui/react-dialog@^1.1.6, @radix-ui/react-dropdown-menu@^2.1.6, @radix-ui/react-hover-card@^1.1.6, @radix-ui/react-label@^2.1.2, @radix-ui/react-menubar@^1.1.6, @radix-ui/react-navigation-menu@^1.2.5, @radix-ui/react-popover@^1.1.6, @radix-ui/react-progress@^1.1.2, @radix-ui/react-radio-group@^1.2.3, @radix-ui/react-scroll-area@^1.2.3, @radix-ui/react-select@^2.1.6, @radix-ui/react-separator@^1.1.2, @radix-ui/react-slider@^1.2.3, @radix-ui/react-slot@^1.1.2, @radix-ui/react-switch@^1.1.3, @radix-ui/react-tabs@^1.1.3, @radix-ui/react-toggle@^1.1.2, @radix-ui/react-toggle-group@^1.1.2, @radix-ui/react-tooltip@^1.1.8, @types/node@^20.10.0, @vitejs/plugin-react-swc@^3.10.2, class-variance-authority@^0.7.1, clsx@*, cmdk@^1.1.1, embla-carousel-react@^8.6.0, input-otp@^1.4.2, lucide-react@^0.487.0, motion@*, next-themes@^0.4.6, react@^18.3.1, react-day-picker@^8.10.1, react-dnd@*, react-dnd-html5-backend@*, react-dom@^18.3.1, react-hook-form@^7.55.0, react-resizable-panels@^2.1.7, recharts@^2.15.2, sonner@^2.0.3, tailwind-merge@*, vaul@^1.1.2, vite@6.3.5
- package.json: @anthropic-ai/sdk@^0.67.0, @radix-ui/react-accordion@^1.2.12, @radix-ui/react-alert-dialog@^1.1.15, @radix-ui/react-avatar@^1.1.10, @radix-ui/react-checkbox@^1.3.3, @radix-ui/react-collapsible@^1.1.12, @radix-ui/react-dialog@^1.1.15, @radix-ui/react-dropdown-menu@^2.1.16, @radix-ui/react-hover-card@^1.1.15, @radix-ui/react-label@^2.1.7, @radix-ui/react-popover@^1.1.15, @radix-ui/react-progress@^1.1.7, @radix-ui/react-radio-group@^1.3.8, @radix-ui/react-select@^2.2.6, @radix-ui/react-separator@^1.1.7, @radix-ui/react-slider@^1.3.6, @radix-ui/react-switch@^1.2.6, @radix-ui/react-tabs@^1.1.13, @radix-ui/react-toast@^1.2.15, @tailwindcss/vite@^4.1.16, @types/react@^19.2.2, @types/react-dom@^19.2.2, @vapi-ai/server-sdk@^0.1.0, @vapi-ai/web@^2.0.0, axios@^1.6.0, class-variance-authority@^0.7.1, clsx@^2.1.1, cmdk@^1.1.1, cors@^2.8.5, date-fns@^4.1.0, dotenv@^16.3.1, embla-carousel-react@^8.6.0, express@^4.18.2, input-otp@^1.4.2, lucide-react@^0.548.0, motion@^12.23.24, nodemon@^3.0.1, react@^19.2.0, react-day-picker@^9.11.1, react-dom@^19.2.0, react-hook-form@^7.55.0, recharts@^3.3.0, sonner@^2.0.3, tailwind-merge@^3.3.1, tailwindcss@^4.0.0-alpha.25, vaul@^1.1.2
- website-demo/package.json: @radix-ui/react-accordion@^1.2.3, @radix-ui/react-alert-dialog@^1.1.6, @radix-ui/react-aspect-ratio@^1.1.2, @radix-ui/react-avatar@^1.1.3, @radix-ui/react-checkbox@^1.1.4, @radix-ui/react-collapsible@^1.1.3, @radix-ui/react-context-menu@^2.2.6, @radix-ui/react-dialog@^1.1.6, @radix-ui/react-dropdown-menu@^2.1.6, @radix-ui/react-hover-card@^1.1.6, @radix-ui/react-label@^2.1.2, @radix-ui/react-menubar@^1.1.6, @radix-ui/react-navigation-menu@^1.2.5, @radix-ui/react-popover@^1.1.6, @radix-ui/react-progress@^1.1.2, @radix-ui/react-radio-group@^1.2.3, @radix-ui/react-scroll-area@^1.2.3, @radix-ui/react-select@^2.1.6, @radix-ui/react-separator@^1.1.2, @radix-ui/react-slider@^1.2.3, @radix-ui/react-slot@^1.1.2, @radix-ui/react-switch@^1.1.3, @radix-ui/react-tabs@^1.1.3, @radix-ui/react-toggle@^1.1.2, @radix-ui/react-toggle-group@^1.1.2, @radix-ui/react-tooltip@^1.1.8, @types/node@^20.10.0, @vitejs/plugin-react-swc@^3.10.2, class-variance-authority@^0.7.1, clsx@*, cmdk@^1.1.1, embla-carousel-react@^8.6.0, input-otp@^1.4.2, lucide-react@^0.487.0, motion@*, next-themes@^0.4.6, react@^18.3.1, react-day-picker@^8.10.1, react-dom@^18.3.1, react-hook-form@^7.55.0, react-resizable-panels@^2.1.7, recharts@^2.15.2, sonner@^2.0.3, tailwind-merge@*, vaul@^1.1.2, vite@6.3.5

### Recent commits (newest first)

- Rebrand: Change product name from ProductName to OptiPanel
- Fix: Add e-commerce metrics aggregation across all shoppers
- Fix: Live Shopper Metrics not updating - use relative API URL
- Fix: Use relative URL for AI chat API calls
- Fix: Configure multi-frontend deployment for Render
- Fix: Remove duplicate app.listen() causing EADDRINUSE error
- Sync: commit workspace changes
- Rename dummy_website → website-demo and frontend02 → frontend-rev-opt
- Convert submodules to regular folders
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### README_OLD.md

```markdown
# Revenue Optimization AI Voice Agent

A CalHacks project that uses AI-powered voice calls to **convert churning users back into active customers** through strategic negotiation. Built with Vapi for natural voice conversations.

## Overview

This system monitors user engagement metrics and automatically triggers personalized phone calls when it detects significant drops in activity. The AI voice agent is trained as a **Revenue Recovery Specialist** that can:
- Identify why users are disengaging
- Negotiate pricing and offer strategic incentives (up to 50% discounts)
- Re-engage users with empathetic conversation
- Convert dead revenue into active revenue

**💰 Turn churn into revenue with AI-powered retention calls.**

## Features

- **Automatic Engagement Monitoring**: Continuously tracks user engagement metrics
- **Smart Drop Detection**: Identifies meaningful drops using statistical analysis
- **Revenue Recovery AI**: Expert negotiation system trained to win back customers
- **Strategic Discounting**: AI can offer 20-50% discounts with clear authority levels
- **5-Phase Conversation Framework**: Discovery → Qualification → Value → Negotiation → Close
- **Dynamic Call Scripts**: Personalized scripts based on drop severity and user behavior
- **AI Voice Conversations**: Natural, empathetic calls powered by Vapi + GPT-4
- **Call History Tracking**: Records all interactions, offers, and outcomes
- **REST API**: Full API for integration with existing systems
- **Webhook Support**: Real-time updates on call status

## Architecture

```
┌─────────────────┐
│  Your Data      │
│  Source         │
└────────┬────────┘
         │
         v
┌─────────────────┐
│  Engagement     │
│  Monitor        │
└────────┬────────┘
         │
         v
┌─────────────────┐      ┌──────────────┐
│  Data Analyzer  │─────>│ Drop         │
│                 │      │ Detected?    │
└─────────────────┘      └──────┬───────┘
                                │ YES
                                v
                         ┌──────────────┐
                         │ Generate     │
                         │ Script       │
                         └──────┬───────┘
                                │
                                v
                         ┌──────────────┐
                         │ Vapi API     │
                         │ (Make Call)  │
                         └──────────────┘
```

## Setup

### 1. Install Dependencies

```bash
npm install
```

### 2. Configure Environment

Copy the example environment file and fill in your credentials:

```bash
cp .env.example .env
```

Edit `.env`:

```env
# Get these from https://vapi.ai
VAPI_API_KEY=your_vapi_api_key_here
VAPI_PHONE_NUMBER_ID=your_vapi_phone_number_id_here

# Server settings
PORT=3000
NODE_ENV=development

# Engagement settings
ENGAGEMENT_DROP_THRESHOLD=0.30  # 30% drop triggers a call
CHECK_INTERVAL_MS=300000        # Check every 5 minutes

# Company info (used in calls)
COMPANY_NAME=Your Company
SUPPORT
[truncated — 5781 more characters]
```

### docs/PROJECT_STRUCTURE.md

```markdown
# Project Structure

```
calhacks/
├── src/
│   ├── config/
│   │   └── vapi.config.js          # Vapi configuration and settings
│   ├── services/
│   │   ├── dataAnalyzer.js         # Analyzes engagement data for drops
│   │   ├── engagementMonitor.js    # Main monitoring service
│   │   └── vapiService.js          # Vapi API integration
│   └── index.js                    # Express server & API endpoints
│
├── examples/
│   ├── usage-example.js            # JavaScript usage examples
│   └── api-usage.sh                # curl API examples
│
├── .env.example                    # Environment variables template
├── .gitignore                      # Git ignore rules
├── package.json                    # Dependencies and scripts
├── README.md                       # Full documentation
├── QUICKSTART.md                   # 5-minute setup guide
├── PROJECT_STRUCTURE.md            # This file
└── test-quick.js                   # Quick system test
```

## Core Components

### 1. Data Analyzer (`src/services/dataAnalyzer.js`)

**Purpose**: Analyzes user engagement data to detect drops and patterns

**Key Methods**:
- `analyzeEngagement(dataPoints)` - Detects engagement drops
- `calculateTrend(dataPoints)` - Identifies trends (declining/improving/stable)
- `detectPatterns(dataPoints)` - Finds sudden drops and consecutive declines

**Input**:
```javascript
[
  { timestamp: "2024-01-01T10:00:00Z", value: 85 },
  { timestamp: "2024-01-02T10:00:00Z", value: 50 }
]
```

**Output**:
```javascript
{
  hasDropped: true,
  dropPercentage: 41.2,
  baseline: 85,
  recentAverage: 50,
  trend: "declining"
}
```

### 2. Vapi Service (`src/services/vapiService.js`)

**Purpose**: Handles all Vapi API interactions for voice calls

**Key Methods**:
- `createAssistant(customScript)` - Creates AI assistant configuration
- `makeCall(callParams)` - Initiates outbound call
- `getCall(callId)` - Retrieves call details
- `generateScript(userData, analysisData)` - Creates dynamic call scripts

**Features**:
- Dynamic script generation based on engagement data
- Call recording and transcription
- Metadata tracking for analytics

### 3. Engagement Monitor (`src/services/engagementMonitor.js`)

**Purpose**: Orchestrates the entire monitoring and calling workflow

**Key Methods**:
- `addUser(user)` - Add user to monitoring system
- `updateUserEngagement(userId, dataPoint)` - Update engagement data
- `checkUser(userId)` - Analyze user and trigger call if needed
- `startMonitoring(intervalMs)` - Start automatic periodic checks
- `getStats()` - Get monitoring statistics

**Workflow**:
1. Maintains list of monitored users
2. Periodically checks each user's engagement
3. Triggers calls when drops detected
4. Enforces cooldown periods (48h default)
5. Tracks call history

### 4. Express Server (`src/index.js`)

**Purpose**: REST API for integration and monitoring

**Endpoints**:

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/health` | Health check |
| GE
[truncated — 4503 more characters]
```

### package.json

```
{
  "name": "revenue-optimizer-vapi",
  "version": "1.0.0",
  "description": "AI voice agent for revenue optimization through engagement monitoring",
  "main": "src/index.js",
  "type": "module",
  "scripts": {
    "start": "node src/index.js",
    "dev": "node --watch src/index.js",
    "monitor": "node src/services/engagementMonitor.js"
  },
  "keywords": [
    "vapi",
    "ai",
    "voice-agent",
    "revenue-optimization"
  ],
  "dependencies": {
    "@anthropic-ai/sdk": "^0.67.0",
    "@radix-ui/react-accordion": "^1.2.12",
    "@radix-ui/react-alert-dialog": "^1.1.15",
    "@radix-ui/react-avatar": "^1.1.10",
    "@radix-ui/react-checkbox": "^1.3.3",
    "@radix-ui/react-collapsible": "^1.1.12",
    "@radix-ui/react-dialog": "^1.1.15",
    "@radix-ui/react-dropdown-menu": "^2.1.16",
    "@radix-ui/react-hover-card": "^1.1.15",
    "@radix-ui/react-label": "^2.1.7",
    "@radix-ui/react-popover": "^1.1.15",
    "@radix-ui/react-progress": "^1.1.7",
    "@radix-ui/react-radio-group": "^1.3.8",
    "@radix-ui/react-select": "^2.2.6",
    "@radix-ui/react-separator": "^1.1.7",
    "@radix-ui/react-slider": "^1.3.6",
    "@radix-ui/react-switch": "^1.2.6",
    "@radix-ui/react-tabs": "^1.1.13",
    "@radix-ui/react-toast": "^1.2.15",
    "@tailwindcss/vite": "^4.1.16",
    "@vapi-ai/server-sdk": "^0.1.0",
    "@vapi-ai/web": "^2.0.0",
    "axios": "^1.6.0",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "cmdk": "^1.1.1",
    "cors": "^2.8.5",
    "date-fns": "^4.1.0",
    "dotenv": "^16.3.1",
    "embla-carousel-react": "^8.6.0",
    "express": "^4.18.2",
    "input-otp": "^1.4.2",
    "lucide-react": "^0.548.0",
    "motion": "^12.23.24",
    "react": "^19.2.0",
    "react-day-picker": "^9.11.1",
    "react-dom": "^19.2.0",
    "react-hook-form": "^7.55.0",
    "recharts": "^3.3.0",
    "sonner": "^2.0.3",
    "tailwind-merge": "^3.3.1",
    "tailwindcss": "^4.0.0-alpha.25",
    "vaul": "^1.1.2"
  },
  "devDependencies": {
    "@types/react": "^19.2.2",
    "@types/react-dom": "^19.2.2",
    "nodemon": "^3.0.1"
  }
}

```

### website-demo/package.json

```

  {
      "name": "Responsive E-commerce Website Design",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
          "@radix-ui/react-accordion": "^1.2.3",
          "@radix-ui/react-alert-dialog": "^1.1.6",
          "@radix-ui/react-aspect-ratio": "^1.1.2",
          "@radix-ui/react-avatar": "^1.1.3",
          "@radix-ui/react-checkbox": "^1.1.4",
          "@radix-ui/react-collapsible": "^1.1.3",
          "@radix-ui/react-context-menu": "^2.2.6",
          "@radix-ui/react-dialog": "^1.1.6",
          "@radix-ui/react-dropdown-menu": "^2.1.6",
          "@radix-ui/react-hover-card": "^1.1.6",
          "@radix-ui/react-label": "^2.1.2",
          "@radix-ui/react-menubar": "^1.1.6",
          "@radix-ui/react-navigation-menu": "^1.2.5",
          "@radix-ui/react-popover": "^1.1.6",
          "@radix-ui/react-progress": "^1.1.2",
          "@radix-ui/react-radio-group": "^1.2.3",
          "@radix-ui/react-scroll-area": "^1.2.3",
          "@radix-ui/react-select": "^2.1.6",
          "@radix-ui/react-separator": "^1.1.2",
          "@radix-ui/react-slider": "^1.2.3",
          "@radix-ui/react-slot": "^1.1.2",
          "@radix-ui/react-switch": "^1.1.3",
          "@radix-ui/react-tabs": "^1.1.3",
          "@radix-ui/react-toggle": "^1.1.2",
          "@radix-ui/react-toggle-group": "^1.1.2",
          "@radix-ui/react-tooltip": "^1.1.8",
          "class-variance-authority": "^0.7.1",
          "clsx": "*",
          "cmdk": "^1.1.1",
          "embla-carousel-react": "^8.6.0",
          "input-otp": "^1.4.2",
          "lucide-react": "^0.487.0",
          "motion": "*",
          "next-themes": "^0.4.6",
          "react": "^18.3.1",
          "react-day-picker": "^8.10.1",
          "react-dom": "^18.3.1",
          "react-hook-form": "^7.55.0",
          "react-resizable-panels": "^2.1.7",
          "recharts": "^2.15.2",
          "sonner": "^2.0.3",
          "tailwind-merge": "*",
          "vaul": "^1.1.2"
      },
      "devDependencies": {
          "@types/node": "^20.10.0",
          "@vitejs/plugin-react-swc": "^3.10.2",
          "vite": "6.3.5"
      },
      "scripts": {
          "dev": "vite",
          "build": "vite build"
      }
  }
```

### frontend-rev-opt/package.json

```

  {
      "name": "v2B2B Revenue Analytics Product (Copy) (Copy)",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
          "@radix-ui/react-accordion": "^1.2.3",
          "@radix-ui/react-alert-dialog": "^1.1.6",
          "@radix-ui/react-aspect-ratio": "^1.1.2",
          "@radix-ui/react-avatar": "^1.1.3",
          "@radix-ui/react-checkbox": "^1.1.4",
          "@radix-ui/react-collapsible": "^1.1.3",
          "@radix-ui/react-context-menu": "^2.2.6",
          "@radix-ui/react-dialog": "^1.1.6",
          "@radix-ui/react-dropdown-menu": "^2.1.6",
          "@radix-ui/react-hover-card": "^1.1.6",
          "@radix-ui/react-label": "^2.1.2",
          "@radix-ui/react-menubar": "^1.1.6",
          "@radix-ui/react-navigation-menu": "^1.2.5",
          "@radix-ui/react-popover": "^1.1.6",
          "@radix-ui/react-progress": "^1.1.2",
          "@radix-ui/react-radio-group": "^1.2.3",
          "@radix-ui/react-scroll-area": "^1.2.3",
          "@radix-ui/react-select": "^2.1.6",
          "@radix-ui/react-separator": "^1.1.2",
          "@radix-ui/react-slider": "^1.2.3",
          "@radix-ui/react-slot": "^1.1.2",
          "@radix-ui/react-switch": "^1.1.3",
          "@radix-ui/react-tabs": "^1.1.3",
          "@radix-ui/react-toggle": "^1.1.2",
          "@radix-ui/react-toggle-group": "^1.1.2",
          "@radix-ui/react-tooltip": "^1.1.8",
          "class-variance-authority": "^0.7.1",
          "clsx": "*",
          "cmdk": "^1.1.1",
          "embla-carousel-react": "^8.6.0",
          "input-otp": "^1.4.2",
          "lucide-react": "^0.487.0",
          "motion": "*",
          "next-themes": "^0.4.6",
          "react": "^18.3.1",
          "react-day-picker": "^8.10.1",
          "react-dnd": "*",
          "react-dnd-html5-backend": "*",
          "react-dom": "^18.3.1",
          "react-hook-form": "^7.55.0",
          "react-resizable-panels": "^2.1.7",
          "recharts": "^2.15.2",
          "sonner": "^2.0.3",
          "tailwind-merge": "*",
          "vaul": "^1.1.2"
      },
      "devDependencies": {
          "@types/node": "^20.10.0",
          "@vitejs/plugin-react-swc": "^3.10.2",
          "vite": "6.3.5"
      },
      "scripts": {
          "dev": "vite",
          "build": "vite build"
      }
  }
```

### src/index.js

```javascript
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { EngagementMonitor } from './services/engagementMonitor.js';
import { VapiService } from './services/vapiService.js';
import { FrontendIntegrationService } from './services/frontendIntegration.js';
import { metricsAggregator } from './services/metricsAggregator.js';
import { EngagementDetector } from './services/engagementDetector.js';
import { AIChatService } from './services/aiChatService.js';

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3001;

// Middleware
app.use(express.json());
app.use(cors()); // Enable CORS for frontend

// Initialize services
const monitor = new EngagementMonitor();
const vapiService = new VapiService();
const frontendIntegration = new FrontendIntegrationService();
const engagementDetector = new EngagementDetector();
const aiChatService = new AIChatService();

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// Get monitoring stats
app.get('/api/stats', (req, res) => {
  const stats = monitor.getStats();
  res.json(stats);
});

// Add user to monitoring
app.post('/api/users', (req, res) => {
  try {
    const user = monitor.addUser(req.body);
    res.json({ success: true, user });
  } catch (error) {
    res.status(400).json({ success: false, error: error.message });
  }
});

// Update user engagement data
app.post('/api/users/:userId/engagement', (req, res) => {
  try {
    const { userId } = req.params;
    monitor.updateUserEngagement(userId, req.body);
    res.json({ success: true, userId });
  } catch (error) {
    res.status(400).json({ success: false, error: error.message });
  }
});

// Manually trigger check for a user
app.post('/api/users/:userId/check', async (req, res) => {
  try {
    const { userId } = req.params;
    const result = await monitor.checkUser(userId);
    res.json({ success: true, result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Get user call history
app.get('/api/users/:userId/calls', (req, res) => {
  try {
    const { userId } = req.params;
    const history = monitor.getUserCallHistory(userId);
    res.json({ success: true, history });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Vapi webhook endpoint for call events
app.post('/api/webhooks/vapi', async (req, res) => {
  const event = req.body;

  console.log('📨 Vapi webhook received:', event.type);

  switch (event.type) {
    case 'call-started':
      console.log(`📞 Call started: ${event.call.id}`);
      break;

    case 'call-ended':
      console.log(`✅ Call ended: ${event.call.id}`);
      console.log(`Duration: ${event.call.duration}s`);
      if (event.call.transcript) {
        console.log('Transcript available');
      }
      break;

    case 'transcript':
      console.log(`💬 Transcript update for call ${event.call.id}`);
      break;

    case 'hang':
      console.log(`📴 Call hung up: ${event.call.id}`);
      break;

    default:
      console.log(`Unknown event type: ${event.type}`);
  }

  res.json({ received: true });
});

// Get call details
app.get('/api/calls/:callId', async (req, res) => {
  try {
    const { callId } = req.params;
    const call = await vapiService.getCall(callId);
    res.json({ success: true, call });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Start/stop monitoring
app.post('/api/monitoring/start', (req, res) => {
  const interval = req.body.intervalMs;
  monitor.startMonitoring(interval);
  res.json({ success: true, message: 'Monitoring started' });
});

app.post('/api/monitoring/stop', (req, res) => {
  monitor.stopMonitoring();
  res.json({ success: true, message: 'Monitoring stopped' });
});

// ============================================================================
// FRONTEND INTEGRATION ENDPOINTS
// ============================================================================

// Analyze single frontend user and trigger call if needed
app.post('/api/frontend/analyze-user', async (req, res) => {
  try {
    const frontendUser = req.body;

    console.log(`\n📨 Received frontend user: ${frontendUser.name}`);

    const result = await frontendIntegration.analyzeAndCall(frontendUser);

    res.json({
      success: true,
      result,
      message: result.status === 'call_initiated'
        ? `Call initiated to ${result.phoneNumber}`
        : result.message
    });
  } catch (error) {
    console.error('Error analyzing frontend user:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

// Batch analyze multiple frontend users
app.post('/api/frontend/analyze-batch', async (req, res) => {
  try {
    const { users } = req.body;

    if (!Array.isArray(users) || users.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'Please provide an array of users'
      });
    }

    console.log(`\n📦 Batch analyzing ${users.length} users from frontend`);

    const results = await frontendIntegration.batchAnalyzeUsers(users);

    const callsInitiated = results.filter(r => r.status === 'call_initiated').length;

    res.json({
      success: true,
      results,
      summary: {
        totalUsers: users.length,
        callsInitiated,
        noActionNeeded: results.filter(r => r.status === 'no_action_needed').length,
        recentlyCalled: results.filter(r => r.status === 'recently_called').length,
        errors: results.filter(r => r.status === 'error').length
      }
    });
  } catch (error) {
    console.error('Error batch analyzing users:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

// Analyze only critical users from frontend
app.post('/api/frontend/analyze-critical', async (req, res) => {
  try {
    const { users } = req.body;

    if (!Array.isArr
[truncated — 7314 more characters]
```

### frontend-rev-opt/src/main.tsx

```typescript

  import { createRoot } from "react-dom/client";
  import App from "./App.tsx";
  import "./index.css";

  createRoot(document.getElementById("root")!).render(<App />);
  
```

### website-demo/src/main.tsx

```typescript

  import { createRoot } from "react-dom/client";
  import App from "./App.tsx";
  import "./index.css";

  createRoot(document.getElementById("root")!).render(<App />);
  
```

### website-demo/src/App.tsx

```typescript
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { ThemeProvider } from './contexts/ThemeContext';
import { CartProvider } from './contexts/CartContext';
import { UserProvider } from './contexts/UserContext';
import { Header } from './components/Header';
import { Footer } from './components/Footer';
import { CartDrawer } from './components/CartDrawer';
import { HomePage } from './pages/HomePage';
import { CategoryPage } from './pages/CategoryPage';
import { ProductDetailPage } from './pages/ProductDetailPage';
import { SearchResultsPage } from './pages/SearchResultsPage';
import { CheckoutPage } from './pages/CheckoutPage';
import { OrderConfirmationPage } from './pages/OrderConfirmationPage';
import { OrderTrackingPage } from './pages/OrderTrackingPage';
import { AccountPage } from './pages/AccountPage';
import { OrdersPage } from './pages/OrdersPage';
import { AuthPage } from './pages/AuthPage';
import { Toaster } from './components/ui/sonner';
import { analyticsTracker } from './services/analyticsTracker';

type Page =
  | 'home'
  | 'category'
  | 'product'
  | 'search'
  | 'checkout'
  | 'confirmation'
  | 'tracking'
  | 'account'
  | 'orders'
  | 'auth';

interface NavigationState {
  page: Page;
  data?: any;
}

function App() {
  const [navigation, setNavigation] = useState<NavigationState>({
    page: 'home',
  });

  const handleNavigate = (page: string, data?: any) => {
    setNavigation({ page: page as Page, data });
    window.scrollTo({ top: 0, behavior: 'smooth' });

    // Track page view
    analyticsTracker.trackPageView(page.charAt(0).toUpperCase() + page.slice(1));
  };

  const handleSearch = (query: string, category?: string) => {
    setNavigation({
      page: 'search',
      data: { query, category },
    });

    // Track search
    analyticsTracker.trackSearch(query);
  };

  const handleClearSearch = () => {
    setNavigation({ page: 'home' });
  };

  const renderPage = () => {
    switch (navigation.page) {
      case 'home':
        return <HomePage onNavigate={handleNavigate} />;
      case 'category':
        return (
          <CategoryPage
            categoryId={navigation.data?.categoryId}
            onNavigate={handleNavigate}
          />
        );
      case 'product':
        return (
          <ProductDetailPage
            productId={navigation.data?.productId}
            onNavigate={handleNavigate}
          />
        );
      case 'search':
        return (
          <SearchResultsPage
            query={navigation.data?.query}
            category={navigation.data?.category}
            onNavigate={handleNavigate}
            onClearSearch={handleClearSearch}
          />
        );
      case 'checkout':
        return <CheckoutPage onNavigate={handleNavigate} />;
      case 'confirmation':
        return <OrderConfirmationPage onNavigate={handleNavigate} />;
      case 'tracking':
        return (
          <OrderTrackingPage
            orderId={navigation.data?.orderId}
            onNavigate={handleNavigate}
          />
        );
      case 'account':
        return <AccountPage onNavigate={handleNavigate} />;
      case 'orders':
        return <OrdersPage onNavigate={handleNavigate} />;
      case 'auth':
        return <AuthPage onNavigate={handleNavigate} />;
      default:
        return <HomePage onNavigate={handleNavigate} />;
    }
  };

  return (
    <ThemeProvider>
      <UserProvider>
        <CartProvider>
          <div className="flex flex-col min-h-screen">
            <Header onNavigate={handleNavigate} onSearch={handleSearch} />
            <main className="flex-1">
              <AnimatePresence mode="wait">
                <motion.div
                  key={navigation.page}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  transition={{ duration: 0.3, ease: 'easeInOut' }}
                >
                  {renderPage()}
                </motion.div>
              </AnimatePresence>
            </main>
            <Footer />
            <CartDrawer onCheckout={() => handleNavigate('checkout')} />
            <Toaster position="top-center" />
          </div>
        </CartProvider>
      </UserProvider>
    </ThemeProvider>
  );
}

export default App;

```

### frontend-rev-opt/src/App.tsx

```typescript
import { useState, useEffect } from 'react';
import { ThemeProvider } from './components/ThemeProvider';
import { Toaster } from './components/ui/sonner';
import { DashboardLoader } from './components/DashboardLoader';
import { MetricsProvider } from './contexts/MetricsContext';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

// Marketing pages
import { LandingPage } from './components/marketing/LandingPage';
import { ProductPage } from './components/marketing/ProductPage';
import { SolutionsPage } from './components/marketing/SolutionsPage';
import { PricingPage } from './components/marketing/PricingPage';
import { SecurityPage } from './components/marketing/SecurityPage';

// App pages
import { OnboardingFlow } from './components/app/OnboardingFlow';
import { AppShell } from './components/app/AppShell';
import { ExecutiveDashboard } from './components/app/ExecutiveDashboard';
import { ExplorePage } from './components/app/ExplorePage';
import { FunnelsPage } from './components/app/FunnelsPage';
import { CohortsPage } from './components/app/CohortsPage';
import { RetentionPage } from './components/app/RetentionPage';
import { RevenuePage } from './components/app/RevenuePage';
import { ExperimentsPage } from './components/app/ExperimentsPage';
import { FlowsPage } from './components/app/FlowsPage';
import { AlertsPage } from './components/app/AlertsPage';
import { ReportsPage } from './components/app/ReportsPage';
import { DataCatalogPage } from './components/app/DataCatalogPage';
import { SettingsPage } from './components/app/SettingsPage';
import { EngagementMonitor } from './components/app/EngagementMonitor';
import { LiveMetricsPage } from './components/app/LiveMetricsPage';
import { AIChatPanel } from './components/app/AIChatPanel';


type Route = 
  | 'landing'
  | 'product'
  | 'solutions'
  | 'pricing'
  | 'security'
  | 'onboarding'
  | 'dashboard'
  | 'explore'
  | 'funnels'
  | 'cohorts'
  | 'retention'
  | 'revenue'
  | 'experiments'
  | 'flows'
  | 'alerts'
  | 'reports'
  | 'catalog'
  | 'engagement'
  | 'livemetrics'
  | 'settings'
  | 'aichat';

export default function App() {
  const [currentRoute, setCurrentRoute] = useState<Route>('landing');
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [hasCompletedOnboarding, setHasCompletedOnboarding] = useState(false);
  const [isLoadingDashboard, setIsLoadingDashboard] = useState(false);

  // Simple hash-based routing
  useEffect(() => {
    const handleHashChange = () => {
      const hash = window.location.hash.slice(1) || 'landing';
      setCurrentRoute(hash as Route);
    };

    window.addEventListener('hashchange', handleHashChange);
    handleHashChange();

    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  const navigate = (route: Route) => {
    window.location.hash = route;
  };

  const handleLogin = () => {
    setIsAuthenticated(true);
    navigate('onboarding');
  };

  const handleOnboardingComplete = () => {
    setHasCompletedOnboarding(true);
    setIsLoadingDashboard(true);
    
    // Show loading screen for 3 seconds
    setTimeout(() => {
      setIsLoadingDashboard(false);
      navigate('dashboard');
    }, 3000);
  };

  // Marketing routes
  const marketingRoutes: Route[] = ['landing', 'product', 'solutions', 'pricing', 'security'];
  const isMarketingRoute = marketingRoutes.includes(currentRoute);

  // Render marketing pages
  if (isMarketingRoute) {
    return (
      <ThemeProvider defaultTheme="dark">
        <div className="min-h-screen">
          {currentRoute === 'landing' && <LandingPage onNavigate={navigate} onLogin={handleLogin} />}
          {currentRoute === 'product' && <ProductPage onNavigate={navigate} onLogin={handleLogin} />}
          {currentRoute === 'solutions' && <SolutionsPage onNavigate={navigate} onLogin={handleLogin} />}
          {currentRoute === 'pricing' && <PricingPage onNavigate={navigate} onLogin={handleLogin} />}
          {currentRoute === 'security' && <SecurityPage onNavigate={navigate} onLogin={handleLogin} />}
        </div>
        <Toaster />
      </ThemeProvider>
    );
  }

  // Loading screen
  if (isLoadingDashboard) {
    return (
      <ThemeProvider defaultTheme="dark">
        <DashboardLoader />
        <Toaster />
      </ThemeProvider>
    );
  }

  // Onboarding flow
  if (isAuthenticated && !hasCompletedOnboarding && currentRoute === 'onboarding') {
    return (
      <ThemeProvider defaultTheme="dark">
        <OnboardingFlow onComplete={handleOnboardingComplete} />
        <Toaster />
      </ThemeProvider>
    );
  }

  // App routes - wrapped in AppShell
  return (
    <ThemeProvider defaultTheme="dark">
      <DndProvider backend={HTML5Backend}>
        <MetricsProvider>
          <AppShell currentRoute={currentRoute} onNavigate={navigate}>
            {currentRoute === 'dashboard' && <ExecutiveDashboard />}
            {currentRoute === 'explore' && <ExplorePage onNavigate={navigate} />}
            {currentRoute === 'funnels' && <FunnelsPage />}
            {currentRoute === 'cohorts' && <CohortsPage />}
            {currentRoute === 'retention' && <RetentionPage />}
            {currentRoute === 'revenue' && <RevenuePage />}
            {currentRoute === 'experiments' && <ExperimentsPage />}
            {currentRoute === 'flows' && <FlowsPage />}
            {currentRoute === 'engagement' && <EngagementMonitor />}
            {currentRoute === 'livemetrics' && <LiveMetricsPage />}
            {currentRoute === 'alerts' && <AlertsPage />}
            {currentRoute === 'reports' && <ReportsPage />}
            {currentRoute === 'catalog' && <DataCatalogPage />}
            {currentRoute === 'aichat' && <AIChatPanel />}
            {currentRoute === 'settings' && <SettingsPage />}
          </AppShell>
          <Toaster />
        </MetricsProvider>
      </DndProvider>
    </ThemeProvider>
  );
}

```

[203 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]