// User types
export type UserRole = 'user' | 'admin'

// Public user info (visible to other users)
export interface UserPublic {
  id: number
  nickname: string
  avatar_url: string | null
  role: UserRole
  telegram_avatar_url: string | null
  created_at: string
}

// Full user info (only for own profile from /auth/me)
export interface User extends UserPublic {
  login?: string  // Only visible to self
  telegram_id?: number | null  // Only visible to self
  telegram_username?: string | null  // Only visible to self
  telegram_first_name?: string | null  // Only visible to self
  telegram_last_name?: string | null  // Only visible to self
}

export interface TokenResponse {
  access_token: string
  token_type: string
  user: User
}

// Login response (may require 2FA for admins)
export interface LoginResponse {
  access_token?: string | null
  token_type: string
  user?: User | null
  requires_2fa: boolean
  two_factor_session_id?: number | null
}

// Marathon types
export type MarathonStatus = 'preparing' | 'active' | 'finished'
export type ParticipantRole = 'participant' | 'organizer'
export type GameProposalMode = 'all_participants' | 'organizer_only'

export interface ParticipantInfo {
  id: number
  role: ParticipantRole
  total_points: number
  current_streak: number
  drop_count: number
  joined_at: string
}

export interface ParticipantWithUser extends ParticipantInfo {
  user: User
}

export interface Marathon {
  id: number
  title: string
  description: string | null
  creator: User
  status: MarathonStatus
  invite_code: string
  is_public: boolean
  game_proposal_mode: GameProposalMode
  auto_events_enabled: boolean
  start_date: string | null
  end_date: string | null
  participants_count: number
  games_count: number
  created_at: string
  my_participation: ParticipantInfo | null
}

export interface MarathonListItem {
  id: number
  title: string
  status: MarathonStatus
  is_public: boolean
  participants_count: number
  start_date: string | null
  end_date: string | null
}

export interface MarathonCreate {
  title: string
  description?: string
  start_date: string
  duration_days: number
  is_public: boolean
  game_proposal_mode: GameProposalMode
}

export interface MarathonPublicInfo {
  id: number
  title: string
  description: string | null
  status: MarathonStatus
  participants_count: number
  creator_nickname: string
}

export interface LeaderboardEntry {
  rank: number
  user: User
  total_points: number
  current_streak: number
  completed_count: number
  dropped_count: number
}

// Game types
export type GameStatus = 'pending' | 'approved' | 'rejected'

export interface Game {
  id: number
  title: string
  cover_url: string | null
  download_url: string
  genre: string | null
  status: GameStatus
  proposed_by: User | null
  approved_by: User | null
  challenges_count: number
  created_at: string
}

export interface GameShort {
  id: number
  title: string
  cover_url: string | null
}

// Challenge types
export type ChallengeType =
  | 'completion'
  | 'no_death'
  | 'speedrun'
  | 'collection'
  | 'achievement'
  | 'challenge_run'
  | 'score_attack'
  | 'time_trial'

export type Difficulty = 'easy' | 'medium' | 'hard'
export type ProofType = 'screenshot' | 'video' | 'steam'

export type ChallengeStatus = 'pending' | 'approved' | 'rejected'

export interface ProposedByUser {
  id: number
  nickname: string
}

export interface Challenge {
  id: number
  game: GameShort
  title: string
  description: string
  type: ChallengeType
  difficulty: Difficulty
  points: number
  estimated_time: number | null
  proof_type: ProofType
  proof_hint: string | null
  is_generated: boolean
  created_at: string
  status: ChallengeStatus
  proposed_by: ProposedByUser | null
}

export interface ChallengePreview {
  game_id: number
  game_title: string
  title: string
  description: string
  type: string
  difficulty: Difficulty
  points: number
  estimated_time: number | null
  proof_type: ProofType
  proof_hint: string | null
}

export interface ChallengesPreviewResponse {
  challenges: ChallengePreview[]
}

