# ThrillWiki - Theme Park & Ride Encyclopedia

## Overview
ThrillWiki is a community-driven web application for discovering, reviewing, and tracking theme parks, rides, and related entities globally. Its core purpose is to provide a centralized platform for enthusiasts to research attractions and contribute to a collaborative knowledge base through user contributions and reviews, offering a comprehensive encyclopedia for the theme park world.

## Recent Changes
**October 27, 2025 - System Logging Improvements (Latest)**
- **Complete Audit History**: Fixed version history filtering to show ALL historical changes, not just current versions
  - Removed `is_current` filter from park, ride, company, and ride_model version queries
  - System log now displays complete audit trail of all entity changes over time
- **RLS Policy Alignment**: Fixed authentication mismatch between frontend and database policies
  - Relaxed admin_audit_log SELECT policy to allow moderators to view logs without AAL2 (MFA step-up)
  - Maintained strict AAL2 requirement for INSERT operations to ensure high security for write operations
  - Viewing logs is read-only and doesn't require the same security level as modifying data
- **Chronological Ordering**: Verified proper timestamp-based sorting of aggregated activities
  - All activities from multiple sources are sorted by timestamp (newest first) after aggregation
  - Ensures coherent, time-ordered display of system events

**October 27, 2025 - Critical Build Fixes**
- **Merge Conflict Resolution**: Resolved unresolved git merge conflict in AuthButtons.tsx that was preventing the app from compiling
  - Removed conflict markers and kept the UserAvatar component implementation for consistency with recent avatar improvements
  - Fixed syntax errors that were blocking Vite dev server from starting
- **Missing Dependency Installation**: Installed @tanstack/react-query-devtools package that was imported but not included in dependencies
  - Resolved module resolution errors preventing the app from loading
  - Restored React Query DevTools functionality for development debugging

**October 2025 - Avatar Display System Improvements**
- **Unified Avatar Component**: Created centralized UserAvatar component with robust retry logic and cache-busting to fix inconsistent avatar display across the application
  - Implemented bounded retry mechanism with two attempts and query parameter-based cache-busting
  - Added loading and error states with smooth transitions
  - Supports size variants (sm, md, lg) for different UI contexts
  - Automatically resets state when avatar URL changes to prevent stale displays
- **Comprehensive Avatar Integration**: Updated all avatar display locations to use UserAvatar component
  - Replaced Avatar usage in AuthButtons header with UserAvatar using key prop for forced re-renders
  - Updated ReviewsList to use UserAvatar for consistent review author avatars
  - Migrated QueueItem moderator and reviewer avatars to UserAvatar component
  - Ensured fallback text generation handles null/undefined cases gracefully across all usages

**October 2025 - Critical Bug Fixes & Stability Improvements**
- **Moderation Queue Sorting Enhancement**: Enhanced sorting controls with visual loading indicators and diagnostic logging:
  - Added animated spinners to sort controls (label and direction button) during data fetch operations
  - Added comprehensive logging to track multi-level sort queries (escalated DESC → user-selected sort → created_at tertiary)
  - Added detailed result preview logging showing first 3 items with sort field values for debugging
  - Disabled sort controls during loading to prevent duplicate requests
  - Mobile-specific loading text changes from "Ascending/Descending" to "Loading..." for clarity
- **Moderation Queue Sorting Fix**: Resolved sorting controls not updating the UI by fixing type mismatch in QueueSortControls (Radix Select passes string, handler expected SortField) and correcting refresh strategy logic (user-initiated sort/filter changes now bypass "notify" freeze mode and always update display)
- **Auth Loading State Fix**: Resolved perpetual loading state issue in auth buttons by simplifying useAuth hook's loading state management, removing blocking conditional logic, adding explicit setLoading(false) calls in all code paths, and ensuring pending email state cleanup occurs before early returns
- **React Hooks Violation Fix**: Resolved critical hooks ordering issue in useSearch that caused app crashes during hot module reload (HMR) by using stable useMemo with entire options object as dependency
- **Race Condition Prevention**: Fixed stale data issues in useEntityVersions by capturing request IDs before async operations and using them consistently in error handlers
- **Enhanced Error Handling**: Improved notificationService with comprehensive error logging, validation, and consistent error message extraction across all edge function invocations
- **CORS Security Hardening**: Removed overly permissive wildcard fallback in upload-image edge function, added proper origin validation and detailed logging for development and production modes
- **Rate Limit Cleanup Resilience**: Added robust error handling to detect-location cleanup with failure tracking, emergency fallback mechanisms, and detailed logging to prevent memory leaks

