// Frontend TypeScript Types for ThrillWiki NextJS Application
// This file contains all TypeScript interfaces and types for the ThrillWiki API

// ============================================================================
// Base Interfaces (merged from thrillwiki-real)
// ============================================================================

export interface ImageVariants {
  thumbnail: string;
  medium: string;
  large: string;
  avatar?: string; // Added for user avatars
}

export interface Photo {
  id: number;
  image_variants: ImageVariants;
  alt_text?: string;
  image_url?: string; // Added for compatibility
  caption?: string;
  photo_type?: string;
  uploaded_by?: {
    id: number;
    username: string;
    display_name: string;
  };
  uploaded_at?: string;
}

// ============================================================================
// Django-CloudflareImages-Toolkit Types (Updated to match actual API)
// ============================================================================

// Django model representation of CloudflareImage
export interface CloudflareImage {
  id: string; // UUID primary key
  cloudflare_id: string; // Cloudflare Image ID
  user?: {
    id: number;
    username: string;
    display_name: string;
  } | null;
  upload_url?: string; // Temporary upload URL (expires)
  public_url?: string; // Public URL (null until uploaded)
  status: "pending" | "uploaded" | "failed" | "expired";
  metadata: {
    [key: string]: any;
  };
  variants: {
    [key: string]: string; // Variant name -> URL mapping
  };
  filename?: string;
  file_size?: number; // bytes
  width?: number;
  height?: number;
  format?: string; // e.g., "jpeg", "png"
  is_ready: boolean;
  expires_at?: string; // ISO datetime for upload URL expiry
  created_at: string; // ISO datetime
  updated_at: string; // ISO datetime
  uploaded_at?: string; // ISO datetime when upload completed
  is_expired: boolean; // Computed property
}

// Request to create direct upload URL
export interface CloudflareDirectUploadRequest {
  metadata?: {
    [key: string]: any;
  };
  require_signed_urls?: boolean;
  expiry_minutes?: number; // Minutes until upload URL expires (default: 30)
  filename?: string;
}

// Response from create upload URL endpoint
export interface CloudflareDirectUploadResponse {
  id: string; // UUID of CloudflareImage record
  cloudflare_id: string; // Cloudflare Image ID
  upload_url: string; // Temporary upload URL from Cloudflare
  expires_at: string; // ISO datetime
  status: "pending";
  metadata: {
    [key: string]: any;
  };
  public_url: null; // Will be populated after upload
}

// Cloudflare's actual upload response (when uploading to their URL)
export interface CloudflareImageUploadResponse {
  success: boolean;
  result: {
    id: string; // Cloudflare Image ID
    filename: string;
    uploaded: string; // ISO datetime
    requireSignedURLs: boolean;
    variants: string[]; // Array of variant URLs
    meta?: {
      [key: string]: any;
    };
  };
  errors?: Array<{
    code: number;
    message: string;
  }>;
  messages?: string[];
}

// Request for standard image upload (not direct upload)
export interface CloudflareImageUploadRequest {
  file?: File; // For direct file upload
  url?: string; // For URL-based upload
  metadata?: {
    [key: string]: any;
  };
  require_signed_urls?: boolean;
}

export interface CloudflareImageVariant {
  id: string;
  options: {
    fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad';
    width?: number;
    height?: number;
    quality?: number; // 1-100
    format?: 'auto' | 'avif' | 'webp' | 'json';
    background?: string; // Hex color for padding
    trim?: {
      top?: number;
      right?: number;
      bottom?: number;
      left?: number;
    };
    metadata?: 'keep' | 'copyright' | 'none';
  };
  never_require_signed_urls?: boolean;
}

export interface CloudflareImageStats {
  count: {
    current: number;
    allowed: number;
  };
  storage: {
    current: number; // bytes
    allowed: number; // bytes
  };
}

export interface CloudflareImageListResponse {
  success: boolean;
  result: {
    images: Array<{
      id: string;
      filename: string;
      uploaded: string;
      require_signed_urls: boolean;
      variants: string[];
      meta?: {
        [key: string]: any;
      };
    }>;
  };
  result_info: {
    count: number;
    page: number;
    per_page: number;
    total_count: number;
  };
}

export interface CloudflareImageDeleteResponse {
  success: boolean;
  result?: {};
  errors?: Array<{
    code: number;
    message: string;
  }>;
}

export interface CloudflareWebhookPayload {
  eventType: 'image.upload' | 'image.delete' | 'image.update';
  eventTime: string; // ISO datetime
  image: {
    id: string;
    filename?: string;
    uploaded?: string;
    variants?: string[];
    metadata?: {
      [key: string]: any;
    };
  };
  account: {
    id: string;
  };
}

// Enhanced Photo interface that supports both legacy and new CloudflareImages-Toolkit
export interface EnhancedPhoto extends Photo {
  cloudflare_image?: CloudflareImage; // New CloudflareImages-Toolkit integration
  cloudflare_image_id?: string; // Reference to CloudflareImage
}

// Enhanced ImageVariants that includes CloudflareImages-Toolkit variants
export interface EnhancedImageVariants extends ImageVariants {
  public?: string; // Default public variant
  [key: string]: string | undefined; // Support for custom variants
}

export interface Location {
  city: string;
  state?: string;
  country: string;
  address?: string;
  latitude?: number;
  longitude?: number;
}

export interface Entity {
  id: number;
  name: string;
  slug: string;
}

// ============================================================================
// Authentication Types
export interface LoginRequest {
  username: string;
  password: string;
  turnstile_token?: string;
}

export interface SignupRequest {
  username: string;
  email: string;
  password: string;
  password_confirm: string;
  display_name: string;
  turnstile_token?: string;
}

export interface LoginResponse {
  access: string;
  refresh: string;
  user: User;
  message: string;
}

export interface AuthResponse {
  access: string;
  refresh: string;
  user: User;
  message: string;
}

export interface SignupResponse {
  access: string | null;
  refresh: string | null;
  user: User;
  message: string;
  email_verification_required: boolean;
}

export interface EmailVerificationResponse {
  message: string;
  success: boolean;
}

export interface ResendVerificationRequest {
  email: string;
}

export interface ResendVerificationResponse {
  message: string;
  success: boolean;
}

export interface TokenRefreshRequest {
  refresh: string;
}

export interface TokenRefreshResponse {
  access: string;
  refresh?: string; // Optional - only returned if refresh token rotation is enabled
}

export interface LogoutResponse {
  message: string;
}

export interface CurrentUserResponse {
  id: number;
  username: string;
  email: string;
  display_name: string;
  is_active: boolean;
  date_joined: string;
}

export interface PasswordResetRequest {
  email: string;
}

export interface PasswordResetResponse {
  detail: string;
}

export interface PasswordChangeRequest {
  old_password: string;
  new_password: string;
  new_password_confirm: string;
}

export interface PasswordChangeResponse {
  detail: string;
}

export interface SocialProvider {
  id: string;
  name: string;
  authUrl: string;
}

export type SocialProvidersResponse = SocialProvider[];

export interface AuthStatusResponse {
  authenticated: boolean;
  user: CurrentUserResponse | null;
}

export interface SocialLoginRequest {
  access_token: string;
}

export interface SocialConnectionsResponse {
  google: { connected: boolean; email?: string };
  discord: { connected: boolean; username?: string };
}

export interface SocialConnectResponse {
  success: boolean;
  message: string;
}

export interface SocialDisconnectResponse {
  success: boolean;
  message: string;
}

// ============================================================================
// Social Provider Management Types
// ============================================================================

export interface ConnectedProvider {
  provider: string;
  provider_name: string;
  uid: string;
  date_joined: string;
  can_disconnect: boolean;
  disconnect_reason: string | null;
  extra_data: Record<string, any>;
}

export interface AvailableProvider {
  id: string;
  name: string;
  auth_url: string;
  connect_url: string;
}

export interface SocialAuthStatus {
  user_id: number;
  username: string;
  email: string;
  has_password_auth: boolean;
  connected_providers: ConnectedProvider[];
  total_auth_methods: number;
  can_disconnect_any: boolean;
  requires_password_setup: boolean;
}

export interface ConnectProviderRequest {
  provider: string;
}

export interface ConnectProviderResponse {
  success: boolean;
  message: string;
  provider: string;
  auth_url: string;
}

export interface DisconnectProviderResponse {
  success: boolean;
  message: string;
  provider: string;
  remaining_providers: string[];
  has_password_auth: boolean;
  suggestions?: string[];
}

export interface SocialProviderListResponse {
  available_providers: AvailableProvider[];
  count: number;
}

export interface ConnectedProvidersListResponse {
  connected_providers: ConnectedProvider[];
  count: number;
  has_password_auth: boolean;
  can_disconnect_any: boolean;
}

export interface SocialProviderError {
  error: string;
  code?: string;
  suggestions?: string[];
  provider?: string;
}

// ============================================================================
// User Account Management Types
// ============================================================================