// Assignment types
export type AssignmentStatus = 'active' | 'completed' | 'dropped' | 'returned'

export interface Assignment {
  id: number
  challenge: Challenge
  status: AssignmentStatus
  proof_url: string | null
  proof_comment: string | null
  points_earned: number
  streak_at_completion: number | null
  started_at: string
  completed_at: string | null
  drop_penalty: number
}

export interface SpinResult {
  assignment_id: number
  game: Game
  challenge: Challenge
  can_drop: boolean
  drop_penalty: number
}

export interface CompleteResult {
  points_earned: number
  streak_bonus: number
  total_points: number
  new_streak: number
}

export interface DropResult {
  penalty: number
  total_points: number
  new_drop_count: number
}

export interface DroppedAssignment {
  id: number
  challenge: Challenge
  dropped_at: string
}

export interface SwapCandidate {
  participant_id: number
  user: User
  challenge_title: string
  challenge_description: string
  challenge_points: number
  challenge_difficulty: Difficulty
  game_title: string
}

// Two-sided swap confirmation types
export type SwapRequestStatus = 'pending' | 'accepted' | 'declined' | 'cancelled'

export interface SwapRequestChallengeInfo {
  title: string
  description: string
  points: number
  difficulty: string
  game_title: string
}

export interface SwapRequestItem {
  id: number
  status: SwapRequestStatus
  from_user: User
  to_user: User
  from_challenge: SwapRequestChallengeInfo
  to_challenge: SwapRequestChallengeInfo
  created_at: string
  responded_at: string | null
}

export interface MySwapRequests {
  incoming: SwapRequestItem[]
  outgoing: SwapRequestItem[]
}

// Common Enemy leaderboard
export interface CommonEnemyLeaderboardEntry {
  participant_id: number
  user: User
  completed_at: string | null
  rank: number | null
  bonus_points: number
}

// Event Assignment (Common Enemy)
export interface EventAssignment {
  assignment: Assignment | null
  event_id: number | null
  challenge_id: number | null
  is_completed: boolean
}

// Activity types
export type ActivityType =
  | 'join'
  | 'spin'
  | 'complete'
  | 'drop'
  | 'start_marathon'
  | 'finish_marathon'
  | 'add_game'
  | 'approve_game'
  | 'reject_game'
  | 'event_start'
  | 'event_end'
  | 'swap'
  | 'rematch'

export interface Activity {
  id: number
  type: ActivityType
  user: User
  data: Record<string, unknown> | null
  created_at: string
}

export interface FeedResponse {
  items: Activity[]
  total: number
  has_more: boolean
}

// Event types
export type EventType =
  | 'golden_hour'
  | 'common_enemy'
  | 'double_risk'
  | 'jackpot'
  | 'swap'
  | 'game_choice'

export interface MarathonEvent {
  id: number
  type: EventType
  start_time: string
  end_time: string | null
  is_active: boolean
  created_by: User | null
  data: Record<string, unknown> | null
  created_at: string
}

export interface EventEffects {
  points_multiplier: number
  drop_free: boolean
  special_action: string | null
  description: string
}

export interface ActiveEvent {
  event: MarathonEvent | null
  effects: EventEffects
  time_remaining_seconds: number | null
}

export interface EventCreate {
  type: EventType
  duration_minutes?: number
  challenge_id?: number
}

export const EVENT_INFO: Record<EventType, { name: string; description: string; color: string }> = {
  golden_hour: {
    name: 'Золотой час',
    description: 'Все очки x1.5!',
    color: 'yellow',
  },
  common_enemy: {
    name: 'Общий враг',
    description: 'Все получают одинаковый челлендж. Первые 3 — бонус!',
    color: 'red',
  },
  double_risk: {
    name: 'Безопасная игра',
    description: 'Дропы бесплатны, но очки x0.5',
    color: 'purple',
  },
  jackpot: {
    name: 'Джекпот',
    description: 'Следующий спин — сложный челлендж с x3 очками!',
    color: 'green',
  },
  swap: {
    name: 'Обмен',
    description: 'Можно поменяться заданием с другим участником',
    color: 'blue',
  },
  game_choice: {
    name: 'Выбор игры',
    description: 'Выбери игру и один из 3 челленджей. Можно заменить задание без штрафа!',
    color: 'orange',
  },
}