**October 2025 - Comprehensive Bug Analysis & Fixes**
- **Rate Limiting Optimization**: Fixed detect-location edge function to only perform cleanup when adding new IPs at capacity, improving performance by short-circuiting existing entries
- **Null Safety**: Fixed PhotoSubmissionDisplay null reference errors by switching from !inner join to regular join with filtering
- **User-Facing Error Messages**: Added error state handling to useSearch and LocationSearch hooks, displaying user-friendly error messages instead of silent failures
- **Image Upload Cleanup**: Enhanced error tracking in imageUploadHelper to report orphaned assets and detailed cleanup failures
- **Type Safety in Edge Functions**: Added explicit null checks and error handling for RPC calls and crypto.randomUUID availability in seed-test-data
- **Improved Error Messages**: Updated all Supabase edge functions with clearer, user-oriented error messages

**October 2025 - Bug Fixes & Stability Improvements**
- Fixed Fast Refresh/HMR issues by separating hook exports from component files (useSidebar, uploadPendingImages)
- Added comprehensive null/undefined safety checks across PhotoModal, EntityHistoryTimeline, useEntityVersions, and EntityEditPreview components
- Improved error handling with specific file names in upload error messages
- Enhanced AutocompleteSearch dropdown UX with proper loading state visibility
- Implemented deep object comparison in EntityEditPreview for accurate change detection
- Verified memory leak prevention (object URL cleanup, subscription cleanup, timeout cleanup all properly implemented)

## User Preferences
Preferred communication style: Simple, everyday language.

## System Architecture

### Frontend
- **Tech Stack:** React + TypeScript with Vite, Radix UI + Tailwind CSS (shadcn/ui), TanStack Query for state management, React Router v6 for routing.
- **Component Structure:** Utilizes layout, page-level, reusable UI, and custom domain components.
- **Design System:** HSL-based color system, dark/light theme support, custom gradients, Inter font, responsive and mobile-first design.
- **State Management:** TanStack Query for server state, React Context for authentication, custom hooks for business logic, and Realtime subscriptions for live updates.

### Backend
- **Database (Supabase PostgreSQL):** Stores core entities (parks, rides, companies), location data, review/rating systems, user profiles, content submission workflows, and image metadata.
- **Authentication & Authorization:** Supabase Auth for user management (magic link, email/password), Cloudflare Turnstile for bot protection, role-based access control (user, moderator, admin, superuser), and Row-Level Security (RLS).
- **Content Moderation:** Two-tier submission workflow with dependency tracking, conflict resolution, real-time updates for moderation queues, automated slug generation, and status tracking.
- **Data Access:** Security definer functions for privileged operations, complex joins, aggregated data, full-text search, and real-time subscriptions.

### Image Management
- **Cloudflare Images Integration:** Used for media storage and transformation, with uploads proxied via Supabase Edge Functions. Supports multiple variants for responsive display and stores metadata in Supabase.
- **Upload Workflow:** Uppy dashboard for multi-file uploads, image editor integration, progress tracking, and automatic resizing/optimization via Cloudflare.

### Notification System (Novu)
- **Architecture:** Multi-channel delivery (in-app, email, push), workflow-based templates, per-workflow user preferences, frequency controls, and headless notifications.
- **Features:** Supports subscriber management and preference syncing via Supabase Edge Functions.

### Search & Discovery
- **Multi-Entity Search:** Unified search across parks, rides, and companies with autocomplete, recent history, category/type filtering, and advanced filters.
- **Location Features:** Automatic unit conversion, geo-based preferences, and distance/measurement system settings.

### User Management
- **Profile System:** Customizable usernames, display names, avatars, bios, privacy controls, home park selection, and activity tracking.
- **User Blocking:** Functionality to block users and hide their content.
- **Role Management:** Hierarchical permission system for superuser, admin, moderator, and user roles, with role-specific UI and routes.

### Admin & Moderation
- **Moderation Queue:** Real-time monitoring of submissions, item-level approval/rejection, dependency conflict resolution, bulk actions, and status tracking.
- **Admin Settings:** System-wide configuration with category-based organization and audit trails.
- **Reports System:** Manages user-generated content reports with status workflows.

## External Dependencies

### Third-Party Services
- **Supabase:** PostgreSQL database, authentication, real-time, Edge Functions, storage.
- **Cloudflare:** Cloudflare Images for media storage/transformation, Turnstile for CAPTCHA.
- **Novu:** Multi-channel notification delivery, workflow management.
- **Uppy:** File upload interface and image editor.
- **Google Fonts:** For the Inter typeface.
- **Radix UI:** For accessible UI components.

### API Integrations
- **Supabase Edge Functions:**
    - `upload-image`: Cloudflare Images upload proxy.
    - `trigger-novu-notification`: Sends Novu notifications.
    - `sync-novu-subscriber`: Manages Novu subscribers.
    - `sync-novu-preferences`: Syncs notification preferences.
- **Database Functions (PostgreSQL):** For privacy checks, role-based permissions, and automated tasks.