## AI Master Prompt: EcoRefresh - Next.js MVP Application
**PROJECT OVERVIEW:**
EcoRefresh is a comprehensive SaaS platform designed to empower users and businesses with intelligent battery life optimization for laptops, primarily by leveraging and managing the capabilities of advanced display technologies like LG's Oxide 1Hz panels. The core problem it solves is the significant battery drain caused by high display refresh rates on modern laptops, which often outpace processing power as the main battery consumer. EcoRefresh provides users with tools to analyze their current battery performance, control their display's refresh rate for optimal power efficiency, and offers insights into laptops that utilize cutting-edge, battery-saving display technologies. For businesses, it offers data-driven insights and consulting for energy efficiency and cost savings. The core value proposition is extended laptop battery life, improved user productivity, and reduced energy consumption.
**TECH STACK:**
- **Frontend Framework:** React (Next.js 14 with App Router)
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL compatibility)
- **Database:** PostgreSQL
- **Authentication:** NextAuth.js (Credentials Provider initially, potentially OAuth later)
- **UI Component Library:** shadcn/ui (built on Radix UI and Tailwind CSS)
- **State Management:** React Context API / Zustand (for global state if needed)
- **Data Fetching:** React Server Components (RSC), Client Components with `fetch`, Server Actions
- **Form Handling:** React Hook Form
- **Validation:** Zod
- **Charting:** Recharts or Chart.js (for battery performance visualization)
- **Deployment:** Vercel (recommended)
**DATABASE SCHEMA:**
1. **`users` Table:**
* `id` (UUID, Primary Key)
* `name` (VARCHAR)
* `email` (VARCHAR, Unique)
* `emailVerified` (TIMESTAMP, Nullable)
* `image` (VARCHAR, Nullable)
* `hashedPassword` (VARCHAR, Nullable) - For credentials provider
* `createdAt` (TIMESTAMP, Default: now())
* `updatedAt` (TIMESTAMP, Default: now())
2. **`accounts` Table (for NextAuth.js):**
* `id` (VARCHAR, Primary Key)
* `userId` (UUID, Foreign Key to `users.id`)
* `type` (VARCHAR) - e.g., 'oauth', 'credentials'
* `provider` (VARCHAR)
* `providerAccountId` (VARCHAR)
* `refresh_token` (TEXT, Nullable)
* `access_token` (TEXT, Nullable)
* `expires_at` (BIGINT, Nullable)
* `token_type` (VARCHAR, Nullable)
* `scope` (VARCHAR, Nullable)
* `id_token` (TEXT, Nullable)
* `session_state` (VARCHAR, Nullable)
3. **`sessions` Table (for NextAuth.js):**
* `sessionToken` (VARCHAR, Primary Key)
* `userId` (UUID, Foreign Key to `users.id`)
* `expires` (TIMESTAMP)
4. **`verificationTokens` Table (for NextAuth.js):**
* `identifier` (VARCHAR)
* `token` (VARCHAR)
* `expires` (TIMESTAMP)
5. **`laptops` Table:**
* `id` (UUID, Primary Key)
* `brand` (VARCHAR, Not Null)
* `model` (VARCHAR, Not Null)
* `cpu` (VARCHAR)
* `ram_gb` (INTEGER)
* `storage_gb` (INTEGER)
* `display_tech` (VARCHAR, e.g., 'IPS', 'OLED', 'Oxide 1Hz')
* `display_size_inches` (DECIMAL(3, 1))
* `native_refresh_rate_max_hz` (INTEGER)
* `battery_capacity_wh` (INTEGER)
* `base_battery_life_hours` (DECIMAL(3, 1))
* `description` (TEXT)
* `imageUrl` (VARCHAR, Nullable)
* `releaseYear` (INTEGER, Nullable)
* `createdAt` (TIMESTAMP, Default: now())
* `updatedAt` (TIMESTAMP, Default: now())
6. **`user_laptop_profiles` Table:**
* `id` (UUID, Primary Key)
* `userId` (UUID, Foreign Key to `users.id`)
* `laptopId` (UUID, Foreign Key to `laptops.id`)
* `customName` (VARCHAR, Nullable)
* `os` (VARCHAR)
* `typical_usage` (TEXT, e.g., 'Web browsing, video streaming, light office work')
* `current_refresh_rate_hz` (INTEGER, Default: 60)
* `custom_battery_life_hours` (DECIMAL(3, 1), Nullable)
* `last_analysis_date` (TIMESTAMP, Nullable)
* `createdAt` (TIMESTAMP, Default: now())
* `updatedAt` (TIMESTAMP, Default: now())
7. **`optimization_logs` Table:**
* `id` (UUID, Primary Key)
* `userLaptopProfileId` (UUID, Foreign Key to `user_laptop_profiles.id`)
* `settingChanged` (VARCHAR, e.g., 'refresh_rate')
* `oldValue` (VARCHAR)
* `newValue` (VARCHAR)
* `timestamp` (TIMESTAMP, Default: now())
* `estimated_impact_percent` (DECIMAL(5, 2), Nullable) - Estimated battery life improvement
8. **`articles` Table:**
* `id` (UUID, Primary Key)
* `title` (VARCHAR, Not Null)
* `slug` (VARCHAR, Unique, Not Null)
* `content` (TEXT, Not Null)
* `authorId` (UUID, Foreign Key to `users.id`, Nullable for guest authors)
* `publishedAt` (TIMESTAMP, Nullable)
* `tags` (VARCHAR[], Nullable)
* `createdAt` (TIMESTAMP, Default: now())
* `updatedAt` (TIMESTAMP, Default: now())
**CORE FEATURES & USER FLOW:**
1. **User Authentication:**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Login'. Redirected to Auth page. User enters email/password or uses OAuth (Google/GitHub later). Upon successful login, redirected to their Dashboard. If sign up, email verification flow is triggered. JWT stored in HttpOnly cookie.
* **Edge Cases:** Invalid credentials, email already exists, password reset flow.
2. **Dashboard (`/dashboard`)**:
* **Flow:** Authenticated users land here. Displays a summary of their current laptop profile (if set up), estimated battery life, recent optimizations, and quick links to key features. If no profile, prompts to add one.
* **Components:** Welcome message, Laptop Summary Card, Quick Actions buttons.
3. **Add/Manage Laptop Profile (`/dashboard/laptops` or modal):**
* **Flow:** User navigates to 'My Laptops'. Clicks 'Add New Laptop'. Selects from a pre-populated list (via `laptops` table) or enters details manually. If selecting from list, they can set a `customName`, `os`, `typical_usage`, and initial `current_refresh_rate_hz`. If the selected laptop supports dynamic refresh rate adjustment, the UI indicates this.
* **Components:** Searchable laptop database dropdown/list, Manual entry form, Profile configuration form.
* **Validation:** Zod validation for all form fields.
4. **Battery Analysis (`/dashboard/analyze/{profileId}`):**
* **Flow:** User selects a laptop profile and clicks 'Analyze Battery'. The system simulates or uses heuristics based on `typical_usage` and `current_refresh_rate_hz` to estimate current battery life. It compares this to a baseline (e.g., max refresh rate or a default setting). Displays results using charts and key metrics (e.g., 'Estimated Battery Life: X hours', 'Potential Gain: Y%'). Records the analysis in `optimization_logs`.
* **Components:** Analysis result cards, Performance charts (Recharts), Explanation text.
* **Backend Logic:** Server Action/API route to perform calculations based on laptop specs, usage patterns, and refresh rate.
5. **Refresh Rate Control (`/dashboard/control/{profileId}`):**
* **Flow:** If the user's laptop model is identified as supporting dynamic refresh rate control (e.g., via integrated OS features or manufacturer software, *this part requires OS-level integration or user confirmation of manual changes*), this section allows adjustment. User selects a desired refresh rate (e.g., 60Hz, 120Hz, or 'Adaptive'). The system attempts to apply this setting (requires backend logic that might interact with OS APIs if possible, or guides the user on manual steps). Logs the change and its estimated impact.
* **Caveat:** Direct OS-level control is complex and may not be feasible in a standard web app. MVP might focus on *guiding* the user or logging *their* manual changes and their perceived impact. A more advanced version might integrate with specific vendor SDKs.
* **Components:** Slider or dropdown for refresh rate, 'Apply Setting' button, Estimated impact display.
6. **Technology Guide (`/guide`):**
* **Flow:** Publicly accessible page. Lists laptops featuring advanced display tech (like Oxide 1Hz). Users can filter/sort by brand, tech, battery life. Each laptop has a detail page with specs and estimated benefits.
* **Components:** Filterable/Sortable Data Table (for `laptops`), Laptop Card components, Detail Page.
7. **Blog/Articles (`/blog`):**
* **Flow:** Displays a list of articles (`articles` table). Clicking an article shows its content. Primarily for SEO and content marketing about battery optimization, display tech, etc.
* **Components:** Article list view, Article detail view.
**API & DATA FETCHING:**
- Utilize Next.js App Router's data fetching capabilities (Server Components, Server Actions, Route Handlers).
- **Auth Endpoints:** Handled by NextAuth.js (`/api/auth/...`).
- **CRUD Operations:** Use Server Actions for mutations (POST, PUT, DELETE) on `user_laptop_profiles`, `optimization_logs`.
- **Data Fetching:** Use RSCs for initial page data (`laptops`, `articles`, user profile summary). Use client-side fetching (e.g., within `useEffect` or via form actions) for dynamic updates in interactive components.
- **Example API Route (Route Handler):** `app/api/laptops/route.ts` for fetching laptop data (GET).
- **Example Server Action:** `async function addLaptopProfile(data)` for handling form submission in 'Add Laptop Profile'.
- **Data Flow:** Server Components fetch data directly from DB using Drizzle ORM. Client Components can trigger Server Actions or call Route Handlers for data modifications or fetching specific subsets of data. Data is passed as props down to components.
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** Minimalist Clean with subtle gradient accents.
- **Color Palette:**
- Primary: `#007AFF` (Vibrant Blue)
- Secondary: `#646EE4` (Softer Purple/Blue)
- Accent/Gradient: `linear-gradient(135deg, #007AFF 0%, #646EE4 100%)`
- Background: `#F9FAFB` (Light Gray)
- Card Background: `#FFFFFF` (White)
- Text (Dark): `#1F2937` (Dark Gray)
- Text (Light): `#FFFFFF`
- Success: `#10B981` (Green)
- Warning: `#F59E0B` (Amber)
- Error: `#EF4444` (Red)
- **Typography:** Inter (Sans-serif) - Headings: Semi-bold, Body: Regular.
- **Layout:** Utilize a responsive grid system (Tailwind CSS). Fixed sidebar navigation for logged-in users, horizontal navigation for public pages. Max-width container for content.
- **Responsiveness:** Mobile-first approach. Ensure usability on various screen sizes. Sidebar collapses into a hamburger menu on smaller screens.
- **Visual Elements:** Clean icons, subtle shadows for cards, smooth transitions.
**COMPONENT BREAKDOWN (Next.js App Router Structure):**
- **`app/`**
- **`layout.tsx`**: Root layout (includes global styles, providers).
- **`page.tsx`**: Public landing page.
- **`auth/`**
- **`layout.tsx`**: Auth-specific layout.
- **`sign-in/page.tsx`**: Sign-in form component.
- **`sign-up/page.tsx`**: Sign-up form component.
- **`dashboard/`**
- **`layout.tsx`**: Dashboard layout (includes sidebar, protected route handling).
- **`page.tsx`**: Main dashboard summary.
- **`laptops/`**
- **`page.tsx`**: List of user's laptop profiles.
- **`[profileId]/`**
- **`page.tsx`**: Profile detail view (Analysis, Control).
- **`edit/page.tsx`**: Edit profile form.
- **`analyze/page.tsx`**: Global analysis tool (without specific profile).
- **`guide/page.tsx`**: Technology Guide page.
- **`blog/`**
- **`page.tsx`**: Blog post listing.
- **`[slug]/page.tsx`**: Individual blog post page.
- **`api/`**
- **`auth/[...nextauth]/route.ts`**: NextAuth.js handler.
- **`laptops/route.ts`**: Route handler for fetching laptop data.
- **`webhook/stripe/route.ts`**: (Future) Stripe webhook handler.
- **`components/`**
- **`ui/`**: Re-exported shadcn/ui components (Button, Input, Card, Sheet, Dialog, Table, etc.).
- **`AuthButton.tsx`**: Sign in/out button.
- **`Sidebar.tsx`**: Navigation sidebar for dashboard.
- **`LaptopCard.tsx`**: Displays summary of a laptop profile.
- **`AnalysisChart.tsx`**: Component using Recharts for data visualization.
- **`DeviceSelector.tsx`**: Dropdown/search for selecting laptops.
- **`DataLoader.tsx`**: Component to handle loading states gracefully.
- **`ErrorMessage.tsx`**: Displays validation or API errors.
- **`Footer.tsx`**: Site footer.
- **`Navbar.tsx`**: Public site navigation bar.
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/out using Next.js's built-in capabilities or a library like `Framer Motion` (optional, for more advanced transitions).
- **Hover Effects:** Gentle scaling or background color changes on buttons and interactive elements using Tailwind CSS `hover:` states.
- **Loading States:** Skeleton loaders (using `Card` or `Skeleton` components) for data fetching. Spinner animations within buttons during submission.
- **Transitions:** Smooth transitions for expanding/collapsing elements (e.g., accordions, dropdowns) using Tailwind CSS `transition` utilities.
**EDGE CASES:**
- **Empty States:** Display user-friendly messages and clear calls to action when lists are empty (e.g., 'No laptops added yet. Add your first laptop profile!').
- **Authentication:** Protect dashboard routes. Redirect unauthenticated users to sign-in. Handle session expiry and re-authentication.
- **Authorization:** Ensure users can only access and modify their own data.
- **Error Handling:** Implement global error handling for API routes. Display clear, user-friendly error messages for form validation, network issues, and server errors. Use `try...catch` blocks in Server Actions and API routes.
- **Validation:** Comprehensive client-side and server-side validation using Zod for all user inputs.
- **Responsiveness:** Ensure all components adapt gracefully to different screen sizes.
- **Dark Mode:** (Future Enhancement) Implement theme switching.
- **Unsupported Hardware:** Clearly communicate when dynamic refresh rate control isn't supported for a user's specific hardware/OS combination.
**SAMPLE/MOCK DATA:**
1. **`laptops` Table Example:**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"brand": "Dell",
"model": "XPS 15 (2023)",
"cpu": "Intel Core i7-13700H",
"ram_gb": 16,
"storage_gb": 512,
"display_tech": "OLED Oxide 1Hz",
"display_size_inches": 15.6,
"native_refresh_rate_max_hz": 120,
"battery_capacity_wh": 80,
"base_battery_life_hours": 10.5,
"description": "High-performance laptop featuring LG's latest 1Hz OLED display technology for exceptional battery life.",
"imageUrl": "/images/dell-xps-15.jpg",
"releaseYear": 2023
}
```
```json
{
"id": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"brand": "Apple",
"model": "MacBook Pro 14" (M2 Pro)",
"cpu": "Apple M2 Pro",
"ram_gb": 16,
"storage_gb": 512,
"display_tech": "Liquid Retina XDR (Mini-LED)",
"display_size_inches": 14.2,
"native_refresh_rate_max_hz": 120,
"battery_capacity_wh": 70,
"base_battery_life_hours": 15.0,
"description": "Powerful and efficient MacBook Pro with a ProMotion display.",
"imageUrl": "/images/mbp-14-m2.jpg",
"releaseYear": 2023
}
```
2. **`user_laptop_profiles` Table Example:**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"userId": "user-uuid-1234",
"laptopId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"customName": "My XPS Workhorse",
"os": "Windows 11 Pro",
"typical_usage": "Web development, VS Code, Docker, Chrome (10+ tabs), occasional video calls",
"current_refresh_rate_hz": 120,
"custom_battery_life_hours": 6.5,
"last_analysis_date": "2024-07-26T10:00:00Z"
}
```
3. **`optimization_logs` Table Example:**
```json
{
"id": "log-uuid-001",
"userLaptopProfileId": "123e4567-e89b-12d3-a456-426614174000",
"settingChanged": "refresh_rate",
"oldValue": "120Hz",
"newValue": "60Hz",
"timestamp": "2024-07-26T11:30:00Z",
"estimated_impact_percent": 25.5
}
```
4. **`articles` Table Example:**
```json
{
"id": "article-uuid-001",
"title": "Understanding Laptop Display Refresh Rates and Battery Life",
"slug": "understanding-refresh-rates-battery-life",
"content": "<p>A deep dive into how display refresh rates affect power consumption...</p>",
"publishedAt": "2024-07-20T09:00:00Z",
"tags": ["battery", "display", "optimization", "tech"]
}
```
```json
{
"id": "article-uuid-002",
"title": "LG's Oxide 1Hz Technology: A Game Changer?",
"slug": "lg-oxide-1hz-game-changer",
"content": "<p>Exploring the impact of LG's new display tech...</p>",
"publishedAt": "2024-07-22T14:00:00Z",
"tags": ["LG Display", "OLED", "battery", "innovation"]
}
```
5. **User Data Example (for testing auth):**
```json
{
"id": "user-uuid-1234",
"name": "Ali Veli",
"email": "ali.veli@example.com",
"image": null
}
```
This prompt provides a detailed blueprint for building a functional MVP of EcoRefresh using modern Next.js practices. It covers the tech stack, database structure, core user flows, API design, UI/UX considerations, and necessary mock data, aiming for a robust and scalable application foundation.