export interface CompleteUserProfile {
  user_id: string;
  username: string;
  email: string;
  display_name: string;
  is_active: boolean;
  date_joined: string;
  role: "USER" | "MODERATOR" | "ADMIN" | "SUPERUSER";
  theme_preference: "light" | "dark";
  profile: {
    profile_id: string;
    display_name: string;
    avatar: string | null;
    avatar_url: string; // Full avatar URL (Cloudflare or default)
    avatar_variants: {
      thumbnail: string; // 64x64
      avatar: string;    // 200x200
      large: string;     // 400x400
    };
    pronouns: string;
    bio: string;
    twitter: string;
    instagram: string;
    youtube: string;
    discord: string;
    coaster_credits: number;
    dark_ride_credits: number;
    flat_ride_credits: number;
    water_ride_credits: number;
  };
}

export interface AccountUpdate {
  display_name?: string;
  email?: string;
}

export interface ProfileUpdate {
  display_name?: string;
  pronouns?: string;
  bio?: string;
  twitter?: string;
  instagram?: string;
  youtube?: string;
  discord?: string;
}

export interface AvatarUpload {
  avatar: File; // Image file (JPEG, PNG, WebP)
}

// For backward compatibility with FormData uploads
export interface AvatarFormData {
  avatar: File; // Image file (JPEG, PNG, WebP)
}

export interface AvatarUploadResponse {
  success: boolean;
  message: string;
  avatar_url: string;
  avatar_variants: {
    thumbnail: string; // 64x64
    avatar: string;    // 200x200
    large: string;     // 400x400
  };
}

export interface AvatarDeleteResponse {
  success: boolean;
  message: string;
  avatar_url: string; // Default UI Avatars URL
}

export interface UserPreferences {
  theme_preference: "light" | "dark";
  email_notifications: boolean;
  push_notifications: boolean;
  privacy_level: "public" | "friends" | "private";
  show_email: boolean;
  show_real_name: boolean;
  show_statistics: boolean;
  allow_friend_requests: boolean;
  allow_messages: boolean;
}

export interface ThemeUpdate {
  theme_preference: "light" | "dark";
}

export interface NotificationSettings {
  email_notifications: {
    new_reviews: boolean;
    review_replies: boolean;
    friend_requests: boolean;
    messages: boolean;
    weekly_digest: boolean;
    new_features: boolean;
    security_alerts: boolean;
  };
  push_notifications: {
    new_reviews: boolean;
    review_replies: boolean;
    friend_requests: boolean;
    messages: boolean;
  };
  in_app_notifications: {
    new_reviews: boolean;
    review_replies: boolean;
    friend_requests: boolean;
    messages: boolean;
    system_announcements: boolean;
  };
}

export interface PrivacySettings {
  profile_visibility: "public" | "friends" | "private";
  show_email: boolean;
  show_real_name: boolean;
  show_join_date: boolean;
  show_statistics: boolean;
  show_reviews: boolean;
  show_photos: boolean;
  show_top_lists: boolean;
  allow_friend_requests: boolean;
  allow_messages: boolean;
  allow_profile_comments: boolean;
  search_visibility: boolean;
  activity_visibility: "public" | "friends" | "private";
}

export interface SecuritySettings {
  two_factor_enabled: boolean;
  login_notifications: boolean;
  session_timeout: number; // days
  require_password_change: boolean; // read-only
  last_password_change: string; // read-only
  active_sessions: number; // read-only
  login_history_retention: number; // days
}

export interface SecuritySettingsUpdate {
  two_factor_enabled?: boolean;
  login_notifications?: boolean;
  session_timeout?: number; // 5-180 days
  login_history_retention?: number; // 30-365 days
}

export interface UserStatistics {
  ride_credits: {
    coaster_credits: number;
    dark_ride_credits: number;
    flat_ride_credits: number;
    water_ride_credits: number;
    total_credits: number;
  };
  contributions: {
    park_reviews: number;
    ride_reviews: number;
    photos_uploaded: number;
    top_lists_created: number;
    helpful_votes_received: number;
  };
  activity: {
    days_active: number;
    last_active: string;
    average_review_rating: number;
    most_reviewed_park: string;
    favorite_ride_type: string;
  };
  achievements: {
    first_review: boolean;
    photo_contributor: boolean;
    top_reviewer: boolean;
    park_explorer: boolean;
    coaster_enthusiast: boolean;
  };
}

export interface TopList {
  id: number;
  title: string;
  category: "RC" | "DR" | "FR" | "WR" | "PK";
  description: string;
  created_at: string;
  updated_at: string;
  items_count: number;
}

export type TopListsResponse = TopList[];

export interface CreateTopList {
  title: string;
  category: "RC" | "DR" | "FR" | "WR" | "PK";
  description?: string;
}

export interface NotificationResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: UserNotification[];
  unread_count: number;
}

export interface UserNotification {
  id: number;
  notification_type: "SUBMISSION" | "REVIEW" | "SOCIAL" | "SYSTEM" | "ACHIEVEMENT";
  title: string;
  message: string;
  is_read: boolean;
  created_at: string;
  read_at: string | null;
  action_url: string | null;
  related_object_type: string | null;
  related_object_id: number | null;
  metadata: Record<string, any>;
}

export interface MarkNotificationsRead {
  notification_ids?: number[]; // Specific notification IDs to mark as read
  mark_all?: boolean;          // Mark all unread notifications as read
}

export interface MarkReadResponse {
  success: boolean;
  marked_count: number;
  message: string;
}

export interface NotificationPreferences {
  email_enabled: boolean;
  push_enabled: boolean;
  in_app_enabled: boolean;
  submission_notifications: {
    email: boolean;
    push: boolean;
    in_app: boolean;
  };
  review_notifications: {
    email: boolean;
    push: boolean;
    in_app: boolean;
  };
  social_notifications: {
    email: boolean;
    push: boolean;
    in_app: boolean;
  };
  system_notifications: {
    email: boolean;
    push: boolean;
    in_app: boolean;
  };
  achievement_notifications: {
    email: boolean;
    push: boolean;
    in_app: boolean;
  };
}

export interface DeletionRequest {
  success: boolean;
  message: string;
  expires_at: string;
  email: string;
}

export interface VerifyDeletion {
  verification_code: string; // 8-character code from email
}

export interface DeletionComplete {
  success: boolean;
  message: string;
  deleted_user: {
    username: string;
    user_id: string;
    email: string;
    date_joined: string;
  };
  preserved_submissions: {
    park_reviews: number;
    ride_reviews: number;
    uploaded_park_photos: number;
    uploaded_ride_photos: number;
    top_lists: number;
    edit_submissions: number;
    photo_submissions: number;
  };
  deletion_request: {
    verification_code: string;
    created_at: string;
    verified_at: string;
  };
}

export interface CancelDeletion {
  success: boolean;
  message: string;
  had_pending_request: boolean;
}

export interface DeletionEligibility {
  can_delete: boolean;
  reason: string | null;
  user_info: {
    username: string;
    user_id: string;
    email: string;
    date_joined: string;
    role: string;
  };
  submissions_to_preserve: {
    park_reviews: number;
    ride_reviews: number;
    uploaded_park_photos: number;
    uploaded_ride_photos: number;
    top_lists: number;
    edit_submissions: number;
    photo_submissions: number;
  };
  total_submissions: number;
}

// ============================================================================
// Queue Routing Response Types
// ============================================================================

export interface AutoApprovedResponse {
  success: true;
  status: "auto_approved";
  message: string;
  data: ParkDetail | RideDetail; // The created/updated entity
  submission: {
    id: number;
    status: "APPROVED";
    approved_at: string;
    approved_by: {
      id: number;
      username: string;
      display_name: string;
    };
  };
}

export interface QueuedResponse {
  success: true;
  status: "queued";
  message: string;
  submission: {
    id: number;
    status: "PENDING";
    created_at: string;
    queue_item: {
      id: number;
      title: string;
      description: string;
      priority: "URGENT" | "HIGH" | "MEDIUM" | "LOW";
      estimated_review_time: string;
    };
  };
}

export interface FailedResponse {
  success: false;
  status: "failed";
  message: string;
  errors: Record<string, string[]>;
}

export type QueueRoutingResponse = AutoApprovedResponse | QueuedResponse | FailedResponse;

export interface EditSubmission {
  id: number;
  title: string;
  description: string;
  status: "PENDING" | "APPROVED" | "REJECTED" | "ESCALATED";
  user: {
    id: number;
    username: string;
    display_name: string;
  };
  created_at: string;
  reviewed_at: string | null;
  reviewer_notes: string | null;
  queue_item?: {
    id: number;
    title: string;
    description: string;
    priority: "URGENT" | "HIGH" | "MEDIUM" | "LOW";
    estimated_review_time: string;
  };
}

export interface PhotoSubmission {
  id: number;
  title: string;
  description: string;
  status: "PENDING" | "APPROVED" | "REJECTED";
  user: {
    id: number;
    username: string;
    display_name: string;
  };
  created_at: string;
  reviewed_at: string | null;
  reviewer_notes: string | null;
  queue_item?: {
    id: number;
    title: string;
    description: string;
    priority: "URGENT" | "HIGH" | "MEDIUM" | "LOW";
    estimated_review_time: string;
  };
}

export interface QueueConfiguration {
  default_priority: "URGENT" | "HIGH" | "MEDIUM" | "LOW";
  estimated_review_times: {
    URGENT: string;    // "2-4 hours"
    HIGH: string;      // "4-8 hours"
    MEDIUM: string;    // "1-2 days"
    LOW: string;       // "2-5 days"
  };
  auto_escalation: {
    enabled: boolean;
    escalate_after_hours: number;
  };
}

