# Project export: Aegis Command

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: TreeHacks 2025
- Tagline: A cutting-edge, AI-driven mission intelligence system that doesn’t just track data—it understands, adapts, and takes action in real time to optimize squad readiness and make life-saving decisions.
- Devpost: https://devpost.com/software/aegis-command
- GitHub: https://github.com/shaashvat01/tree
- Demo: https://v0-new-project-nhhecb7ns8k-ojqdea.vercel.app/
- Video: https://www.youtube.com/embed/1Xa9xg3BdDQ?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 1 GitHub contributor(s) — Shaashvat Mittal (8 commits)

## Devpost submission (written by the team)

### Inspiration

In modern military operations, commanders must make split-second decisions that impact mission success and soldier safety. But with overwhelming data streams, how do we ensure that critical insights are not lost? We envisioned an AI-powered command system that doesn’t just track soldier performance—it analyzes, predicts, and acts in real time. Our goal was to build something that could enhance combat readiness, prevent injuries, and optimize tactical strategies before risks escalate. That’s how Aegis Command was born—a mission intelligence system that moves from reactive responses to proactive decision-making.

### What it does

Aegis Command is a real-time AI-powered military operations dashboard that: Monitors squad health using real-time biometrics (heart rate, fatigue, hydration) via Terra API Predicts risks like exhaustion or dehydration and autonomously suggests tactical adjustments Provides mission control for real-time squad formation, movement tracking, and adaptive strategy recommendations Integrates AI-powered chat for commanders to ask questions and receive instant insights Enables rapid medical assistance, automatically detecting distress and deploying medical teams Utilizes data-driven squad allocation, ensuring the right soldiers are deployed at the right time By combining real-time data, AI-driven insights, and automation, Aegis Command maximizes operational efficiency and soldier safety.

### How we built it

Aegis Command is built using a cutting-edge tech stack, integrating multiple powerful tools: 💻 Frontend (Built with Vercel v0): Next.js & TypeScript for a scalable and responsive UI Tailwind CSS & Shadcn UI for modern, intuitive design Recharts & Lucide React for real-time visual analytics 💻 Frontend (Built with Vercel v0): Next.js & TypeScript for a scalable and responsive UI Tailwind CSS & Shadcn UI for modern, intuitive design Recharts & Lucide React for real-time visual analytics 🖥️ Backend & AI Integration Terra API for wearable biometric data Perplexity API for AI-powered decision-making & command interaction WebSockets for real-time mission updates 🖥️ Backend & AI Integration Terra API for wearable biometric data Perplexity API for AI-powered decision-making & command interaction WebSockets for real-time mission updates 🔍 Intelligent Processing Dynamic squad formation algorithms based on performance metrics AI-driven risk assessment & tactical recommendations Predictive health analysis for proactive medical alerts 🔍 Intelligent Processing Dynamic squad formation algorithms based on performance metrics AI-driven risk assessment & tactical recommendations Predictive health analysis for proactive medical alerts We leveraged Vercel v0 to rapidly prototype and deploy a fully functional, interactive AI-driven military command center in record time.

### Challenges we ran into

Building an AI-powered command system in a short timeframe came with several challenges: Integrating real-time biometric data – We worked with Terra API to simulate wearable health data, ensuring accuracy in squad health monitoring. Developing proactive AI – Instead of waiting for user input, we designed AI models that autonomously suggest tactical changes. Ensuring real-time updates – Military decisions require instantaneous insights, so we optimized WebSocket-based live updates to ensure zero delay. Optimizing UI for mission-critical use – Every second counts in the field. We designed the UX/UI for speed, clarity, and rapid decision-making. Despite these challenges, we pushed through to create a high-impact, AI-driven military intelligence platform.

### Accomplishments we're proud of

In just a short time, we built a fully operational AI-powered mission command center. Our key achievements: Successfully integrated real-time health monitoring using Terra API Developed AI-driven tactical decision-making for autonomous risk assessment Created a dynamic squad formation system, ensuring optimal mission readiness Designed a seamless AI assistant for commanders to interact with live battlefield data Built a visually stunning, high-performance UI using Vercel v0 Enabled autonomous medical alerts for proactive health management We’re proud to have created a system that goes beyond data tracking—one that actively protects and optimizes soldiers’ well-being in the field.

### What we learned

This project pushed us to the cutting edge of AI-driven mission intelligence. AI can be proactive, not just reactive – By designing AI to predict, recommend, and act autonomously, we unlocked a new level of operational intelligence. Data visualization matters – Commanders need instant clarity, so we optimized UI/UX to present complex insights in seconds. Real-time updates require smart optimization – We fine-tuned WebSockets & API integrations to keep data live and responsive. The right tools accelerate development – Using Vercel v0, Terra API, and Perplexity AI, we built a production-ready platform faster than we thought possible. Above all, we learned that technology can save lives—when designed to anticipate risks and act before they happen.

### What's next

