PROJECT OVERVIEW:
Develop a fully functional, multi-page Next.js MVP application for 'Kea Traffic Masters'. This application aims to solve the problem of dynamic and intelligent traffic management, inspired by the problem of kea parrots manipulating traffic cones. The core value proposition is to provide an AI-powered platform that optimizes traffic flow, anticipates disruptions, and intelligently manages resources like traffic cones and barriers. It will serve as a command center for traffic authorities and construction site managers, enabling proactive and adaptive traffic control strategies. The system should be capable of detecting anomalies, suggesting optimal resource placement, and providing real-time situational awareness.
TECH STACK:
- Framework: Next.js (App Router)
- Language: TypeScript
- UI Library: shadcn/ui (for pre-built, accessible components)
- Styling: Tailwind CSS
- ORM: Drizzle ORM
- Database: PostgreSQL (or compatible, e.g., Vercel Postgres)
- Authentication: NextAuth.js (for robust user authentication, supporting email/password and potentially OAuth)
- State Management: React Context API and server state management via Next.js features (e.g., Server Components, Route Handlers)
- Real-time: Socket.IO or similar for real-time dashboard updates (optional for MVP, focus on polling first)
- AI Integration: Placeholder for future AI model integration (e.g., image recognition for anomaly detection, predictive traffic modeling). For MVP, simulate AI suggestions.
- Form Handling: React Hook Form with Zod for validation
- Charting: Recharts or similar for data visualization on the dashboard.
DATABASE SCHEMA:
1. **Users Table:**
* `id`: UUID (Primary Key)
* `name`: VARCHAR(255)
* `email`: VARCHAR(255) UNIQUE NOT NULL
* `hashedPassword`: VARCHAR(255) (if using email/password auth)
* `image`: VARCHAR(255) (URL to profile picture)
* `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
2. **Sites Table:** (Represents distinct traffic management zones or construction sites)
* `id`: UUID (Primary Key)
* `name`: VARCHAR(255) NOT NULL
* `location`: GEOGRAPHY(Point, 4326) OR JSON (for lat/lng)
* `description`: TEXT
* `createdByUserId`: UUID REFERENCES "Users"("id")
* `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
3. **Cones Table:** (Represents individual traffic cones or virtual markers)
* `id`: UUID (Primary Key)
* `siteId`: UUID REFERENCES "Sites"("id") ON DELETE CASCADE
* `currentLocation`: GEOGRAPHY(Point, 4326) OR JSON (for lat/lng)
* `status`: VARCHAR(50) DEFAULT 'active' (e.g., 'active', 'moved', 'missing', 'maintenance')
* `lastMovedAt`: TIMESTAMP WITH TIME ZONE
* `assignedAIState`: VARCHAR(100) (e.g., 'optimal_position', 'requires_attention', 'simulated_anomaly')
* `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
4. **TrafficEvents Table:** (Records significant traffic incidents or anomalies)
* `id`: UUID (Primary Key)
* `siteId`: UUID REFERENCES "Sites"("id") ON DELETE CASCADE
* `eventType`: VARCHAR(100) NOT NULL (e.g., 'congestion', 'accident', 'road_closure', 'cone_tampering')
* `severity`: INTEGER (e.g., 1-5)
* `description`: TEXT
* `occurredAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `resolvedAt`: TIMESTAMP WITH TIME ZONE
* `detectedBy`: VARCHAR(50) (e.g., 'AI_Vision', 'Sensor', 'Manual')
* `location`: GEOGRAPHY(Point, 4326) OR JSON (for lat/lng)
5. **AIRecommendations Table:** (Logs AI-generated suggestions for cone placement or actions)
* `id`: UUID (Primary Key)
* `siteId`: UUID REFERENCES "Sites"("id") ON DELETE CASCADE
* `recommendationType`: VARCHAR(100) NOT NULL (e.g., 'reposition_cone', 'deploy_barrier', 'alert_operator')
* `details`: JSONB (e.g., `{"coneId": "...", "newLocation": {...}}`)
* `generatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `status`: VARCHAR(50) DEFAULT 'pending' (e.g., 'pending', 'applied', 'rejected', 'expired')
* `appliedByUserId`: UUID REFERENCES "Users"("id")
* `appliedAt`: TIMESTAMP WITH TIME ZONE
CORE FEATURES & USER FLOW:
1. **Authentication (Sign Up / Login / Logout):**
* User visits the landing page.
* Clicks 'Sign Up' or 'Login'.
* Sign Up: Enters name, email, password. Submits form. Zod validates input. If valid, email/password is hashed and stored. User is logged in and redirected to the dashboard.
* Login: Enters email and password. Submits form. NextAuth.js verifies credentials against the database. If valid, session is created, and user is redirected to the dashboard. Handles errors (invalid credentials).
* Logout: User clicks 'Logout' button. Session is destroyed. Redirected to the landing page.
* Edge Case: Password reset flow (future enhancement, not MVP).
2. **Site Management (Create / View / Edit):**
* Authenticated user navigates to 'Sites' page.
* Clicks 'Create New Site'. A modal or form appears.
* User enters site name, description, and optionally sets a location (using a map interface or lat/lng input). Form validation via Zod.
* On submit, a new record is created in the `Sites` table, linked to the current `userId`.
* The 'Sites' page displays a list of sites the user has access to (initially, sites they created).
* Clicking a site name navigates to the Site Dashboard.
* 'Edit' functionality allows modification of site details (name, description, location).
* Edge Case: Handling permissions for shared sites (future enhancement).
3. **Traffic Cone Management (View / Simulate Move):**
* User navigates to a specific Site Dashboard.
* The dashboard displays a map view showing the site boundaries and the current locations of traffic cones (fetched from `Cones` table).
* Each cone is represented by an icon. Clicking a cone shows its status (`active`, `moved`, etc.) and `lastMovedAt`.
* **Simulate Cone Move:** A button or interaction allows the user to 'move' a cone. This simulates the AI's core inspiration. Clicking 'Simulate Move' on a cone triggers a frontend action. The UI updates the cone's visual position on the map and potentially its status to 'moved'. A corresponding entry can be logged in `AIRecommendations` table with status 'applied' for simulation purposes, or directly update the `Cones` table status and `lastMovedAt`.
* Edge Case: What if a cone is 'missing'? Display a different icon/status.
4. **AI Simulation & Anomaly Detection (View):**
* On the Site Dashboard, the system simulates AI-driven actions.
* **AI Recommendation Display:** The system periodically (or on button click) generates a simulated AI recommendation (e.g., 'Reposition Cone X for better flow'). This is logged in the `AIRecommendations` table. These recommendations appear as notifications or a dedicated section on the dashboard.
* **Simulated Anomaly:** The system can randomly flag a cone or a zone as having a 'simulated_anomaly' or trigger a 'TrafficEvent' (e.g., 'simulated_congestion'). These appear prominently on the dashboard map and in a dedicated 'Events' feed.
* User sees these simulated anomalies and AI suggestions on their dashboard. For MVP, there's no actual AI model, just triggered simulations based on predefined logic or random events.
* Edge Case: Displaying multiple simultaneous events or recommendations.
5. **Dashboard Overview (Data Visualization):**
* The main dashboard (accessible after login) provides a high-level overview.
* **Key Metrics:** Display cards showing total sites managed, active cones, recent alerts/events.
* **Activity Feed:** A chronological list of recent actions, AI recommendations, and detected events.
* **Map Summary:** A small, summarized map showing active sites or areas with recent activity.
* **Charts:** (Using Recharts) Display trends like 'Number of Events Over Time' or 'Cone Movement Frequency' for a selected site or overall.
* Edge Case: Handling no data available for charts (displaying a placeholder).
API & DATA FETCHING:
- **API Routes (Next.js Route Handlers):**
* `POST /api/auth/signup`, `POST /api/auth/login` (handled by NextAuth.js adapters)
* `GET /api/sites`: Fetch list of sites for the logged-in user.
* `POST /api/sites`: Create a new site.
* `GET /api/sites/[siteId]`: Fetch details for a specific site.
* `PUT /api/sites/[siteId]`: Update a site.
* `GET /api/sites/[siteId]/cones`: Fetch cones for a specific site.
* `POST /api/sites/[siteId]/cones/move`: Simulate moving a cone (updates `Cones` table, logs recommendation).
* `GET /api/sites/[siteId]/events`: Fetch traffic events for a site.
* `POST /api/sites/[siteId]/events`: Simulate creating a traffic event.
* `GET /api/sites/[siteId]/recommendations`: Fetch AI recommendations for a site.
* `POST /api/recommendations/[recId]/apply`: Mark a recommendation as applied.
* `GET /api/dashboard/summary`: Fetch summary data for the main dashboard.
- **Data Fetching:**
* Server Components will fetch data directly using Drizzle ORM queries within async functions.
* Client Components will use Route Handlers via `fetch` API, potentially using a data fetching library like SWR or React Query for caching and revalidation, especially for dynamic data like cone status.
* Example (Server Component): `async function SiteDashboard({ siteId }) { const cones = await db.query.cones.findMany({ where: (cones, { eq }) => eq(cones.siteId, siteId) }); return <ConeMap cones={cones} /> }`
* Example (Client Component using fetch): `async function ConeList() { const res = await fetch('/api/sites/abc/cones'); const cones = await res.json(); return <ul>{cones.map(cone => <li key={cone.id}>{cone.id}</li>)}</ul> }`
COMPONENT BREAKDOWN (Next.js App Router Structure):
- `app/layout.tsx`: Root layout (includes `<html>`, `<body>`, global providers, Tailwind CSS setup, shadcn/ui ThemeProvider).
- `app/page.tsx`: Landing Page (marketing content, Sign Up/Login buttons).
- `app/(auth)/login/page.tsx`: Login page.
- `app/(auth)/signup/page.tsx`: Sign Up page.
- `app/(app)/layout.tsx`: Main application layout (protected route, includes sidebar, header, main content area).
- `app/(app)/dashboard/page.tsx`: Main dashboard overview page. Fetches summary data. Includes Key Metrics cards, Activity Feed, Summary Map, Charts.
- `app/(app)/sites/page.tsx`: List of managed sites. Displays sites in a card or table format. Includes 'Create Site' button/modal.
- `app/(app)/sites/[siteId]/page.tsx`: Individual Site Dashboard. Displays a map, list of cones, AI recommendations, traffic events.
- `components/ui/map.tsx`: (Placeholder) Interactive map component (e.g., using Leaflet, Mapbox GL JS, or Google Maps API wrapper). Displays site boundaries, cone locations, event markers.
- `components/ui/cone-marker.tsx`: Renders individual cones on the map, potentially with status indicators.
- `components/ui/cone-list.tsx`: Table or list view of cones associated with the site.
- `components/ui/event-feed.tsx`: Displays recent traffic events.
- `components/ui/recommendation-list.tsx`: Displays AI recommendations.
- `components/forms/site-form.tsx`: Modal or page for creating/editing site details.
- `components/cards/metric-card.tsx`: Displays key metrics (e.g., Number of Sites, Active Cones).
- `components/charts/event-trend-chart.tsx`: Uses Recharts to display event trends.
- `components/layout/sidebar.tsx`: Navigation sidebar for 'Dashboard', 'Sites', 'Settings' etc.
- `components/layout/header.tsx`: Top navigation bar, includes user profile dropdown, logout button.
- `components/auth/signup-form.tsx`: Form for user registration.
- `components/auth/login-form.tsx`: Form for user login.
- `components/common/button.tsx`: Reusable button component (from shadcn/ui).
- `components/common/input.tsx`: Reusable input component (from shadcn/ui).
- `components/common/dialog.tsx`: Reusable dialog/modal component (from shadcn/ui).
- `lib/db.ts`: Drizzle ORM instance and schema setup.
- `lib/auth.ts`: NextAuth.js configuration.
- `hooks/use-data-fetching.ts`: (Optional) Custom hook for data fetching logic with caching/revalidation.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, Professional with a touch of technological sophistication.
- **Color Palette:**
- Primary: Deep Blue (`#1E3A8A` - Tailwind `blue-800`)
- Secondary: Teal/Cyan (`#06B6D4` - Tailwind `cyan-400` for accents, highlights)
- Background: Dark Gray (`#1F2937` - Tailwind `gray-800`)
- Surface: Slightly Lighter Gray (`#374151` - Tailwind `gray-700` for cards, modals)
- Text: Light Gray/White (`#F3F4F6` - Tailwind `gray-200`)
- Accent/Alerts: Orange/Red (`#F97316` - Tailwind `orange-500`, `#EF4444` - Tailwind `red-500` for critical alerts).
- **Typography:** Sans-serif fonts like Inter or Poppins for headings and body text. Ensure good readability and hierarchy.
- **Layout:** Utilize Next.js App Router's layout system. A common structure would be a Sidebar-Content layout for authenticated users. Use cards and clear visual separation for information blocks. Maintain consistent spacing and padding using Tailwind's spacing scale.
- **Responsiveness:** Mobile-first approach. Ensure the app is fully responsive and usable on various screen sizes, from mobile devices to desktops. Sidebar might collapse into a hamburger menu on smaller screens.
- **Visual Elements:** Use clean icons (e.g., from Lucide Icons integrated with shadcn/ui). Map visualizations should be clear and uncluttered. Subtle use of gradients or subtle background patterns could enhance the modern feel without being distracting.
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/fade-out transitions between pages or sections (e.g., using Framer Motion if needed, or CSS transitions).
- **Hover Effects:** Apply subtle hover effects on interactive elements like buttons and cards (e.g., slight scale-up, background color change).
- **Loading States:** Use spinners or skeleton loaders (from shadcn/ui) when data is being fetched or actions are processing. Integrate with `use` hook for server components suspense.
- **Component Animations:** Animate the appearance of new items in lists or notifications (e.g., fade-in, slide-up).
- **Map Animations:** Smooth panning and zooming on the map. Potentially animate cone movements if implementing that level of detail.
EDGE CASES:
- **Authentication:** Handle expired sessions, incorrect login details, and unauthorized access attempts gracefully. Redirect to login page where appropriate.
- **Empty States:** Design clear and helpful empty states for lists, dashboards, and maps when no data is available (e.g., 'No sites created yet. Click here to add one.', 'No traffic events recorded for this site.').
- **Data Validation:** Implement robust server-side validation for all API inputs using Zod to prevent data corruption and security issues.
- **Error Handling:** Implement global error handling (e.g., using Error Boundaries in React) and specific error handling for API calls. Display user-friendly error messages.
- **Permissions:** (MVP focuses on single-user ownership) Ensure only authorized users can view/edit their own sites and data.
- **Map Load Errors:** Handle potential errors when loading map tiles or essential map data.
- **Real-time Updates:** If using WebSockets, handle connection issues, disconnections, and reconnections gracefully.
SAMPLE/MOCK DATA:
1. **User:**
* `id`: '123e4567-e89b-12d3-a456-426614174000'
* `name`: 'Alice Wonderland'
* `email`: 'alice@example.com'
2. **Site:**
* `id`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `name`: 'Milford Sound Tunnel Approach'
* `location`: `{ lat: -44.5833, lng: 168.0750 }`
* `description`: 'Roadworks leading to the Milford Sound Tunnel.'
* `createdByUserId`: '123e4567-e89b-12d3-a456-426614174000'
3. **Cone (Active):**
* `id`: 'c1c2c3c4-d5e6-f789-0123-456789abcdef01'
* `siteId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `currentLocation`: `{ lat: -44.5835, lng: 168.0755 }`
* `status`: 'active'
* `assignedAIState`: 'optimal_position'
4. **Cone (Moved):**
* `id`: 'd2d3d4d5-e6f7-8901-2345-67890abcdef012'
* `siteId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `currentLocation`: `{ lat: -44.5830, lng: 168.0760 }`
* `status`: 'moved'
* `lastMovedAt`: '2024-07-27T10:30:00Z'
* `assignedAIState`: 'requires_attention'
5. **Traffic Event (Congestion):**
* `id`: 'e3e4e5e6-f789-0123-4567-890abcdef01234'
* `siteId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `eventType`: 'congestion'
* `severity`: 3
* `description`: 'Heavy traffic buildup due to tunnel maintenance.'
* `occurredAt`: '2024-07-27T11:00:00Z'
* `detectedBy`: 'Sensor'
* `location`: `{ lat: -44.5833, lng: 168.0750 }`
6. **AI Recommendation:**
* `id`: 'f4f5f6f7-8901-2345-6789-0abcdef0123456'
* `siteId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `recommendationType`: 'reposition_cone'
* `details`: `{ "coneId": "c1c2c3c4-d5e6-f789-0123-456789abcdef01", "newLocation": { "lat": -44.5836, "lng": 168.0751 }, "reason": "Improve traffic flow around the construction zone." }`
* `generatedAt`: '2024-07-27T11:15:00Z'
* `status`: 'pending'
7. **Site 2:**
* `id`: 'b2c3d4e5-f6a7-8901-2345-67890abcdef013'
* `name`: 'Highway Section 5B - Repair'
* `location`: `{ lat: 34.0522, lng: -118.2437 }`
* `description`: 'Ongoing road repair work on I-10 Eastbound.'
* `createdByUserId`: '123e4567-e89b-12d3-a456-426614174000'
8. **Cone (Near Missing):**
* `id`: 'e5f6a7b8-9012-3456-7890-abcdef01234567'
* `siteId`: 'b2c3d4e5-f6a7-8901-2345-67890abcdef013'
* `currentLocation`: `{ lat: 34.0525, lng: -118.2435 }`
* `status`: 'active'
* `assignedAIState`: 'check_position'
9. **Traffic Event (Obstruction):**
* `id`: 'g6h7i8j9-0123-4567-890a-bcdef012345678'
* `siteId`: 'b2c3d4e5-f6a7-8901-2345-67890abcdef013'
* `eventType`: 'obstruction'
* `severity`: 4
* `description`: 'Large debris fallen on the roadway.'
* `occurredAt`: '2024-07-27T11:30:00Z'
* `detectedBy`: 'AI_Vision'
* `location`: `{ lat: 34.0523, lng: -118.2436 }`
10. **AI Recommendation (Barrier):**
* `id`: 'h7i8j9k0-1234-5678-90ab-cdef0123456789'
* `siteId`: 'b2c3d4e5-f6a7-8901-2345-67890abcdef013'
* `recommendationType`: 'deploy_barrier'
* `details`: `{ "barrierLocation": { "lat": 34.0523, "lng": -118.2436 }, "extent": 50, "reason": "Secure the area around the debris." }`
* `generatedAt`: '2024-07-27T11:35:00Z'
* `status`: 'pending'
TURKISH TRANSLATIONS (for key UI elements):
- 'Sign Up': 'Kayıt Ol'
- 'Login': 'Giriş Yap'
- 'Logout': 'Çıkış Yap'
- 'Dashboard': 'Gösterge Paneli'
- 'Sites': 'Saha Yönetimi'
- 'Create New Site': 'Yeni Saha Oluştur'
- 'Site Name': 'Saha Adı'
- 'Description': 'Açıklama'
- 'Location': 'Konum'
- 'Save': 'Kaydet'
- 'Cancel': 'İptal'
- 'Cones': 'Koniler'
- 'Traffic Events': 'Trafik Olayları'
- 'AI Recommendations': 'Yapay Zeka Önerileri'
- 'Active': 'Aktif'
- 'Moved': 'Hareket Ettirildi'
- 'Missing': 'Kayıp'
- 'Event Type': 'Olay Türü'
- 'Severity': 'Önem Derecesi'
- 'Occurred At': 'Olay Zamanı'
- 'Recommended Action': 'Önerilen Eylem'
- 'Status': 'Durum'
- 'Applied': 'Uygulandı'
- 'Rejected': 'Reddedildi'
- 'Pending': 'Beklemede'
- 'Apply': 'Uygula'
- 'Edit': 'Düzenle'
- 'Delete': 'Sil'
- 'Simulate Move': 'Hareketini Simüle Et'
- 'No data available': 'Veri Bulunamadı'
- 'Loading...': 'Yükleniyor...'
- 'Error': 'Hata'
- 'Settings': 'Ayarlar'
- 'Profile': 'Profil'
- 'Welcome back, [User Name]!': 'Tekrar Hoş Geldin, [Kullanıcı Adı]!'