// ============================================================================
// Parks API Types
// ============================================================================

export interface ParkListResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: ParkSummary[];
}

export interface ParkSummary {
  id: number;
  name: string;
  slug: string;
  description: string;
  location: {
    country: string;
    state: string;
    city: string;
    address: string;
    latitude: number;
    longitude: number;
  };
  operator: {
    id: number;
    name: string;
    slug: string;
  } | null;
  property_owner: {
    id: number;
    name: string;
    slug: string;
  } | null;
  opening_date: string | null;
  closing_date: string | null;
  status: "OPERATING" | "CLOSED_TEMP" | "CLOSED_PERM" | "UNDER_CONSTRUCTION";
  ride_count: number;
  average_rating: number | null;
  banner_image: string | null;
  card_image: string | null;
  created_at: string;
  updated_at: string;
}

export interface CreateParkRequest {
  name: string;
  description?: string;
  operator_id?: number;
  property_owner_id?: number;
  opening_date?: string; // YYYY-MM-DD format
  closing_date?: string; // YYYY-MM-DD format
  status?: "OPERATING" | "CLOSED_TEMP" | "CLOSED_PERM" | "UNDER_CONSTRUCTION";
  location: {
    country: string;
    state: string;
    city: string;
    address?: string;
    latitude?: number;
    longitude?: number;
  };
}

export interface ParkDetail extends ParkSummary {
  rides: RideSummary[];
  photos: ParkPhoto[];
  reviews_count: number;
  recent_reviews: ReviewSummary[];
  statistics: {
    total_rides: number;
    roller_coasters: number;
    dark_rides: number;
    flat_rides: number;
    water_rides: number;
    transport_rides: number;
  };
}

export interface ParkPhoto {
  id: number;
  image_url: string;
  image_variants: {
    thumbnail: string;
    medium: string;
    large: string;
  };
  caption: string;
  photo_type: "GENERAL" | "ENTRANCE" | "RIDE" | "FOOD" | "SHOP" | "SHOW";
  uploaded_by: {
    id: number;
    username: string;
    display_name: string;
  };
  uploaded_at: string;
}

export interface ParkFilterOptions {
  park_types: Array<{value: string; label: string}>;
  continents: string[];
  countries: string[];
  states: string[];
  ordering_options: Array<{value: string; label: string}>;
}

export interface ParkSearchFilters {
  page?: number;
  page_size?: number;
  search?: string;
  country?: string;
  state?: string;
  city?: string;
  status?: string;
  operator_id?: number;
  operator_slug?: string;
  property_owner_id?: number;
  property_owner_slug?: string;
  min_rating?: number;
  max_rating?: number;
  min_ride_count?: number;
  max_ride_count?: number;
  opening_year?: number;
  min_opening_year?: number;
  max_opening_year?: number;
  has_roller_coasters?: boolean;
  min_roller_coaster_count?: number;
  max_roller_coaster_count?: number;
  ordering?: string;
  continent?: string;
  park_type?: string;
}

export interface ParkCompanySearchResult {
  id: number;
  name: string;
  slug: string;
}

export type ParkCompanySearchResponse = ParkCompanySearchResult[];

export interface ParkSearchSuggestion {
  suggestion: string;
}

export type ParkSearchSuggestionsResponse = ParkSearchSuggestion[];

export interface ParkImageSettings {
  banner_image?: number; // Photo ID
  card_image?: number;   // Photo ID
}

export interface ParkPhotosResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: ParkPhoto[];
}

export interface UploadParkPhoto {
  image: File;
  caption?: string;
  photo_type?: "GENERAL" | "ENTRANCE" | "RIDE" | "FOOD" | "SHOP" | "SHOW";
}

export interface UpdateParkPhoto {
  caption?: string;
  photo_type?: "GENERAL" | "ENTRANCE" | "RIDE" | "FOOD" | "SHOP" | "SHOW";
}

// ============================================================================
// Rides API Types
// ============================================================================

export interface RideListResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: RideSummary[];
}

export interface RideSummary {
  id: number;
  name: string;
  slug: string;
  description: string;
  category: "RC" | "DR" | "FR" | "WR" | "TR" | "OT";
  status: "OPERATING" | "CLOSED_TEMP" | "SBNO" | "CLOSING" | "CLOSED_PERM" | "UNDER_CONSTRUCTION" | "DEMOLISHED" | "RELOCATED";
  park: {
    id: number;
    name: string;
    slug: string;
  };
  manufacturer: {
    id: number;
    name: string;
    slug: string;
  } | null;
  designer: {
    id: number;
    name: string;
    slug: string;
  } | null;
  ride_model: {
    id: number;
    name: string;
    slug: string;
    manufacturer: {
      id: number;
      name: string;
      slug: string;
    };
  } | null;
  opening_date: string | null;
  closing_date: string | null;
  status_since: string | null;
  min_height_in: number | null;
  max_height_in: number | null;
  capacity_per_hour: number | null;
  ride_duration_seconds: number | null;
  average_rating: number | null;
  reviews_count: number;
  banner_image: string | null;
  card_image: string | null;
  coaster_stats: {
    roller_coaster_type: string;
    track_material: string;
    launch_type: string;
    height_ft: number | null;
    speed_mph: number | null;
    inversions: number;
    length_ft: number | null;
    duration_seconds: number | null;
  } | null;
  created_at: string;
  updated_at: string;
}

export interface CreateRideRequest {
  name: string;
  description?: string;
  category: "RC" | "DR" | "FR" | "WR" | "TR" | "OT";
  status?: "OPERATING" | "CLOSED_TEMP" | "SBNO" | "CLOSING" | "CLOSED_PERM" | "UNDER_CONSTRUCTION" | "DEMOLISHED" | "RELOCATED";
  park_id: number;
  park_area_id?: number;
  manufacturer_id?: number;
  designer_id?: number;
  ride_model_id?: number;
  opening_date?: string; // YYYY-MM-DD format
  closing_date?: string; // YYYY-MM-DD format
  status_since?: string; // YYYY-MM-DD format
  min_height_in?: number;
  max_height_in?: number;
  capacity_per_hour?: number;
  ride_duration_seconds?: number;
}

export interface RideDetail extends RideSummary {
  photos: RidePhoto[];
  reviews_count: number;
  recent_reviews: ReviewSummary[];
  location: {
    latitude: number;
    longitude: number;
  } | null;
  park_area: {
    id: number;
    name: string;
  } | null;
  ride_types: Array<{
    id: number;
    name: string;
    category: string;
  }>;
}

export interface RidePhoto {
  id: number;
  image_url: string;
  image_variants: {
    thumbnail: string;
    medium: string;
    large: string;
  };
  caption: string;
  photo_type: "GENERAL" | "STATION" | "LIFT" | "ELEMENT" | "TRAIN" | "QUEUE";
  uploaded_by: {
    id: number;
    username: string;
    display_name: string;
  };
  uploaded_at: string;
}

export interface RideFilterOptions {
  categories: Array<{value: string; label: string}>;
  statuses: Array<{value: string; label: string}>;
  post_closing_statuses: Array<{value: string; label: string}>;
  roller_coaster_types: Array<{value: string; label: string}>;
  track_materials: Array<{value: string; label: string}>;
  launch_types: Array<{value: string; label: string}>;
  ordering_options: Array<{value: string; label: string}>;
  filter_ranges: {
    rating: {min: number; max: number; step: number};
    height_requirement: {min: number; max: number; step: number; unit: string};
    capacity: {min: number; max: number; step: number; unit: string};
    height_ft: {min: number; max: number; step: number; unit: string};
    speed_mph: {min: number; max: number; step: number; unit: string};
    inversions: {min: number; max: number; step: number; unit: string};
    opening_year: {min: number; max: number; step: number; unit: string};
  };
  boolean_filters: Array<{
    key: string;
    label: string;
    description: string;
  }>;
}

export interface RideImageSettings {
  banner_image?: number; // Photo ID
  card_image?: number;   // Photo ID
}

export interface RidePhotosResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: RidePhoto[];
}

export interface UploadRidePhoto {
  image: File;
  caption?: string;
  photo_type?: "GENERAL" | "STATION" | "LIFT" | "ELEMENT" | "TRAIN" | "QUEUE";
}

export interface UpdateRidePhoto {
  caption?: string;
  photo_type?: "GENERAL" | "STATION" | "LIFT" | "ELEMENT" | "TRAIN" | "QUEUE";
}

// ============================================================================
// Park Change Management Types
// ============================================================================

export interface ParkChangeInfo {
  old_park: {
    id: number;
    name: string;
    slug: string;
  };
  new_park: {
    id: number;
    name: string;
    slug: string;
  };
  url_changes: {
    old_url: string;
    new_url: string;
  };
  slug_changes?: {
    old_slug: string;
    new_slug: string;
    conflict_resolved: boolean;
  };
  park_area_cleared: boolean;
  change_timestamp: string;
}

export interface ManufacturerRideModels {
  manufacturer: {
    id: number;
    name: string;
    slug: string;
    description: string;
    founded_year: number | null;
    headquarters: string;
  };
  ride_models: Array<{
    id: number;
    name: string;
    slug: string;
    category: string;
    description: string;
    first_installation: string | null;
    installations_count: number;
  }>;
}

