You are an expert AI full-stack developer tasked with creating a single-page application (SPA) for managing energy conservation strategies, inspired by recent news about Asian governments implementing 4-day work weeks and WFH to combat fuel crises. The application will be named 'Enerji Tasarruf Asistanı' (Energy Saving Assistant).
## PROJECT OVERVIEW:
This application aims to empower individuals and organizations to proactively manage their energy consumption in response to fluctuating fuel prices and potential energy crises. It will provide real-time fuel price tracking, personalized conservation strategy recommendations (e.g., WFH, 4-day week suggestions based on crisis alerts), and basic energy usage analysis. The core value proposition is to help users reduce energy costs, minimize environmental impact, and build resilience against energy market volatility. The primary problem addressed is the lack of accessible, actionable, and personalized tools for energy conservation, especially during times of crisis.
## TECH STACK:
- **Frontend Framework:** React (v18+)
- **State Management:** Zustand (lightweight and efficient for SPAs)
- **Styling:** Tailwind CSS (for rapid UI development and utility-first approach)
- **Routing:** React Router DOM (for client-side navigation)
- **Data Fetching:** Axios (for API requests)
- **Charting:** Recharts (for data visualization)
- **Form Handling:** React Hook Form (for efficient form management)
- **Date Handling:** date-fns (modern and modular date utility library)
- **Build Tool:** Vite (for fast development server and build times)
## CORE FEATURES:
1. **Real-time Fuel Price Tracker:**
* **User Flow:** Upon loading the app, the dashboard displays current national and potentially global fuel prices. Users can select specific regions or fuel types to monitor. Prices update automatically at a defined interval (e.g., every 15-30 minutes) or via a manual refresh button.
* **Details:** Fetches data from a reliable public or premium API. Displays price trends (e.g., 24h, 7d, 30d). Allows users to set price alerts for specific thresholds.
2. **Conservation Strategy Recommendations:**
* **User Flow:** Based on global/national energy crisis alerts (potentially triggered by external news feeds or specific API flags) and user-defined profile (e.g., industry, company size, individual), the system suggests actionable conservation measures. Examples include suggesting WFH policies, optimizing travel schedules, recommending a 4-day work week, or promoting public transport. The system will provide estimated savings based on user input or industry benchmarks.
* **Details:** This feature will initially use static recommendation logic triggered by flags. Future iterations could involve more sophisticated AI analysis. For MVP, it will display pre-defined strategies relevant to crisis scenarios.
3. **Basic Energy Usage Analysis:**
* **User Flow:** Users can manually input their primary energy consumption data (e.g., monthly fuel expenses, electricity bills, estimated travel km). The dashboard visualizes this data using charts (e.g., line charts for trends, bar charts for monthly comparisons). The goal is to provide a simple overview of consumption patterns.
* **Details:** Focus on ease of input. Allows input for key metrics like fuel cost, electricity cost, and vehicle mileage. Data is stored locally or in a simple backend for persistence.
4. **Crisis Alert System:**
* **User Flow:** When the system detects a significant fuel price surge or a declared energy crisis event (based on curated news or API data), users receive a prominent notification within the app. Clicking the notification reveals the Crisis Alert details and associated recommended conservation strategies.
* **Details:** Leverages a simplified crisis detection mechanism. Notifications are visually distinct (e.g., red banner, modal). Links directly to relevant recommendations.
5. **Personalized Dashboard:**
* **User Flow:** The main dashboard aggregates key information: current fuel prices, active crisis alerts, personalized recommendations, and a summary of energy usage analysis. Users can potentially reorder or hide certain dashboard widgets.
* **Details:** A clean, modular layout. Prioritizes critical information. Responsive design ensures usability across devices.
## UI/UX DESIGN:
- **Layout:** Single-page application structure. A main navigation sidebar (collapsible on smaller screens) for accessing different sections (Dashboard, Price Tracker, Analysis, Settings). Main content area displays the active section.
- **Color Palette:** Primary: Deep Teal (#008080), Secondary: Soft Gray (#F0F0F0), Accent: Warm Orange (#FFA500) for alerts and calls to action, Text: Dark Gray (#333333). Use shades and tints for depth.
- **Typography:** Use a clean, sans-serif font family like 'Inter' or 'Roboto'. H1/H2 for titles, body text for content. Ensure good readability and contrast.
- **Responsive Design:** Mobile-first approach. Utilize Tailwind's responsive prefixes (sm:, md:, lg:, xl:) extensively. Sidebar becomes a hamburger menu on mobile. Grids adjust dynamically. Ensure touch targets are adequately sized.
- **Interactions:** Subtle hover effects on buttons and cards. Smooth transitions for route changes and modal appearances. Loading spinners or skeleton screens for data fetching.
## COMPONENT BREAKDOWN:
- **`App.jsx`:** Main application component, sets up routing and global layout.
- **`Navigation.jsx`:** Sidebar/header navigation component. Receives `open` state and `setOpen` function.
- **`DashboardPage.jsx`:** Main landing page. Aggregates components like `PriceSummaryCard`, `AlertsBanner`, `RecommendationWidget`, `UsageChartCard`.
- **`PriceTrackerPage.jsx`:** Dedicated page for detailed fuel price tracking. Contains `PriceChart`, `RegionSelector`, `PriceAlerts` components.
- **`AnalysisPage.jsx`:** Page for inputting and viewing energy usage data. Contains `UsageInputForm`, `MonthlyUsageChart`, `FuelCostTrendChart`.
- **`SettingsPage.jsx`:** User settings, profile configuration, alert preferences.
- **`PriceSummaryCard.jsx`:** Displays current national/global fuel prices. Props: `prices` (object).
- **`AlertsBanner.jsx`:** Displays active crisis alerts. Props: `alerts` (array), `onAlertClick` (function).
- **`RecommendationWidget.jsx`:** Shows personalized conservation tips. Props: `recommendations` (array), `estimatedSavings` (string).
- **`UsageChartCard.jsx`:** Wrapper for charts, displays title and potentially controls. Props: `title` (string).
- **`PriceChart.jsx`:** Displays historical price data. Props: `data` (array), `dataKey` (string).
- **`RegionSelector.jsx`:** Dropdown/selector for choosing regions. Props: `regions` (array), `onSelect` (function).
- **`PriceAlerts.jsx`:** Component to set and manage price alerts. Props: `onSetAlert` (function).
- **`UsageInputForm.jsx`:** Form for manual energy data entry. Props: `onSubmit` (function), `initialData` (object).
- **`MonthlyUsageChart.jsx`:** Recharts component for monthly usage trends. Props: `data` (array).
- **`FuelCostTrendChart.jsx`:** Recharts component for fuel cost trends. Props: `data` (array).
- **`LoadingSpinner.jsx`:** Reusable loading indicator.
- **`Notification.jsx`:** Displays transient notifications/alerts.
## DATA MODEL:
- **State Management (Zustand Store):**
```javascript
{
prices: { national: null, regional: {}, global: {} }, // Fuel prices data
alerts: [], // Active crisis alerts
recommendations: [], // Generated conservation strategies
usageData: { monthlyFuelCost: [], monthlyElectricity: [], monthlyKm: [] }, // User's energy usage data
userProfile: { industry: '', country: '', preferences: {} }, // User specific settings
loading: { prices: false, alerts: false, recommendations: false, usage: false }, // Loading states
error: null // Error handling
}
```
- **Mock Data Formats:**
* **Price Data:** `{ date: '2023-10-27T10:00:00Z', value: 1.75 }` (for historical data)
* **Current Price:** `{ name: 'Super Unleaded', price: 1.75, change24h: 0.02, changePercent24h: 1.15 }`
* **Alert:** `{ id: 'alert-123', type: 'crisis', message: 'Major fuel shortage expected due to geopolitical events.', severity: 'high', timestamp: '2023-10-27T09:00:00Z', relatedRecommendations: ['WFH-policy', 'reduce-travel'] }`
* **Usage Entry:** `{ month: '2023-10', fuelCost: 500, electricityCost: 300, kmDriven: 1200 }`
## ANIMATIONS & INTERACTIONS:
- **Hover Effects:** Subtle scaling or background color changes on interactive elements like buttons, cards, and navigation links.
- **Transitions:** Smooth fade-in/fade-out for modals, loading states, and route changes using `Framer Motion` or CSS transitions.
- **Loading States:** Implement `LoadingSpinner` components or skeleton screens while data is being fetched. Disable interactive elements during loading.
- **Micro-interactions:** Visual feedback on form submission (e.g., button changes state), success/error messages appearing smoothly.
## EDGE CASES:
- **Empty States:** Display informative messages and clear calls to action when data is unavailable (e.g., 'No alerts currently active.', 'Enter your first energy usage record to see charts.').
- **Error Handling:** Gracefully handle API errors, network issues, or data parsing errors. Display user-friendly error messages via the `Notification` component. Log errors for debugging.
- **Validation:** Implement client-side validation for all user input forms (e.g., ensuring numbers are entered for costs/distances, valid date formats). Provide clear inline error messages.
- **Accessibility (a11y):** Use semantic HTML5 elements. Ensure sufficient color contrast. Add ARIA attributes where necessary. Ensure keyboard navigation is fully functional. Use `alt` tags for meaningful images.
## SAMPLE DATA:
1. **Current National Fuel Price:**
```json
{ "name": "Benzin (95 Oktan)", "price": 38.50, "currency": "TRY", "change24h": 0.75, "changePercent24h": 1.98 }
```
2. **Historical Price Data (for Charting):
```json
[
{ "date": "2023-10-20", "price": 37.00 },
{ "date": "2023-10-21", "price": 37.50 },
{ "date": "2023-10-22", "price": 37.80 },
{ "date": "2023-10-23", "price": 38.10 },
{ "date": "2023-10-24", "price": 38.50 }
]
```
3. **Active Crisis Alert:**
```json
{
"id": "crisis-a1b2c3d4",
"type": "fuel-shortage-warning",
"message": "Küresel petrol arzında yaşanan kesintiler nedeniyle önümüzdeki 2 hafta içinde yakıt fiyatlarında %15-20 artış ve olası kıtlık beklenmektedir.",
"severity": "high",
"timestamp": "2023-10-27T08:30:00Z",
"source": "Geopolitical Events",
"relatedRecommendations": ["Implement WFH Policy", "Optimize Logistics Routes", "Encourage Public Transport"]
}
```
4. **Sample Recommendation:**
```json
{
"id": "WFH-policy",
"title": "Evden Çalışma Politikasını Uygulayın",
"description": "Haftada en az 2 gün uzaktan çalışmayı teşvik ederek ulaşım kaynaklı yakıt tüketimini azaltın.",
"estimatedSavings": "Aylık %5-10 yakıt maliyeti tasarrufu"
}
```
5. **User's Monthly Usage Data Entry:**
```json
{ "month": "2023-09", "fuelCost": 4500, "electricityCost": 2800, "kmDriven": 1500 }
```
6. **User Profile Sample:**
```json
{ "industry": "Logistics", "country": "Turkey", "preferredUnits": "metric", "alertPreferences": { "priceDrop": true, "crisisWarning": true } }
```
7. **Empty Usage Data State:** `[]` for any usage arrays.
8. **Empty Alerts State:** `[]`.
9. **Error Object:** `{ message: 'Failed to fetch fuel prices. Please try again later.', code: 503 }`
10. **Configuration Setting:** `{ theme: 'dark', language: 'tr', priceUpdateInterval: 30 }`
## DEPLOYMENT NOTES:
- **Build Command:** Use `npm run build` (or `yarn build`) via Vite.
- **Environment Variables:** Configure `VITE_API_KEY` for external data sources (fuel prices, news feeds), `VITE_API_BASE_URL` if using a custom backend. Use `.env` files for local development and CI/CD variables for production.
- **Performance Optimizations:** Code splitting with React Router. Lazy loading components. Optimize image assets. Use `React.memo` and `useCallback` to prevent unnecessary re-renders. Minify JS/CSS during build.
- **HTTPS:** Ensure deployment uses HTTPS for secure data transfer.
- **PWA Considerations:** While not strictly required for MVP, consider adding a manifest file and service worker for basic offline capabilities and installability in future iterations.