Aegis Command is just the beginning. The future of AI-powered military operations includes: AI-driven mission planning – Training AI to autonomously adjust squad formations and optimize tactical strategies. Expanding integrations – Incorporating satellite data, environmental monitoring, and real-time threat detection. Enhanced medical AI – Implementing real-time anomaly detection to proactively identify critical health risks. Scaling beyond military use – Aegis Command can be adapted for emergency response teams, disaster relief operations, and elite sports training. We’re building an AI-driven command center that redefines the future of mission intelligence.

## README (from the GitHub repository)

# Aegis Command

## Overview
Aegis Command is an AI-driven mission intelligence system designed to monitor, analyze, and optimize soldier performance in real-time. It predicts risks, enhances squad readiness, and automates decision-making, helping military teams maintain operational efficiency and ensure personnel safety.

By integrating the Terra API for real-time health monitoring, AI-powered analytics for performance evaluation, and Zoom for instant communication, Aegis Command functions as a proactive command center that delivers actionable intelligence.

## Key Features

### Real-Time Health & Performance Tracking
- Monitors heart rate, fatigue, hydration, and readiness using the Terra API.
- Dynamically groups soldiers into squads based on live performance metrics.
- Alerts commanders to potential health risks before they become critical.

### AI-Powered Tactical Insights
- Uses machine learning to analyze past mission data and predict exhaustion, injuries, or performance drops.
- Provides real-time tactical recommendations based on squad readiness.
- Automatically alerts medical teams if critical health conditions are detected.

### Secure Communication & Command Execution
- Zoom integration enables real-time communication between squads and commanders.
- AI-driven chat interface (powered by Perplexity API) allows instant data retrieval and decision support.

### Interactive Command Dashboard
- Built using Next.js, Tailwind CSS, and Vercel v0 for efficient development and deployment.
- Fully responsive UI with intuitive charts, squad overviews, and AI alerts.
- Live mission updates through WebSocket integration.

## Tech Stack

| Category              | Technology Used |
|-----------------------|-----------------|
| **Frontend**          | Next.js, Tailwind CSS, ShadCN, Recharts |
| **Backend**           | Terra API |
| **AI & Analytics**    | Perplexity API, Time-Series Forecasting |
| **Real-Time Updates** | WebSockets |
| **Communication**     | Zoom SDK Integration |
| **Deployment**        | Vercel (v0 for frontend development) |

## How It Works

1. Terra API collects live biometric data from soldiers.
2. AI analyzes trends, predicts risks, and updates squad formations dynamically.
3. Commanders receive real-time squad health insights on the dashboard.
4. If critical issues arise, AI automatically alerts medical teams and suggests tactical adjustments.
5. Soldiers and commanders communicate via Zoom, ensuring seamless mission execution.


## Detected evidence (automated analysis)