// ============================================================================
// Search & Core API Types
// ============================================================================

export interface CompanySearchResult {
  id: number;
  name: string;
  slug: string;
}

export type CompanySearchResponse = CompanySearchResult[];

export interface RideModelSearchResult {
  id: number;
  name: string;
  category: string;
}

export type RideModelSearchResponse = RideModelSearchResult[];

export interface SearchSuggestion {
  suggestion: string;
}

export type SearchSuggestionsResponse = SearchSuggestion[];

export interface EntitySearchResponse {
  results: Array<{
    id: number;
    name: string;
    slug: string;
    entity_type: "park" | "ride" | "company";
    description: string;
    location?: string;
    park_name?: string; // For rides
    score: number; // Relevance score
  }>;
  total_count: number;
}

export interface EntityNotFoundRequest {
  search_query: string;
  entity_type?: "park" | "ride" | "company";
  additional_info?: string;
}

export interface EntityNotFoundResponse {
  success: boolean;
  message: string;
}

export interface EntitySuggestion {
  id: number;
  name: string;
  entity_type: "park" | "ride" | "company";
  subtitle?: string; // Additional context (e.g., park name for rides)
}

export type EntitySuggestionsResponse = EntitySuggestion[];

// ============================================================================
// Maps API Types
// ============================================================================

export interface MapLocationsResponse {
  locations: Array<{
    id: number;
    name: string;
    entity_type: "park" | "ride";
    latitude: number;
    longitude: number;
    category?: string; // For rides
    park_name?: string; // For rides
    status: string;
    marker_color: string;
  }>;
  clusters: Array<{
    latitude: number;
    longitude: number;
    count: number;
    bounds: {
      sw_lat: number;
      sw_lng: number;
      ne_lat: number;
      ne_lng: number;
    };
  }>;
}

export interface LocationDetail {
  id: number;
  name: string;
  entity_type: "park" | "ride";
  latitude: number;
  longitude: number;
  address: string;
  description: string;
  status: string;
  images: string[];
  park_name?: string; // For rides
  category?: string; // For rides
  opening_date?: string;
  website_url?: string;
}

export interface MapSearchResponse {
  results: Array<{
    id: number;
    name: string;
    entity_type: "park" | "ride";
    latitude: number;
    longitude: number;
    relevance_score: number;
  }>;
}

export interface MapStatsResponse {
  total_parks: number;
  total_rides: number;
  parks_with_coordinates: number;
  rides_with_coordinates: number;
  coverage_percentage: number;
  last_updated: string;
}

export interface MapCacheResponse {
  cache_size: number;
  cache_hits: number;
  cache_misses: number;
  last_cleared: string;
}

export interface CacheInvalidateResponse {
  success: boolean;
  message: string;
}

// ============================================================================
// Health & Statistics Types
// ============================================================================

export interface HealthCheckResponse {
  status: "healthy" | "degraded" | "unhealthy";
  timestamp: string;
  version: string;
  checks: {
    database: {
      status: "healthy" | "unhealthy";
      response_time_ms: number;
    };
    cache: {
      status: "healthy" | "unhealthy";
      response_time_ms: number;
    };
    storage: {
      status: "healthy" | "unhealthy";
      response_time_ms: number;
    };
  };
}

export interface SimpleHealthResponse {
  status: "ok";
  timestamp: string;
}

export interface PerformanceMetricsResponse {
  cpu_usage: number;
  memory_usage: number;
  disk_usage: number;
  active_connections: number;
  response_times: {
    avg_ms: number;
    p95_ms: number;
    p99_ms: number;
  };
  error_rates: {
    last_hour: number;
    last_day: number;
  };
}

export interface SystemStatsResponse {
  parks: {
    total: number;
    operating: number;
    closed: number;
    under_construction: number;
  };
  rides: {
    total: number;
    by_category: {
      roller_coasters: number;
      dark_rides: number;
      flat_rides: number;
      water_rides: number;
      transport: number;
      other: number;
    };
    by_status: {
      operating: number;
      closed_temp: number;
      closed_perm: number;
      under_construction: number;
    };
  };
  users: {
    total: number;
    active_last_30_days: number;
    new_this_month: number;
  };
  content: {
    reviews: number;
    photos: number;
    top_lists: number;
  };
  last_updated: string;
}

export interface StatsRecalculateResponse {
  success: boolean;
  message: string;
  started_at: string;
}

// ============================================================================
// Trending & Discovery Types
// ============================================================================

export interface TrendingResponse {
  trending_parks: Array<{
    id: number;
    name: string;
    slug: string;
    trend_score: number;
    trend_change: number; // Percentage change
    recent_activity: string;
  }>;
  trending_rides: Array<{
    id: number;
    name: string;
    slug: string;
    park_name: string;
    trend_score: number;
    trend_change: number;
    recent_activity: string;
  }>;
}

export interface NewContentResponse {
  new_parks: Array<{
    id: number;
    name: string;
    slug: string;
    added_date: string;
    opening_date: string | null;
  }>;
  new_rides: Array<{
    id: number;
    name: string;
    slug: string;
    park_name: string;
    category: string;
    added_date: string;
    opening_date: string | null;
  }>;
}

export interface TriggerTrendingResponse {
  success: boolean;
  message: string;
  calculation_started: string;
}

// ============================================================================
// Reviews & Rankings Types
// ============================================================================

export interface LatestReviewsResponse {
  reviews: ReviewSummary[];
}

export interface ReviewSummary {
  id: number;
  rating: number;
  title: string;
  content: string;
  entity_type: "park" | "ride";
  entity_id: number;
  entity_name: string;
  park_name?: string; // For ride reviews
  author: {
    id: number;
    username: string;
    display_name: string;
    avatar_url: string;
  };
  created_at: string;
  helpful_votes: number;
  total_votes: number;
}

export interface RankingsResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: RankedRide[];
  metadata: {
    total_rides: number;
    average_rating: number;
    total_reviews: number;
    last_updated: string;
  };
}

export interface RankedRide {
  rank: number;
  id: number;
  name: string;
  slug: string;
  category: string;
  park: {
    id: number;
    name: string;
    slug: string;
  };
  manufacturer: {
    id: number;
    name: string;
    slug: string;
  } | null;
  average_rating: number;
  reviews_count: number;
  rating_distribution: {
    "1": number;
    "2": number;
    "3": number;
    "4": number;
    "5": number;
    "6": number;
    "7": number;
    "8": number;
    "9": number;
    "10": number;
  };
  coaster_stats: {
    height_ft: number | null;
    speed_mph: number | null;
    inversions: number;
    roller_coaster_type: string;
    track_material: string;
  } | null;
  banner_image: string | null;
  card_image: string | null;
}

export interface RideRankingDetail {
  ride: RankedRide;
  global_rank: number;
  category_rank: number;
  park_rank: number;
  manufacturer_rank: number | null;
  similar_rides: Array<{
    id: number;
    name: string;
    park_name: string;
    average_rating: number;
    rank_difference: number; // Positive if ranked higher, negative if lower
  }>;
  ranking_history: Array<{
    date: string;
    global_rank: number;
    category_rank: number;
    average_rating: number;
    reviews_count: number;
  }>;
}

export interface RankingCalculationResponse {
  success: boolean;
  message: string;
  calculation_started: string;
  estimated_completion: string;
}

// ============================================================================
// Email Service Types
// ============================================================================

export interface ContactEmailRequest {
  name: string;
  email: string;
  subject: string;
  message: string;
  category?: "GENERAL" | "BUG_REPORT" | "FEATURE_REQUEST" | "CONTENT_ISSUE" | "ACCOUNT_ISSUE";
}

export interface ContactEmailResponse {
  success: boolean;
  message: string;
  reference_id: string;
}

export interface NewsletterSubscribeRequest {
  email: string;
  preferences?: {
    weekly_digest: boolean;
    new_features: boolean;
    community_highlights: boolean;
  };
}

export interface NewsletterSubscribeResponse {
  success: boolean;
  message: string;
  subscription_id: string;
}

export interface NewsletterUnsubscribeRequest {
  email: string;
  token?: string; // Unsubscribe token from email
}

export interface NewsletterUnsubscribeResponse {
  success: boolean;
  message: string;
}

// ============================================================================
// History API Types
// ============================================================================

export interface EntityHistoryResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: HistoryEntry[];
}

export interface HistoryEntry {
  id: number;
  timestamp: string;
  user: {
    id: number;
    username: string;
    display_name: string;
  } | null;
  action: "CREATE" | "UPDATE" | "DELETE";
  changes: Array<{
    field: string;
    old_value: any;
    new_value: any;
  }>;
  reason: string | null;
  ip_address: string;
}

export interface RecentChangesResponse {
  changes: Array<{
    id: number;
    entity_type: "park" | "ride";
    entity_id: number;
    entity_name: string;
    action: "CREATE" | "UPDATE" | "DELETE";
    timestamp: string;
    user: {
      id: number;
      username: string;
      display_name: string;
    } | null;
    summary: string; // Human-readable summary of changes
  }>;
  total_count: number;
}

// ============================================================================
// Error Response Types
// ============================================================================

export interface ApiError {
  status: "error";
  error: {
    code: string;
    message: string;
    details?: any;
    request_user?: string;
  };
  data: null;
}

