# PROJECT OVERVIEW
**App Name:** Civ Legacy
**Concept:** Civ Legacy is a modern SaaS platform built around the nostalgia and mechanics of the classic Civilization 1 game. It empowers users to create, customize, share, and play their own Civ-like games using a powerful, yet accessible, web-based interface and a robust underlying game engine. The core value proposition is to revive the beloved gameplay of Civ 1 with modern technology, fostering a vibrant community of creators and players. It solves the problem of limited access to and modification capabilities for the original Civ 1 game by providing an open, extensible, and continuously updated platform.
**Target Audience:** Nostalgic Civ 1 players, strategy game enthusiasts, indie game developers, modders, and players interested in building and sharing custom game experiences.
**Core Value:** Re-imagining classic 4X strategy gameplay for the modern era, enabling community-driven game creation and play.
---
# TECH STACK
* **Frontend Framework:** React (Next.js App Router)
* **Styling:** Tailwind CSS
* **State Management:** Zustand (for global state) & React Context API (for theme/auth)
* **UI Components:** shadcn/ui (built on Radix UI and Tailwind CSS)
* **Data Fetching:** React Query (for server state management)
* **ORM:** Drizzle ORM
* **Database:** PostgreSQL (or SQLite for simpler MVP/local dev)
* **Authentication:** NextAuth.js (e.g., with Google, GitHub, or email/password providers)
* **API Layer:** Next.js API Routes (or server actions)
* **Deployment:** Vercel / Netlify / Cloudflare Pages
* **Optional (for complex game logic):** WebAssembly (if heavy computation needs offloading from JS, though initially stick to JS/TS)
---
# DATABASE SCHEMA (PostgreSQL with Drizzle ORM syntax)
```typescript
import { pgTable, serial, varchar, text, timestamp, integer, boolean, jsonb, primaryKey, foreignKey, uniqueIndex } from 'drizzle-orm/pg-core';
// Users Table
export const users = pgTable('users', {
id: varchar('id', { length: 255 }).primaryKey(), // Auth.js user ID
name: varchar('name', { length: 255 }),
email: varchar('email', { length: 255 }).notNull().unique(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: varchar('image', { length: 255 }),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Games Table (Represents user-created game configurations/scenarios)
export const games = pgTable('games', {
id: serial('id').primaryKey(),
userId: varchar('userId', { length: 255 }).notNull().references(() => users.id, { onDelete: 'cascade' }),
title: varchar('title', { length: 255 }).notNull(),
description: text('description'),
config: jsonb('config').notNull(), // JSON blob for game settings (e.g., map size, starting resources, unit types)
isPublic: boolean('isPublic').default(false), // Whether the game is publicly visible/playable
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Game Instances Table (Represents a specific playthrough of a game)
export const gameInstances = pgTable('gameInstances', {
id: serial('id').primaryKey(),
gameId: integer('gameId').notNull().references(() => games.id, { onDelete: 'cascade' }),
userId: varchar('userId', { length: 255 }).notNull().references(() => users.id, { onDelete: 'cascade' }),
gameState: jsonb('gameState').notNull(), // Stores the current state of the game being played (e.g., turn number, unit positions, player resources)
isCompleted: boolean('isCompleted').default(false),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Mod/Asset Table (For user-uploaded graphics, music, text replacements)
export const mods = pgTable('mods', {
id: serial('id').primaryKey(),
userId: varchar('userId', { length: 255 }).notNull().references(() => users.id, { onDelete: 'cascade' }),
gameId: integer('gameId').references(() => games.id, { onDelete: 'set null' }), // Optional: Link mod to a specific game
name: varchar('name', { length: 255 }).notNull(),
description: text('description'),
assetUrl: varchar('assetUrl', { length: 1024 }), // URL to the hosted asset (e.g., S3 bucket)
assetType: varchar('assetType', { length: 50 }), // e.g., 'graphics', 'music', 'text', 'ruleset'
version: varchar('version', { length: 50 }),
isPublic: boolean('isPublic').default(true),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Ensure necessary indexes for performance
// (Drizzle automatically handles primary keys and foreign key constraints)
// Example of adding a unique index if needed
// export const exampleTable = pgTable('example', {
// id: serial('id').primaryKey(),
// uniqueField: varchar('uniqueField', { length: 100 }).notNull().unique(),
// });
```
---
# CORE FEATURES & USER FLOW
1. **User Authentication:**
* **Flow:** User visits the landing page -> Clicks 'Sign Up' or 'Login' -> Presented with options (Google, GitHub, Email/Password) -> Selects option -> Authenticates via chosen provider -> Redirected to dashboard.
* **Edge Cases:** Invalid credentials, email already exists, social login errors, session management.
* **Implementation:** NextAuth.js with chosen providers.
2. **Game Creation (Dashboard):**
* **Flow:** Logged-in user navigates to 'My Games' -> Clicks 'Create New Game' -> Enters Game Title & Description -> Enters the Game Configuration Editor.
* **Game Configuration Editor:**
* **Tabs/Sections:** Map Settings, Units, Economy, Technology, Rules.
* **Map Settings:** Choose map size (e.g., Small, Medium, Large - mapping to grid dimensions), terrain types, starting resources.
* **Units:** Define unit types (e.g., Settler, Warrior, Archer) with basic stats (attack, defense, movement, cost).
* **Economy:** Set up basic resource generation (food, production, gold).
* **Technology:** Define a simple tech tree (e.g., list of techs with prerequisites).
* **Rules:** Set victory conditions (e.g., Conquest, Score), turn limit.
* **Saving:** User clicks 'Save Draft' or 'Publish Game'. Public games appear in the community library.
* **Edge Cases:** Invalid configuration inputs, required fields missing, complex dependencies between settings.
* **Implementation:** Interactive forms using shadcn/ui components, state managed with Zustand/Context. Validation on client and server.
3. **Game Library & Discovery:**
* **Flow:** User navigates to 'Game Library' -> Views a list of publicly available games (created by them and others) -> Can filter/sort by date, popularity, title -> Clicks on a game to view its details.
* **Game Detail Page:** Shows game title, description, creator, configuration summary, and a 'Play Game' button.
* **Edge Cases:** Empty library, filtering/searching with no results.
* **Implementation:** Fetching public games from the API, displaying in a card-based layout.
4. **Playing a Game (Game Instance):**
* **Flow:** User clicks 'Play Game' on a Game Detail page -> A new `gameInstance` is created in the database with the initial state derived from the selected `game.config` -> User is taken to the game interface.
* **Game Interface:**
* **Main View:** 2D grid-based map displaying terrain and units.
* **Top Bar:** Turn counter, current player resources (food, production, gold), victory progress.
* **Unit Actions:** Select a unit -> Action buttons appear (Move, Attack, Found City, etc.).
* **City Management:** Select a city -> City screen opens (production queue, building options).
* **Tech Tree:** View available techs and prerequisites.
* **End Turn:** Button to proceed to the next turn.
* **Turn Logic:** When 'End Turn' is clicked, the backend processes player actions, resolves combat, advances cities, checks for victory conditions, and saves the `gameState`. The UI then updates to reflect the new state.
* **Edge Cases:** Combat resolution, unit pathfinding (basic implementation initially), city growth, resource management, victory condition triggers.
* **Implementation:** Frontend rendering of the game state (likely using Canvas or a library like React-konva if complex visuals are needed, or simple divs/CSS grid for MVP). Backend logic in API routes/server actions to process turns and update `gameState` in the database.
5. **Modding/Asset Management (Future MVP/V2):**
* **Flow:** User navigates to 'My Mods' -> Uploads assets (images, sound files, text files) -> Associates them with a specific game or makes them globally available.
* **Integration:** The game engine would need to load these custom assets when a game or instance is initialized.
* **Edge Cases:** File size limits, format validation, asset conflicts.
* **Implementation:** File upload handling (e.g., using `uploadthing` or direct S3 uploads), storing asset URLs in the `mods` table.
---
# API & DATA FETCHING
* **Authentication:** Handled by NextAuth.js (`/api/auth/[...nextauth]`). Client-side access to user session via `useSession` hook.
* **Game Management (CRUD):**
* `GET /api/games`: Fetch list of public games (with pagination/filtering).
* `POST /api/games`: Create a new game configuration.
* `GET /api/games/{id}`: Fetch details of a specific game config.
* `PUT /api/games/{id}`: Update a game configuration (user-owned only).
* `DELETE /api/games/{id}`: Delete a game configuration (user-owned only).
* `GET /api/games/my`: Fetch list of games created by the current user.
* **Game Instance Management:**
* `POST /api/games/{gameId}/play`: Start a new game instance.
* `GET /api/game-instances/{instanceId}`: Fetch the current state of a specific game instance.
* `POST /api/game-instances/{instanceId}/next-turn`: Submit player actions and trigger turn processing.
* `PUT /api/game-instances/{instanceId}`: Save intermediate game state (autosave).
* `DELETE /api/game-instances/{instanceId}`: Abandon/delete a game instance.
* **Data Fetching Strategy:** Use React Query for server state. `useQuery` for fetching data (games, game instances), `useMutation` for mutations (create game, submit turn). Define query keys carefully for caching and invalidation.
* **Example Request/Response (`POST /api/games`):**
* **Request Body:** `{ title: 'My Awesome Game', description: '...', config: { mapSize: 'medium', startingUnits: [...] } }`
* **Response Body (Success):** `201 Created, { id: 123, userId: 'user1', title: 'My Awesome Game', ..., createdAt: '...' }`
* **Response Body (Error):** `400 Bad Request, { error: 'Title is required' }` or `401 Unauthorized`.
---
# COMPONENT BREAKDOWN (Next.js App Router)
* **`app/layout.tsx`:** Root layout, includes global providers (Context API for theme/auth), base Tailwind directives, `<html>`, `<body>` tags.
* **`app/page.tsx`:** Landing Page. Features, call to action, login/signup links. (Marketing focus).
* **`app/(auth)/login/page.tsx`:** Login page.
* **`app/(auth)/signup/page.tsx`:** Sign up page.
* **`app/(app)/dashboard/page.tsx`:** User Dashboard. Overview of 'My Games', 'My Instances', quick links.
* **`app/(app)/games/page.tsx`:** Game Library. Lists public games. Uses `GameList` and `GameCard` components.
* **`app/(app)/games/[gameId]/page.tsx`:** Game Detail Page. Shows game configuration details, 'Play Game' button.
* **`app/(app)/games/create/page.tsx`:** Game Creation page (entry point).
* **`app/(app)/games/edit/[gameId]/page.tsx`:** Game Configuration Editor. Uses `ConfigForm` component with nested sections (Map, Units, etc.).
* **`app/(app)/play/[instanceId]/page.tsx`:** Game Play Interface. The main game screen. Contains:
* `GameMap` component (renders the grid).
* `GameUI` component (top bar with resources, turn button).
* `UnitActionPanel` component (appears on unit selection).
* `CityScreen` component (modal/overlay for city management).
* `TechTree` component (modal/overlay).
* **`app/(app)/profile/page.tsx`:** User Profile Page.
* **`app/api/...`:** API Routes (as described above).
* **`components/ui/`:** Reusable shadcn/ui components (Button, Input, Card, Dialog, etc.).
* **`components/layout/`:** Header, Footer, Sidebar components.
* **`components/game/`:** Game-specific components (`GameMap`, `GameUnit`, `CityView`, `TechNode`).
* **`hooks/`:** Custom hooks (e.g., `useGameEngine`, `useAuth`).
* **`lib/`:** Utility functions, database connection, Drizzle schema definitions.
* **`styles/`:** Global CSS, Tailwind configuration.
**State Management:**
* **Global:** Zustand store for user session, theme settings.
* **Server State:** React Query for managing API data (games, instances).
* **Local/Component:** React `useState` for form inputs, UI states (e.g., modal open/closed, selected unit).
* **Game State:** The `gameState` JSON blob in `gameInstances` table is the source of truth. Frontend reads from it and sends actions to the backend to modify it.
---
# UI/UX DESIGN & VISUAL IDENTITY
* **Design Style:** Modern, clean, with subtle retro-futuristic elements reflecting the Civ 1 inspiration. Emphasis on clarity and usability for complex game interfaces.
* **Color Palette:**
* Primary: Deep Blue (`#1A202C` - Dark Background)
* Secondary: Teal (`#4FD1C5` - Accents, Buttons)
* Accent: Gold (`#ECC94B` - Highlights, Resources)
* Neutrals: Light Gray (`#A0AEC0`), Off-White (`#F7FAFC`)
* Alerts: Red (`#F56565`)
* **Typography:**
* Headings: A slightly stylized sans-serif, e.g., 'Poppins' or 'Inter' (Bold).
* Body Text: Clean sans-serif, e.g., 'Inter' (Regular).
* **Layout:** Responsive grid system. Clear separation of concerns on game screen (map, info panels, action buttons). Use of cards for lists (games, mods).
* **Responsiveness:** Mobile-first approach. Ensure game interface is usable on smaller screens (potentially with touch-friendly controls), while desktop offers more space.
* **Visual Elements:** Subtle gradients in backgrounds, clean icons (e.g., from lucide-react), pixel-art inspired elements for units/cities if feasible within the clean aesthetic.
---
# ANIMATIONS
* **Page Transitions:** Smooth fades using Next.js `next/navigation` or a library like Framer Motion.
* **Button Hovers:** Slight scale or background color change.
* **Loading States:** Skeleton loaders for lists, spinners within buttons for async operations (React Query handles this well).
* **Game Elements:** Subtle animations for unit movement (path visualization), city production progress, tech discovery.
* **UI Feedback:** Micro-interactions on successful saves or actions.
---
# EDGE CASES & VALIDATION
* **Authentication:** Handle expired sessions, re-authentication, unauthorized access attempts gracefully (redirects, error messages).
* **Game Configuration:** Implement robust client-side and server-side validation for all configuration options. Provide clear error messages.
* **Game State:** Ensure atomicity when processing turns. If a turn fails, the game state should remain consistent. Implement rollback mechanisms if necessary.
* **Empty States:** Design informative empty states for 'My Games', 'Game Library', etc., with clear calls to action.
* **Error Handling:** Catch API errors, display user-friendly messages. Use React Query's error handling and retry mechanisms.
* **Data Integrity:** Use database constraints (NOT NULL, UNIQUE, FOREIGN KEY) to maintain data integrity.
* **Concurrent Access:** For MVP, assume single-player focus or simple turn-based concurrency. More complex real-time features would require different strategies (WebSockets, optimistic updates).
---
# SAMPLE/MOCK DATA
1. **User:**
```json
{
"id": "user_abc123",
"name": "AwesomeGamer",
"email": "gamer@example.com",
"image": "/images/avatars/default.png"
}
```
2. **Game Configuration (`games.config`):**
```json
{
"map": {"size": "medium", "terrainTypes": ["plains", "grassland", "hills", "water"]},
"resources": {"food": 2, "production": 1, "gold": 0},
"units": [
{"id": "settler", "name": "Settler", "cost": 80, "movement": 2, "buildable": true},
{"id": "warrior", "name": "Warrior", "cost": 40, "attack": 2, "defense": 1, "movement": 2, "buildable": true}
],
"techTree": {
"start": {"name": "Pottery", "prerequisites": []},
"pottery": {"name": "Writing", "prerequisites": ["Pottery"]}
},
"victoryConditions": ["conquest", "score"]
}
```
3. **Game Instance State (`gameInstances.gameState` - Initial):**
```json
{
"turn": 1,
"players": [
{
"id": "player1", // Corresponds to user_abc123
"resources": {"food": 10, "production": 5, "gold": 50},
"cities": [{"name": "New City", "position": {"x": 5, "y": 5}, "productionProgress": 0, "size": 1}],
"units": [{"id": "settler1", "type": "settler", "position": {"x": 4, "y": 4}}, {"id": "warrior1", "type": "warrior", "position": {"x": 3, "y": 3}}]
}
],
"mapData": [[{"terrain": "plains", "resource": null}, ...]], // Grid data
"turnOrder": ["player1"]
}
```
4. **Game Instance State (`gameInstances.gameState` - Mid-game Update Example):**
```json
{
"turn": 15,
"players": [
{
"id": "player1",
"resources": {"food": 25, "production": 30, "gold": 150},
"cities": [
{"name": "New City", "position": {"x": 5, "y": 5}, "productionProgress": 40, "size": 2},
{"name": "Metropolis", "position": {"x": 12, "y": 8}, "productionProgress": 0, "size": 1}
],
"units": [{"id": "settler1", "type": "settler", "position": {"x": 7, "y": 6}}, {"id": "warrior1", "type": "warrior", "position": {"x": 6, "y": 5}}, {"id": "archer1", "type": "archer", "position": {"x": 8, "y": 7}}]
}
],
"mapData": [...],
"turnOrder": ["player1", "player2"],
"activeNotifications": ["City 'Metropolis' production complete: Archer"]
}
```
5. **Game List Item:**
```json
{
"id": 101,
"title": "Classic Earth Map",
"description": "A standard game on a familiar world map.",
"userId": "user_xyz789",
"isPublic": true,
"createdAt": "2023-10-27T10:00:00Z"
}
```
6. **Mod Entry:**
```json
{
"id": 55,
"userId": "user_abc123",
"name": "Steampunk Units Pack",
"description": "Adds visually unique steampunk-themed units.",
"assetUrl": "https://civlegacy.storage.googleapis.com/mods/steampunk_units.zip",
"assetType": "graphics",
"version": "1.0",
"isPublic": true,
"createdAt": "2023-10-26T15:30:00Z"
}
```
---
**Final Note:** This prompt is designed to guide an AI in generating a comprehensive and functional MVP. Focus on robust Next.js App Router structure, clear state management, secure authentication, and a well-defined game loop. Ensure the UI is clean and intuitive, reflecting the project's goals. The game engine logic within the turn processing API route will be the most complex part, requiring careful implementation to handle game rules and state transitions accurately.