You are an expert AI assistant tasked with generating the complete frontend code for a single-page application (SPA) named 'GeoCloud Resilience'. This application serves as a Software-as-a-Service (SaaS) solution designed to provide businesses with automated cloud infrastructure backup and disaster recovery capabilities, specifically addressing risks arising from geopolitical events and localized infrastructure failures. The target audience is IT managers, infrastructure engineers, and CTOs in medium to large enterprises concerned about business continuity.
**1. PROJECT OVERVIEW:**
GeoCloud Resilience aims to mitigate the impact of cloud infrastructure disruptions, such as those caused by geopolitical events (like the example from Hacker News concerning AWS in Bahrain and Dubai) or natural disasters. The core value proposition is to offer automated, geographically distributed backups and a rapid, reliable disaster recovery mechanism. This ensures business continuity by allowing critical applications and data to be quickly restored or rerouted to alternative, unaffected cloud regions. The application provides a centralized dashboard for monitoring backup status, recovery readiness, and potential regional risks, alongside proactive alerts.
**2. TECH STACK:**
- **Framework:** React.js (using Vite for fast development environment)
- **Styling:** Tailwind CSS (with Headless UI for accessible, unstyled components)
- **State Management:** Zustand (for its simplicity and performance)
- **Routing:** React Router DOM
- **API Client:** Axios (for making HTTP requests)
- **Date Handling:** date-fns
- **Icons:** Heroicons
- **Forms:** React Hook Form (with Zod for schema validation)
**3. CORE FEATURES (User Flows):**
**a. Dashboard:**
- **User Flow:** Upon login, the user lands on the main dashboard. The dashboard displays a summary of the overall system status, including the number of protected regions, last backup success time across all regions, upcoming scheduled backups, and a real-time risk assessment overview (e.g., a map highlighting regions with potential threats). It also shows recent alerts and a quick link to initiate a disaster recovery process.
- **Details:** Visualizations like charts for backup success rates over time, a world map with color-coded region statuses (Healthy, Warning, Critical), and cards summarizing key metrics.
**b. Region Management:**
- **User Flow:** Users navigate to the 'Regions' section to view, add, or configure cloud regions for protection. They can select their primary cloud provider (initially AWS, expandable later), choose specific Availability Zones (AZs) or entire regions to monitor and back up. For each region, they define backup frequency, target backup regions, and disaster recovery region.
- **Details:** A table listing all configured regions, their primary cloud provider, backup status, last backup timestamp, and configured DR region. Adding a region involves a form to select provider, region name, backup schedule (e.g., daily, hourly), and one or more designated backup/DR regions.
**c. Backup Configuration:**
- **User Flow:** Within the 'Region Management' section or a dedicated 'Backup Settings' area, users can fine-tune backup policies. This includes setting RPO (Recovery Point Objective), choosing backup types (e.g., full, incremental), defining data retention policies, and potentially enabling encryption for backups.
- **Details:** Forms allowing users to set RPO targets (e.g., 1 hour, 24 hours), select retention periods (e.g., 7 days, 30 days), and toggle backup encryption.
**d. Disaster Recovery (DR) Orchestration:**
- **User Flow:** In case of a primary region failure (indicated by alerts or manual detection), the user navigates to the 'Disaster Recovery' section. They can select the affected region and initiate the DR process. The system automatically starts provisioning resources and restoring data in the pre-configured DR region. The user can monitor the progress of the DR failover in real-time.
- **Details:** A dedicated DR page showing the status of the current recovery operation (e.g., 'Initiating', 'Restoring Data', 'Verifying Resources', 'Active in DR Region'). It should provide an estimated time to completion and logs of the recovery steps. A 'Failback' option should also be available once the primary region is restored.
**e. Alerting and Notifications:**
- **User Flow:** Users configure their notification preferences (email, in-app). The system automatically sends alerts for critical events: backup failures, detected regional risks (based on external data feeds or user-defined thresholds), DR initiation, and DR completion.
- **Details:** A settings page for managing notification channels and alert thresholds. An 'Alerts History' section to review past notifications.
**4. UI/UX DESIGN:**
- **Layout:** A clean, modern, and professional single-page application layout. A persistent sidebar navigation for main sections (Dashboard, Regions, Backups, DR, Alerts, Settings). The main content area displays the relevant information for the selected section.
- **Color Palette:** Primary: Dark Blue (#1E3A8A) for backgrounds/navigation, Secondary: Teal (#14B8A6) for active states and calls to action, Accent: Light Gray (#F3F4F6) for content backgrounds, Text: White (#FFFFFF) and Dark Gray (#374151).
- **Typography:** Use a clean, sans-serif font family like Inter or Inter UI. Headings should be bold and appropriately sized, body text should be legible.
- **Responsive Design:** Mobile-first approach. The layout must adapt seamlessly to various screen sizes (mobile, tablet, desktop). Sidebar might collapse into a hamburger menu on smaller screens. Use Tailwind CSS's responsive modifiers (sm:, md:, lg:).
- **Components:** Utilize Headless UI for accessible and unstyled components (Dialogs, Menus, Tabs, etc.) that can be styled with Tailwind.
**5. DATA MODEL (Zustand Store Structure):**
```javascript
// Example for Zustand store
interface Region {
id: string;
name: string;
provider: 'AWS' | 'Azure' | 'GCP'; // Initially AWS
status: 'Healthy' | 'Warning' | 'Critical' | 'Unknown';
lastBackup: string | null;
backupFrequency: string;
drRegion: string;
backupRegions: string[];
}
interface Alert {
id: string;
timestamp: string;
message: string;
severity: 'Info' | 'Warning' | 'Error';
read: boolean;
}
interface DisasterRecoveryState {
currentOperation: 'Idle' | 'Initiating' | 'Restoring' | 'Verifying' | 'Active' | 'Failback';
targetRegion: string | null;
startTime: string | null;
estimatedCompletion: string | null;
logs: string[];
}
interface AppState {
regions: Region[];
alerts: Alert[];
drState: DisasterRecoveryState;
isLoading: boolean;
error: string | null;
// Actions
fetchRegions: () => Promise<void>;
addRegion: (regionData: Omit<Region, 'id' | 'status' | 'lastBackup'>) => Promise<void>;
updateRegion: (regionId: string, updates: Partial<Omit<Region, 'id'>>) => void;
fetchAlerts: () => Promise<void>;
addAlert: (alertData: Omit<Alert, 'id' | 'timestamp' | 'read'>) => void;
initiateDR: (regionId: string) => Promise<void>;
monitorDRProgress: (operationId: string) => Promise<void>;
cancelDR: () => void;
fetchDRState: () => Promise<void>;
}
```
**Mock Data Format:**
```json
{
"regions": [
{
"id": "reg_12345",
"name": "us-east-1",
"provider": "AWS",
"status": "Healthy",
"lastBackup": "2024-04-15T10:30:00Z",
"backupFrequency": "Hourly",
"drRegion": "eu-west-1",
"backupRegions": ["eu-central-1"]
},
{
"id": "reg_67890",
"name": "eu-central-1",
"provider": "AWS",
"status": "Warning",
"lastBackup": "2024-04-15T09:00:00Z",
"backupFrequency": "Daily",
"drRegion": "ap-southeast-1",
"backupRegions": ["us-west-2"]
}
],
"alerts": [
{
"id": "alert_abcde",
"timestamp": "2024-04-15T11:00:00Z",
"message": "High latency detected in us-east-1. Initiating backup check.",
"severity": "Warning",
"read": false
}
],
"drState": {
"currentOperation": "Idle",
"targetRegion": null,
"startTime": null,
"estimatedCompletion": null,
"logs": []
}
}
```
**6. COMPONENT BREAKDOWN:**
- **`App.jsx`**: Main application component, sets up routing.
- **`Layout.jsx`**: Main layout structure, includes Sidebar and main content area.
- **`Sidebar.jsx`**: Navigation menu component. Props: `items` (array of navigation links), `isOpen` (boolean for mobile state).
- **`DashboardPage.jsx`**: Displays the main dashboard overview. Components: `StatCard`, `RegionStatusMap`, `RecentAlertsList`, `QuickActions`.
- **`StatCard.jsx`**: Displays a single key metric (e.g., 'Regions Protected', 'Last Backup Success'). Props: `title`, `value`, `icon`.
- **`RegionStatusMap.jsx`**: Interactive map showing region statuses. Props: `regions` (array).
- **`RecentAlertsList.jsx`**: Displays a list of recent alerts. Props: `alerts` (array).
- **`QuickActions.jsx`**: Buttons for common actions like 'Initiate DR'.
- **`RegionManagementPage.jsx`**: Page for managing cloud regions. Components: `RegionTable`, `AddRegionForm`, `RegionDetailModal`.
- **`RegionTable.jsx`**: Displays regions in a sortable, filterable table. Props: `regions` (array), `onEdit` (function), `onDelete` (function).
- **`AddRegionForm.jsx`**: Form for adding/editing region configurations. Props: `initialData` (object, optional), `onSubmit` (function), `providers` (array).
- **`RegionDetailModal.jsx`**: Modal to show detailed info and actions for a specific region. Props: `region` (object), `isOpen`, `onClose`, `onInitiateDR`.
- **`DisasterRecoveryPage.jsx`**: Manages the DR process. Components: `DRStatusDisplay`, `DRControlPanel`, `DRLogViewer`.
- **`DRStatusDisplay.jsx`**: Shows the current status and progress of a DR operation. Props: `drState` (object).
- **`DRControlPanel.jsx`**: Buttons to initiate, monitor, or cancel DR. Props: `onInitiate`, `onCancel`, `currentStatus`.
- **`DRLogViewer.jsx`**: Displays logs related to the DR process. Props: `logs` (array).
- **`AlertsPage.jsx`**: Lists all historical alerts. Components: `AlertTable`, `NotificationSettingsForm`.
- **`AlertTable.jsx`**: Table displaying alerts. Props: `alerts` (array).
- **`NotificationSettingsForm.jsx`**: Form for configuring notification preferences.
- **`SettingsPage.jsx`**: General application settings.
- **`LoadingSpinner.jsx`**: Reusable loading indicator.
- **`ErrorDisplay.jsx`**: Component to show error messages.
- **`Modal.jsx`**: Generic modal component. Props: `isOpen`, `onClose`, `children`.
**7. ANIMATIONS & INTERACTIONS:**
- **Page Transitions:** Subtle fade-in/fade-out transitions between pages/sections using CSS or a library like Framer Motion (if complexity warrants).
- **Hover Effects:** Subtle background color changes or slight scaling on interactive elements like buttons and table rows.
- **Loading States:** Use `LoadingSpinner.jsx` component with appropriate overlays or inline placeholders when fetching data or performing actions. Disable buttons during loading states.
- **Form Interactions:** Visual feedback on input focus (e.g., border color change). Success/error messages appearing smoothly.
- **DR Progress:** Animate progress bars or status indicators during DR operations.
- **Map Interactions:** Smooth zooming and panning on the `RegionStatusMap`.
**8. EDGE CASES:**
- **Empty States:** Display user-friendly messages and clear calls to action when lists are empty (e.g., 'No regions configured yet. Add your first region to get started.').
- **Error Handling:** Gracefully handle API errors (network issues, server errors). Display informative error messages to the user using `ErrorDisplay.jsx`. Log errors for debugging.
- **Validation:** Implement client-side validation using React Hook Form and Zod for all forms (Region configuration, settings). Ensure data integrity.
- **Accessibility (a11y):** Use semantic HTML. Ensure all interactive elements are keyboard navigable. Use ARIA attributes where necessary. Leverage Headless UI components for built-in accessibility.
- **Unauthorized Access:** Implement basic checks or route protection to ensure only logged-in users can access application features (assuming authentication is handled externally or mocked for MVP).
- **Simultaneous DR:** Prevent initiating multiple DR processes concurrently for the same region or conflicting regions.
- **No Available DR Regions:** Handle cases where a user attempts to configure a DR process but no valid DR regions are available or configured.
**9. SAMPLE DATA (API Responses/Mock Data):**
(See 'DATA MODEL' section for detailed mock data structures. Below are examples integrated into specific scenarios.)
- **Dashboard Initial Load:** Fetch regions and alerts. Display loading spinners. Populate `StatCard`s, `RegionStatusMap`, and `RecentAlertsList` upon successful data retrieval.
- **Region List:** `[{ "id": "reg_aws_us_1", "name": "us-east-1", "provider": "AWS", "status": "Healthy", "lastBackup": "2024-04-15T14:00:00Z", "backupFrequency": "Hourly", "drRegion": "eu-west-1", "backupRegions": ["eu-central-1"] }, ...]`
- **Alerts Feed:** `[{ "id": "al_001", "timestamp": "2024-04-15T13:45:00Z", "message": "Potential geopolitical instability detected near ap-northeast-1. Recommend reviewing backup status.", "severity": "Info", "read": false }, ...]`
- **DR Process Start:** User clicks 'Initiate DR' for `us-east-1`. API call `POST /api/dr/initiate` with `{ regionId: 'reg_aws_us_1' }`. The `drState` updates to `"currentOperation": "Initiating"`, `"targetRegion": "eu-west-1"`, `"estimatedCompletion": "~15 minutes"`. The `DRLogViewer` shows 'Initiating DR for us-east-1...'.
- **DR Progress Update:** Simulate API polling or WebSocket messages. `drState` updates: `"currentOperation": "Restoring"`, `logs: [... "Restoring data volume...", "Configuring EC2 instances..."]`. Progress bar updates.
- **DR Failure:** If DR fails, `drState` updates: `"currentOperation": "Failed"`, `logs: [... "Error: Insufficient capacity in eu-west-1."]`. An alert is generated.
- **DR Success:** `drState` updates: `"currentOperation": "Active"`, `logs: [... "DR successful. Services operating from eu-west-1."]`. A notification is sent.
- **Empty Regions:** If `regions` array is empty, the `RegionManagementPage` displays a message: 'You haven't added any cloud regions yet. Click the button below to add your first protected region.' with a prominent 'Add Region' button.
**10. DEPLOYMENT NOTES:**
- **Build Command:** `npm run build` (or `yarn build`). This will create an optimized production build in the `dist` folder.
- **Environment Variables:** Use `.env` files for environment-specific configurations. Key variables might include:
- `VITE_API_BASE_URL`: The base URL for your backend API (if applicable).
- `VITE_MAPBOX_TOKEN`: (If using Mapbox for the map component).
- `VITE_AUTH_PROVIDER`: (e.g., 'mock', 'cognito', 'auth0') for authentication.
- **Static Hosting:** The build output is a set of static files (HTML, CSS, JS) suitable for hosting on any static web server (e.g., AWS S3 + CloudFront, Vercel, Netlify, Nginx).
- **Performance Optimizations:**
- Code Splitting: Vite handles this automatically for route-based or component-based splitting.
- Lazy Loading: Implement lazy loading for components and images, especially on the dashboard and map.
- Image Optimization: Ensure images used are appropriately sized and optimized.
- Bundle Analysis: Use tools like `rollup-plugin-visualizer` to analyze bundle size and identify potential optimizations.
- Caching: Implement effective client-side caching strategies for API data where appropriate.
- **CORS:** Ensure your backend API (if separate) is configured to handle Cross-Origin Resource Sharing (CORS) requests from your frontend domain.
- **HTTPS:** Always deploy using HTTPS.