export interface EnhancedApiError {
  status: "error";
  error: {
    code: string;
    message: string;
    error_code: string;
    user_info?: {
      username: string;
      role: string;
      is_superuser: boolean;
      is_staff: boolean;
    };
    help_text?: string;
    details?: any;
    request_user?: string;
  };
  data: null;
}

export interface ValidationError {
  [field: string]: string[];
}

export interface AuthError {
  detail: string;
}

export interface PermissionError {
  detail: string;
}

export interface NotFoundError {
  detail: string;
}

export interface ServerError {
  detail: string;
}

// ============================================================================
// Common Utility Types
// ============================================================================

export type RideCategory = "RC" | "DR" | "FR" | "WR" | "TR" | "OT";
export type RideStatus = "OPERATING" | "CLOSED_TEMP" | "SBNO" | "CLOSING" | "CLOSED_PERM" | "UNDER_CONSTRUCTION" | "DEMOLISHED" | "RELOCATED";
export type ParkStatus = "OPERATING" | "CLOSED_TEMP" | "CLOSED_PERM" | "UNDER_CONSTRUCTION";
export type UserRole = "USER" | "MODERATOR" | "ADMIN" | "SUPERUSER";
export type ThemePreference = "light" | "dark";
export type PrivacyLevel = "public" | "friends" | "private";
export type NotificationType = "SUBMISSION" | "REVIEW" | "SOCIAL" | "SYSTEM" | "ACHIEVEMENT";
export type EntityType = "park" | "ride" | "company";
export type PhotoType = "GENERAL" | "ENTRANCE" | "RIDE" | "FOOD" | "SHOP" | "SHOW" | "STATION" | "LIFT" | "ELEMENT" | "TRAIN" | "QUEUE";
export type HealthStatus = "healthy" | "degraded" | "unhealthy";
export type ActionType = "CREATE" | "UPDATE" | "DELETE";

// ============================================================================
// API Response Wrapper Types
// ============================================================================

export interface PaginatedResponse<T> {
  count: number;
  next: string | null;
  previous: string | null;
  results: T[];
}

export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
  errors?: ValidationError;
}

// ============================================================================
// Form Data Types for File Uploads
// ============================================================================

export interface FileUploadData {
  file: File;
  caption?: string;
  photo_type?: PhotoType;
}

// ============================================================================
// Filter and Search Types
// ============================================================================

export interface FilterOption {
  value: string;
  label: string;
}

export interface FilterRange {
  min: number;
  max: number;
  step: number;
  unit?: string;
}

export interface BooleanFilter {
  key: string;
  label: string;
  description: string;
}

export interface SearchFilters {
  search?: string;
  categories?: RideCategory[];
  statuses?: RideStatus[];
  park_id?: number;
  park_slug?: string;
  manufacturer_id?: number;
  manufacturer_slug?: string;
  designer_id?: number;
  designer_slug?: string;
  min_rating?: number;
  max_rating?: number;
  min_height_requirement?: number;
  max_height_requirement?: number;
  min_capacity?: number;
  max_capacity?: number;
  min_height_ft?: number;
  max_height_ft?: number;
  min_speed_mph?: number;
  max_speed_mph?: number;
  min_inversions?: number;
  max_inversions?: number;
  has_inversions?: boolean;
  opening_year?: number;
  min_opening_year?: number;
  max_opening_year?: number;
  ordering?: string;
  page?: number;
  page_size?: number;
}

// ============================================================================
// Location and Geographic Types
// ============================================================================

export interface Coordinates {
  latitude: number;
  longitude: number;
}

export interface BoundingBox {
  sw_lat: number;
  sw_lng: number;
  ne_lat: number;
  ne_lng: number;
}

export interface LocationData {
  country: string;
  state: string;
  city: string;
  address?: string;
  latitude?: number;
  longitude?: number;
}

// ============================================================================
// Statistics and Analytics Types
// ============================================================================

export interface RatingDistribution {
  "1": number;
  "2": number;
  "3": number;
  "4": number;
  "5": number;
  "6": number;
  "7": number;
  "8": number;
  "9": number;
  "10": number;
}

export interface CoasterStats {
  roller_coaster_type: string;
  track_material: string;
  launch_type: string;
  height_ft: number | null;
  speed_mph: number | null;
  inversions: number;
  length_ft: number | null;
  duration_seconds: number | null;
}

export interface ParkStatistics {
  total_rides: number;
  roller_coasters: number;
  dark_rides: number;
  flat_rides: number;
  water_rides: number;
  transport_rides: number;
}

// ============================================================================
// Company and Manufacturer Types
// ============================================================================

export interface CompanyInfo {
  id: number;
  name: string;
  slug: string;
  description?: string;
  founded_year?: number | null;
  headquarters?: string;
}

export interface RideModelInfo {
  id: number;
  name: string;
  slug: string;
  category: string;
  description?: string;
  first_installation?: string | null;
  installations_count?: number;
  manufacturer: CompanyInfo;
}

// ============================================================================
// User and Profile Types
// ============================================================================

export interface UserInfo {
  id: number;
  username: string;
  display_name: string;
  avatar_url?: string;
}

export interface ProfileStatistics {
  coaster_credits: number;
  dark_ride_credits: number;
  flat_ride_credits: number;
  water_ride_credits: number;
  total_credits: number;
}

export interface UserAchievements {
  first_review: boolean;
  photo_contributor: boolean;
  top_reviewer: boolean;
  park_explorer: boolean;
  coaster_enthusiast: boolean;
}

// ============================================================================
// Content Moderation Types
// ============================================================================

export interface ModerationReport {
  id: number;
  report_type: "SPAM" | "HARASSMENT" | "INAPPROPRIATE_CONTENT" | "MISINFORMATION" | "COPYRIGHT" | "PRIVACY" | "HATE_SPEECH" | "VIOLENCE" | "OTHER";
  report_type_display: string;
  status: "PENDING" | "UNDER_REVIEW" | "RESOLVED" | "DISMISSED";
  status_display: string;
  priority: "LOW" | "MEDIUM" | "HIGH" | "URGENT";
  priority_display: string;
  reported_entity_type: "park" | "ride" | "review" | "photo" | "user" | "comment";
  reported_entity_id: number;
  reason: string;
  description: string;
  evidence_urls: string[];
  reported_by: {
    id: number;
    username: string;
    display_name: string;
    email: string;
    role: UserRole;
  };
  assigned_moderator: {
    id: number;
    username: string;
    display_name: string;
    email: string;
    role: UserRole;
  } | null;
  content_type: {
    id: number;
    app_label: string;
    model: string;
  } | null;
  resolution_action: string;
  resolution_notes: string;
  resolved_at: string | null;
  created_at: string;
  updated_at: string;
  // Computed fields
  is_overdue: boolean;
  time_since_created: string;
}

export interface ModerationReportsResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: ModerationReport[];
  stats: {
    pending: number;
    under_review: number;
    resolved_today: number;
    total_open: number;
  };
}

export interface CreateModerationReport {
  report_type: "INAPPROPRIATE_CONTENT" | "SPAM" | "HARASSMENT" | "COPYRIGHT" | "MISINFORMATION" | "OTHER";
  reported_entity_type: "park" | "ride" | "review" | "photo" | "user" | "comment";
  reported_entity_id: number;
  reason: string;
  description: string;
  evidence_urls?: string[];
}

export interface ModerationQueueItem {
  id: number;
  item_type: "CONTENT_REVIEW" | "USER_REVIEW" | "BULK_ACTION" | "POLICY_VIOLATION" | "APPEAL" | "OTHER";
  status: "PENDING" | "IN_PROGRESS" | "COMPLETED" | "CANCELLED";
  priority: "LOW" | "MEDIUM" | "HIGH" | "URGENT";
  title: string;
  description: string;
  entity_type: string;
  entity_id: number | null;
  entity_preview: Record<string, any>;
  assigned_to: {
    id: number;
    username: string;
    display_name: string;
    email: string;
    role: UserRole;
  } | null;
  assigned_at: string | null;
  estimated_review_time: number; // minutes
  flagged_by: {
    id: number;
    username: string;
    display_name: string;
  } | null;
  tags: string[];
  content_type: {
    id: number;
    app_label: string;
    model: string;
  } | null;
  related_report: ModerationReport | null;
  created_at: string;
  updated_at: string;
  // Computed fields
  is_overdue: boolean;
  time_in_queue: number; // minutes
  estimated_completion: string;
}

export interface ModerationQueueResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: ModerationQueueItem[];
  queue_stats: {
    total_pending: number;
    total_in_progress: number;
    average_resolution_time: number; // minutes
    oldest_pending_age: number; // hours
    my_assigned: number;
  };
}

// Unified moderation report update interface
export interface UpdateModerationReportData {
  status?: "PENDING" | "UNDER_REVIEW" | "RESOLVED" | "DISMISSED";
  priority?: "LOW" | "MEDIUM" | "HIGH" | "URGENT";
  assigned_moderator?: number | null;
  resolution_notes?: string;
  resolution_action?: string;
}

// Backward compatibility alias
export interface UpdateModerationReport extends UpdateModerationReportData {
  assigned_moderator_id?: number | null; // Legacy field name
}