Indexed codebase: 47 recognized source files, 147 KB.
- CSS (language) — detected in the code
- Next.js (technology) — detected in the code
- React (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Vercel AI SDK (technology) — detected in the code
- Express (technology) — claimed on Devpost, not found in the code
- Node.js (technology) — claimed on Devpost, not found in the code
- OpenAI (technology) — claimed on Devpost, not found in the code
- Vercel (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (55 of 55)

```
.DS_Store
my-app/.eslintrc.json
my-app/.gitignore
my-app/app/ai-tactical/page.tsx
my-app/app/api/perplexity-search/route.ts
my-app/app/api/squad-health/route.ts
my-app/app/api/weather/route.ts
my-app/app/globals.css
my-app/app/layout.tsx
my-app/app/medical-assistance/page.tsx
my-app/app/mission-control/page.tsx
my-app/app/page.tsx
my-app/app/settings/page.tsx
my-app/app/squad-health/page.tsx
my-app/components.json
my-app/components/ai-intelligence-search.tsx
my-app/components/medical-assistance/emergency-assistance.tsx
my-app/components/medical-assistance/status-panel.tsx
my-app/components/medical-assistance/symptom-description-chat.tsx
my-app/components/sidebar.tsx
my-app/components/theme-provider.tsx
my-app/components/top-navbar.tsx
my-app/components/ui/alert.tsx
my-app/components/ui/avatar.tsx
my-app/components/ui/badge.tsx
my-app/components/ui/button.tsx
my-app/components/ui/card.tsx
my-app/components/ui/input.tsx
my-app/components/ui/label.tsx
my-app/components/ui/progress.tsx
my-app/components/ui/scroll-area.tsx
my-app/components/ui/select.tsx
my-app/components/ui/separator.tsx
my-app/components/ui/sheet.tsx
my-app/components/ui/sidebar.tsx
my-app/components/ui/skeleton.tsx
my-app/components/ui/slider.tsx
my-app/components/ui/switch.tsx
my-app/components/ui/tabs.tsx
my-app/components/ui/tooltip.tsx
my-app/hooks/use-commander-chat.ts
my-app/hooks/use-mobile.tsx
my-app/hooks/use-websocket.ts
my-app/lib/utils.ts
my-app/next.config.mjs
my-app/package.json
my-app/postcss.config.mjs
my-app/README.md
my-app/server/websocket-server.ts
my-app/styles/globals.css
my-app/tailwind.config.ts
my-app/tsconfig.json
my-app/utils/api-helpers.ts
my-app/utils/formatText.ts
README.md
```

### Dependencies

- my-app/package.json: @ai-sdk/openai-compatible@^0.1.10, @radix-ui/react-avatar@^1.1.3, @radix-ui/react-dialog@^1.1.6, @radix-ui/react-label@^2.1.2, @radix-ui/react-progress@^1.1.2, @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-tooltip@^1.1.8, @types/node@^20, @types/react@^18, @types/react-dom@^18, ai@^4.1.41, class-variance-authority@^0.7.1, clsx@^2.1.1, eslint@^8, eslint-config-next@14.2.16, lucide-react@^0.475.0, next@14.2.16, next-themes@^0.4.4, postcss@^8, react@^18, react-dom@^18, recharts@^2.15.1, tailwind-merge@^3.0.1, tailwindcss@^3.4.17, tailwindcss-animate@^1.0.7, typescript@^5, ws@^8.18.0

### Recent commits (newest first)

- Update README.md
- Update README.md
- final
- perplexity working
- new
- adding zoom
- fix
- added zoom
- initial setup
- Initial commit

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

### my-app/package.json

```
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@ai-sdk/openai-compatible": "^0.1.10",
    "@radix-ui/react-avatar": "^1.1.3",
    "@radix-ui/react-dialog": "^1.1.6",
    "@radix-ui/react-label": "^2.1.2",
    "@radix-ui/react-progress": "^1.1.2",
    "@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-tooltip": "^1.1.8",
    "ai": "^4.1.41",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "lucide-react": "^0.475.0",
    "next": "14.2.16",
    "next-themes": "^0.4.4",
    "react": "^18",
    "react-dom": "^18",
    "recharts": "^2.15.1",
    "tailwind-merge": "^3.0.1",
    "tailwindcss-animate": "^1.0.7",
    "ws": "^8.18.0"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "eslint": "^8",
    "eslint-config-next": "14.2.16",
    "postcss": "^8",
    "tailwindcss": "^3.4.17",
    "typescript": "^5"
  }
}

```

### my-app/app/layout.tsx

```typescript
import type React from "react"
import "./globals.css"
import { Inter } from "next/font/google"
import { SidebarProvider } from "@/components/ui/sidebar"
import TopNavbar from "@/components/top-navbar"
import Sidebar from "@/components/sidebar"

const inter = Inter({ subsets: ["latin"] })

export const metadata = {
  title: "Aegis Command Dashboard",
  description: "Real-time health metrics and AI-powered decision-making",
  generator: "v0.dev",
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className="dark">
      <body className={`${inter.className} bg-background text-foreground`}>
        <SidebarProvider>
          <div className="flex h-screen overflow-hidden">
            <Sidebar />
            <div className="flex flex-col flex-1 overflow-hidden">
              <TopNavbar />
              <main className="flex-1 overflow-x-hidden overflow-y-auto bg-background">{children}</main>
            </div>
          </div>
        </SidebarProvider>
      </body>
    </html>
  )
}

import "./globals.css"

import "./globals.css"

import "./globals.css"


```

### my-app/app/page.tsx

```typescript
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Activity, Briefcase, FileText, AmbulanceIcon as FirstAid } from "lucide-react"
import Link from "next/link"

export default function Home() {
  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6 text-high-contrast">Aegis Command Dashboard</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <DashboardCard
          title="Squad Health"
          description="Real-time health metrics for your squad."
          icon={<Activity className="h-6 w-6" />}
          link="/squad-health"
        />
        <DashboardCard
          title="AI Tactical"
          description="AI-powered tactical adjustments and recommendations."
          icon={<Briefcase className="h-6 w-6" />}
          link="/ai-tactical"
        />
        <DashboardCard
          title="Mission Control"
          description="Current mission status and objectives."
          icon={<FileText className="h-6 w-6" />}
          link="/mission-control"
        />
        <DashboardCard
          title="Medical Assistance"
          description="Request and manage medical support."
          icon={<FirstAid className="h-6 w-6" />}
          link="/medical-assistance"
        />
      </div>
    </div>
  )
}

function DashboardCard({ title, description, icon, link }) {
  return (
    <Link href={link}>
      <Card className="hover:bg-primary/10 transition-colors duration-200">
        <CardHeader>
          <CardTitle className="flex items-center text-high-contrast">
            {icon}
            <span className="ml-2">{title}</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground">{description}</p>
        </CardContent>
      </Card>
    </Link>
  )
}


```

### my-app/app/medical-assistance/page.tsx

```typescript
"use client"

import { useState, useEffect } from "react"
import { useWebSocket } from "@/hooks/use-websocket"
import { StatusPanel } from "@/components/medical-assistance/status-panel"
import { EmergencyAssistance } from "@/components/medical-assistance/emergency-assistance"
import { SymptomDescriptionChat } from "@/components/medical-assistance/symptom-description-chat"

// Mock data for demonstration
const initialMedicalData = {
  availableMedics: 3,
  emergencySupplies: 75,
  vaccinationStatus: 92,
}

const mockMedicalReports = [
  { id: 1, date: "2025-01-15", description: "Annual check-up - All clear" },
  { id: 2, date: "2025-03-22", description: "Minor sprain during training - Treated" },
  { id: 3, date: "2025-06-10", description: "Routine vaccination update" },
]

const mockNearbyMedics = [
  { id: 1, name: "Medic Team Alpha", distance: "0.5 km", eta: "3 mins" },
  { id: 2, name: "Field Hospital Bravo", distance: "2.1 km", eta: "8 mins" },
  { id: 3, name: "Medevac Charlie", distance: "5.0 km", eta: "15 mins" },
]

export default function MedicalAssistancePage() {
  const [medicalData, setMedicalData] = useState(initialMedicalData)
  const [isEmergency, setIsEmergency] = useState(false)
  const { isConnected, lastMessage, sendMessage } = useWebSocket("wss://your-websocket-server.com/medical-assistance")

  useEffect(() => {
    if (lastMessage) {
      if (lastMessage.type === "medicalUpdate") {
        setMedicalData(lastMessage.value)
      } else if (lastMessage.type === "emergencyStatus") {
        setIsEmergency(lastMessage.value)
      }
    }
  }, [lastMessage])

  useEffect(() => {
    // Simulate real-time updates
    const interval = setInterval(() => {
      setMedicalData((prev) => ({
        ...prev,
        availableMedics: Math.max(0, prev.availableMedics + Math.floor(Math.random() * 3) - 1),
        emergencySupplies: Math.max(0, Math.min(100, prev.emergencySupplies + Math.floor(Math.random() * 5) - 2)),
      }))
    }, 10000)

    return () => clearInterval(interval)
  }, [])

  const handleRequestAssistance = () => {
    setIsEmergency(true)
    sendMessage({ type: "emergencyRequest", value: true })
    // In a real application, this would trigger alerts to commanders and medics
    alert("Emergency medical assistance requested. Medics have been alerted.")
  }

  return (
    <div className="container mx-auto px-4 py-8 text-high-contrast">
      <h1 className="text-3xl font-bold mb-6">Medical Assistance</h1>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <StatusPanel medicalData={medicalData} medicalReports={mockMedicalReports} />
        <EmergencyAssistance
          isEmergency={isEmergency}
          onRequestAssistance={handleRequestAssistance}
          nearbyMedics={mockNearbyMedics}
        />
      </div>

      <SymptomDescriptionChat />
    </div>
  )
}


```

### my-app/app/ai-tactical/page.tsx

```typescript
"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { AlertTriangle, CheckCircle } from "lucide-react"
import { useWebSocket } from "@/hooks/use-websocket"

// Mock data for demonstration
const mockSuggestions = [
  { id: 1, text: "Suggest hydration break for Squad Alpha", severity: "low" },
  { id: 2, text: "Recommend mission delay due to extreme weather conditions", severity: "high" },
  { id: 3, text: "Advise formation swap to improve defensive posture", severity: "medium" },
]

export default function AITacticalAdjustments() {
  const [readiness, setReadiness] = useState(75)
  const [activeSuggestion, setActiveSuggestion] = useState(mockSuggestions[0])
  const { isConnected, lastMessage } = useWebSocket("wss://your-websocket-server.com/ai-tactical")

  useEffect(() => {
    if (lastMessage) {
      if (lastMessage.type === "readiness") {
        setReadiness(lastMessage.value)
      } else if (lastMessage.type === "suggestion") {
        setActiveSuggestion(lastMessage.value)
      }
    }
  }, [lastMessage])

  // Simulate real-time updates
  useEffect(() => {
    const interval = setInterval(() => {
      setReadiness((prev) => Math.max(0, Math.min(100, prev + Math.random() * 10 - 5)))
      setActiveSuggestion(mockSuggestions[Math.floor(Math.random() * mockSuggestions.length)])
    }, 5000)
    return () => clearInterval(interval)
  }, [])

  return (
    <div className="container mx-auto px-4 py-8 text-high-contrast">
      <h1 className="text-3xl font-bold mb-6">AI Tactical Adjustments</h1>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="col-span-1 lg:col-span-2 bg-card border-border">
          <CardHeader>
            <CardTitle className="text-xl text-high-contrast">Live Tactical Suggestions</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="p-4 bg-high-contrast rounded-lg border border-border mb-4">
              <h3 className="text-lg font-semibold mb-2">Current Suggestion:</h3>
              <p className="text-muted-foreground">{activeSuggestion.text}</p>
              <div
                className={`mt-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                  activeSuggestion.severity === "high"
                    ? "bg-destructive text-destructive-foreground"
                    : activeSuggestion.severity === "medium"
                      ? "bg-yellow-600 text-yellow-100"
                      : "bg-green-600 text-green-100"
                }`}
              >
                {activeSuggestion.severity.charAt(0).toUpperCase() + activeSuggestion.severity.slice(1)} Priority
              </div>
            </div>
            <div className="flex space-x-2">
              <Button variant="default" className="military-btn military-btn-primary">
                Accept AI Suggestion
              </Button>
              <Button variant="destructive" className="military-btn military-btn-danger">
                Override
              </Button>
              <Button variant="outline" className="military-btn military-btn-secondary">
                Request More Data
              </Button>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-card border-border">
          <CardHeader>
            <CardTitle className="text-xl text-high-contrast">Mission Readiness</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="mb-2">
              <span className="text-2xl font-bold">{readiness.toFixed(1)}%</span>
            </div>
            <Progress value={readiness} className="w-full h-4" />
            <div className="mt-4">
              <ReadinessIndicator readiness={readiness} />
            </div>
          </CardContent>
        </Card>
      </div>

      <Card className="mt-6 bg-card border-border">
        <CardHeader>
          <CardTitle className="text-xl text-high-contrast">Tactical Recommendations</CardTitle>
        </CardHeader>
        <CardContent>
          <TacticalRecommendations />
        </CardContent>
      </Card>
    </div>
  )
}

function ReadinessIndicator({ readiness }: { readiness: number }) {
  if (readiness >= 80) {
    return (
      <div className="flex items-center text-green-400">
        <CheckCircle className="w-5 h-5 mr-2" />
        <span>High Readiness</span>
      </div>
    )
  } else if (readiness >= 50) {
    return (
      <div className="flex items-center text-yellow-400">
        <AlertTriangle className="w-5 h-5 mr-2" />
        <span>Moderate Readiness</span>
      </div>
    )
  } else {
    return (
      <div className="flex items-center text-destructive">
        <AlertTriangle className="w-5 h-5 mr-2" />
        <span>Low Readiness - Caution Advised</span>
      </div>
    )
  }
}

function TacticalRecommendations() {
  return (
    <div className="space-y-4">
      <div className="p-4 bg-high-contrast rounded-lg border border-border">
        <h3 className="text-lg font-semibold mb-2">Hydration Status</h3>
        <p className="text-muted-foreground">
          Squad Bravo showing signs of dehydration. Recommend immediate water break.
        </p>
      </div>
      <div className="p-4 bg-high-contrast rounded-lg border border-border">
        <h3 className="text-lg font-semibold mb-2">Weather Impact</h3>
        <p className="text-muted-foreground">
          Incoming sandstorm detected. Suggest postponing non-critical operations for 2 hours.
        </p>
      </div>
      <div className="p-4 bg-high-contrast rounded-lg border border-border">
        <h3 className="text-lg font-semibold mb-2">Equipment Status</h3>
        <p className="text-muted-foreground">
          Night vision goggles for Squad Charlie malfunctioning. Advise immediate replacement.

[truncated — 44 more characters]
```

### my-app/app/settings/page.tsx

```typescript
"use client"

import { useState } from "react"
import { useTheme } from "next-themes"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Slider } from "@/components/ui/slider"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { AlertCircle, Moon, Sun } from "lucide-react"

export default function SettingsPage() {
  const { setTheme, theme } = useTheme()
  const [loading, setLoading] = useState(false)

  const handleSave = async () => {
    setLoading(true)
    // Simulating an API call
    await new Promise((resolve) => setTimeout(resolve, 1000))
    setLoading(false)
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">Settings</h1>
      <Tabs defaultValue="profile" className="space-y-4">
        <TabsList>
          <TabsTrigger value="profile">User Profile</TabsTrigger>
          <TabsTrigger value="ai">AI & Autonomy</TabsTrigger>
          <TabsTrigger value="squad">Squad & Mission</TabsTrigger>
          <TabsTrigger value="display">Display & Theme</TabsTrigger>
        </TabsList>

        <TabsContent value="profile">
          <Card>
            <CardHeader>
              <CardTitle>User Profile Settings</CardTitle>
              <CardDescription>Manage your personal information and notification preferences.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center space-x-4">
                <Avatar className="h-20 w-20">
                  <AvatarImage src="/placeholder-avatar.jpg" alt="Profile picture" />
                  <AvatarFallback>JD</AvatarFallback>
                </Avatar>
                <Button>Change Picture</Button>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="name">Name</Label>
                  <Input id="name" placeholder="John Doe" />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="role">Role</Label>
                  <Select defaultValue="commander">
                    <SelectTrigger id="role">
                      <SelectValue placeholder="Select role" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="commander">Commander</SelectItem>
                      <SelectItem value="soldier">Soldier</SelectItem>
                      <SelectItem value="medic">Medic</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-2">
                <Label>Notification Preferences</Label>
                <div className="flex items-center space-x-2">
                  <Switch id="email-notifications" />
                  <Label htmlFor="email-notifications">Email Notifications</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch id="sms-notifications" />
                  <Label htmlFor="sms-notifications">SMS Notifications</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch id="in-app-notifications" />
                  <Label htmlFor="in-app-notifications">In-App Alerts</Label>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="ai">
          <Card>
            <CardHeader>
              <CardTitle>AI & Autonomy Settings</CardTitle>
              <CardDescription>Configure AI assistance and autonomy levels.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="ai-autonomy">AI Autonomy Level</Label>
                <Select defaultValue="semi-auto">
                  <SelectTrigger id="ai-autonomy">
                    <SelectValue placeholder="Select autonomy level" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="manual">Manual</SelectItem>
                    <SelectItem value="semi-auto">Semi-Auto</SelectItem>
                    <SelectItem value="fully-auto">Fully Auto</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>AI Alert Settings</Label>
                <div className="flex items-center space-x-2">
                  <Switch id="fatigue-detection" />
                  <Label htmlFor="fatigue-detection">Fatigue Detection</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch id="health-issues" />
                  <Label htmlFor="health-issues">Health Issues</Label>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="squad">
          <Card>
            <CardHeader>
              <CardTitle>Squad & Mission Preferences</CardTitle>
              <CardDescription>Manage squad roles and mission settings.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="access-level">Default Access Level</Label>
                <Select defaultValue="squad-leader">
                  <SelectTri
[truncated — 3048 more characters]
```

### my-app/app/mission-control/page.tsx

```typescript
"use client"

import type React from "react"

import { useState, useEffect, useCallback } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Slider } from "@/components/ui/slider"
import {
  Shield,
  Thermometer,
  Siren,
  Send,
  CloudRain,
  Wind,
  Eye,
  KeyIcon as Strategy,
  AlertTriangle,
} from "lucide-react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Badge } from "@/components/ui/badge"
import { useWebSocket } from "@/hooks/use-websocket"
import { formatText } from "@/utils/formatText"
import { AlertCircle } from "lucide-react" // Import AlertCircle

interface Message {
  id: number
  role: "user" | "assistant" | "error"
  content: string
}

interface SquadFormation {
  alpha: { readiness: number; formation: string; pace: number }
  bravo: { readiness: number; formation: string; pace: number }
  charlie: { readiness: number; formation: string; pace: number }
}

interface WeatherData {
  temperature: number
  humidity: number
  windSpeed: number
  forecast: string
}

const initialSquadFormation: SquadFormation = {
  alpha: { readiness: 75, formation: "Diamond", pace: 70 },
  bravo: { readiness: 60, formation: "Line", pace: 60 },
  charlie: { readiness: 90, formation: "Wedge", pace: 80 },
}

const initialWeatherData: WeatherData = {
  temperature: 28,
  humidity: 65,
  windSpeed: 15,
  forecast: "Storm approaching in 3 hours",
}

export default function MissionControl() {
  const [alerts, setAlerts] = useState<string[]>([])
  const [squadFormation, setSquadFormation] = useState<SquadFormation>(initialSquadFormation)
  const [weatherData, setWeatherData] = useState<WeatherData>(initialWeatherData)
  const [messages, setMessages] = useState<Message[]>([])
  const [input, setInput] = useState("")
  const [isStreaming, setIsStreaming] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const { status, lastMessage } = useWebSocket("wss://your-websocket-server.com/mission-control")

  useEffect(() => {
    if (lastMessage) {
      if (lastMessage.type === "alert") {
        setAlerts((prev) => [lastMessage.value, ...prev].slice(0, 5))
      } else if (lastMessage.type === "squadUpdate") {
        setSquadFormation(lastMessage.value)
      }
    }
  }, [lastMessage])

  useEffect(() => {
    const fetchWeatherData = async () => {
      try {
        const response = await fetch("/api/weather")
        if (!response.ok) {
          throw new Error("Failed to fetch weather data")
        }
        const json = await response.json()
        if (json.error) {
          throw new Error(json.error)
        }
        setWeatherData(json)
      } catch (error) {
        console.error("Error fetching weather data:", error)
        setError(error instanceof Error ? error.message : "Failed to fetch weather data")
      }
    }

    fetchWeatherData()
    const interval = setInterval(fetchWeatherData, 60000)
    return () => clearInterval(interval)
  }, [])

  // Simulate real-time updates and AI-generated alerts
  useEffect(() => {
    const interval = setInterval(() => {
      // Update squad readiness
      setSquadFormation((prev) => ({
        ...prev,
        alpha: { ...prev.alpha, readiness: Math.max(0, Math.min(100, prev.alpha.readiness + Math.random() * 10 - 5)) },
        bravo: { ...prev.bravo, readiness: Math.max(0, Math.min(100, prev.bravo.readiness + Math.random() * 10 - 5)) },
        charlie: {
          ...prev.charlie,
          readiness: Math.max(0, Math.min(100, prev.charlie.readiness + Math.random() * 10 - 5)),
        },
      }))

      // Generate AI alerts
      if (Math.random() > 0.7) {
        const newAlert = generateAIAlert(squadFormation, weatherData)
        setAlerts((prev) => [newAlert, ...prev].slice(0, 5))
      }
    }, 5000)

    return () => clearInterval(interval)
  }, [squadFormation, weatherData])

  const handleFormationChange = (squad: keyof SquadFormation, value: string) => {
    setSquadFormation((prev) => ({
      ...prev,
      [squad]: { ...prev[squad], formation: value },
    }))
  }

  const handlePaceChange = (squad: keyof SquadFormation, value: number) => {
    setSquadFormation((prev) => ({
      ...prev,
      [squad]: { ...prev[squad], pace: value },
    }))
  }

  const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setInput(e.target.value)
    setError(null)
  }, [])

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault()
      if (!input.trim()) return

      setIsStreaming(true)
      setError(null)
      const newMessage: Message = { id: Date.now(), role: "user", content: input }
      setMessages((prev) => [...prev, newMessage])
      setInput("")

      try {
        const response = await fetch("/api/perplexity-search", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ query: input }),
        })

        const data = await response.json()

        if (!response.ok) {
          throw new Error(data.error || `HTTP error! status: ${response.status}`)
        }

        if (!data.result) {
          throw new Error("No response received from AI")
        }

        const aiResponse: Message = {
          id: Date.now() + 1,
          role: "assistant",
          content: data.result,
        }
        setMessages((prev) => [...prev, aiResponse])
      } catch (err) {
        console.error("Error fetching search results:", err)
        const errorMessage = err instanceof Error ? err.message : "An unexpected error occurred"
        setError(errorMessage)
        const errorResponse: Message = {
          id: Date.now() + 1,
          role: "error",
          content: "I apologize, but I'm having trouble responding right now. Please try again.",
        }
       
[truncated — 10742 more characters]
```

### my-app/app/squad-health/page.tsx

```typescript
"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Activity,
  AlertTriangle,
  ArrowDown,
  ArrowUp,
  Battery,
  Flame,
  Heart,
  HeartPulse,
  Loader2,
  Shield,
  Zap,
} from "lucide-react"
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
  BarChart,
  Bar,
  Cell,
} from "recharts"

interface SoldierData {
  id: string
  name: string
  avgHeartRate: number
  maxHeartRate: number
  minHeartRate: number
  totalSteps: number
  caloriesBurned: number
  fatigueOnset: string
}

interface SquadMetrics {
  combatReadiness: number
  averageFatigue: number
  squadMorale: number
  alertLevel: number
}

interface BestSquadResult {
  filter: string
  squadSize: number
  selectedSoldiers: string
  score: number
}

const bestSquadData: BestSquadResult[] = [
  { filter: "Endurance Score", squadSize: 1, selectedSoldiers: "John Doe", score: 8.91 },
  { filter: "Recovery Rate", squadSize: 1, selectedSoldiers: "Jane Smith", score: 6.42 },
  { filter: "Heart Rate Stability", squadSize: 1, selectedSoldiers: "Mike Johnson", score: 3.87 },
  { filter: "Fatigue Resistance", squadSize: 1, selectedSoldiers: "Sarah Williams", score: 7.92 },
  { filter: "Endurance Score", squadSize: 2, selectedSoldiers: "John Doe, Chris Brown", score: 8.12 },
  { filter: "Recovery Rate", squadSize: 2, selectedSoldiers: "Jane Smith, Emily Davis", score: 6.88 },
  { filter: "Heart Rate Stability", squadSize: 2, selectedSoldiers: "Mike Johnson, Sarah Williams", score: 4.22 },
  { filter: "Fatigue Resistance", squadSize: 2, selectedSoldiers: "Sarah Williams, Chris Brown", score: 7.34 },
  { filter: "Endurance Score", squadSize: 3, selectedSoldiers: "John Doe, Chris Brown, Emily Davis", score: 7.99 },
  { filter: "Recovery Rate", squadSize: 3, selectedSoldiers: "Jane Smith, Emily Davis, Mike Johnson", score: 6.72 },
  {
    filter: "Heart Rate Stability",
    squadSize: 3,
    selectedSoldiers: "Mike Johnson, Sarah Williams, Chris Brown",
    score: 4.41,
  },
  {
    filter: "Fatigue Resistance",
    squadSize: 3,
    selectedSoldiers: "Sarah Williams, Chris Brown, John Doe",
    score: 7.01,
  },
  {
    filter: "Endurance Score",
    squadSize: 4,
    selectedSoldiers: "John Doe, Chris Brown, Emily Davis, Jane Smith",
    score: 7.85,
  },
  {
    filter: "Recovery Rate",
    squadSize: 4,
    selectedSoldiers: "Jane Smith, Emily Davis, Mike Johnson, Sarah Williams",
    score: 6.55,
  },
  {
    filter: "Heart Rate Stability",
    squadSize: 4,
    selectedSoldiers: "Mike Johnson, Sarah Williams, Chris Brown, John Doe",
    score: 4.31,
  },
  {
    filter: "Fatigue Resistance",
    squadSize: 4,
    selectedSoldiers: "Sarah Williams, Chris Brown, John Doe, Jane Smith",
    score: 6.89,
  },
  {
    filter: "Endurance Score",
    squadSize: 5,
    selectedSoldiers: "John Doe, Chris Brown, Emily Davis, Jane Smith, Mike Johnson",
    score: 7.72,
  },
  {
    filter: "Recovery Rate",
    squadSize: 5,
    selectedSoldiers: "Jane Smith, Emily Davis, Mike Johnson, Sarah Williams, Chris Brown",
    score: 6.38,
  },
  {
    filter: "Heart Rate Stability",
    squadSize: 5,
    selectedSoldiers: "Mike Johnson, Sarah Williams, Chris Brown, John Doe, Jane Smith",
    score: 4.29,
  },
  {
    filter: "Fatigue Resistance",
    squadSize: 5,
    selectedSoldiers: "Sarah Williams, Chris Brown, John Doe, Jane Smith, Emily Davis",
    score: 6.72,
  },
]

export default function SquadHealthOverview() {
  const [squadData, setSquadData] = useState<SoldierData[]>([])
  const [squadMetrics, setSquadMetrics] = useState<SquadMetrics>({
    combatReadiness: 0,
    averageFatigue: 0,
    squadMorale: 0,
    alertLevel: 0,
  })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [selectedFilter, setSelectedFilter] = useState<string>("Endurance Score")
  const [selectedSquadSize, setSelectedSquadSize] = useState<number>(1)
  const [bestSquadResult, setBestSquadResult] = useState<BestSquadResult | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Simulating API call
        await new Promise((resolve) => setTimeout(resolve, 1500))

        // Mock data
        const mockSquadData: SoldierData[] = [
          {
            id: "254183cf-4c15-4062-ac53-8953ba3f4768",
            name: "John Doe",
            avgHeartRate: 152.78,
            maxHeartRate: 165.5,
            minHeartRate: 79.0,
            totalSteps: 1847,
            caloriesBurned: 1304.13,
            fatigueOnset: "Not Reached",
          },
          {
            id: "b03f6bbb-74c2-4925-b781-4a56eebec337",
            name: "Jane Smith",
            avgHeartRate: 81.11,
            maxHeartRate: 115.65,
            minHeartRate: 62.0,
            totalSteps: 5979,
            caloriesBurned: 1378.16,
            fatigueOnset: "2025-01-09",
          },
          {
            id: "65cf37dc-5d3e-471f-9ff6-3f557d233ae2",
            name: "Mike Johnson",
            avgHeartRate: 149.71,
            maxHeartRate: 137.83,
            minHeartRate: 60.0,
            totalSteps: 11488,
            caloriesBurned: 529.69,
            fatigueOnset: "Not Reached",
          },
          {
            id: "91aa9c86-7e5b-44ba-bf2c-87c8772f2270",
            name: "Sarah Williams",
            avgHeartRate: 78.05,
            maxHeartRate: 170.17,
            minHeartRate: 63.0,
            totalSteps: 9350,
            ca
[truncated — 14781 more characters]
```

### my-app/app/api/perplexity-search/route.ts

```typescript
import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
import { generateText } from "ai"
import { NextResponse } from "next/server"

interface RequestBody {
  query: string
}

const perplexity = createOpenAICompatible({
  name: "perplexity",
  apiKey: process.env.PERPLEXITY_API_KEY,
  baseURL: "https://api.perplexity.ai/",
})

export async function POST(req: Request) {
  try {
    if (!process.env.PERPLEXITY_API_KEY) {
      return NextResponse.json({ error: "API key is not configured" }, { status: 500 })
    }

    const body = (await req.json()) as RequestBody

    if (!body.query) {
      return NextResponse.json({ error: "Query is required" }, { status: 400 })
    }

    const { text } = await generateText({
      model: perplexity("llama-3.1-sonar-small-128k-online"),
      prompt: `You are a military command AI assistant. Provide clear, concise, and tactical responses to mission-related queries. Always prioritize operational security and safety.

Query: ${body.query}

Response:`,
    })

    if (!text) {
      return NextResponse.json({ error: "No response generated" }, { status: 500 })
    }

    return NextResponse.json({ result: text })
  } catch (error) {
    console.error("Perplexity API Error:", error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "An unexpected error occurred while processing your request" },
      { status: 500 },
    )
  }
}


```

### my-app/app/api/weather/route.ts

```typescript
export async function GET() {
  try {
    // San Francisco coordinates
    const lat = 37.7749
    const lon = -122.4194

    const response = await fetch(
      `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&current=temperature_2m,relative_humidity_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m&forecast_days=1`,
    )

    if (!response.ok) {
      throw new Error("Weather API request failed")
    }

    const data = await response.json()

    // Calculate weather forecast message based on conditions
    let forecast = "Clear conditions expected"
    const nextFewHours = data.hourly.temperature_2m.slice(0, 4)
    const avgTemp = nextFewHours.reduce((a: number, b: number) => a + b, 0) / nextFewHours.length
    const currentTemp = data.current.temperature_2m

    if (Math.abs(avgTemp - currentTemp) > 5) {
      forecast = `Temperature change of ${Math.abs(avgTemp - currentTemp).toFixed(1)}°C expected in next few hours`
    }

    if (data.current.wind_speed_10m > 20) {
      forecast = "Strong winds detected. Exercise caution."
    }

    return Response.json({
      temperature: Math.round(data.current.temperature_2m),
      humidity: Math.round(data.current.relative_humidity_2m),
      windSpeed: Math.round(data.current.wind_speed_10m),
      forecast,
    })
  } catch (error) {
    console.error("Error fetching weather data:", error)
    return Response.json({ error: "Failed to fetch weather data" }, { status: 500 })
  }
}


```

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