You are an expert AI assistant tasked with building a fully functional, multi-page Next.js MVP application for a SaaS platform called 'Port Monitor Pro'. This application will provide real-time and historical port status monitoring, focusing on critical maritime choke points like the Strait of Hormuz. The core value proposition is to offer accurate, timely, and consolidated information on port operations, ship traffic, and related news, leveraging AI for predictive insights and risk assessment.
**PROJECT OVERVIEW:**
'Port Monitor Pro' addresses the challenge of fragmented and delayed information in maritime logistics and geopolitical risk analysis. Users, including shipping operators, brokers, logistics managers, and financial analysts, struggle to get a clear, real-time picture of port status, especially during geopolitical tensions or operational disruptions. The problem is compounded by the high cost of live ship tracking APIs and the latency in publicly available data. Our solution is a unified SaaS platform that aggregates data from various sources (ship tracking APIs, news feeds, official reports, potentially AI-scraped data), processes it, and presents actionable insights on port availability, traffic density, and potential risks. The core value is providing a competitive edge through informed decision-making, reducing operational risks and costs.
**TECH STACK:**
- **Frontend Framework:** React (Next.js 14+ with App Router)
- **Styling:** Tailwind CSS (v3+)
- **ORM:** Drizzle ORM (with PostgreSQL adapter)
- **Database:** PostgreSQL
- **UI Components:** shadcn/ui (for accessible, reusable components)
- **Authentication:** NextAuth.js (for robust user authentication with email/password and OAuth providers like Google)
- **State Management:** React Context API / Zustand (for global state, where appropriate) and component-level state.
- **Data Fetching:** Server Actions (for mutations) and Route Handlers (for API endpoints), `fetch` API with caching.
- **Mapping:** React Leaflet or Mapbox GL JS for ship tracking visualization.
- **Charting:** Recharts or Chart.js for data visualization.
- **Form Handling:** React Hook Form with Zod for validation.
- **Deployment:** Vercel
- **Additional Packages:** `clsx` for conditional class names, `date-fns` for date manipulation, `lucide-react` for icons.
**DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
1. **`users` Table:**
* `id` (UUID, Primary Key)
* `name` (Text)
* `email` (Text, Unique)
* `emailVerified` (Timestamp)
* `image` (Text)
* `hashedPassword` (Text, Nullable)
* `createdAt` (Timestamp, Default now())
* `updatedAt` (Timestamp, Default now())
2. **`accounts` Table (for NextAuth.js):**
* `id` (BigInt, Primary Key, Auto-increment)
* `userId` (UUID, Foreign Key to `users.id`)
* `type` (Text)
* `provider` (Text)
* `providerAccountId` (Text)
* `refresh_token` (Text, Nullable)
* `access_token` (Text, Nullable)
* `expires_at` (BigInt, Nullable)
* `token_type` (Text, Nullable)
* `scope` (Text, Nullable)
* `id_token` (Text, Nullable)
* `session_state` (Text, Nullable)
3. **`sessions` Table (for NextAuth.js):**
* `sessionToken` (Text, Primary Key)
* `userId` (UUID, Foreign Key to `users.id`)
* `expires` (Timestamp)
4. **`verificationTokens` Table (for NextAuth.js):**
* `identifier` (Text)
* `token` (Text, Unique)
* `expires` (Timestamp)
5. **`ports` Table:**
* `id` (UUID, Primary Key)
* `name` (Text, Unique)
* `country` (Text)
* `latitude` (Numeric)
* `longitude` (Numeric)
* `description` (Text, Nullable)
* `is_critical` (Boolean, Default: false)
6. **`port_statuses` Table:**
* `id` (UUID, Primary Key)
* `portId` (UUID, Foreign Key to `ports.id`)
* `timestamp` (Timestamp)
* `status` (Enum: 'Open', 'Closed', 'Congested', 'Restricted', 'Unknown')
* `density_level` (Integer, Nullable, 1-5 scale)
* `source` (Text, e.g., 'marinetraffic_scrape', 'imf_report', 'news_analysis')
* `confidence_score` (Numeric, Nullable, 0.0-1.0)
* `notes` (Text, Nullable)
7. **`ship_movements` Table:**
* `id` (UUID, Primary Key)
* `mmsi` (Text, Index)
* `portId` (UUID, Foreign Key to `ports.id`, Nullable)
* `timestamp` (Timestamp)
* `latitude` (Numeric)
* `longitude` (Numeric)
* `heading` (Integer, Nullable)
* `speed` (Numeric, Nullable)
* `course` (Numeric, Nullable)
* `status` (Text, Nullable, e.g., 'Underway using engine', 'Moored')
* `source` (Text, e.g., 'ais_scrape')
8. **`news_items` Table:**
* `id` (UUID, Primary Key)
* `portId` (UUID, Foreign Key to `ports.id`, Nullable)
* `title` (Text)
* `url` (Text)
* `publishedAt` (Timestamp)
* `source` (Text)
* `summary` (Text, Nullable)
* `sentiment` (Enum: 'Positive', 'Negative', 'Neutral', Nullable)
* `relevance_score` (Numeric, Nullable)
9. **`user_port_subscriptions` Table:**
* `userId` (UUID, Foreign Key to `users.id`)
* `portId` (UUID, Foreign Key to `ports.id`)
* `createdAt` (Timestamp, Default now())
* Primary Key (`userId`, `portId`)
10. **`alert_rules` Table:**
* `id` (UUID, Primary Key)
* `userId` (UUID, Foreign Key to `users.id`)
* `portId` (UUID, Foreign Key to `ports.id`, Nullable)
* `rule_type` (Enum: 'StatusChange', 'DensityIncrease', 'NewsSentiment', 'TrafficAnomaly')
* `threshold_value` (Text, Nullable)
* `is_active` (Boolean, Default: true)
* `createdAt` (Timestamp, Default now())
**CORE FEATURES & USER FLOW:**
1. **User Authentication:**
* **Flow:** User lands on the homepage -> Clicks 'Sign Up' or 'Login' -> Presented with Email/Password form and OAuth options (Google) -> Enters credentials or uses OAuth -> Upon successful login, redirected to the Dashboard.
* **MVP:** Email/Password, Google OAuth.
* **Edge Cases:** Password reset, invalid credentials, duplicate email, OAuth callback handling.
2. **Dashboard - Port Overview:**
* **Flow:** Logged-in user lands on `/dashboard` -> Displays a list or grid of subscribed ports with their current status (e.g., 'Open', 'Congested', 'Closed') and a summary indicator (e.g., color dot, brief status text).
* **Data Display:** Port Name, Country, Current Status, Timestamp of last update, Density Level (if available), Quick link to Port Detail page.
* **MVP:** Shows subscribed ports; global critical ports are visible by default.
3. **Port Detail Page:**
* **Flow:** User clicks on a port from the Dashboard or Search -> Navigates to `/ports/[portId]` -> Displays detailed information for that port.
* **Sections:**
* **Current Status:** Prominent display of the latest known status, source, confidence, and timestamp.
* **Historical Status Chart:** Line chart showing status changes over the last 7 days (or selected period).
* **Ship Movements Map:** Interactive map showing recent ship movements near the port (last 24 hours). Markers indicate vessel type and status (moored, underway).
* **Related News Feed:** List of recent news articles relevant to the port, showing title, source, publication date, and sentiment score.
* **Alerts:** Section to view/manage active alerts for this port.
* **MVP:** Display all sections with data fetched from respective backend services.
4. **Port Search & Subscription:**
* **Flow:** User navigates to `/search` or uses a global search bar -> Enters a port name or country -> Search results displayed -> User clicks 'Subscribe' button next to a port -> The port is added to their Dashboard list.
* **MVP:** Basic search by port name; subscription functionality.
5. **Alert Management:**
* **Flow:** User navigates to `/settings/alerts` -> Views existing alert rules -> Clicks 'Create New Alert' -> Selects Port, Rule Type (e.g., 'Status Change to Closed'), optionally sets thresholds -> Saves the rule.
* **MVP:** Ability to create alerts for status changes and density increases for subscribed ports.
**API & DATA:**
- **Data Ingestion:** Background cron jobs or serverless functions will periodically scrape/fetch data from:
- Publicly available AIS data sources (e.g., simulating the `marinetraffic.com` JSON copy).
- Official port status websites or reports (e.g., `portwatch.imf.org` - acknowledging lag).
- News APIs (e.g., GNews, NewsAPI) filtered for relevant keywords.
- Potentially, an AI agent to parse unstructured text from reports/news for status/sentiment.
- **API Endpoints (Next.js Route Handlers - `app/api/...`):**
- `GET /api/ports`: Fetch list of all ports (for search).
- `GET /api/ports/{portId}`: Fetch detailed info for a specific port (status, history, map data, news).
- `GET /api/users/me/subscriptions`: Fetch user's subscribed ports.
- `POST /api/users/me/subscriptions`: Subscribe to a port.
- `DELETE /api/users/me/subscriptions`: Unsubscribe from a port.
- `GET /api/alerts`: Fetch user's alert rules.
- `POST /api/alerts`: Create a new alert rule.
- `PUT /api/alerts/{alertId}`: Update an alert rule.
- `DELETE /api/alerts/{alertId}`: Delete an alert rule.
- `GET /api/auth/...`: Handled by NextAuth.js.
- **Data Fetching in Components:** Utilize Server Components for initial data loads where possible (e.g., Dashboard). Use Server Actions for mutations (subscribe, create alert). Client Components will fetch data via API routes or use Server Actions directly for dynamic updates or user interactions.
**COMPONENT BREAKDOWN (Next.js App Router Structure):**
- **`app/`**
- **`layout.tsx`:** Root layout (includes header, footer, global styles).
- **`page.tsx`:** Homepage (marketing/landing content, pre-login view).
- **`auth/`**
- **`signin/page.tsx`:** Sign-in page (email/password, OAuth buttons).
- **`signup/page.tsx`:** Sign-up page.
- **`dashboard/`**
- **`page.tsx`:** Main dashboard page. Server Component fetching subscribed ports. Loads `PortGrid` component.
- **`loading.tsx`:** Dashboard loading state.
- **`ports/[portId]/`**
- **`page.tsx`:** Port detail page. Server Component fetching all data for the port. Loads `PortStatusCard`, `HistoricalChart`, `ShipMap`, `NewsFeed`.
- **`loading.tsx`:** Port detail loading state.
- **`search/page.tsx`:** Port search page. Client Component with search input and results list. Loads `SearchResultList`.
- **`settings/`**
- **`layout.tsx`:** Settings layout (sidebar navigation).
- **`profile/page.tsx`:** User profile settings.
- **`alerts/page.tsx`:** Alert management page. Client Component. Loads `AlertRuleList`, `CreateAlertForm`.
- **`api/`**
- **`.../route.ts`:** Route Handlers for backend API endpoints.
- **`components/`**
- **`ui/`** (shadcn/ui components: Button, Card, Input, Table, Sheet, DropdownMenu, etc.)
- **`layout/`**: Header, Footer, SidebarNav, PageWrapper.
- **`dashboard/`**: `PortCard`, `PortGrid`.
- **`ports/`**: `PortStatusCard`, `HistoricalChart`, `ShipMap` (using Leaflet/Mapbox), `NewsFeed`, `NewsItem`.
- **`search/`**: `SearchBar`, `SearchResultList`, `SearchResultItem`.
- **`alerts/`**: `AlertRuleList`, `AlertRuleItem`, `CreateAlertForm`.
- **`common/`**: `LoadingSpinner`, `ErrorMessage`, `MapComponent` (abstracted).
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Style:** "Modern Minimalist Clean" with a touch of professional seriousness.
- **Color Palette:**
- Primary: Deep Blue (`#0B2040`)
- Secondary: Teal (`#00A99D`)
- Accent: Orange (`#F58A07`)
- Neutrals: Light Gray (`#F8F9FA`), Medium Gray (`#CED4DA`), Dark Gray (`#343A40`)
- Status Indicators: Green (`#28A745` - Open), Yellow (`#FFC107` - Congested), Red (`#DC3545` - Closed), Orange (`#FD7E14` - Restricted).
- **Typography:** Sans-serif fonts. 'Inter' for body text and UI elements, 'Poppins' or similar for headings. Ensure good readability and hierarchy.
- **Layout:** Clean, spacious layout using a 12-column Tailwind grid. Clear visual hierarchy. Sidebar navigation in settings. Main content area is focused.
- **Responsiveness:** Mobile-first approach. Components should adapt gracefully from small screens to large desktops. Use Tailwind's responsive modifiers (`sm:`, `md:`, `lg:`).
- **Visual Elements:** Subtle use of gradients in backgrounds or active states. Clean icons from `lucide-react`. Data visualizations (charts, maps) should be clear and informative.
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/out transitions between pages using Next.js's `Layout Shift` mitigation and potentially Framer Motion if more complex animations are desired later.
- **Component Interactions:** Smooth transitions on hover states for buttons and cards (e.g., slight scale-up or background color change).
- **Loading States:** Use `shadcn/ui`'s skeleton loaders or `LoadingSpinner` components with subtle opacity transitions while data is being fetched.
- **Map Animations:** Smooth zooming and panning on the map component.
**EDGE CASES & VALIDATION:**
- **Authentication:** Handle unauthorized access gracefully (redirect to login, display messages). Implement role-based access if needed later.
- **Data Fetching Errors:** Display user-friendly error messages if API calls fail. Implement retry mechanisms where appropriate.
- **Empty States:** Design informative empty states for dashboards, alert lists, search results (e.g., 'You haven't subscribed to any ports yet. Start by searching!', 'No alerts configured.').
- **Form Validation:** Use Zod and React Hook Form for robust client-side and server-side validation of all user inputs (login, signup, alerts).
- **Data Integrity:** Ensure data consistency. Handle potential duplicates from scraping. Implement logic to prioritize data sources based on reliability and timeliness.
- **Rate Limiting:** Implement rate limiting on API endpoints to prevent abuse.
- **Outdated Data:** Clearly display the timestamp of the last data update. Consider background processes to refresh stale data or alert users if a data source stops reporting.
**SAMPLE/MOCK DATA:**
1. **Port:** `{ id: 'uuid-hormuz', name: 'Strait of Hormuz', country: 'Oman/Iran', latitude: 27.0, longitude: 56.0, is_critical: true }`
2. **Port Status (Hormuz, Congested):** `{ id: 'uuid-status-1', portId: 'uuid-hormuz', timestamp: '2023-10-27T10:00:00Z', status: 'Congested', density_level: 4, source: 'news_analysis', confidence_score: 0.85, notes: 'Increased naval presence reported.' }`
3. **Port Status (Suez, Open):** `{ id: 'uuid-status-2', portId: 'uuid-suez', timestamp: '2023-10-27T09:45:00Z', status: 'Open', density_level: 2, source: 'ais_scrape', confidence_score: 0.95 }`
4. **Ship Movement:** `{ id: 'uuid-ship-1', mmsi: '123456789', portId: 'uuid-hormuz', timestamp: '2023-10-27T09:55:00Z', latitude: 26.9, longitude: 56.1, heading: 90, speed: 5, status: 'Underway using engine' }`
5. **News Item (Hormuz related):** `{ id: 'uuid-news-1', portId: 'uuid-hormuz', title: 'Tensions rise in Persian Gulf', url: 'http://example.com/news1', publishedAt: '2023-10-27T08:30:00Z', source: 'Reuters', summary: 'Geopolitical analysts express concern over recent military drills near the Strait of Hormuz.', sentiment: 'Negative', relevance_score: 0.9 }`
6. **User:** `{ id: 'uuid-user-1', name: 'Alice Smith', email: 'alice@example.com', image: '/path/to/alice.jpg' }`
7. **Subscription:** `{ userId: 'uuid-user-1', portId: 'uuid-hormuz' }`
8. **Alert Rule:** `{ id: 'uuid-alert-1', userId: 'uuid-user-1', portId: 'uuid-hormuz', rule_type: 'StatusChange', threshold_value: 'Closed', is_active: true }`
9. **Port (Rotterdam):** `{ id: 'uuid-rotterdam', name: 'Port of Rotterdam', country: 'Netherlands', latitude: 51.9, longitude: 4.4, is_critical: false }`
10. **Port Status (Rotterdam, Open):** `{ id: 'uuid-status-3', portId: 'uuid-rotterdam', timestamp: '2023-10-27T11:00:00Z', status: 'Open', density_level: 3, source: 'portwatch_imf', confidence_score: 0.7 }`