You are an AI assistant tasked with generating a complete, fully functional Next.js MVP application based on the following specifications. The goal is to build a sophisticated SaaS platform that addresses the user problem of 'rent-seeking' by eliminating unnecessary friction in online processes.
1. **PROJECT OVERVIEW**
* **App Name:** Frictionless Flow
* **Problem Solved:** Addresses the 'rent-seeking' issue in the U.S. economy where intermediaries, added friction, and information asymmetry exploit user limitations (time, patience, diligence) to extract value. Examples include third-party reservation platforms, complex insurance quote processes, and time-wasting customer service calls.
* **Value Proposition:** Frictionless Flow is an AI-powered automation platform that streamlines online tasks, removes intermediaries, and provides users with direct access to better prices and services. It saves users time and money by intelligently navigating complex processes and offering optimized solutions.
* **Core Goal:** To create a multi-page, fully functional Next.js application with a robust backend, database integration, user authentication, and a clean, intuitive user interface.
2. **TECH STACK**
* **Framework:** Next.js (App Router)
* **Language:** TypeScript
* **Styling:** Tailwind CSS
* **UI Library:** shadcn/ui (for pre-built, accessible components)
* **Database:** PostgreSQL (via Vercel Postgres or similar)
* **ORM:** Drizzle ORM (for type-safe database interactions)
* **Authentication:** NextAuth.js (with PostgreSQL adapter)
* **State Management:** React Context API / Zustand (for global state)
* **AI Integration:** OpenAI API (or a similar LLM provider) for task understanding and execution logic.
* **Deployment:** Vercel (recommended)
* **Other Packages:** `zod` (for validation), `react-hook-form` (for form management), `clsx` (for conditional class names), `lucide-react` (for icons).
3. **DATABASE SCHEMA**
* **`users` Table:**
* `id`: UUID (Primary Key)
* `name`: VARCHAR
* `email`: VARCHAR (Unique)
* `emailVerified`: TIMESTAMP
* `image`: VARCHAR (Optional)
* `createdAt`: TIMESTAMP (Default: NOW())
* `updatedAt`: TIMESTAMP
* **`accounts` Table:** (For NextAuth.js)
* `id`: BIGSERIAL (Primary Key)
* `userId`: UUID (Foreign Key to `users.id`)
* `type`: VARCHAR
* `provider`: VARCHAR
* `providerAccountId`: VARCHAR
* `refresh_token`: TEXT (Optional)
* `access_token`: TEXT (Optional)
* `expires_at`: BIGINT (Optional)
* `token_type`: VARCHAR (Optional)
* `scope`: VARCHAR (Optional)
* `id_token`: TEXT (Optional)
* `session_state`: VARCHAR (Optional)
* **`sessions` Table:** (For NextAuth.js)
* `id`: BIGSERIAL (Primary Key)
* `sessionToken`: VARCHAR (Unique)
* `userId`: UUID (Foreign Key to `users.id`)
* `expires`: TIMESTAMP
* **`verificationTokens` Table:** (For NextAuth.js)
* `identifier`: VARCHAR
* `token`: VARCHAR
* `expires`: TIMESTAMP
* **`tasks` Table:**
* `id`: UUID (Primary Key)
* `userId`: UUID (Foreign Key to `users.id`)
* `description`: TEXT (User's natural language request)
* `status`: VARCHAR (e.g., 'pending', 'processing', 'completed', 'failed')
* `result`: JSONB (Stores structured results or links)
* `createdAt`: TIMESTAMP (Default: NOW())
* `updatedAt`: TIMESTAMP
* **`task_steps` Table:** (To track detailed progress of a task)
* `id`: UUID (Primary Key)
* `taskId`: UUID (Foreign Key to `tasks.id`)
* `stepDescription`: VARCHAR (e.g., 'Finding best flight option', 'Contacting restaurant', 'Validating user info')
* `status`: VARCHAR (e.g., 'pending', 'in_progress', 'completed', 'failed')
* `details`: JSONB (Optional logs or data specific to the step)
* `createdAt`: TIMESTAMP (Default: NOW())
4. **CORE FEATURES & USER FLOW**
* **Feature 1: User Authentication**
* **Flow:** User lands on the homepage. Clicks 'Sign In' or 'Sign Up'. Presented with options (Google, Email/Password). Upon successful authentication, redirected to the dashboard. 'Sign Out' option available in user dropdown.
* **Details:** Implement email/password signup with verification, and OAuth (Google) via NextAuth.js. Store user data in the `users` table. Associate sessions and accounts.
* **Feature 2: Task Creation**
* **Flow:** Authenticated user navigates to the 'Create Task' page. Enters a natural language request (e.g., "Book a table for 2 at 'Gusto' restaurant for Friday 8 PM, or find the closest alternative if unavailable"). Submits the task. Task status is set to 'pending' and added to the `tasks` table.
* **Details:** Use a `Textarea` or input field. Implement client-side validation (e.g., required field). Upon submission, trigger an API call to `/api/tasks` (POST).
* **Feature 3: AI Task Processing**
* **Flow:** A background job or a server-side process monitors pending tasks. When a new task is detected, its description is sent to the AI (OpenAI API). The AI analyzes the request, breaks it down into actionable steps, identifies necessary information, and potentially interacts with external services (simulated or real APIs).
* **Details:** The `tasks` table `status` is updated to 'processing'. The AI response (structured steps) is saved in `task_steps`. The AI logic should handle identifying the core intent (reservation, quote, etc.) and required parameters. Example AI prompt structure for processing:
```
Analyze the following user request and break it down into specific, actionable steps. Identify the user's intent (e.g., reservation, booking, information gathering, purchase), required entities (e.g., date, time, location, service type, quantity), and potential friction points. If the request involves multiple options or fallback scenarios, outline them clearly. Respond in JSON format with 'intent', 'entities', 'steps' (an array of objects, each with 'action' and 'details'), and 'frictionAnalysis'.
User Request: "{userTaskDescription}"
```
* **Feature 4: Task Monitoring & Results**
* **Flow:** User views their tasks on the Dashboard. Each task shows its current status ('pending', 'processing', 'completed', 'failed'). Upon completion, the 'result' field in the `tasks` table is updated. User can click on a completed task to view detailed results, including confirmation details, links, or any extracted information.
* **Details:** Implement real-time or periodic polling to update task statuses on the frontend. Display `task_steps` for a given task to show granular progress. If a task fails, provide a reason (e.g., AI could not understand, external service error, invalid data).
* **Feature 5: Friction Analysis Dashboard (Future MVP/Iteration)**
* **Flow:** A dedicated section showing aggregated analysis of friction points encountered across all tasks. Suggestions for improving user workflows or highlighting services that are particularly inefficient.
* **Details:** This would involve analyzing the `frictionAnalysis` output from the AI and potentially comparing data across different task types.
5. **API & DATA FETCHING**
* **`POST /api/tasks`:** Create a new task. Request Body: `{ description: string }`. Response: `{ id: string, status: string, createdAt: string }`.
* **`GET /api/tasks`:** Get all tasks for the authenticated user. Response: `Array<{ id: string, description: string, status: string, createdAt: string }>`. Supports filtering by status.
* **`GET /api/tasks/[id]`:** Get details for a specific task, including its steps. Response: `{ id: string, description: string, status: string, createdAt: string, result: any, steps: Array<{ stepDescription: string, status: string, details?: any }> }`.
* **Data Fetching:** Utilize Next.js Server Components for initial data loading where appropriate (e.g., dashboard task list). Use client-side fetching (e.g., `fetch` with SWR or React Query) for dynamic updates or form submissions within client components.
* **Server Actions:** Consider using Server Actions for mutations (like task creation) directly from components for a streamlined data flow.
6. **COMPONENT BREAKDOWN (Next.js App Router Structure)**
* **`app/layout.tsx`:** Root layout (includes Head, Providers, global styles).
* **`app/page.tsx`:** Landing Page (Marketing content, call to action).
* **`app/auth/signin/page.tsx`:** Sign-in page (using NextAuth.js components).
* **`app/(app)/dashboard/page.tsx`:** (Protected Route) Main dashboard displaying user's tasks (list view).
* **`app/(app)/tasks/new/page.tsx`:** (Protected Route) Page for creating a new task (form).
* **`app/(app)/tasks/[id]/page.tsx`:** (Protected Route) Task Detail page, showing status, steps, and results.
* **`app/(app)/settings/page.tsx`:** (Protected Route) User settings page (profile, auth management).
* **`components/ui/`:** Re-export shadcn/ui components (Button, Input, Card, Alert, Table, etc.).
* **`components/layout/`:** `Navbar`, `Footer`, `Sidebar` (if applicable).
* **`components/auth/`:** `SignInForm`, `SignUpForm` components.
* **`components/tasks/`:** `TaskList`, `TaskListItem`, `TaskForm`, `TaskDetailView`, `TaskStepList`.
* **`components/common/`:** `LoadingSpinner`, `AlertMessage`, `Icon`.
* **State Management:** Use `useState`, `useReducer` for local component state. Employ Context API or Zustand for global state like user authentication status and perhaps task lists across different parts of the app.
7. **UI/UX DESIGN & VISUAL IDENTITY**
* **Design Style:** Minimalist Clean with subtle gradient accents.
* **Color Palette:**
* Primary (Dark background): `#1a1a2e`
* Secondary (Accent): `#0077b6` (Vibrant Blue)
* Tertiary (Subtle Gradient): `#48cae4` to `#0077b6`
* Text (Light): `#e0e0e0`
* Muted Text: `#a0a0a0`
* Success: `#28a745`
* Error: `#dc3545`
* **Typography:** A clean sans-serif font family. Use Inter or Poppins for headings and body text.
* Headings: Poppins Bold (e.g., 36px for H1, 24px for H2)
* Body: Inter Regular (e.g., 16px)
* **Layout:** Consistent use of spacing and padding. Utilize a max-width container for content on larger screens. Sidebar for navigation in authenticated sections. Clear visual hierarchy.
* **Responsiveness:** Mobile-first approach. Ensure usability on all screen sizes (smartphones, tablets, desktops). Tailwind CSS's responsive modifiers (`sm:`, `md:`, `lg:`) should be used extensively.
* **Visual Elements:** Subtle use of gradients in buttons or as background accents. Clean icons. Data presented in clear tables or cards.
8. **SAMPLE/MOCK DATA**
* **Task 1 (Pending Reservation):**
* `id`: 'd8e1c2b7-a3f0-4d5e-8c1a-9b0f3e4d5c6b'
* `userId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `description`: 'Book a table for 4 at "The Italian Place" for Saturday 7 PM.'
* `status`: 'pending'
* `createdAt`: '2023-10-27T10:00:00Z'
* **Task 2 (Processing Flight Search):**
* `id`: 'f1e0d9c8-b7a6-4e5d-9c0b-a8f1e0d9c8b7'
* `userId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `description`: 'Find the cheapest round-trip flights from JFK to LHR for next month.'
* `status`: 'processing'
* `createdAt`: '2023-10-27T10:05:00Z'
* **Task 3 (Completed Insurance Quote):**
* `id`: 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d'
* `userId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `description`: 'Get a car insurance quote for a 2022 Toyota Camry, standard coverage.'
* `status`: 'completed'
* `createdAt`: '2023-10-26T15:30:00Z'
* `result`: `{ "provider": "InsureCo", "quoteId": "IC98765", "amount": 1250.50, "currency": "USD", "coverageDetails": "Standard", "link": "/view-quote/IC98765" }`
* **Task 4 (Failed - Ambiguous Request):**
* `id`: 'b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e'
* `userId`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `description`: 'Find something interesting to do.'
* `status`: 'failed'
* `createdAt`: '2023-10-27T11:00:00Z'
* `result`: `{ "error": "Ambiguous request. Please provide more specific details about what you are looking for (e.g., type of activity, location, date)." }`
* **Task 5 (Task Steps for Completed Insurance Quote):**
* `taskId`: 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d'
* `steps`: [
{ `stepDescription`: 'Parse user request for car insurance details', `status`: 'completed', `details`: `{ "vehicle": "Toyota Camry 2022", "coverage": "Standard" }` },
{ `stepDescription`: 'Querying insurance providers API', `status`: 'completed', `details`: `{ "provider_queried": "InsureCo" }` },
{ `stepDescription`: 'Processing quote from InsureCo', `status`: 'completed', `details`: `{ "quoteId": "IC98765", "amount": 1250.50 }` },
{ `stepDescription`: 'Generating confirmation link', `status`: 'completed', `details`: `{ "link": "/view-quote/IC98765" }` }
]
* **User Profile Data:**
* `id`: 'a1b2c3d4-e5f6-7890-1234-567890abcdef'
* `name`: 'Alex Johnson'
* `email`: 'alex.j@example.com'
* `image`: 'https://example.com/path/to/alex.jpg'
9. **ANIMATIONS**
* **Page Transitions:** Subtle fade-in/out transitions between pages using Next.js's built-in features or a library like `Framer Motion`.
* **Button Hover Effects:** Slight scale-up or color change on button hover.
* **Loading States:** Use `shadcn/ui`'s `Skeleton` or `Spinner` components for loading data in tables or cards. Apply subtle animations to loading indicators.
* **Form Transitions:** Smooth transitions when submitting forms or when validation errors appear.
* **Interactive Elements:** Gentle hover effects on list items in the task list.
10. **EDGE CASES & VALIDATION**
* **Auth:** Handle expired sessions, invalid credentials, OAuth errors gracefully. Implement password reset flow for email/password auth.
* **Task Creation:** Validate user input rigorously using `zod` and `react-hook-form`. Handle cases where the AI cannot understand the request (return 'failed' status with a clear error message).
* **API Errors:** Implement global error handling for API routes. Return consistent error formats (e.g., `{ error: { message: string, code: string } }`). Use `try...catch` blocks extensively.
* **Empty States:** Design informative empty states for the dashboard (e.g., "No tasks yet. Create your first task!"), settings, etc.
* **AI Rate Limiting/Errors:** Implement retry mechanisms and circuit breaker patterns for AI API calls. Handle API key issues or service outages.
* **Data Integrity:** Ensure database constraints are met. Use Drizzle ORM's migration tools.
* **User Permissions:** Ensure only authenticated users can access their own data.
**Important:** This prompt is designed to generate a multi-page, interactive Next.js application with a backend, database, authentication, and AI integration. It must not be limited to a single-page application or a mere landing page. The generated code should be production-ready for an MVP. Ensure all Turkish text elements from the user request/concept are translated and incorporated into the UI components and prompts where relevant (e.g., for AI task descriptions if the AI needs to communicate back in Turkish or understand nuanced Turkish requests if applicable in future iterations).