export interface ModerationAction {
  id: number;
  action_type: "WARNING" | "USER_SUSPENSION" | "USER_BAN" | "CONTENT_REMOVAL" | "CONTENT_EDIT" | "CONTENT_RESTRICTION" | "ACCOUNT_RESTRICTION" | "OTHER";
  action_type_display: string;
  reason: string;
  details: string;
  duration_hours: number | null;
  created_at: string;
  updated_at: string;
  expires_at: string | null;
  is_active: boolean;
  moderator: {
    id: number;
    username: string;
    display_name: string;
    email: string;
    role: UserRole;
  };
  target_user: {
    id: number;
    username: string;
    display_name: string;
    email: string;
    role: UserRole;
  };
  related_report: ModerationReport | null;
  // Computed fields
  is_expired: boolean;
  time_remaining: string | null;
}

// ============================================================================
// User Moderation Types
// ============================================================================

export interface UserModerationProfile {
  user: {
    id: number;
    username: string;
    display_name: string;
    email: string;
    date_joined: string;
    last_login: string | null;
    is_active: boolean;
    role: "USER" | "MODERATOR" | "ADMIN" | "SUPERUSER";
  };
  moderation_history: {
    total_reports_against: number;
    total_warnings: number;
    total_suspensions: number;
    total_bans: number;
    current_restrictions: ModerationAction[];
    recent_actions: ModerationAction[];
  };
  account_stats: {
    total_reviews: number;
    total_photos: number;
    total_reports_made: number;
    helpful_votes_received: number;
    account_age_days: number;
    last_activity: string;
  };
  risk_assessment: {
    risk_level: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";
    risk_factors: string[];
    trust_score: number; // 0-100
    automated_flags: number;
  };
}

export interface UserModerationAction {
  action_type: "WARNING" | "SUSPEND" | "BAN" | "RESTRICT_POSTING" | "RESTRICT_PHOTOS" | "REMOVE_CONTENT";
  reason: string;
  details: string;
  duration_hours?: number; // Required for temporary actions
  notify_user: boolean;
  remove_content?: boolean; // For content-related actions
  content_types?: ("reviews" | "photos" | "comments")[]; // Specific content to remove
}

export interface UserModerationActionResponse {
  success: boolean;
  message: string;
  action: ModerationAction;
  affected_content?: {
    reviews_removed: number;
    photos_removed: number;
    comments_removed: number;
  };
}

export interface UserModerationStats {
  total_users: number;
  active_users_30d: number;
  users_with_restrictions: number;
  users_banned: number;
  users_suspended: number;
  pending_appeals: number;
  moderation_actions_today: number;
  average_response_time_hours: number;
}

// ============================================================================
// Bulk Operations Types
// ============================================================================

export interface BulkOperation {
  id: string;
  operation_type: "UPDATE_PARKS" | "UPDATE_RIDES" | "IMPORT_DATA" | "EXPORT_DATA" | "RECALCULATE_STATS" | "MODERATE_CONTENT" | "USER_ACTIONS";
  status: "PENDING" | "RUNNING" | "COMPLETED" | "FAILED" | "CANCELLED";
  created_by: {
    id: number;
    username: string;
    display_name: string;
  };
  created_at: string;
  started_at: string | null;
  completed_at: string | null;
  progress: {
    total_items: number;
    processed_items: number;
    failed_items: number;
    percentage: number;
  };
  parameters: Record<string, any>;
  results: {
    success_count: number;
    error_count: number;
    warnings: string[];
    errors: string[];
    summary: string;
  } | null;
  estimated_duration_minutes: number | null;
  can_cancel: boolean;
}

export interface BulkOperationsResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: BulkOperation[];
  active_operations: number;
  queued_operations: number;
}

export interface CreateBulkOperation {
  operation_type: "UPDATE_PARKS" | "UPDATE_RIDES" | "IMPORT_DATA" | "EXPORT_DATA" | "RECALCULATE_STATS" | "MODERATE_CONTENT" | "USER_ACTIONS";
  parameters: Record<string, any>;
  description?: string;
  priority?: "LOW" | "NORMAL" | "HIGH";
  schedule_for?: string; // ISO datetime for scheduled operations
}

export interface BulkUpdateParks {
  operation_type: "UPDATE_PARKS";
  parameters: {
    park_ids?: number[];
    filters?: {
      country?: string;
      state?: string;
      status?: ParkStatus;
      operator_id?: number;
    };
    updates: {
      status?: ParkStatus;
      operator_id?: number;
      property_owner_id?: number;
      description?: string;
      custom_fields?: Record<string, any>;
    };
    batch_size?: number;
  };
}

export interface BulkUpdateRides {
  operation_type: "UPDATE_RIDES";
  parameters: {
    ride_ids?: number[];
    filters?: {
      park_id?: number;
      category?: RideCategory;
      status?: RideStatus;
      manufacturer_id?: number;
    };
    updates: {
      status?: RideStatus;
      manufacturer_id?: number;
      designer_id?: number;
      ride_model_id?: number;
      capacity_per_hour?: number;
      custom_fields?: Record<string, any>;
    };
    batch_size?: number;
  };
}

export interface BulkImportData {
  operation_type: "IMPORT_DATA";
  parameters: {
    data_type: "PARKS" | "RIDES" | "COMPANIES" | "REVIEWS";
    source_format: "CSV" | "JSON" | "XML";
    file_url: string;
    mapping_config: Record<string, string>;
    validation_rules?: Record<string, any>;
    conflict_resolution: "SKIP" | "UPDATE" | "CREATE_NEW";
    batch_size?: number;
  };
}

export interface BulkExportData {
  operation_type: "EXPORT_DATA";
  parameters: {
    data_type: "PARKS" | "RIDES" | "COMPANIES" | "REVIEWS" | "USERS";
    format: "CSV" | "JSON" | "XML";
    filters?: Record<string, any>;
    include_fields?: string[];
    exclude_fields?: string[];
    include_relationships?: boolean;
  };
}

export interface BulkModerateContent {
  operation_type: "MODERATE_CONTENT";
  parameters: {
    content_type: "reviews" | "photos" | "comments";
    action: "APPROVE" | "REJECT" | "FLAG" | "REMOVE";
    filters?: {
      reported_by_users?: number[];
      content_ids?: number[];
      date_range?: {
        start: string;
        end: string;
      };
      keywords?: string[];
    };
    reason?: string;
    notify_users?: boolean;
  };
}

export interface BulkUserActions {
  operation_type: "USER_ACTIONS";
  parameters: {
    user_ids?: number[];
    filters?: {
      role?: UserRole;
      registration_date_range?: {
        start: string;
        end: string;
      };
      last_activity_before?: string;
      has_violations?: boolean;
    };
    action: "SUSPEND" | "UNSUSPEND" | "BAN" | "UNBAN" | "SEND_EMAIL" | "UPDATE_ROLE";
    action_parameters?: {
      duration_hours?: number;
      reason?: string;
      email_template?: string;
      new_role?: UserRole;
    };
    notify_users?: boolean;
  };
}

export interface BulkOperationResult {
  operation_id: string;
  success: boolean;
  message: string;
  estimated_completion: string;
}

// ============================================================================
// Moderation Statistics and Dashboard Types
// ============================================================================

export interface ModerationStatsData {
  // Report stats
  total_reports: number;
  pending_reports: number;
  resolved_reports: number;
  overdue_reports: number;
  // Queue stats
  queue_size: number;
  assigned_items: number;
  unassigned_items: number;
  // Action stats
  total_actions: number;
  active_actions: number;
  expired_actions: number;
  // Bulk operation stats
  running_operations: number;
  completed_operations: number;
  failed_operations: number;
  // Performance metrics
  average_resolution_time_hours: number;
  reports_by_priority: Record<string, number>;
  reports_by_type: Record<string, number>;
}

export interface AssignQueueItemData {
  moderator_id: number;
}

export interface CompleteQueueItemData {
  action: "NO_ACTION" | "CONTENT_REMOVED" | "CONTENT_EDITED" | "USER_WARNING" | "USER_SUSPENDED" | "USER_BANNED";
  notes?: string;
}

export interface CreateModerationActionData {
  action_type: "WARNING" | "USER_SUSPENSION" | "USER_BAN" | "CONTENT_REMOVAL" | "CONTENT_EDIT" | "CONTENT_RESTRICTION" | "ACCOUNT_RESTRICTION" | "OTHER";
  reason: string;
  details: string;
  duration_hours?: number;
  target_user_id: number;
  related_report_id?: number;
}

export interface UpdateModerationReportData {
  status?: "PENDING" | "UNDER_REVIEW" | "RESOLVED" | "DISMISSED";
  priority?: "LOW" | "MEDIUM" | "HIGH" | "URGENT";
  assigned_moderator?: number | null;
  resolution_notes?: string;
  resolution_action?: string;
}

export interface UserModerationProfileData {
  user: {
    id: number;
    username: string;
    display_name: string;
    email: string;
    role: UserRole;
  };
  reports_made: number;
  reports_against: number;
  warnings_received: number;
  suspensions_received: number;
  active_restrictions: number;
  risk_level: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";
  risk_factors: string[];
  recent_reports: ModerationReport[];
  recent_actions: ModerationAction[];
  account_status: string;
  last_violation_date: string | null;
  next_review_date: string | null;
}

// ============================================================================
// Moderation Filter Types
// ============================================================================

