# AI Master Prompt: Advanced YouTube Search MVP (Next.js)
## 1. PROJECT OVERVIEW
**Application Name:** TubeFilter (Advanced Tube Search)
**Problem:** YouTube's default search functionality often yields overwhelming or irrelevant results for users seeking specific content. Users struggle to refine their searches effectively, leading to wasted time and frustration.
**Solution:** TubeFilter provides a user-friendly interface that leverages advanced search prefixes and custom filters to significantly improve YouTube search accuracy and efficiency. It empowers users to find exactly what they're looking for quickly, saving them time and enhancing their content discovery experience.
**Core Value Proposition:** Find any YouTube video faster and with pinpoint accuracy. TubeFilter transforms YouTube search from a frustrating chore into a streamlined process, delivering precisely the content you need without the noise.
**Target Users:** General YouTube viewers, researchers, students, content creators, and individuals looking for niche content who are dissatisfied with standard YouTube search results and desire more control over their queries.
## 2. TECH STACK
* **Framework:** Next.js (App Router)
* **Language:** TypeScript
* **Styling:** Tailwind CSS
* **ORM:** Drizzle ORM (PostgreSQL compatible)
* **Database:** PostgreSQL (or compatible, e.g., Vercel Postgres, Neon)
* **UI Components:** shadcn/ui (built on Radix UI and Tailwind CSS)
* **Authentication:** NextAuth.js (or Clerk for easier integration)
* **State Management:** React Context API / Zustand (for global state if needed)
* **API Client:** `fetch` API / Axios
* **Form Handling:** React Hook Form + Zod for validation
* **Deployment:** Vercel (recommended)
* **YouTube API:** Google YouTube Data API v3 (for fetching video data - ensure API key management is secure)
## 3. DATABASE SCHEMA (Drizzle ORM - PostgreSQL)
```sql
-- Users Table (managed by Auth Provider like NextAuth.js or Clerk)
-- Example fields: id, name, email, emailVerified, image
-- Saved Searches Table
CREATE TABLE saved_searches (
id SERIAL PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL, -- User-defined name for the search filter
query_params JSONB NOT NULL, -- Stores all search parameters (keywords, exclude_keywords, channel, min_views, date_after, date_before, etc.)
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- User Preferences Table (Optional, for UI settings like theme, default filters)
CREATE TABLE user_preferences (
id SERIAL PRIMARY KEY,
user_id TEXT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
default_search_params JSONB,
theme VARCHAR(50) DEFAULT 'light',
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- NOTE: The `users` table schema depends heavily on the chosen authentication provider.
-- If using NextAuth.js with default adapter, it will be managed.
-- If using Clerk, their schema applies.
-- For Drizzle, you'd define corresponding TypeScript interfaces.
-- Example Drizzle Schema Representation (TypeScript):
import { pgTable, text, timestamp, jsonb, serial } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// Assuming 'users' table is defined elsewhere based on auth provider
export const savedSearches = pgTable('saved_searches', {
id: serial('id').primaryKey(),
userId: text('user_id').notNull(), // This should match the type from your auth user model
name: text('name').notNull(),
queryParams: jsonb('query_params').notNull(),
createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' }).defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date' }).defaultNow(),
});
// Example relation (if users table is defined in the same schema file)
// export const savedSearchesRelations = relations(savedSearches, ({ one }) => ({
// user: one(users, {
// fields: [savedSearches.userId],
// references: [users.id],
// }),
// }));
```
## 4. CORE FEATURES & USER FLOW
**Feature 1: Advanced Search Form**
* **User Flow:**
1. User navigates to the "Search" page.
2. The page displays a comprehensive form with fields for:
* Keywords (required)
* Exclude Keywords (optional, multiple allowed)
* Channel Name/ID (optional)
* Minimum Views (optional, number input)
* Maximum Views (optional, number input)
* Published After (optional, date picker)
* Published Before (optional, date picker)
* Video Duration (e.g., Short, Medium, Long - dropdown)
* Video Type (e.g., Live, Premiere - checkbox/multi-select)
3. User fills in desired criteria.
4. User clicks the "Search" button.
5. Frontend constructs the appropriate Google YouTube Data API v3 query parameters based on the form inputs.
6. The application sends a request to its own API endpoint (e.g., `/api/youtube/search`).
7. The backend API calls the YouTube Data API v3 with the constructed parameters.
8. The backend API returns the search results to the frontend.
9. Search results are displayed on the "Results" page.
* **Edge Cases:** Invalid input (e.g., non-numeric views), no keywords entered, API rate limits exceeded, no results found.
**Feature 2: Save Search Filters**
* **User Flow:**
1. After performing a search or while on the search form, the user sees a "Save Search" button.
2. Clicking "Save Search" opens a modal or navigates to a form to name the search filter.
3. User enters a descriptive name (e.g., "Latest Tech Reviews") and clicks "Save".
4. Frontend sends the current form parameters and the name to the `/api/saved-searches` endpoint.
5. Backend validates and saves the search parameters (`queryParams`) and name to the `saved_searches` table, associated with the logged-in `user_id`.
6. Upon successful save, a confirmation message is shown.
* **Edge Cases:** Duplicate search name (prompt user to rename or overwrite), failed save operation, user not logged in.
**Feature 3: Saved Searches Management**
* **User Flow:**
1. User navigates to a "My Saved Searches" page (accessible from dashboard or navigation).
2. The page fetches the user's saved searches from `/api/saved-searches`.
3. Saved searches are displayed as a list (e.g., cards or table rows), showing the name and potentially a summary of the parameters.
4. Each saved search has options to:
* "Load & Search": Populates the advanced search form with these parameters and initiates a search.
* "Edit": Opens the modal/form to rename or modify the search parameters.
* "Delete": Removes the saved search from the database.
* **Edge Cases:** No saved searches found, error fetching saved searches, deleting a search.
**Feature 4: Search Results Display & Actions**
* **User Flow:**
1. The "Results" page displays videos returned from the YouTube API.
2. Each video item includes:
* Thumbnail
* Title (clickable, links to YouTube)
* Channel Name (clickable, links to channel)
* View Count
* Published Date
* Video Duration
3. Checkboxes are available next to each video.
4. A "Play Selected" button appears when one or more videos are selected.
5. Clicking "Play Selected" will potentially open a modal with these videos queued in an embedded YouTube player, or redirect to YouTube playlists.
6. A "Add to Playlist" button (requires YouTube OAuth or manual copying).
* **Edge Cases:** Videos removed from YouTube, API errors, empty search results, handling many results (pagination).
**Authentication Flow:**
1. User visits the site.
2. If not logged in, core search functionality might be limited (e.g., can't save searches). A "Sign In / Sign Up" prompt is visible.
3. User clicks "Sign In", redirected to authentication provider's page (e.g., Google, GitHub via NextAuth.js).
4. User authenticates.
5. User is redirected back to the application.
6. Protected routes (like "My Saved Searches") are now accessible.
7. User's `userId` is available globally for database operations.
## 5. API & DATA FETCHING
* **`/api/youtube/search` (POST):**
* **Request Body:** `{ queryParams: { keywords: string, excludeKeywords?: string[], channel?: string, minViews?: number, dateAfter?: string, ... } }`
* **Response Body (Success):** `{ videos: YouTubeVideo[] }` where `YouTubeVideo` is a structured object containing video details (id, title, channel, views, publishedAt, etc.).
* **Response Body (Error):** `{ error: string }`
* **Logic:** Validates input, constructs YouTube API request, handles API key securely (server-side), calls YouTube API, parses response, returns structured video data.
* **`/api/saved-searches` (GET):**
* **Request Body:** None (uses logged-in user's ID)
* **Response Body (Success):** `{ searches: SavedSearch[] }` where `SavedSearch` includes id, name, queryParams.
* **Logic:** Fetches saved searches for the authenticated user from the `saved_searches` table.
* **`/api/saved-searches` (POST):**
* **Request Body:** `{ name: string, queryParams: object }`
* **Response Body (Success):** `{ message: 'Search saved successfully' }` or the saved search object.
* **Logic:** Saves a new search filter for the authenticated user.
* **`/api/saved-searches/[id]` (PUT/PATCH):**
* **Request Body:** `{ name?: string, queryParams?: object }`
* **Response Body (Success):** `{ message: 'Search updated successfully' }`
* **Logic:** Updates an existing saved search for the authenticated user.
* **`/api/saved-searches/[id]` (DELETE):**
* **Request Body:** None
* **Response Body (Success):** `{ message: 'Search deleted successfully' }`
* **Logic:** Deletes a saved search for the authenticated user.
**Data Fetching:** Use server components for initial data loads where possible (e.g., user's saved searches on dashboard). Use client components with `useEffect` or libraries like SWR/React Query for dynamic data fetching (e.g., search results, form state updates).
## 6. COMPONENT BREAKDOWN (Next.js App Router)
* **`app/layout.tsx`:** Root layout, includes `<html>`, `<body>`, global providers (e.g., theme provider, auth provider), global styles, and Tailwind CSS setup.
* **`app/page.tsx`:** Homepage. Features a prominent search bar (linking to the main search page) and possibly highlights "Saved Searches" for logged-in users.
* **`app/(app)/search/page.tsx`:** The main Advanced Search page. Contains the `AdvancedSearchForm` component.
* **`components/AdvancedSearchForm.tsx`:** The core form component. Manages form state (using React Hook Form), validation (Zod), and handles input changes. Includes all filter fields. Has "Search" and "Save Search" buttons.
* **`components/SaveSearchModal.tsx`:** Modal for naming and saving a search. Triggered by "Save Search" button.
* **`app/(app)/results/page.tsx`:** Displays search results.
* **`components/SearchResultsList.tsx`:** Renders the list of videos fetched from the API. Displays each video item.
* **`components/SearchResultItem.tsx`:** Represents a single video in the results list. Includes thumbnail, title, channel, views, date, duration, and a checkbox.
* **`components/PlaySelectedButton.tsx`:** Button to handle playing selected videos.
* **`app/(app)/saved-searches/page.tsx`:** Page to manage saved searches.
* **`components/SavedSearchList.tsx`:** Fetches and displays the list of saved searches.
* **`components/SavedSearchItem.tsx`:** Represents a single saved search with "Load", "Edit", and "Delete" actions.
* **`app/api/youtube/search/route.ts`:** API route for handling YouTube searches.
* **`app/api/saved-searches/route.ts`:** API route for CRUD operations on saved searches.
* **`app/auth/[...nextauth]/route.ts` (or similar for Clerk):** Authentication route handler.
* **`components/ui/button.tsx`, `components/ui/input.tsx`, `components/ui/card.tsx`, etc.:** Re-exported components from `shadcn/ui`.
* **`lib/db.ts`:** Drizzle ORM instance and database connection setup.
* **`lib/schemas.ts`:** Zod validation schemas.
* **`lib/youtube.ts`:** Utility functions for interacting with the YouTube API.
* **`lib/auth.ts`:** Auth configuration and options for NextAuth.js.
## 7. UI/UX DESIGN & VISUAL IDENTITY
* **Design Style:** Minimalist Clean with subtle interactive elements.
* **Color Palette:**
* Primary (Brand): Deep Blue (`#1A237E`)
* Secondary (Accents/Interactive): Teal (`#00ACC1`)
* Background: Light Gray (`#F5F5F5`)
* Surface/Card Background: White (`#FFFFFF`)
* Text (Primary): Dark Gray (`#333333`)
* Text (Secondary): Medium Gray (`#757575`)
* Success/Confirmation: Green (`#4CAF50`)
* Error/Alert: Red (`#F44336`)
* **Typography:**
* Headings: Poppins (Bold, Semi-Bold)
* Body Text: Inter (Regular, Medium)
* **Layout:**
* Generous whitespace.
* Clear visual hierarchy.
* Sticky header/navbar for navigation and potentially search access.
* Main content area for forms and results.
* Responsive design: Mobile-first approach, adapting to tablet and desktop gracefully.
* **UI Elements:**
* `shadcn/ui` components for consistency.
* Clean input fields with clear labels.
* Intuitive date pickers.
* Clear buttons with hover states.
* Loading spinners/skeletons for data fetching.
* Visually distinct "Save Search" and "Load Search" actions.
## 8. SAMPLE/MOCK DATA
**Sample Saved Search (`queryParams` JSON):**
```json
{
"keywords": "Next.js tutorial",
"excludeKeywords": ["deprecated", "old version"],
"channel": "Fireship",
"minViews": 10000,
"publishedAfter": "2023-01-01T00:00:00Z",
"duration": "medium"
}
```
**Sample YouTube Search Results (`YouTubeVideo[]`):
```javascript
[
{
"id": "dQw4w9WgXcQ",
"title": "Next.js 13 Full Course - Build a Complete App",
"channelTitle": "Codevolution",
"viewCount": 1500000,
"publishedAt": "2023-05-15T10:00:00Z",
"thumbnailUrl": "https://i.ytimg.com/vi/dQw4w9WgXcQ/default.jpg",
"duration": "PT1H30M"
},
{
"id": "abcdef12345",
"title": "5 Essential Next.js Features for 2024",
"channelTitle": "Traversy Media",
"viewCount": 85000,
"publishedAt": "2023-11-20T14:30:00Z",
"thumbnailUrl": "https://i.ytimg.com/vi/abcdef12345/default.jpg",
"duration": "PT15M"
},
{
"id": "xyz7890",
"title": "Deploying Next.js Apps with Vercel",
"channelTitle": "Vercel",
"viewCount": 250000,
"publishedAt": "2023-08-01T09:00:00Z",
"thumbnailUrl": "https://i.ytimg.com/vi/xyz7890/default.jpg",
"duration": "PT25M"
}
]
```
## 9. TURKISH TRANSLATIONS
* **App Title:** TubeFilter (Gelişmiş Tüp Araması)
* **Search Page Title:** Gelişmiş Arama
* **Keywords:** Anahtar Kelimeler
* **Exclude Keywords:** Hariç Tutulacak Kelimeler
* **Channel:** Kanal Adı/ID
* **Min. Views:** Min. Görüntülenme
* **Published After:** Yayınlanma Tarihi Sonrası
* **Published Before:** Yayınlanma Tarihi Öncesi
* **Duration:** Süre
* **Search:** Ara
* **Save Search:** Aramayı Kaydet
* **Saved Searches:** Kaydedilen Aramalar
* **Load Search:** Aramayı Yükle
* **Edit:** Düzenle
* **Delete:** Sil
* **Results:** Sonuçlar
* **No results found:** Sonuç bulunamadı.
* **Sign In:** Giriş Yap
* **Sign Up:** Kayıt Ol
* **Settings:** Ayarlar
* **My Account:** Hesabım
* **Loading...:** Yükleniyor...
* **Clear Filters:** Filtreleri Temizle
* **Play Selected:** Seçilenleri Oynat
* **Add to Playlist:** Listeye Ekle
## 10. ANIMATIONS
* **Page Transitions:** Subtle fade-in/slide-in animations for page navigations using Next.js's built-in features or libraries like `Framer Motion`.
* **Button Hovers:** Slight scale-up or background color change on interactive elements.
* **Loading States:** Use `shadcn/ui`'s skeleton loaders or a simple `Spinner` component with CSS transitions while data is being fetched.
* **Form Input Focus:** Subtle border highlight or shadow effect when an input field is focused.
* **Save/Delete Confirmation:** Toast notifications with slide-in/fade-out animations.
## 11. EDGE CASES & VALIDATION
* **Input Validation:** Use Zod schemas with React Hook Form to validate all form inputs in real-time (e.g., ensure numbers are numbers, dates are valid formats, required fields are filled).
* **API Errors:** Implement robust error handling for both the backend API and the YouTube API calls. Display user-friendly error messages (e.g., "Could not fetch videos. Please try again later.", "YouTube API limit reached.").
* **No Results:** Display a clear message and suggestions (e.g., "Try adjusting your search terms or filters") when no videos match the criteria.
* **Empty States:** Design specific UI states for when there are no saved searches, no recent activity, etc.
* **Authentication:** Gracefully handle scenarios where a user is logged out unexpectedly or attempts to access protected routes without logging in. Redirect to login or show an appropriate message.
* **YouTube API Quotas:** Monitor API usage. Implement caching where feasible. Consider strategies for handling quota exhaustion (e.g., temporarily disabling search, prompting users about limits).
* **Deleted Videos:** Handle cases where a video in the search results might have been removed from YouTube by the time the user clicks on it.