// Game Choice types
export interface GameChoiceChallenge {
  id: number
  title: string
  description: string
  difficulty: Difficulty
  points: number
  estimated_time: number | null
  proof_type: ProofType
  proof_hint: string | null
}

export interface GameChoiceChallenges {
  game_id: number
  game_title: string
  challenges: GameChoiceChallenge[]
}

// Admin types
export interface AdminUser {
  id: number
  login: string
  nickname: string
  role: UserRole
  avatar_url: string | null
  telegram_id: number | null
  telegram_username: string | null
  marathons_count: number
  created_at: string
  is_banned: boolean
  banned_at: string | null
  banned_until: string | null  // null = permanent ban
  ban_reason: string | null
}

export interface AdminMarathon {
  id: number
  title: string
  status: MarathonStatus
  creator: User
  participants_count: number
  games_count: number
  start_date: string | null
  end_date: string | null
  created_at: string
}

export interface PlatformStats {
  users_count: number
  marathons_count: number
  games_count: number
  total_participations: number
}

// Admin action log types
export type AdminActionType =
  | 'user_ban'
  | 'user_unban'
  | 'user_role_change'
  | 'marathon_force_finish'
  | 'marathon_delete'
  | 'content_update'
  | 'broadcast_all'
  | 'broadcast_marathon'
  | 'admin_login'
  | 'admin_2fa_success'
  | 'admin_2fa_fail'

export interface AdminLog {
  id: number
  admin_id: number
  admin_nickname: string
  action: AdminActionType
  target_type: string
  target_id: number
  details: Record<string, unknown> | null
  ip_address: string | null
  created_at: string
}

export interface AdminLogsResponse {
  logs: AdminLog[]
  total: number
}

// Broadcast types
export interface BroadcastResponse {
  sent_count: number
  total_count: number
}

// Static content types
export interface StaticContent {
  id: number
  key: string
  title: string
  content: string
  updated_at: string
  created_at: string
}

// Dashboard stats
export interface DashboardStats {
  users_count: number
  banned_users_count: number
  marathons_count: number
  active_marathons_count: number
  games_count: number
  total_participations: number
  recent_logs: AdminLog[]
}

// Dispute types
export type DisputeStatus = 'open' | 'valid' | 'invalid'

export interface DisputeComment {
  id: number
  user: User
  text: string
  created_at: string
}

export interface DisputeVote {
  user: User
  vote: boolean // true = valid, false = invalid
  created_at: string
}

export interface Dispute {
  id: number
  raised_by: User
  reason: string
  status: DisputeStatus
  comments: DisputeComment[]
  votes: DisputeVote[]
  votes_valid: number
  votes_invalid: number
  my_vote: boolean | null
  expires_at: string
  created_at: string
  resolved_at: string | null
}

export interface AssignmentDetail {
  id: number
  challenge: Challenge
  participant: User
  status: AssignmentStatus
  proof_url: string | null
  proof_image_url: string | null
  proof_comment: string | null
  points_earned: number
  streak_at_completion: number | null
  started_at: string
  completed_at: string | null
  can_dispute: boolean
  dispute: Dispute | null
}

export interface ReturnedAssignment {
  id: number
  challenge: Challenge
  original_completed_at: string
  dispute_reason: string
}

// Profile types
export interface UserStats {
  marathons_count: number
  wins_count: number
  completed_assignments: number
  total_points_earned: number
}

export interface UserProfilePublic {
  id: number
  nickname: string
  avatar_url: string | null
  created_at: string
  stats: UserStats
}

export interface PasswordChangeData {
  current_password: string
  new_password: string
}