export interface ModerationReportFilters {
  status?: "PENDING" | "UNDER_REVIEW" | "RESOLVED" | "DISMISSED";
  priority?: "LOW" | "MEDIUM" | "HIGH" | "URGENT";
  report_type?: "SPAM" | "HARASSMENT" | "INAPPROPRIATE_CONTENT" | "MISINFORMATION" | "COPYRIGHT" | "PRIVACY" | "HATE_SPEECH" | "VIOLENCE" | "OTHER";
  reported_by?: number;
  assigned_moderator?: number;
  created_after?: string;
  created_before?: string;
  resolved_after?: string;
  resolved_before?: string;
  content_type?: string;
  unassigned?: boolean;
  overdue?: boolean;
  has_resolution?: boolean;
  search?: string;
  ordering?: string;
  page?: number;
  page_size?: number;
}

export interface ModerationQueueFilters {
  status?: "PENDING" | "IN_PROGRESS" | "COMPLETED" | "CANCELLED";
  priority?: "LOW" | "MEDIUM" | "HIGH" | "URGENT";
  item_type?: "CONTENT_REVIEW" | "USER_REVIEW" | "BULK_ACTION" | "POLICY_VIOLATION" | "APPEAL" | "OTHER";
  assigned_to?: number;
  unassigned?: boolean;
  created_after?: string;
  created_before?: string;
  assigned_after?: string;
  assigned_before?: string;
  content_type?: string;
  has_related_report?: boolean;
  search?: string;
  ordering?: string;
  page?: number;
  page_size?: number;
}

export interface ModerationActionFilters {
  action_type?: "WARNING" | "USER_SUSPENSION" | "USER_BAN" | "CONTENT_REMOVAL" | "CONTENT_EDIT" | "CONTENT_RESTRICTION" | "ACCOUNT_RESTRICTION" | "OTHER";
  moderator?: number;
  target_user?: number;
  is_active?: boolean;
  created_after?: string;
  created_before?: string;
  expires_after?: string;
  expires_before?: string;
  expired?: boolean;
  expiring_soon?: boolean;
  has_related_report?: boolean;
  search?: string;
  ordering?: string;
  page?: number;
  page_size?: number;
}

export interface BulkOperationFilters {
  status?: "PENDING" | "RUNNING" | "COMPLETED" | "FAILED" | "CANCELLED";
  operation_type?: "UPDATE_PARKS" | "UPDATE_RIDES" | "IMPORT_DATA" | "EXPORT_DATA" | "MODERATE_CONTENT" | "USER_ACTIONS" | "OTHER";
  priority?: "LOW" | "MEDIUM" | "HIGH" | "URGENT";
  created_by?: number;
  created_after?: string;
  created_before?: string;
  started_after?: string;
  started_before?: string;
  completed_after?: string;
  completed_before?: string;
  can_cancel?: boolean;
  has_failures?: boolean;
  in_progress?: boolean;
  search?: string;
  ordering?: string;
  page?: number;
  page_size?: number;
}

export interface UserModerationSearchFilters {
  query?: string;
  role?: UserRole;
  has_restrictions?: boolean;
  registration_after?: string;
  registration_before?: string;
  last_activity_before?: string;
  risk_level?: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";
  page?: number;
  page_size?: number;
}

// ============================================================================
// Park Reviews Types
// ============================================================================

export interface ParkReview {
  id: number;
  park: {
    id: number;
    name: string;
    slug: string;
  };
  author: {
    id: number;
    username: string;
    display_name: string;
    avatar_url: string;
  };
  rating: number; // 1-10 scale
  title: string;
  content: string;
  visit_date: string | null;
  pros: string[];
  cons: string[];
  categories: {
    atmosphere: number | null; // 1-10
    cleanliness: number | null; // 1-10
    staff_friendliness: number | null; // 1-10
    value_for_money: number | null; // 1-10
    food_quality: number | null; // 1-10
    ride_variety: number | null; // 1-10
  };
  recommended_for: ("families" | "thrill_seekers" | "coaster_enthusiasts" | "first_timers" | "couples" | "groups")[];
  crowd_level: "VERY_LOW" | "LOW" | "MODERATE" | "HIGH" | "VERY_HIGH" | null;
  weather_conditions: "SUNNY" | "CLOUDY" | "RAINY" | "SNOWY" | "WINDY" | null;
  photos: ParkReviewPhoto[];
  helpful_votes: number;
  total_votes: number;
  user_vote: "HELPFUL" | "NOT_HELPFUL" | null; // Current user's vote
  is_verified_visit: boolean;
  created_at: string;
  updated_at: string;
  moderation_status: "APPROVED" | "PENDING" | "FLAGGED" | "REMOVED";
  response_from_park: {
    id: number;
    content: string;
    responder_name: string;
    responder_title: string;
    created_at: string;
  } | null;
}

export interface ParkReviewPhoto {
  id: number;
  image_url: string;
  image_variants: ImageVariants;
  caption: string;
  photo_type: "ENTRANCE" | "RIDES" | "FOOD" | "ATMOSPHERE" | "CROWDS" | "OTHER";
  uploaded_at: string;
}

export interface ParkReviewsResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: ParkReview[];
  summary: {
    average_rating: number;
    total_reviews: number;
    rating_distribution: RatingDistribution;
    category_averages: {
      atmosphere: number;
      cleanliness: number;
      staff_friendliness: number;
      value_for_money: number;
      food_quality: number;
      ride_variety: number;
    };
    recent_trends: {
      last_30_days_average: number;
      trend_direction: "UP" | "DOWN" | "STABLE";
      trend_percentage: number;
    };
  };
}

export interface CreateParkReview {
  rating: number; // 1-10 scale
  title: string;
  content: string;
  visit_date?: string; // YYYY-MM-DD format
  pros?: string[];
  cons?: string[];
  categories?: {
    atmosphere?: number; // 1-10
    cleanliness?: number; // 1-10
    staff_friendliness?: number; // 1-10
    value_for_money?: number; // 1-10
    food_quality?: number; // 1-10
    ride_variety?: number; // 1-10
  };
  recommended_for?: ("families" | "thrill_seekers" | "coaster_enthusiasts" | "first_timers" | "couples" | "groups")[];
  crowd_level?: "VERY_LOW" | "LOW" | "MODERATE" | "HIGH" | "VERY_HIGH";
  weather_conditions?: "SUNNY" | "CLOUDY" | "RAINY" | "SNOWY" | "WINDY";
}

export interface UpdateParkReview {
  rating?: number;
  title?: string;
  content?: string;
  visit_date?: string;
  pros?: string[];
  cons?: string[];
  categories?: {
    atmosphere?: number;
    cleanliness?: number;
    staff_friendliness?: number;
    value_for_money?: number;
    food_quality?: number;
    ride_variety?: number;
  };
  recommended_for?: ("families" | "thrill_seekers" | "coaster_enthusiasts" | "first_timers" | "couples" | "groups")[];
  crowd_level?: "VERY_LOW" | "LOW" | "MODERATE" | "HIGH" | "VERY_HIGH";
  weather_conditions?: "SUNNY" | "CLOUDY" | "RAINY" | "SNOWY" | "WINDY";
}

export interface ParkReviewVote {
  vote_type: "HELPFUL" | "NOT_HELPFUL";
}

export interface ParkReviewVoteResponse {
  success: boolean;
  message: string;
  new_vote: "HELPFUL" | "NOT_HELPFUL" | null;
  helpful_votes: number;
  total_votes: number;
}

export interface UploadParkReviewPhoto {
  image: File;
  caption?: string;
  photo_type?: "ENTRANCE" | "RIDES" | "FOOD" | "ATMOSPHERE" | "CROWDS" | "OTHER";
}

export interface ParkReviewFilters {
  rating_min?: number;
  rating_max?: number;
  visit_date_after?: string;
  visit_date_before?: string;
  has_photos?: boolean;
  verified_visits_only?: boolean;
  crowd_level?: ("VERY_LOW" | "LOW" | "MODERATE" | "HIGH" | "VERY_HIGH")[];
  weather_conditions?: ("SUNNY" | "CLOUDY" | "RAINY" | "SNOWY" | "WINDY")[];
  recommended_for?: ("families" | "thrill_seekers" | "coaster_enthusiasts" | "first_timers" | "couples" | "groups")[];
  ordering?: "newest" | "oldest" | "highest_rated" | "lowest_rated" | "most_helpful";
  page?: number;
  page_size?: number;
}

// ============================================================================
// External API Types (merged from thrillwiki-real)
// ============================================================================

// Main entity types from external API
export interface Park {
  id: number;
  name: string;
  slug: string;
  location?: Location;
  status: string;
  description?: string;
  average_rating?: number;
  coaster_count?: number;
  ride_count?: number;
  opening_date?: string;
  operator?: { id: number; name: string };
  primary_photo?: Photo;
  created_at: string;
  date_opened: string;
}

export interface Ride {
  id: number;
  name: string;
  slug: string;
  category: string;
  park?: Park | number;
  status: string;
  description?: string;
  average_rating?: number;
  capacity_per_hour?: number;
  ride_duration_seconds?: number;
  primary_photo?: Photo;
  created_at: string;
  park_change_info?: ParkChangeInfo; // Added for park change operations
}

