# PokeVerse - Pokémon Encyclopedia (Full Documentation) This is a comprehensive technical overview of the PokeVerse Pokémon encyclopedia web application built with modern web technologies. ## Project Overview A Next.js 15 application that provides detailed information about Pokémon species, types, abilities, and evolution chains using the PokéAPI as the data source. Features include daily Pokémon discovery, random exploration, type system analysis, comprehensive search functionality, educational guides, and full Progressive Web App capabilities. ## Technology Stack - **Framework**: Next.js 15 with App Router pattern - **Language**: TypeScript with strict type checking - **Styling**: Tailwind CSS v4 with custom design system - **Internationalization**: next-intl v4.4.0 for comprehensive multilingual support (en, ja, pt-BR, roomaji) - **Authentication**: Supabase Auth with Google OAuth integration - **Database**: Supabase (PostgreSQL) with Row Level Security (RLS) - **Data Source**: PokéAPI (https://pokeapi.co/api/v2/) - **Image Optimization**: Next.js Image component with CDN fallbacks - **State Management**: React hooks and context (no external state library) - **Build Tool**: Turbopack for development performance - **PWA**: Progressive Web App with service worker and offline support - **Package Manager**: pnpm (preferred) or npm - **Testing**: Jest (tests in `src/lib/__tests__/`) - **Linting**: ESLint with Next.js configuration - **Performance**: Web Vitals monitoring and optimization - **Deployment**: Cloudflare Pages with Edge Runtime compatibility ## Architecture ### Core Architecture **API Integration**: Uses PokeAPI (https://pokeapi.co/api/v2) as the data source with comprehensive error handling and fallback mechanisms in `src/lib/api.ts`. The app handles network failures gracefully and provides detailed error messages through the custom `PokemonApiError` class. **Type System**: Complete TypeScript definitions in `src/types/pokemon.ts` covering both PokeAPI raw responses and normalized application data structures. Includes component props, hook return types, and error interfaces for all 18 Pokémon types. **Data Flow**: - API layer (`src/lib/api.ts`) handles all external data fetching with comprehensive error handling - Custom hooks (`src/hooks/`) manage state and data fetching logic: - `usePokemon` - Pokemon list data fetching with pagination - `usePokemonDetail` - Individual Pokemon details with species info - `useDailyPokemon` - Deterministic daily Pokemon generation using user fingerprinting - `useRandomPokemon` - Random Pokemon discovery - Components consume data through these hooks for separation of concerns **PWA Support**: Full Progressive Web App implementation with: - Service Worker (`public/sw.js`) for offline caching of API data, images, and pages - Web App Manifest (`src/app/manifest.ts`) with app icons, shortcuts, and install prompts - Offline page (`src/app/offline/page.tsx`) for graceful degradation - Background sync and push notification infrastructure **Theme System**: Uses a custom ThemeProvider for dark/light mode switching with system preference detection and persistence. **Internationalization (i18n)**: Built with next-intl for comprehensive multilingual support: - Middleware-based locale routing with 'as-needed' prefix strategy (English without prefix, other locales with prefix) - Supported locales: English (en), Japanese (ja), Portuguese Brazilian (pt-BR), Romaji (roomaji) - Dynamic route structure using `[locale]` segment for all pages - Translation message loading from `/messages/{locale}.json` (438+ keys per locale) - PokeAPI data translation helpers (`type-translations.ts`, `ability-translations.ts`) - Extracts localized names, types, abilities, and effects from PokeAPI responses - Automatic fallback to English for missing translations - SEO-optimized with locale-specific metadata and Open Graph tags - Custom middleware integration with Supabase auth, CSP headers, and nonce generation ### Key Features **Multilingual Support**: Full internationalization with 4 languages using next-intl v4.4.0: - Supported locales: English (en), Japanese (ja), Portuguese Brazilian (pt-BR), Romaji (roomaji) - Clean URL structure with 'as-needed' locale prefix strategy (en without prefix, others with prefix) - 438+ translation keys covering all UI strings, navigation, errors, and content - PokeAPI multilingual data integration for Pokémon names, types, abilities, and descriptions - Translation helper functions for seamless data localization - Locale-specific SEO metadata and social sharing optimization - Language switcher in navigation for easy locale switching **Authentication & User Management**: Full Supabase integration for user authentication and data persistence: - Google OAuth sign-in with profile picture and display name support - User profiles stored in Supabase with avatar URLs, theme preferences, and metadata - Row Level Security (RLS) policies ensure users can only access their own data - Server-side and client-side Supabase clients for different contexts - Edge Runtime compatible for Cloudflare Pages deployment - User data structure includes: - User profiles (username, display name, avatar URL, theme preference) - User preferences (show shiny, default view, items per page) - Favorite Pokémon tracking - Daily Pokémon viewing history - Achievement tracking system **Daily Pokémon**: Unique daily Pokémon per user using deterministic generation based on user ID and date (`src/lib/daily.ts`). Creates consistent daily experiences across sessions with history tracking in Supabase database. **Guides System**: Comprehensive educational content in `/guides/` with structured SEO-optimized articles covering: - Beginner guides (getting started, type effectiveness basics, first team building) - Battle strategy (advanced matchups, status effects, competitive team building) - Training & evolution (stats, IVs, move selection, evolution timing) - Catching & discovery (rare Pokémon, shiny hunting, legendary encounters) **News System**: Structured news articles in `/news/` with: - Individual article pages following consistent layout patterns - Featured/non-featured article management in the main news index - Image optimization and local asset storage for article covers - SEO-optimized metadata and Open Graph integration **SEO Optimization**: Comprehensive metadata (title ≤ 60 chars, description ≤ 160 chars, keywords ≤ 100 chars), structured data (Schema.org), robots.txt, and dynamic sitemap generation covering 1328 Pokémon entries (1025 main-line + 303 form variants), type pages, and guide content. Open Graph image generation for social media sharing. **Image Optimization**: Multi-tier fallback system for Pokémon images with CDN backup through `getPokemonImageUrl()`. Supports both regular and shiny variants with proper loading states. **Type System Integration**: Complete implementation of all 18 Pokémon types with effectiveness charts, damage calculations, and detailed type-specific pages showing primary/secondary typing distinctions. **Search System**: Direct name/ID search with input sanitization converting spaces to hyphens for PokeAPI compatibility. Validates queries and handles special characters safely. **Error Handling**: Custom `PokemonApiError` class with specific HTTP status code handling. All API calls include comprehensive error boundaries and user-friendly fallback states. **Responsive Design**: Mobile-first approach using Tailwind CSS with consistent spacing and typography systems. ## Directory Structure ``` src/ ├── app/ # Next.js App Router pages and layouts │ ├── [locale]/ # Internationalized pages with dynamic locale routing │ │ ├── daily/ # Daily Pokémon feature │ │ ├── guides/ # Educational content and strategy guides │ │ │ ├── getting-started/ │ │ │ ├── first-pokemon-team/ │ │ │ ├── advanced-type-matchups/ │ │ │ ├── competitive-team-building/ │ │ │ ├── evolution-strategies/ │ │ │ └── move-selection/ │ │ ├── news/ # News articles with structured content │ │ │ ├── mega-stones-legends-za/ │ │ │ ├── mega-dimension-bonuses/ │ │ │ └── pokemon-pokopia-announcement-2025/ │ │ ├── offline/ # PWA offline fallback page │ │ ├── pokemon/ # Pokémon database and detail pages │ │ │ └── [id]/ # Dynamic Pokemon detail pages with opengraph images │ │ ├── random/ # Random Pokémon discovery │ │ ├── types/ # Pokémon type system explorer │ │ │ └── [type]/ # Dynamic type-specific pages │ │ └── page.tsx # Localized homepage │ ├── api/ # API routes (vitals monitoring) │ ├── auth/ # Authentication routes │ │ └── callback/ # OAuth callback handler (Edge Runtime) │ ├── globals.css # Global styles and Tailwind imports │ ├── layout.tsx # Root layout with theme provider and metadata │ ├── manifest.ts # PWA web app manifest │ ├── sitemap.ts # Dynamic sitemap generation │ ├── robots.ts # SEO robots configuration │ └── opengraph-image.tsx # Dynamic OG image generation ├── components/ # Reusable UI components organized by domain │ ├── layout/ # Layout components (header, footer, navigation) │ ├── pokemon/ # Pokémon-specific components (cards, lists, details) │ ├── seo/ # SEO and structured data components │ └── ui/ # General UI components (buttons, cards, loading states) ├── hooks/ # Custom React hooks for data fetching and state ├── i18n/ # Internationalization configuration │ ├── routing.ts # Locale routing configuration (en, ja, pt-BR, roomaji) │ └── request.ts # Request-scoped i18n setup ├── lib/ # Utility functions, API client, and business logic │ ├── __tests__/ # Jest test files │ ├── api.ts # Complete PokeAPI integration with error handling │ ├── daily.ts # Daily Pokémon generation algorithms │ ├── type-translations.ts # Type name translation helpers │ ├── ability-translations.ts # Ability name/effect translation helpers │ ├── csp.ts # Content Security Policy configuration │ ├── nonce.ts # CSP nonce generation for script security │ ├── supabase/ # Supabase client configuration and utilities │ │ ├── client.ts # Client-side Supabase instance │ │ ├── server.ts # Server-side Supabase client │ │ ├── middleware.ts # Supabase middleware for session refresh │ │ ├── auth.ts # Authentication helper functions │ │ ├── profiles.ts # User profile management │ │ ├── preferences.ts # User preferences management │ │ ├── favorites.ts # Favorite Pokémon management │ │ └── daily.ts # Daily Pokémon history tracking │ └── utils.ts # General utility functions ├── types/ # TypeScript type definitions covering all PokeAPI responses ├── constants/ # Application constants, type colors, and configuration │ └── pokemon.ts # Type colors, stat mappings, and Pokemon-specific constants └── styles/ # Design tokens and global styles └── design-tokens.ts # Design system tokens and theme definitions messages/ # Translation files with 438+ keys per locale # en.json, ja.json, pt-BR.json, roomaji.json ``` ## Key Files ### Core Application - `src/app/layout.tsx` - Root layout with theme provider, metadata, and global providers - `src/app/page.tsx` - Homepage with navigation cards and feature highlights - `src/lib/api.ts` - PokéAPI client with error handling, caching, and fallback mechanisms - `src/types/pokemon.ts` - Complete TypeScript definitions for Pokémon data and API responses ### PWA Implementation - `public/sw.js` - Service Worker for offline caching and background sync - `src/app/manifest.ts` - Web App Manifest with icons, shortcuts, and install prompts - `src/app/offline/page.tsx` - Offline fallback page for graceful degradation ### Features - `src/app/daily/page.tsx` - Daily Pokémon discovery feature with deterministic generation - `src/app/guides/` - Educational content system with comprehensive strategy guides - `src/app/news/` - News articles system with featured article management and SEO optimization - `src/app/pokemon/page.tsx` - Pokémon database listing with search and pagination - `src/app/pokemon/[id]/page.tsx` - Individual Pokémon detail pages with dynamic metadata - `src/app/random/page.tsx` - Random Pokémon exploration with discovery features - `src/app/types/page.tsx` - Pokémon type system explorer with effectiveness charts - `src/app/types/[type]/page.tsx` - Type-specific pages with detailed information ### SEO & Metadata - `src/app/sitemap.ts` - Dynamic sitemap generation for all Pokemon, types, and guides - `src/app/robots.ts` - SEO-optimized robots.txt configuration - `src/app/opengraph-image.tsx` - Dynamic Open Graph image generation - `src/components/seo/` - Structured data components for rich search results ### UI Components - `src/components/pokemon/` - Pokémon-specific components (cards, lists, details, stats) - `src/components/ui/` - Reusable UI components (buttons, cards, loading states, themes) - `src/components/layout/` - Layout components (header, footer, navigation, breadcrumbs) ### Data Management - `src/hooks/usePokemon.ts` - Pokemon list data fetching with pagination and filtering - `src/hooks/usePokemonDetail.ts` - Individual Pokemon details with species information - `src/hooks/useDailyPokemon.ts` - Daily Pokemon generation with user fingerprinting - `src/hooks/useRandomPokemon.ts` - Random Pokemon discovery functionality ### Internationalization - `src/i18n/routing.ts` - Locale routing configuration with supported locales (en, ja, pt-BR, roomaji) and prefix strategy - `src/i18n/request.ts` - Request-scoped i18n configuration and message loading - `messages/en.json` - English translations (438+ keys covering UI, navigation, errors, content) - `messages/ja.json` - Japanese translations (438+ keys with complete feature coverage) - `messages/pt-BR.json` - Portuguese Brazilian translations (438+ keys) - `messages/roomaji.json` - Romaji translations (438+ keys) - `src/lib/type-translations.ts` - Helper functions for translating Pokémon type names from next-intl messages - `src/lib/ability-translations.ts` - Helper functions for extracting localized ability names and effects from PokeAPI data - `src/middleware.ts` - Custom middleware integrating next-intl routing, Supabase auth, CSP headers, and nonce generation ### Utilities - `src/lib/daily.ts` - Daily Pokémon generation logic with deterministic algorithms - `src/lib/utils.ts` - General utility functions (classNames, formatters, validators) - `src/constants/pokemon.ts` - Type colors, stat color mappings, and Pokemon constants - `src/styles/design-tokens.ts` - Design system tokens and theme definitions ## Development ### Commands - `pnpm dev` - Start development server with Turbopack (preferred for faster builds) - `npm run dev` - Start development server (alternative) - `pnpm build` - Build production version with optimizations - `pnpm start` - Start production server - `pnpm lint` - Run ESLint for code quality checks - `pnpm test` - Run unit tests (Jest tests available in `src/lib/__tests__/`) - `pnpm typecheck` - Run TypeScript type checking (if configured) ### Code Patterns - **Error Handling**: Custom error classes with specific error messages and HTTP status codes - **Type Safety**: Strict TypeScript with comprehensive type definitions for all API responses - **Component Props**: Properly typed component interfaces with JSDoc comments - **API Integration**: Centralized API client with fallback mechanisms and retry logic - **Responsive Design**: Mobile-first approach with Tailwind CSS utility classes - **Performance**: Image optimization, lazy loading, efficient data fetching, and caching strategies - **Accessibility**: ARIA labels, semantic HTML, keyboard navigation, and screen reader support ### Important Implementation Details **Error Handling**: Custom `PokemonApiError` class with specific HTTP status code handling. All API calls include comprehensive error boundaries and user-friendly fallback states. **Image Loading**: Multi-tier fallback system prioritizing official artwork, then sprites, then CDN backups. Handles both regular and shiny variants with proper aspect ratios and loading states. **Search**: Direct name/ID search with input sanitization converting spaces to hyphens for PokeAPI compatibility. Validates queries and handles special characters safely. **Caching Strategy**: Service Worker implements: - Network-first for API requests with cache fallback - Cache-first for images with background updates - Stale-while-revalidate for navigation requests - Separate cache buckets for different content types **Daily Pokémon Algorithm**: Uses deterministic hashing of user ID + date to ensure: - Same Pokémon per user per day across sessions/devices - Different Pokémon for different users on same day - Proper distribution across 1025 available Pokémon - Privacy-preserving fallback using browser fingerprinting **Type Effectiveness System**: Complete implementation of 18x18 type chart with: - Damage multiplier calculations (2x, 1x, 0.5x, 0x) - Visual effectiveness charts and explanations - Primary/secondary type handling for dual-type Pokémon - STAB (Same Type Attack Bonus) calculations **State Management**: Uses React hooks and context for theme state. No external state management library - data fetching handled through custom hooks with built-in caching and error states. **Internationalization Implementation**: - **Routing Strategy**: 'as-needed' locale prefix - default locale (en) uses clean URLs without prefix, other locales (ja, pt-BR, roomaji) include language code in path - **Supported Locales**: English (en), Japanese (ja), Portuguese Brazilian (pt-BR), Romaji (roomaji) - **Middleware Integration**: Custom middleware chain in `src/middleware.ts` handles next-intl routing for all 4 languages, Supabase session management and authentication, CSP headers with cryptographic nonce generation (`src/lib/nonce.ts`) - **TransformStream Fix**: Prevents Next.js 15 streaming errors by returning intl redirects immediately (status 307/308) and creating fresh responses for other requests - **Translation Helpers**: - `getTypeTranslation()` - Retrieves localized type names from next-intl message files - `getAbilityTranslation()` - Extracts ability names from PokeAPI's multilingual data with English fallback - `getAbilityEffect()` - Fetches localized ability effect descriptions with automatic fallback - **PokeAPI Localization**: Leverages PokeAPI's built-in language support for species names, genus text, ability names/effects, and flavor text entries - **Message Loading**: Dynamic imports load translation files per request based on detected/requested locale - **Navigation**: Custom Link, redirect, usePathname, and useRouter from next-intl maintain locale context across all navigation - **SEO Integration**: Locale-specific metadata generation with Open Graph tags, alternate language links, and structured data **Styling**: Tailwind CSS with design tokens in `src/styles/design-tokens.ts`. Type-specific colors, gradients, and stat color mappings defined in `src/constants/pokemon.ts` for consistent theming across components. **Performance**: Uses Next.js Image optimization, lazy loading, Turbopack for development builds, and comprehensive PWA caching for optimal user experience. ## Data Flow 1. **API Layer** (`src/lib/api.ts`) handles all external data fetching with comprehensive error handling and fallback mechanisms 2. **Custom Hooks** (`src/hooks/`) manage state and data fetching logic with built-in loading states and error handling 3. **Components** consume data through hooks for proper separation of concerns and reusability 4. **Error Boundaries** handle API failures gracefully with user-friendly fallback states 5. **Loading States** provide immediate user feedback during data fetching operations 6. **Caching** through Service Worker ensures optimal performance and offline functionality ## Special Features ### Internationalization (i18n) System - **Supported Languages**: English (en) as default, Japanese (ja), Portuguese Brazilian (pt-BR), and Romaji (roomaji) - **Routing Strategy**: 'as-needed' locale prefix strategy for clean URLs - English: Clean URLs without prefix (e.g., `/pokemon`, `/types`) - Other languages: Locale-prefixed URLs (e.g., `/ja/pokemon`, `/pt-BR/pokemon`, `/roomaji/types`) - **Translation Coverage**: 438+ translation keys per locale covering: - UI strings (buttons, labels, placeholders, validation messages) - Navigation and menu items - Error messages and loading states - Page titles, descriptions, and content - Feature-specific terminology - **PokeAPI Integration**: Leverages PokeAPI's built-in multilingual data: - Pokémon species names in multiple languages - Type names and descriptions - Ability names and effect descriptions - Move names and flavor text entries - Generation and genus information - **Translation Helpers**: - `getTypeTranslation()` - Fetches localized type names from next-intl messages - `getAbilityTranslation()` - Extracts ability names from PokeAPI multilingual data - `getAbilityEffect()` - Retrieves localized ability effect text with fallback logic - **Middleware Architecture**: Custom middleware chain (`src/middleware.ts`) that: - Detects user's preferred locale from browser settings or URL - Handles locale-based routing and redirects for all 4 supported languages - Integrates with Supabase session management and authentication - Manages CSP (Content Security Policy) headers and cryptographic nonce generation - Prevents TransformStream errors in Next.js 15 Edge Runtime - Ensures compatibility with Cloudflare Pages Edge Runtime deployment - **SEO Optimization**: - Locale-specific metadata and Open Graph tags - Alternate language link tags for search engines - Translated structured data for rich search results - Localized sitemaps and robots.txt handling - **Developer Experience**: - Type-safe translation keys with TypeScript - Hot-reloading of translation files in development - Consistent translation hook usage across components - Easy addition of new languages via locale file duplication ### Authentication & User Management - **Supabase Integration**: Complete backend integration with PostgreSQL database - **Google OAuth**: Sign-in with automatic profile creation via database triggers - Access user avatar via `user.user_metadata.avatar_url` or `user.user_metadata.picture` - Access display name via `user.user_metadata.full_name` or `user.user_metadata.name` - **User Data Structure** with Row Level Security (RLS): - `user_profiles` - User information (username, display name, avatar URL, theme preference) - `user_preferences` - App settings (show shiny, default view, items per page) - `user_favorites` - Favorite Pokémon tracking - `daily_pokemon_history` - Daily Pokémon viewing history - `user_achievements` - Achievement tracking system - **Client Types**: Separate client-side (`src/lib/supabase/client.ts`) and server-side (`src/lib/supabase/server.ts`) implementations - **Edge Runtime**: OAuth callback route configured for Cloudflare Pages deployment - **Security**: RLS policies on all tables ensure data isolation per user ### Daily Pokémon System - Uses deterministic generation based on user ID and date for consistent daily experiences - Implemented in `src/lib/daily.ts` with fallback to browser fingerprinting for privacy - Creates unique daily Pokémon per user while ensuring different users get different Pokémon - History tracking in Supabase (`daily_pokemon_history` table) for authenticated users - Utilizes localStorage for persistence across sessions for anonymous users ### Guides System - Comprehensive educational content in `/guides/` directory with structured SEO-optimized articles - Covers beginner guides (getting started, type effectiveness, first team building) - Advanced battle strategy (matchups, status effects, competitive team building) - Training & evolution guides (stats, IVs, move selection, evolution timing) - Discovery content (rare Pokémon, shiny hunting, legendary encounters) ### PWA Implementation - Service Worker (`public/sw.js`) for offline caching of API data, images, and application pages - Web App Manifest (`src/app/manifest.ts`) with app icons, shortcuts, and install prompts - Offline page (`src/app/offline/page.tsx`) for graceful degradation when network is unavailable - Background sync capabilities for data updates when connection is restored - Push notification infrastructure for future features ### SEO Implementation - **Metadata Requirements**: Strict character limits enforced - Page titles: ≤ 60 characters - Meta descriptions: ≤ 160 characters - Keywords: ≤ 100 characters (when stored as comma-separated string) - Content must be concise summaries, not truncated text - Dynamic metadata generation for all pages including Pokemon, types, and guides - Structured data (Schema.org) for rich search results and enhanced Google listings - Automatic sitemap generation covering 1328 Pokémon entries (1025 main-line + 303 form variants), type pages, and guide content - Optimized robots.txt configuration for search engine crawling - Open Graph image generation (`opengraph-image.tsx`) for social media sharing - Locale-specific metadata for all supported languages ### Image Optimization - Next.js Image component with multiple fallback sources and CDN configuration - Multi-tier fallback system: official artwork → sprites → CDN backups - Support for both regular and shiny Pokémon variants - Proper loading states, aspect ratios, and error handling - Lazy loading and responsive image serving for optimal performance ### Type System Integration - Complete implementation of all 18 Pokémon types with visual representation - Type effectiveness charts showing damage multipliers and relationships - Damage calculation system with STAB (Same Type Attack Bonus) support - Primary/secondary type handling for dual-type Pokémon - Color-coded type system with consistent visual hierarchy ## Configuration & Environment ### Supabase Setup For initial setup or migration from Firebase, refer to `SUPABASE_SETUP.md`: - **Environment Variables** (required in `.env.local`): - `NEXT_PUBLIC_SUPABASE_URL` - Your Supabase project URL - `NEXT_PUBLIC_SUPABASE_ANON_KEY` - Your Supabase anonymous key - **Database Schema**: Run `supabase/schema.sql` to create tables and RLS policies - **OAuth Configuration**: Set up Google OAuth provider in Supabase dashboard - **Automatic Profile Creation**: Database triggers create user profiles on first sign-in ### TypeScript Configuration - Strict mode enabled with `@/*` path aliases to `./src/*` - ESLint rules: - `@typescript-eslint/no-explicit-any: "error"` - Prohibits use of `any` type - `@typescript-eslint/no-unused-vars: "warn"` - Warns on unused variables ### Deployment Configuration - **Cloudflare Pages**: Edge Runtime compatible on dynamic routes - **Edge Runtime Routes**: `/auth/callback/route.ts` uses `export const runtime = 'edge';` - **Security**: Content Security Policy (CSP) with nonce-based script execution (`src/lib/csp.ts`) - **PWA**: Service worker caching with network-first for API, cache-first for images This codebase follows strict TypeScript practices, comprehensive error handling, accessibility best practices, and responsive design patterns throughout. The architecture is designed for scalability, maintainability, and optimal user experience across all devices and network conditions.