## AI Master Prompt for GeoLens MVP Generation
**PROJECT OVERVIEW:**
GeoLens is an AI-powered SaaS platform designed to provide in-depth analysis and foresight on geopolitical events and their impact on global trade, energy markets, and naval warfare. The application addresses the user problem identified in a Hacker News discussion regarding the US Navy's stance on the Strait of Hormuz, highlighting the evolving dynamics of naval power due to inexpensive unmanned anti-ship weapons and geopolitical tensions. GeoLens aims to translate complex geopolitical shifts into actionable intelligence for professionals, analysts, policymakers, and investors. Its core value proposition is to offer a comprehensive, data-driven understanding of geopolitical risks and their economic consequences, enabling users to make more informed strategic decisions.
**TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (with PostgreSQL as the database driver)
- **UI Library:** shadcn/ui (for pre-built, accessible components)
- **Authentication:** NextAuth.js (for robust user authentication)
- **Data Fetching:** React Server Components, Server Actions, API Routes
- **State Management:** React Context API, Zustand (for global state if needed)
- **Charting:** Recharts or Chart.js (for data visualization)
- **Deployment:** Vercel (recommended)
- **Other:** Axios (for external API calls if needed), clsx (for conditional class names)
**DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
1. **`users` Table:**
* `id` (UUID, primary key, default gen_random_uuid())
* `name` (TEXT)
* `email` (TEXT, unique, not null)
* `emailVerified` (TIMESTAMP with time zone)
* `image` (TEXT)
* `createdAt` (TIMESTAMP with time zone, default now())
* `updatedAt` (TIMESTAMP with time zone, default now())
* `stripeCustomerId` (TEXT, unique) // For subscription management
2. **`accounts` Table (for NextAuth.js):**
* `id` (TEXT, primary key)
* `userId` (UUID, foreign key to `users.id`, not null)
* `type` (TEXT, not null)
* `provider` (TEXT, not null)
* `providerAccountId` (TEXT, not null)
* `refresh_token` (TEXT)
* `access_token` (TEXT)
* `expires_at` (BIGINT)
* `token_type` (TEXT)
* `scope` (TEXT)
* `id_token` (TEXT)
* `session_state` (TEXT)
3. **`sessions` Table (for NextAuth.js):**
* `id` (TEXT, primary key)
* `sessionToken` (TEXT, unique, not null)
* `userId` (UUID, foreign key to `users.id`, not null)
* `expires` (TIMESTAMP with time zone, not null)
4. **`verificationTokens` Table (for NextAuth.js):**
* `identifier` (TEXT, not null)
* `token` (TEXT, not null)
* `expires` (TIMESTAMP with time zone, not null)
5. **`geopolitical_events` Table:**
* `id` (UUID, primary key, default gen_random_uuid())
* `title` (TEXT, not null)
* `description` (TEXT)
* `eventTimestamp` (TIMESTAMP with time zone, not null)
* `location` (TEXT, not null) // e.g., 'Strait of Hormuz', 'South China Sea'
* `latitude` (DECIMAL)
* `longitude` (DECIMAL)
* `severity` (INTEGER) // 1-5 scale
* `involvedParties` (TEXT[]) // Array of strings, e.g., ['US Navy', 'Iran']
* `source` (TEXT) // URL or name of the news source
* `createdAt` (TIMESTAMP with time zone, default now())
6. **`impact_analyses` Table:**
* `id` (UUID, primary key, default gen_random_random_uuid())
* `eventId` (UUID, foreign key to `geopolitical_events.id`, not null)
* `analysisType` (TEXT) // e.g., 'Economic', 'Naval', 'Political'
* `summary` (TEXT, not null)
* `detailedReport` (JSONB) // Structured data for detailed impacts (e.g., price changes, trade volume impact)
* `aiGeneratedAt` (TIMESTAMP with time zone, default now())
* `modelVersion` (TEXT) // Version of the AI model used for analysis
7. **`technology_trends` Table:**
* `id` (UUID, primary key, default gen_random_uuid())
* `name` (TEXT, not null) // e.g., 'Unmanned Anti-Ship Weapons', 'Hypersonic Missiles'
* `description` (TEXT)
* `impactOnGeopolitics` (TEXT)
* `relatedEvents` (UUID[]) // Array of event IDs
* `createdAt` (TIMESTAMP with time zone, default now())
8. **`subscriptions` Table:**
* `id` (UUID, primary key, default gen_random_uuid())
* `userId` (UUID, foreign key to `users.id`, unique, not null)
* `stripeSubscriptionId` (TEXT, unique, not null)
* `plan` (TEXT, not null) // e.g., 'free', 'standard', 'premium'
* `status` (TEXT, not null) // e.g., 'active', 'canceled', 'past_due'
* `currentPeriodEnd` (TIMESTAMP with time zone)
* `createdAt` (TIMESTAMP with time zone, default now())
* `updatedAt` (TIMESTAMP with time zone, default now())
**CORE FEATURES & USER FLOW:**
1. **User Authentication (Sign Up / Sign In):**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Sign In'. Redirected to authentication page. Options: Email/Password (if implemented, requires password hashing and reset flow), Google OAuth, GitHub OAuth via NextAuth.js.
* **Post-Auth:** Upon successful login, user is redirected to the main dashboard. If the user is new, they might see a brief onboarding tour. If they have an existing subscription, their plan dictates feature access.
* **Edge Case:** Invalid credentials, email not verified, account locked.
2. **Real-Time Geopolitical Event Feed & Map Visualization:**
* **Flow:** Authenticated users access the 'Events' page. A list of recent geopolitical events is displayed, sortable by date, severity, and location. A map component (e.g., using Leaflet or Mapbox GL JS) shows event markers based on latitude/longitude. Clicking a marker displays event details (title, description, involved parties, timestamp) in a popup or sidebar.
* **Data Source:** Initially, mock data will be used. Future iterations would involve integrating with news APIs (e.g., NewsAPI, GDELT) or specialized geopolitical data providers, processed by a backend script/service.
* **Backend:** API route `/api/events` to fetch events, potentially with filters. Server Action for adding/updating events (initially admin-only).
* **Edge Case:** No events found, location data missing, map fails to load.
3. **AI-Powered Impact Analysis:**
* **Flow:** On the 'Events' page, users can click an 'Analyze Impact' button next to a specific event. This triggers a backend process (potentially asynchronous). The user is notified when the analysis is ready. The analysis results (summary, detailed report) are displayed on an 'Analysis' tab or modal associated with the event. Premium users have access to more detailed reports and faster processing.
* **Backend:** An API route (e.g., `/api/events/[eventId]/analyze`) or a Server Action triggers the AI analysis. This involves calling an external LLM API (e.g., OpenAI, Gemini) with a carefully crafted prompt, providing the event details and asking for impact assessment across specified domains (economy, trade, energy, naval). The result is stored in the `impact_analyses` table.
* **Edge Case:** AI analysis fails, rate limits exceeded, inappropriate content generated, insufficient data for analysis.
4. **Technology Trends Overview:**
* **Flow:** Users navigate to the 'Trends' page. A list or card view of key technological trends impacting geopolitics is displayed. Each trend has a description and a summary of its geopolitical impact. Clicking a trend might show related events or more detailed analysis (for premium users).
* **Data Source:** Mock data initially. Future integration with research databases or expert input.
* **Backend:** API route `/api/trends` to fetch trends.
* **Edge Case:** No trends available.
5. **Dashboard:**
* **Flow:** The default authenticated user view. Presents a high-level overview: summary statistics (e.g., number of recent events), key active events, recent impact analyses, and potentially charts showing trends over time (e.g., event frequency by region). Components should be configurable based on user subscription level.
* **Backend:** Requires aggregated data fetched via multiple API calls or dedicated dashboard API routes.
* **Edge Case:** Empty states for all widgets.
**API & DATA FETCHING:**
- **Next.js App Router:** Leverage React Server Components (RSC) for fetching data directly on the server for pages like the dashboard and event list where initial load performance is critical. Use `fetch` extended with caching options.
- **API Routes:** Use `/api/` routes for dynamic data fetching, mutations, or actions that require client-side interaction or complex logic not suitable for RSC (e.g., webhook handlers, complex search).
- **Server Actions:** Ideal for form submissions and mutations (e.g., creating a new event - admin only, updating user profile). Ensure proper `try...catch` blocks and validation.
- **Data Flow:** Data flows from the database (via Drizzle ORM) to Server Components, which then pass data as props to Client Components. Client Components can trigger mutations via Server Actions or fetch data from API Routes using client-side fetching libraries (like `swr` or `axios` if needed).
- **Example API Route (`/api/events` GET):**
* **Request:** `GET /api/events?limit=20&offset=0&sortBy=timestamp&order=desc`
* **Response (200 OK):**
```json
{
"data": [
{
"id": "uuid-event-1",
"title": "Tensions Escalate Near Strait of Hormuz",
"eventTimestamp": "2024-03-15T10:00:00Z",
"location": "Strait of Hormuz",
"severity": 4,
"involvedParties": ["Iran", "US Navy"]
},
// ... more events
],
"total": 150
}
```
* **Response (401 Unauthorized):** If authentication fails.
* **Response (500 Internal Server Error):** If database error.
**COMPONENT BREAKDOWN (Next.js App Router Structure):**
```
app/
├── api/
│ ├── auth/
│ │ └── [...nextauth]/route.ts // NextAuth.js API route
│ ├── events/
│ │ └── route.ts // API for events (CRUD if needed)
│ └── ...
├── (app)/(dashboard)/
│ ├── layout.tsx // Dashboard layout (sidebar, header)
│ ├── page.tsx // Main dashboard overview (RSC)
│ ├── events/
│ │ ├── page.tsx // Events list page (RSC with client components for map/filters)
│ │ └── components/
│ │ ├── EventMap.tsx // Client component for map visualization
│ │ ├── EventList.tsx // Client component for interactive list
│ │ └── EventDetailModal.tsx // Client component for modal view
│ ├── analyses/
│ │ ├── page.tsx // Page to view all analyses (RSC)
│ │ └── [eventId]/
│ │ └── page.tsx // Specific analysis page (RSC)
│ ├── trends/
│ │ ├── page.tsx // Technology trends page (RSC)
│ │ └── components/
│ │ └── TrendCard.tsx // Client component for displaying trends
│ └── settings/
│ └── page.tsx // User settings (profile, subscription) (RSC with forms)
├── (auth)/
│ ├── layout.tsx // Auth layout (simple centered)
│ └── page.tsx // Sign in / Sign up page
├── layout.tsx // Root layout (html, body, providers)
└── page.tsx // Landing Page / Marketing Page
components/ui/
├── Accordion.tsx
├── Button.tsx
├── Card.tsx
├── Input.tsx
├── Sheet.tsx // For modals/sidebars
├── Tooltip.tsx
└── ... (all shadcn/ui components)
lib/
├── db.ts // Drizzle DB connection & schema definition
├── auth.ts // NextAuth.js configuration
├── utils.ts // Utility functions
└── ai.ts // AI service interaction logic
styles/
└── globals.css // Global styles & Tailwind directives
```
**State Management:** Primarily server-driven state via RSC props. Client components use local state (`useState`, `useReducer`) for UI interactions. Global state (e.g., user auth status, theme) managed via Zustand or React Context.
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Style:** Modern, clean, and professional, with a slight futuristic/tech-inspired edge. Focus on clarity and data readability.
- **Color Palette:**
- Primary: Deep Navy Blue (`#0B132B`)
- Secondary: Cool Gray (`#5A6F80`)
- Accent: Electric Blue (`#007BFF`) or Teal (`#1ABC9C`)
- Background: Light Off-White/Gray (`#F8F9FA`)
- Text: Dark Gray (`#343A40`)
- Success/Positive Indicator: Green (`#28A745`)
- Warning/Negative Indicator: Red (`#DC3545`)
- **Typography:** A clean sans-serif font family like Inter or Poppins for headings and body text. Ensure good readability and hierarchy.
- **Layout:** Utilize a sidebar navigation for authenticated sections (Dashboard, Events, Trends, Settings). Main content area displays information clearly. Use cards, tables, and charts effectively. Responsive design is crucial, adapting layouts for desktop, tablet, and mobile.
- **Sections:** Consistent header with logo, navigation, and user profile dropdown. Footer with links (About, Contact, Privacy Policy).
- **Visual Elements:** Subtle use of gradients in backgrounds or buttons. Clean iconography. Data visualizations (charts, maps) should be prominent and interactive.
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/out transitions between pages using Next.js's `AnimatePresence` (if using `framer-motion`).
- **Hover Effects:** Gentle scale or background color changes on interactive elements like buttons and cards.
- **Loading States:** Use skeleton loaders (e.g., `react-content-loader` or shadcn/ui's placeholder components) or spinners (`lucide-react` icons) for data fetching operations. Animate spinners smoothly.
- **Micro-interactions:** Smooth expansion/collapse for accordions, subtle transitions when data updates in tables or charts.
**SAMPLE/MOCK DATA:**
1. **`geopolitical_events`:**
```json
[
{
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"title": "Naval Drills Commence in South China Sea",
"description": "Multiple nations begin joint naval exercises in contested waters, increasing regional tensions.",
"eventTimestamp": "2024-07-20T08:00:00Z",
"location": "South China Sea",
"latitude": 11.0,
"longitude": 115.0,
"severity": 3,
"involvedParties": ["China", "Vietnam", "US Navy (Observer)"],
"source": "Reuters",
"createdAt": "2024-07-19T15:30:00Z"
},
{
"id": "b8f0c1a2-3b4c-4d5e-6f7a-8b9c0d1e2f3a",
"title": "Iran Seizes Tanker Near Strait of Hormuz",
"description": "Iranian forces boarded and seized a commercial tanker in the Persian Gulf, citing alleged violations.",
"eventTimestamp": "2024-07-18T11:30:00Z",
"location": "Persian Gulf",
"latitude": 26.0,
"longitude": 56.5,
"severity": 4,
"involvedParties": ["Iran", "Marshall Islands (Flag)"],
"source": "AP News",
"createdAt": "2024-07-18T12:00:00Z"
}
]
```
2. **`impact_analyses` (for the Iran event above):**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"eventId": "b8f0c1a2-3b4c-4d5e-6f7a-8b9c0d1e2f3a",
"analysisType": "Economic",
"summary": "Incident led to a temporary spike in oil prices (Brent crude +2.5%) and increased shipping insurance premiums in the Persian Gulf region. Minor disruption to regional trade flows expected.",
"detailedReport": {
"oilPriceImpact": {
"brent": {"change": "+2.5%", "previous": "$85.00", "current": "$87.12"},
"wti": {"change": "+1.8%", "previous": "$81.50", "current": "$83.00"}
},
"shipping": {
"insurancePremiumIncrease": "~15% for vessels transiting Persian Gulf",
"routeDisruption": "Minor, temporary delays reported at Jebel Ali port."
},
"currencyImpact": {
"usd": "Slight strengthening against regional currencies."
}
},
"aiGeneratedAt": "2024-07-18T14:00:00Z",
"modelVersion": "gpt-4-turbo-preview-2024-04-09"
}
```
3. **`technology_trends`:**
```json
[
{
"id": "9a8b7c6d-5e4f-3a2b-1c0d-9e8f7a6b5c4d",
"name": "Counter-Drone Systems",
"description": "Advancements in technologies designed to detect, track, and neutralize unmanned aerial vehicles (UAVs) or drones.",
"impactOnGeopolitics": "Significantly alters battlefield dynamics, particularly in asymmetric warfare scenarios. Increases the cost and risk for drone-based attacks, potentially deterring certain actors. Challenges traditional air defense systems.",
"relatedEvents": [],
"createdAt": "2024-07-10T10:00:00Z"
},
{
"id": "1b2a3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d",
"name": "Unmanned Anti-Ship Weapons",
"description": "Autonomous or remotely operated missiles, drones, and underwater vehicles designed to target and destroy naval vessels.",
"impactOnGeopolitics": "Reduces the traditional dominance of large surface warships. Increases the threat to naval fleets from smaller, cheaper platforms. Reshapes naval strategy and force projection, as demonstrated by the evolving posture described in the Hacker News article.",
"relatedEvents": ["b8f0c1a2-3b4c-4d5e-6f7a-8b9c0d1e2f3a"],
"createdAt": "2024-07-10T10:05:00Z"
}
]
```
4. **User Profile:**
```json
{
"id": "user-uuid-123",
"name": "Jane Doe",
"email": "jane.doe@example.com",
"image": "https://example.com/avatar.jpg",
"plan": "premium",
"stripeCustomerId": "cus_abc123xyz"
}
```
5. **Subscription Status:**
```json
{
"userId": "user-uuid-123",
"plan": "premium",
"status": "active",
"currentPeriodEnd": "2025-01-15T23:59:59Z"
}
```
**EDGE CASES:**
- **Authentication:** Implement robust error handling for login/signup failures (incorrect password, email not found, OAuth errors). Handle password reset flow if email/password auth is used. Ensure protected routes redirect unauthenticated users to the login page.
- **Authorization:** Differentiate access based on subscription plans (e.g., 'premium' users can access detailed AI analysis and advanced features). Implement checks in API routes and Server Actions.
- **Empty States:** Design informative and visually appealing empty states for all data-driven components (e.g., 'No events found matching your criteria', 'Your dashboard is empty. Start exploring events!').
- **Data Validation:** Implement both client-side (for immediate feedback) and server-side (for security) validation for all user inputs (forms, API requests).
- **Error Handling:** Implement global error handling (e.g., using Error Boundaries in React) and specific `try...catch` blocks around asynchronous operations (API calls, database interactions). Display user-friendly error messages. Log errors for debugging.
- **AI Rate Limiting/Failures:** Implement retry mechanisms with exponential backoff for AI API calls. Provide fallback content or clear messaging if AI analysis fails or is unavailable. Cache AI results to reduce redundant calls.
- **External API Failures:** Handle failures gracefully when integrating with third-party APIs (news, data providers). Implement timeouts and fallback strategies.
- **Responsiveness:** Ensure the UI adapts seamlessly across all device sizes. Test thoroughly on various viewports.
- **SEO:** Implement basic SEO practices for the landing page (meta tags, sitemaps). Consider pre-rendering for marketing content if necessary.