export interface Company {
  id: number;
  name: string;
  slug: string;
  roles: string[];
  notable_parks: { id: number; name: string }[];
  logo_url?: string;
  website?: string;
  description?: string;
  founded_year?: number;
  status?: string;
  ride_count?: number;
  park_count?: number;
  headquarters?: Location;
  ride_model_count?: number;
}

export interface Review {
  id: number;
  user: User;
  entity: Entity;
  entity_type: 'park' | 'ride';
  rating: number;
  text: string;
  created_at: string;
}

// Stats interface from external API
export interface Stats {
  total_parks: number;
  total_rides: number;
  total_manufacturers: number;
  total_operators: number;
  total_designers: number;
  total_property_owners: number;
  total_roller_coasters: number;
  total_photos: number;
  total_park_photos: number;
  total_ride_photos: number;
  total_reviews: number;
  total_park_reviews: number;
  total_ride_reviews: number;
  roller_coasters: number;
  operating_parks: number;
  operating_rides: number;
  last_updated: string;
  relative_last_updated: string;
}

export interface TrendingItem {
  id: number;
  name: string;
  park: string;
  category: string;
  rating: number;
  rank: number;
  views: number;
  views_change: string;
  slug: string;
  date_opened: string;
  park_slug?: string;
}

// User interface from external API
export interface User {
  id: string;
  username: string;
  email: string;
  display_name: string;
  avatar_url?: string;
}

// Auth types from external API
export interface RegisterRequest {
  email: string;
  username: string;
  password?: string;
  display_name: string;
}

// Filter types from external API
export interface FilterOptions {
  categories?: [string, string][];
  statuses?: [string, string][];
  roles?: [string, string][];
  countries?: string[];
  track_materials?: [string, string][];
  boolean_filters?: BooleanFilter[];
  filter_ranges?: {
    height_ft?: FilterRange;
    speed_mph?: FilterRange;
    rating?: FilterRange;
  };
  ordering_options?: OrderingOption[];
}

export interface OrderingOption {
  value: string;
  label: string;
}

// ============================================================================
// Hybrid Rides Filtering Types
// ============================================================================

export interface HybridRideData {
  // Basic ride info
  id: number;
  name: string;
  slug: string;
  description?: string;
  category: RideCategory;
  status: RideStatus;
  post_closing_status?: string;
  
  // Dates and computed fields
  opening_date?: string;
  closing_date?: string;
  status_since?: string;
  opening_year?: number;
  
  // Park fields
  park_name: string;
  park_slug: string;
  park_city?: string;
  park_state?: string;
  park_country?: string;
  
  // Park area fields
  park_area_name?: string;
  park_area_slug?: string;
  
  // Company fields
  manufacturer_name?: string;
  manufacturer_slug?: string;
  designer_name?: string;
  designer_slug?: string;
  
  // Ride model fields
  ride_model_name?: string;
  ride_model_slug?: string;
  ride_model_category?: string;
  ride_model_manufacturer_name?: string;
  ride_model_manufacturer_slug?: string;
  
  // Ride specifications
  min_height_in?: number;
  max_height_in?: number;
  capacity_per_hour?: number;
  ride_duration_seconds?: number;
  average_rating?: number;
  
  // Roller coaster stats
  coaster_height_ft?: number;
  coaster_length_ft?: number;
  coaster_speed_mph?: number;
  coaster_inversions?: number;
  coaster_ride_time_seconds?: number;
  coaster_track_type?: string;
  coaster_track_material?: string;
  coaster_roller_coaster_type?: string;
  coaster_max_drop_height_ft?: number;
  coaster_launch_type?: string;
  coaster_train_style?: string;
  coaster_trains_count?: number;
  coaster_cars_per_train?: number;
  coaster_seats_per_car?: number;
  
  // Images
  banner_image_url?: string;
  card_image_url?: string;
  
  // URLs
  url: string;
  park_url?: string;
  
  // Computed fields for filtering
  search_text: string;
  
  // Metadata
  created_at: string;
  updated_at: string;
}

export interface HybridRideFilterMetadata {
  // Static options
  categories: Array<{value: string; label: string}>;
  statuses: Array<{value: string; label: string}>;
  post_closing_statuses: Array<{value: string; label: string}>;
  roller_coaster_types: Array<{value: string; label: string}>;
  track_materials: Array<{value: string; label: string}>;
  launch_types: Array<{value: string; label: string}>;
  
  // Dynamic data
  parks: Array<{
    park__id: number;
    park__name: string;
    park__slug: string;
  }>;
  park_areas: Array<{
    park_area__id: number;
    park_area__name: string;
    park_area__slug: string;
  }>;
  manufacturers: Array<{
    id: number;
    name: string;
    slug: string;
  }>;
  designers: Array<{
    id: number;
    name: string;
    slug: string;
  }>;
  ride_models: Array<{
    id: number;
    name: string;
    slug: string;
    manufacturer__name: string;
    manufacturer__slug: string;
    category: string;
  }>;
  
  // Ranges
  ranges: {
    rating: {min: number; max: number; step: number; unit: string};
    height_requirement: {min: number; max: number; step: number; unit: string};
    capacity: {min: number; max: number; step: number; unit: string};
    ride_duration: {min: number; max: number; step: number; unit: string};
    height_ft: {min: number; max: number; step: number; unit: string};
    length_ft: {min: number; max: number; step: number; unit: string};
    speed_mph: {min: number; max: number; step: number; unit: string};
    inversions: {min: number; max: number; step: number; unit: string};
    ride_time: {min: number; max: number; step: number; unit: string};
    max_drop_height_ft: {min: number; max: number; step: number; unit: string};
    trains_count: {min: number; max: number; step: number; unit: string};
    cars_per_train: {min: number; max: number; step: number; unit: string};
    seats_per_car: {min: number; max: number; step: number; unit: string};
    opening_year: {min: number; max: number; step: number; unit: string};
  };
  
  // Boolean filters
  boolean_filters: Array<{
    key: string;
    label: string;
    description: string;
  }>;
  
  // Ordering options
  ordering_options: Array<{value: string; label: string}>;
}

export interface HybridRideResponse {
  strategy: 'client_side' | 'server_side';
  data: HybridRideData[];
  total_count: number;
  has_more: boolean;
  filter_metadata: HybridRideFilterMetadata;
}

export interface HybridRideFilters {
  // Text search
  search?: string;
  
  // Park filters
  park_slug?: string;
  park_id?: number;
  
  // Multi-value filters (comma-separated strings)
  categories?: string; // "RC,DR,FR"
  statuses?: string; // "OPERATING,CLOSED_TEMP"
  manufacturer_ids?: string; // "1,2,3"
  designer_ids?: string; // "1,2,3"
  ride_model_ids?: string; // "1,2,3"
  roller_coaster_types?: string; // "SITDOWN,INVERTED"
  track_materials?: string; // "STEEL,WOOD,HYBRID"
  launch_types?: string; // "CHAIN,LSM,HYDRAULIC"
  
  // Numeric filters
  opening_year?: number;
  min_opening_year?: number;
  max_opening_year?: number;
  min_rating?: number;
  max_rating?: number;
  min_height_requirement?: number;
  max_height_requirement?: number;
  min_capacity?: number;
  max_capacity?: number;
  min_height_ft?: number;
  max_height_ft?: number;
  min_speed_mph?: number;
  max_speed_mph?: number;
  min_inversions?: number;
  max_inversions?: number;
  
  // Boolean filters
  has_inversions?: boolean;
  
  // Ordering
  ordering?: string;
}

export interface HybridRideProgressiveResponse {
  data: HybridRideData[];
  has_more: boolean;
  total_count: number;
}

// Frontend utility types for hybrid filtering
export interface RideFilterState {
  search: string;
  categories: RideCategory[];
  statuses: RideStatus[];
  parkId?: number;
  manufacturerIds: number[];
  designerIds: number[];
  rideModelIds: number[];
  rollerCoasterTypes: string[];
  trackMaterials: string[];
  launchTypes: string[];
  ratingRange: [number, number];
  heightRequirementRange: [number, number];
  capacityRange: [number, number];
  heightFtRange: [number, number];
  speedMphRange: [number, number];
  inversionRange: [number, number];
  openingYearRange: [number, number];
  hasInversions?: boolean;
  ordering: string;
}

export interface RideFilterActions {
  setSearch: (search: string) => void;
  setCategories: (categories: RideCategory[]) => void;
  setStatuses: (statuses: RideStatus[]) => void;
  setParkId: (parkId?: number) => void;
  setManufacturerIds: (ids: number[]) => void;
  setDesignerIds: (ids: number[]) => void;
  setRideModelIds: (ids: number[]) => void;
  setRollerCoasterTypes: (types: string[]) => void;
  setTrackMaterials: (materials: string[]) => void;
  setLaunchTypes: (types: string[]) => void;
  setRatingRange: (range: [number, number]) => void;
  setHeightRequirementRange: (range: [number, number]) => void;
  setCapacityRange: (range: [number, number]) => void;
  setHeightFtRange: (range: [number, number]) => void;
  setSpeedMphRange: (range: [number, number]) => void;
  setInversionRange: (range: [number, number]) => void;
  setOpeningYearRange: (range: [number, number]) => void;
  setHasInversions: (hasInversions?: boolean) => void;
  setOrdering: (ordering: string) => void;
  resetFilters: () => void;
}
