import { useState, useEffect } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { marathonsApi, gamesApi } from '@/api'
import type { Marathon, Game, Challenge, ChallengePreview, GameType, ProofType } from '@/types'
import { NeonButton, Input, GlassCard, StatsCard } from '@/components/ui'
import { useAuthStore } from '@/store/auth'
import { useToast } from '@/store/toast'
import { useConfirm } from '@/store/confirm'
import { fuzzyFilter } from '@/utils/fuzzySearch'
import {
  Plus, Trash2, Sparkles, Play, Loader2, Gamepad2, X, Save, Eye,
  ChevronDown, ChevronUp, Edit2, Check, CheckCircle, XCircle, Clock, User, ArrowLeft, Zap, Search, Settings
} from 'lucide-react'
import { MarathonSettingsModal } from '@/components/MarathonSettingsModal'

export function LobbyPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const user = useAuthStore((state) => state.user)
  const toast = useToast()
  const confirm = useConfirm()

  const [marathon, setMarathon] = useState<Marathon | null>(null)
  const [games, setGames] = useState<Game[]>([])
  const [pendingGames, setPendingGames] = useState<Game[]>([])
  const [isLoading, setIsLoading] = useState(true)

  // Add game form
  const [showAddGame, setShowAddGame] = useState(false)
  const [gameTitle, setGameTitle] = useState('')
  const [gameUrl, setGameUrl] = useState('')
  const [gameUrlError, setGameUrlError] = useState<string | null>(null)
  const [gameGenre, setGameGenre] = useState('')
  const [gameType, setGameType] = useState<GameType>('challenges')
  const [playthroughPoints, setPlaythroughPoints] = useState(50)
  const [playthroughDescription, setPlaythroughDescription] = useState('')
  const [playthroughProofType, setPlaythroughProofType] = useState<ProofType>('screenshot')
  const [playthroughProofHint, setPlaythroughProofHint] = useState('')
  const [isAddingGame, setIsAddingGame] = useState(false)

  // Edit game modal
  const [editingGame, setEditingGame] = useState<Game | null>(null)
  const [editTitle, setEditTitle] = useState('')
  const [editUrl, setEditUrl] = useState('')
  const [editGenre, setEditGenre] = useState('')
  const [editGameType, setEditGameType] = useState<GameType>('challenges')
  const [editPlaythroughPoints, setEditPlaythroughPoints] = useState(50)
  const [editPlaythroughDescription, setEditPlaythroughDescription] = useState('')
  const [editPlaythroughProofType, setEditPlaythroughProofType] = useState<ProofType>('screenshot')
  const [editPlaythroughProofHint, setEditPlaythroughProofHint] = useState('')
  const [isEditingGame, setIsEditingGame] = useState(false)

  const validateUrl = (url: string): boolean => {
    if (!url.trim()) return true // Empty is ok, will be caught by required check
    try {
      const parsed = new URL(url.trim())
      if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
        return false
      }
      // Check that hostname has at least one dot (domain.tld)
      const hostname = parsed.hostname
      if (!hostname || !hostname.includes('.')) {
        return false
      }
      // Check that TLD is valid (2-6 letters only, like com, ru, org, online)
      const parts = hostname.split('.')
      const tld = parts[parts.length - 1].toLowerCase()
      if (tld.length < 2 || tld.length > 6 || !/^[a-z]+$/.test(tld)) {
        return false
      }
      return true
    } catch {
      return false
    }
  }

  const handleGameUrlChange = (value: string) => {
    setGameUrl(value)
    if (value.trim() && !validateUrl(value)) {
      setGameUrlError('Введите корректную ссылку (например: https://store.steampowered.com/...)')
    } else {
      setGameUrlError(null)
    }
  }

  // Moderation
  const [moderatingGameId, setModeratingGameId] = useState<number | null>(null)

  // Generate challenges
  const [isGenerating, setIsGenerating] = useState(false)
  const [generateMessage, setGenerateMessage] = useState<string | null>(null)
  const [previewChallenges, setPreviewChallenges] = useState<ChallengePreview[] | null>(null)
  const [isSaving, setIsSaving] = useState(false)
  const [editingIndex, setEditingIndex] = useState<number | null>(null)
  const [showGenerateSelection, setShowGenerateSelection] = useState(false)
  const [selectedGamesForGeneration, setSelectedGamesForGeneration] = useState<number[]>([])

  // View existing challenges
  const [expandedGameId, setExpandedGameId] = useState<number | null>(null)
  const [gameChallenges, setGameChallenges] = useState<Record<number, Challenge[]>>({})
  const [loadingChallenges, setLoadingChallenges] = useState<number | null>(null)

  // Manual challenge creation
  const [addingChallengeToGameId, setAddingChallengeToGameId] = useState<number | null>(null)
  const [newChallenge, setNewChallenge] = useState({
    title: '',
    description: '',
    type: 'completion',
    difficulty: 'medium',
    points: 50,
    estimated_time: 30,
    proof_type: 'screenshot',
    proof_hint: '',
  })
  const [isCreatingChallenge, setIsCreatingChallenge] = useState(false)

  // Edit challenge
  const [editingChallengeId, setEditingChallengeId] = useState<number | null>(null)
  const [editChallenge, setEditChallenge] = useState({
    title: '',
    description: '',
    type: 'completion',
    difficulty: 'medium',
    points: 50,
    estimated_time: 30,
    proof_type: 'screenshot',
    proof_hint: '',
  })
  const [isUpdatingChallenge, setIsUpdatingChallenge] = useState(false)

  // Proposed challenges
  const [proposedChallenges, setProposedChallenges] = useState<Challenge[]>([])
  const [myProposedChallenges, setMyProposedChallenges] = useState<Challenge[]>([])
  const [approvingChallengeId, setApprovingChallengeId] = useState<number | null>(null)
  const [isProposingChallenge, setIsProposingChallenge] = useState(false)
  const [editingProposedId, setEditingProposedId] = useState<number | null>(null)

  // Start marathon
  const [isStarting, setIsStarting] = useState(false)

  // Search
  const [searchQuery, setSearchQuery] = useState('')
  const [generateSearchQuery, setGenerateSearchQuery] = useState('')

  // Games list filters
  const [filterProposer, setFilterProposer] = useState<number | 'all'>('all')
  const [filterChallenges, setFilterChallenges] = useState<'all' | 'with' | 'without'>('all')

  // Generation filters
  const [generateFilterProposer, setGenerateFilterProposer] = useState<number | 'all'>('all')
  const [generateFilterChallenges, setGenerateFilterChallenges] = useState<'all' | 'with' | 'without'>('all')

  // Settings modal
  const [showSettings, setShowSettings] = useState(false)

  useEffect(() => {
    loadData()
  }, [id])

  const loadData = async () => {
    if (!id) return
    try {
      const marathonData = await marathonsApi.get(parseInt(id))
      setMarathon(marathonData)

      const gamesData = await gamesApi.list(parseInt(id))
      setGames(gamesData)

      if (marathonData.my_participation?.role === 'organizer' || user?.role === 'admin') {
        try {
          const pending = await gamesApi.listPending(parseInt(id))
          setPendingGames(pending)
        } catch {
          setPendingGames([])
        }
        // Load proposed challenges for organizers
        try {
          const proposed = await gamesApi.getProposedChallenges(parseInt(id))
          setProposedChallenges(proposed)
        } catch {
          setProposedChallenges([])
        }
      }

      // Load my proposed challenges for all participants
      if (marathonData.my_participation) {
        try {
          const myProposed = await gamesApi.getMyProposedChallenges(parseInt(id))
          setMyProposedChallenges(myProposed)
        } catch {
          setMyProposedChallenges([])
        }
      }
    } catch (error) {
      console.error('Failed to load data:', error)
      navigate('/marathons')
    } finally {
      setIsLoading(false)
    }
  }

  const handleAddGame = async () => {
    if (!id || !gameTitle.trim() || !gameUrl.trim() || !validateUrl(gameUrl)) return

    // Validate playthrough fields
    if (gameType === 'playthrough') {
      if (!playthroughDescription.trim()) {
        toast.warning('Заполните описание прохождения')
        return
      }
    }

    setIsAddingGame(true)
    try {
      await gamesApi.create(parseInt(id), {
        title: gameTitle.trim(),
        download_url: gameUrl.trim(),
        genre: gameGenre.trim() || undefined,
        game_type: gameType,
        ...(gameType === 'playthrough' && {
          playthrough_points: playthroughPoints,
          playthrough_description: playthroughDescription.trim(),
          playthrough_proof_type: playthroughProofType,
          playthrough_proof_hint: playthroughProofHint.trim() || undefined,
        }),
      })
      // Reset form
      setGameTitle('')
      setGameUrl('')
      setGameUrlError(null)
      setGameGenre('')
      setGameType('challenges')
      setPlaythroughPoints(50)
      setPlaythroughDescription('')
      setPlaythroughProofType('screenshot')
      setPlaythroughProofHint('')
      setShowAddGame(false)
      await loadData()
    } catch (error) {
      console.error('Failed to add game:', error)
    } finally {
      setIsAddingGame(false)
    }
  }

  const openEditModal = (game: Game) => {
    setEditingGame(game)
    setEditTitle(game.title)
    setEditUrl(game.download_url)
    setEditGenre(game.genre || '')
    setEditGameType(game.game_type || 'challenges')
    setEditPlaythroughPoints(game.playthrough_points || 50)
    setEditPlaythroughDescription(game.playthrough_description || '')
    setEditPlaythroughProofType((game.playthrough_proof_type as ProofType) || 'screenshot')
    setEditPlaythroughProofHint(game.playthrough_proof_hint || '')
  }

  const closeEditModal = () => {
    setEditingGame(null)
  }

  const handleEditGame = async () => {
    if (!editingGame) return

    // Validate playthrough fields
    if (editGameType === 'playthrough' && !editPlaythroughDescription.trim()) {
      toast.warning('Заполните описание прохождения')
      return
    }

    setIsEditingGame(true)
    try {
      await gamesApi.update(editingGame.id, {
        title: editTitle.trim(),
        download_url: editUrl.trim(),
        genre: editGenre.trim() || undefined,
        game_type: editGameType,
        ...(editGameType === 'playthrough' && {
          playthrough_points: editPlaythroughPoints,
          playthrough_description: editPlaythroughDescription.trim(),
          playthrough_proof_type: editPlaythroughProofType,
          playthrough_proof_hint: editPlaythroughProofHint.trim() || undefined,
        }),
      })
      toast.success('Игра обновлена')
      closeEditModal()
      await loadData()
    } catch (error) {
      console.error('Failed to update game:', error)
      toast.error('Не удалось обновить игру')
    } finally {
      setIsEditingGame(false)
    }
  }

  const handleDeleteGame = async (gameId: number) => {
    const confirmed = await confirm({
      title: 'Удалить игру?',
      message: 'Игра и все её челленджи будут удалены.',
      confirmText: 'Удалить',
      cancelText: 'Отмена',
      variant: 'danger',
    })
    if (!confirmed) return

    try {
      await gamesApi.delete(gameId)
      await loadData()
    } catch (error) {
      console.error('Failed to delete game:', error)
    }
  }

  const handleApproveGame = async (gameId: number) => {
    setModeratingGameId(gameId)
    try {
      await gamesApi.approve(gameId)
      await loadData()
    } catch (error) {
      console.error('Failed to approve game:', error)
    } finally {
      setModeratingGameId(null)
    }
  }

  const handleRejectGame = async (gameId: number) => {
    const confirmed = await confirm({
      title: 'Отклонить игру?',
      message: 'Игра будет удалена из списка ожидающих.',
      confirmText: 'Отклонить',
      cancelText: 'Отмена',
      variant: 'danger',
    })
    if (!confirmed) return

    setModeratingGameId(gameId)
    try {
      await gamesApi.reject(gameId)
      await loadData()
    } catch (error) {
      console.error('Failed to reject game:', error)
    } finally {
      setModeratingGameId(null)
    }
  }

  const handleToggleGameChallenges = async (gameId: number) => {
    if (expandedGameId === gameId) {
      setExpandedGameId(null)
      return
    }

    setExpandedGameId(gameId)

    if (!gameChallenges[gameId]) {
      setLoadingChallenges(gameId)
      try {
        const challenges = await gamesApi.getChallenges(gameId)
        setGameChallenges(prev => ({ ...prev, [gameId]: challenges }))
      } catch (error) {
        console.error('Failed to load challenges:', error)
        setGameChallenges(prev => ({ ...prev, [gameId]: [] }))
      } finally {
        setLoadingChallenges(null)
      }
    }
  }

  const handleCreateChallenge = async (gameId: number) => {
    if (!newChallenge.title.trim() || !newChallenge.description.trim()) {
      toast.warning('Заполните название и описание')
      return
    }

    setIsCreatingChallenge(true)
    try {
      await gamesApi.createChallenge(gameId, {
        title: newChallenge.title.trim(),
        description: newChallenge.description.trim(),
        type: newChallenge.type,
        difficulty: newChallenge.difficulty,
        points: newChallenge.points,
        estimated_time: newChallenge.estimated_time || undefined,
        proof_type: newChallenge.proof_type,
        proof_hint: newChallenge.proof_hint.trim() || undefined,
      })
      toast.success('Задание добавлено')
      setNewChallenge({
        title: '',
        description: '',
        type: 'completion',
        difficulty: 'medium',
        points: 50,
        estimated_time: 30,
        proof_type: 'screenshot',
        proof_hint: '',
      })
      setAddingChallengeToGameId(null)
      const challenges = await gamesApi.getChallenges(gameId)
      setGameChallenges(prev => ({ ...prev, [gameId]: challenges }))
      await loadData()
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось добавить задание')
    } finally {
      setIsCreatingChallenge(false)
    }
  }

  const handleDeleteChallenge = async (challengeId: number, gameId: number) => {
    const confirmed = await confirm({
      title: 'Удалить задание?',
      message: 'Это действие нельзя отменить.',
      confirmText: 'Удалить',
      cancelText: 'Отмена',
      variant: 'danger',
    })
    if (!confirmed) return

    try {
      await gamesApi.deleteChallenge(challengeId)
      const challenges = await gamesApi.getChallenges(gameId)
      setGameChallenges(prev => ({ ...prev, [gameId]: challenges }))
      await loadData()
    } catch (error) {
      console.error('Failed to delete challenge:', error)
    }
  }

  const handleStartEditChallenge = (challenge: Challenge) => {
    setEditingChallengeId(challenge.id)
    setEditChallenge({
      title: challenge.title,
      description: challenge.description,
      type: challenge.type,
      difficulty: challenge.difficulty,
      points: challenge.points,
      estimated_time: challenge.estimated_time || 30,
      proof_type: challenge.proof_type,
      proof_hint: challenge.proof_hint || '',
    })
  }

  const handleUpdateChallenge = async (challengeId: number, gameId: number) => {
    if (!editChallenge.title.trim() || !editChallenge.description.trim()) {
      toast.warning('Заполните название и описание')
      return
    }

    setIsUpdatingChallenge(true)
    try {
      await gamesApi.updateChallenge(challengeId, {
        title: editChallenge.title.trim(),
        description: editChallenge.description.trim(),
        type: editChallenge.type,
        difficulty: editChallenge.difficulty,
        points: editChallenge.points,
        estimated_time: editChallenge.estimated_time || undefined,
        proof_type: editChallenge.proof_type,
        proof_hint: editChallenge.proof_hint.trim() || undefined,
      })
      toast.success('Задание обновлено')
      setEditingChallengeId(null)
      const challenges = await gamesApi.getChallenges(gameId)
      setGameChallenges(prev => ({ ...prev, [gameId]: challenges }))
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось обновить задание')
    } finally {
      setIsUpdatingChallenge(false)
    }
  }

  const loadProposedChallenges = async () => {
    if (!id) return
    try {
      const proposed = await gamesApi.getProposedChallenges(parseInt(id))
      setProposedChallenges(proposed)
    } catch (error) {
      console.error('Failed to load proposed challenges:', error)
    }
  }

  const handleApproveChallenge = async (challengeId: number) => {
    setApprovingChallengeId(challengeId)
    try {
      await gamesApi.approveChallenge(challengeId)
      toast.success('Задание одобрено')
      await loadProposedChallenges()
      // Reload challenges for the game
      const challenge = proposedChallenges.find(c => c.id === challengeId)
      if (challenge) {
        const challenges = await gamesApi.getChallenges(challenge.game.id)
        setGameChallenges(prev => ({ ...prev, [challenge.game.id]: challenges }))
      }
      await loadData()
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось одобрить задание')
    } finally {
      setApprovingChallengeId(null)
    }
  }

  const handleRejectChallenge = async (challengeId: number) => {
    const confirmed = await confirm({
      title: 'Отклонить задание?',
      message: 'Задание будет удалено.',
      confirmText: 'Отклонить',
      cancelText: 'Отмена',
      variant: 'danger',
    })
    if (!confirmed) return

    setApprovingChallengeId(challengeId)
    try {
      await gamesApi.rejectChallenge(challengeId)
      toast.success('Задание отклонено')
      await loadProposedChallenges()
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось отклонить задание')
    } finally {
      setApprovingChallengeId(null)
    }
  }

  const handleStartEditProposed = (challenge: Challenge) => {
    setEditingProposedId(challenge.id)
    setEditChallenge({
      title: challenge.title,
      description: challenge.description,
      type: challenge.type,
      difficulty: challenge.difficulty,
      points: challenge.points,
      estimated_time: challenge.estimated_time || 30,
      proof_type: challenge.proof_type,
      proof_hint: challenge.proof_hint || '',
    })
  }

  const handleUpdateProposedChallenge = async (challengeId: number) => {
    if (!editChallenge.title.trim() || !editChallenge.description.trim()) {
      toast.warning('Заполните название и описание')
      return
    }

    setIsUpdatingChallenge(true)
    try {
      await gamesApi.updateChallenge(challengeId, {
        title: editChallenge.title.trim(),
        description: editChallenge.description.trim(),
        type: editChallenge.type,
        difficulty: editChallenge.difficulty,
        points: editChallenge.points,
        estimated_time: editChallenge.estimated_time || undefined,
        proof_type: editChallenge.proof_type,
        proof_hint: editChallenge.proof_hint.trim() || undefined,
      })
      toast.success('Задание обновлено')
      setEditingProposedId(null)
      await loadProposedChallenges()
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось обновить задание')
    } finally {
      setIsUpdatingChallenge(false)
    }
  }

  const handleProposeChallenge = async (gameId: number) => {
    if (!newChallenge.title.trim() || !newChallenge.description.trim()) {
      toast.warning('Заполните название и описание')
      return
    }

    setIsProposingChallenge(true)
    try {
      await gamesApi.proposeChallenge(gameId, {
        title: newChallenge.title.trim(),
        description: newChallenge.description.trim(),
        type: newChallenge.type,
        difficulty: newChallenge.difficulty,
        points: newChallenge.points,
        estimated_time: newChallenge.estimated_time || undefined,
        proof_type: newChallenge.proof_type,
        proof_hint: newChallenge.proof_hint.trim() || undefined,
      })
      toast.success('Задание предложено на модерацию')
      setNewChallenge({
        title: '',
        description: '',
        type: 'completion',
        difficulty: 'medium',
        points: 50,
        estimated_time: 30,
        proof_type: 'screenshot',
        proof_hint: '',
      })
      setAddingChallengeToGameId(null)
      await loadData()
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось предложить задание')
    } finally {
      setIsProposingChallenge(false)
    }
  }

  const handleDeleteMyProposedChallenge = async (challengeId: number) => {
    const confirmed = await confirm({
      title: 'Удалить предложение?',
      message: 'Предложенное задание будет удалено.',
      confirmText: 'Удалить',
      cancelText: 'Отмена',
      variant: 'danger',
    })
    if (!confirmed) return

    try {
      await gamesApi.deleteChallenge(challengeId)
      toast.success('Предложение удалено')
      await loadData()
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось удалить предложение')
    }
  }

  const handleGenerateChallenges = async () => {
    if (!id) return

    setIsGenerating(true)
    setGenerateMessage(null)
    try {
      // Pass selected games if any, otherwise generate for all games without challenges
      const gameIds = selectedGamesForGeneration.length > 0 ? selectedGamesForGeneration : undefined
      const result = await gamesApi.previewChallenges(parseInt(id), gameIds)
      if (result.challenges.length === 0) {
        setGenerateMessage('Нет игр для генерации заданий')
      } else {
        setPreviewChallenges(result.challenges)
        setShowGenerateSelection(false)
        setGenerateSearchQuery('')
      }
    } catch (error) {
      console.error('Failed to generate challenges:', error)
      setGenerateMessage('Не удалось сгенерировать задания')
    } finally {
      setIsGenerating(false)
    }
  }

  const toggleGameSelection = (gameId: number) => {
    setSelectedGamesForGeneration(prev =>
      prev.includes(gameId)
        ? prev.filter(id => id !== gameId)
        : [...prev, gameId]
    )
  }

  const clearGameSelection = () => {
    setSelectedGamesForGeneration([])
  }

  const handleSaveChallenges = async () => {
    if (!id || !previewChallenges) return

    setIsSaving(true)
    try {
      const result = await gamesApi.saveChallenges(parseInt(id), previewChallenges)
      setGenerateMessage(result.message)
      setPreviewChallenges(null)
      setGameChallenges({})
      await loadData()
    } catch (error) {
      console.error('Failed to save challenges:', error)
      setGenerateMessage('Не удалось сохранить задания')
    } finally {
      setIsSaving(false)
    }
  }

  const handleRemovePreviewChallenge = (index: number) => {
    if (!previewChallenges) return
    setPreviewChallenges(previewChallenges.filter((_, i) => i !== index))
    if (editingIndex === index) setEditingIndex(null)
  }

  const handleUpdatePreviewChallenge = (index: number, field: keyof ChallengePreview, value: string | number) => {
    if (!previewChallenges) return
    setPreviewChallenges(previewChallenges.map((ch, i) =>
      i === index ? { ...ch, [field]: value } : ch
    ))
  }

  const handleCancelPreview = () => {
    setPreviewChallenges(null)
    setEditingIndex(null)
  }

  const handleStartMarathon = async () => {
    if (!id) return

    const confirmed = await confirm({
      title: 'Начать марафон?',
      message: 'После старта нельзя будет добавить новые игры.',
      confirmText: 'Начать',
      cancelText: 'Отмена',
      variant: 'warning',
    })
    if (!confirmed) return

    setIsStarting(true)
    try {
      await marathonsApi.start(parseInt(id))
      navigate(`/marathons/${id}/play`)
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Не удалось запустить марафон')
    } finally {
      setIsStarting(false)
    }
  }

  if (isLoading || !marathon) {
    return (
      <div className="flex flex-col items-center justify-center py-24">
        <Loader2 className="w-12 h-12 animate-spin text-neon-500 mb-4" />
        <p className="text-gray-400">Загрузка лобби...</p>
      </div>
    )
  }

  const isOrganizer = marathon.my_participation?.role === 'organizer' || user?.role === 'admin'
  const approvedGames = games.filter(g => g.status === 'approved')
  const totalChallenges = approvedGames.reduce((sum, g) => sum + g.challenges_count, 0)

  // Get unique proposers for generation filter (from approved games)
  const uniqueProposers = approvedGames.reduce((acc, game) => {
    if (game.proposed_by && !acc.some(u => u.id === game.proposed_by?.id)) {
      acc.push(game.proposed_by)
    }
    return acc
  }, [] as { id: number; nickname: string }[])

  // Get unique proposers for games list filter (from all games)
  const allGamesProposers = games.reduce((acc, game) => {
    if (game.proposed_by && !acc.some(u => u.id === game.proposed_by?.id)) {
      acc.push(game.proposed_by)
    }
    return acc
  }, [] as { id: number; nickname: string }[])

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'approved':
        return (
          <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-lg bg-green-500/20 text-green-400 border border-green-500/30">
            <CheckCircle className="w-3 h-3" />
            Одобрено
          </span>
        )
      case 'pending':
        return (
          <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-lg bg-yellow-500/20 text-yellow-400 border border-yellow-500/30">
            <Clock className="w-3 h-3" />
            На модерации
          </span>
        )
      case 'rejected':
        return (
          <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-lg bg-red-500/20 text-red-400 border border-red-500/30">
            <XCircle className="w-3 h-3" />
            Отклонено
          </span>
        )
      default:
        return null
    }
  }

  const renderGameCard = (game: Game, showModeration = false) => (
    <div key={game.id} className="glass rounded-xl overflow-hidden border border-dark-600">
      {/* Game header */}
      <div
        className={`flex items-center justify-between p-4 ${
          (game.status === 'approved') ? 'cursor-pointer hover:bg-dark-700/50 transition-colors' : ''
        }`}
        onClick={() => game.status === 'approved' && handleToggleGameChallenges(game.id)}
      >
        <div className="flex items-center gap-3 flex-1 min-w-0">
          {game.status === 'approved' && (
            <span className="text-gray-400 shrink-0">
              {expandedGameId === game.id ? (
                <ChevronUp className="w-4 h-4" />
              ) : (
                <ChevronDown className="w-4 h-4" />
              )}
            </span>
          )}
          <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-neon-500/20 to-accent-500/20 border border-neon-500/20 flex items-center justify-center flex-shrink-0">
            <Gamepad2 className="w-5 h-5 text-neon-400" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <h4 className="font-semibold text-white">{game.title}</h4>
              {game.game_type === 'playthrough' && (
                <span className="text-xs px-2 py-0.5 rounded-lg bg-accent-500/20 text-accent-400 border border-accent-500/30">
                  Прохождение
                </span>
              )}
              {getStatusBadge(game.status)}
            </div>
            <div className="text-sm text-gray-400 flex items-center gap-3 flex-wrap">
              {game.genre && <span>{game.genre}</span>}
              {game.status === 'approved' && (
                <span className="flex items-center gap-1">
                  <Sparkles className="w-3 h-3 text-accent-400" />
                  {game.challenges_count} заданий
                </span>
              )}
              {game.proposed_by && (
                <span className="flex items-center gap-1 text-gray-500">
                  <User className="w-3 h-3" />
                  {game.proposed_by.nickname}
                </span>
              )}
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0" onClick={(e) => e.stopPropagation()}>
          {showModeration && game.status === 'pending' && (
            <>
              <button
                onClick={() => handleApproveGame(game.id)}
                disabled={moderatingGameId === game.id}
                className="p-2 rounded-lg text-green-400 hover:bg-green-500/10 transition-colors disabled:opacity-50"
              >
                {moderatingGameId === game.id ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <CheckCircle className="w-4 h-4" />
                )}
              </button>
              <button
                onClick={() => handleRejectGame(game.id)}
                disabled={moderatingGameId === game.id}
                className="p-2 rounded-lg text-red-400 hover:bg-red-500/10 transition-colors disabled:opacity-50"
              >
                <XCircle className="w-4 h-4" />
              </button>
            </>
          )}
          {isOrganizer && (
            <button
              onClick={() => openEditModal(game)}
              className="p-2 rounded-lg text-neon-400 hover:bg-neon-500/10 transition-colors"
              title="Редактировать"
            >
              <Edit2 className="w-4 h-4" />
            </button>
          )}
          {(isOrganizer || game.proposed_by?.id === user?.id) && (
            <button
              onClick={() => handleDeleteGame(game.id)}
              className="p-2 rounded-lg text-red-400 hover:bg-red-500/10 transition-colors"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Expanded challenges list */}
      {expandedGameId === game.id && (
        <div className="border-t border-dark-600 p-4 space-y-2 bg-dark-800/30">
          {loadingChallenges === game.id ? (
            <div className="flex justify-center py-4">
              <Loader2 className="w-5 h-5 animate-spin text-neon-400" />
            </div>
          ) : (
            <>
              {(() => {
                // For organizers: hide pending challenges (they see them in separate block)
                // For regular users: hide their own pending/rejected challenges (they see them in "My proposals")
                //                    but show their own approved challenges in both places
                const visibleChallenges = isOrganizer
                  ? gameChallenges[game.id]?.filter(c => c.status !== 'pending') || []
                  : gameChallenges[game.id]?.filter(c =>
                      !(c.proposed_by?.id === user?.id && c.status !== 'approved')
                    ) || []

                return visibleChallenges.length > 0 ? (
                visibleChallenges.map((challenge) => (
                  <div
                    key={challenge.id}
                    className="p-3 bg-dark-700/50 rounded-lg border border-dark-600"
                  >
                    {editingChallengeId === challenge.id ? (
                      // Edit form
                      <div className="space-y-3">
                        <Input
                          placeholder="Название задания"
                          value={editChallenge.title}
                          onChange={(e) => setEditChallenge(prev => ({ ...prev, title: e.target.value }))}
                        />
                        <textarea
                          placeholder="Описание"
                          value={editChallenge.description}
                          onChange={(e) => setEditChallenge(prev => ({ ...prev, description: e.target.value }))}
                          className="input w-full resize-none"
                          rows={2}
                        />
                        <div className="grid grid-cols-2 gap-2">
                          <div>
                            <label className="text-xs text-gray-400 mb-1 block">Тип</label>
                            <select
                              value={editChallenge.type}
                              onChange={(e) => setEditChallenge(prev => ({ ...prev, type: e.target.value }))}
                              className="input w-full"
                            >
                              <option value="completion">Прохождение</option>
                              <option value="no_death">Без смертей</option>
                              <option value="speedrun">Спидран</option>
                              <option value="collection">Коллекция</option>
                              <option value="achievement">Достижение</option>
                              <option value="challenge_run">Челлендж-ран</option>
                            </select>
                          </div>
                          <div>
                            <label className="text-xs text-gray-400 mb-1 block">Сложность</label>
                            <select
                              value={editChallenge.difficulty}
                              onChange={(e) => setEditChallenge(prev => ({ ...prev, difficulty: e.target.value }))}
                              className="input w-full"
                            >
                              <option value="easy">Легко</option>
                              <option value="medium">Средне</option>
                              <option value="hard">Сложно</option>
                            </select>
                          </div>
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                          <div>
                            <label className="text-xs text-gray-400 mb-1 block">Очки</label>
                            <Input
                              type="number"
                              value={editChallenge.points}
                              onChange={(e) => setEditChallenge(prev => ({ ...prev, points: parseInt(e.target.value) || 0 }))}
                              min={1}
                            />
                          </div>
                          <div>
                            <label className="text-xs text-gray-400 mb-1 block">Тип пруфа</label>
                            <select
                              value={editChallenge.proof_type}
                              onChange={(e) => setEditChallenge(prev => ({ ...prev, proof_type: e.target.value }))}
                              className="input w-full"
                            >
                              <option value="screenshot">Скриншот</option>
                              <option value="video">Видео</option>
                              <option value="steam">Steam</option>
                            </select>
                          </div>
                        </div>
                        <div>
                          <label className="text-xs text-gray-400 mb-1 block">Подсказка для пруфа</label>
                          <Input
                            placeholder="Что именно должно быть на скриншоте/видео"
                            value={editChallenge.proof_hint}
                            onChange={(e) => setEditChallenge(prev => ({ ...prev, proof_hint: e.target.value }))}
                          />
                        </div>
                        <div className="flex gap-2">
                          <NeonButton
                            size="sm"
                            onClick={() => handleUpdateChallenge(challenge.id, game.id)}
                            isLoading={isUpdatingChallenge}
                            icon={<Check className="w-4 h-4" />}
                          >
                            Сохранить
                          </NeonButton>
                          <NeonButton
                            variant="outline"
                            size="sm"
                            onClick={() => setEditingChallengeId(null)}
                          >
                            Отмена
                          </NeonButton>
                        </div>
                      </div>
                    ) : (
                      // Display challenge
                      <div className="flex items-start justify-between gap-3">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1 flex-wrap">
                            {challenge.status === 'pending' && getStatusBadge('pending')}
                            <span className={`text-xs px-2 py-0.5 rounded-lg border ${
                              challenge.difficulty === 'easy' ? 'bg-green-500/20 text-green-400 border-green-500/30' :
                              challenge.difficulty === 'medium' ? 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30' :
                              'bg-red-500/20 text-red-400 border-red-500/30'
                            }`}>
                              {challenge.difficulty === 'easy' ? 'Легко' :
                               challenge.difficulty === 'medium' ? 'Средне' : 'Сложно'}
                            </span>
                            <span className="text-xs text-neon-400 font-semibold">
                              +{challenge.points}
                            </span>
                            {challenge.is_generated && (
                              <span className="text-xs text-gray-500 flex items-center gap-1">
                                <Sparkles className="w-3 h-3" /> ИИ
                              </span>
                            )}
                            {challenge.proposed_by && (
                              <span className="text-xs text-gray-500 flex items-center gap-1">
                                <User className="w-3 h-3" /> {challenge.proposed_by.nickname}
                              </span>
                            )}
                          </div>
                          <h5 className="text-sm font-medium text-white">{challenge.title}</h5>
                          <p className="text-xs text-gray-400 mt-1">{challenge.description}</p>
                          {challenge.proof_hint && (
                            <p className="text-xs text-gray-500 mt-1">Пруф: {challenge.proof_hint}</p>
                          )}
                        </div>
                        {isOrganizer && (
                          <div className="flex gap-1 shrink-0">
                            <button
                              onClick={() => handleStartEditChallenge(challenge)}
                              className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-dark-600 transition-colors"
                            >
                              <Edit2 className="w-3 h-3" />
                            </button>
                            <button
                              onClick={() => handleDeleteChallenge(challenge.id, game.id)}
                              className="p-1.5 rounded-lg text-red-400 hover:bg-red-500/10 transition-colors"
                            >
                              <Trash2 className="w-3 h-3" />
                            </button>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                ))
              ) : (
                <p className="text-center text-gray-500 py-4 text-sm">
                  Нет заданий
                </p>
              )
              })()}

              {/* Add/Propose challenge form */}
              {game.status === 'approved' && (
                addingChallengeToGameId === game.id ? (
                  <div className="mt-4 p-4 glass rounded-xl space-y-3 border border-neon-500/20">
                    <h4 className="font-semibold text-white text-sm flex items-center gap-2">
                      <Plus className="w-4 h-4 text-neon-400" />
                      {isOrganizer ? 'Новое задание' : 'Предложить задание'}
                    </h4>
                    <Input
                      placeholder="Название задания"
                      value={newChallenge.title}
                      onChange={(e) => setNewChallenge(prev => ({ ...prev, title: e.target.value }))}
                    />
                    <textarea
                      placeholder="Описание (что нужно сделать)"
                      value={newChallenge.description}
                      onChange={(e) => setNewChallenge(prev => ({ ...prev, description: e.target.value }))}
                      className="input w-full resize-none"
                      rows={2}
                    />
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Тип</label>
                        <select
                          value={newChallenge.type}
                          onChange={(e) => setNewChallenge(prev => ({ ...prev, type: e.target.value }))}
                          className="input w-full"
                        >
                          <option value="completion">Прохождение</option>
                          <option value="no_death">Без смертей</option>
                          <option value="speedrun">Спидран</option>
                          <option value="collection">Коллекция</option>
                          <option value="achievement">Достижение</option>
                          <option value="challenge_run">Челлендж-ран</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Сложность</label>
                        <select
                          value={newChallenge.difficulty}
                          onChange={(e) => setNewChallenge(prev => ({ ...prev, difficulty: e.target.value }))}
                          className="input w-full"
                        >
                          <option value="easy">Легко (20-40 очков)</option>
                          <option value="medium">Средне (45-75 очков)</option>
                          <option value="hard">Сложно (90-150 очков)</option>
                        </select>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Очки</label>
                        <Input
                          type="number"
                          value={newChallenge.points}
                          onChange={(e) => setNewChallenge(prev => ({ ...prev, points: parseInt(e.target.value) || 0 }))}
                          min={1}
                        />
                      </div>
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Время (мин)</label>
                        <Input
                          type="number"
                          value={newChallenge.estimated_time}
                          onChange={(e) => setNewChallenge(prev => ({ ...prev, estimated_time: parseInt(e.target.value) || 0 }))}
                          min={1}
                        />
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Тип пруфа</label>
                        <select
                          value={newChallenge.proof_type}
                          onChange={(e) => setNewChallenge(prev => ({ ...prev, proof_type: e.target.value }))}
                          className="input w-full"
                        >
                          <option value="screenshot">Скриншот</option>
                          <option value="video">Видео</option>
                          <option value="steam">Steam</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Подсказка</label>
                        <Input
                          placeholder="Что на пруфе"
                          value={newChallenge.proof_hint}
                          onChange={(e) => setNewChallenge(prev => ({ ...prev, proof_hint: e.target.value }))}
                        />
                      </div>
                    </div>
                    <div className="flex gap-2">
                      {isOrganizer ? (
                        <NeonButton
                          size="sm"
                          onClick={() => handleCreateChallenge(game.id)}
                          isLoading={isCreatingChallenge}
                          disabled={!newChallenge.title || !newChallenge.description}
                          icon={<Plus className="w-4 h-4" />}
                        >
                          Добавить
                        </NeonButton>
                      ) : (
                        <NeonButton
                          size="sm"
                          onClick={() => handleProposeChallenge(game.id)}
                          isLoading={isProposingChallenge}
                          disabled={!newChallenge.title || !newChallenge.description}
                          icon={<Plus className="w-4 h-4" />}
                        >
                          Предложить
                        </NeonButton>
                      )}
                      <NeonButton
                        variant="outline"
                        size="sm"
                        onClick={() => setAddingChallengeToGameId(null)}
                      >
                        Отмена
                      </NeonButton>
                    </div>
                    {!isOrganizer && (
                      <p className="text-xs text-gray-500">
                        Задание будет отправлено на модерацию организаторам
                      </p>
                    )}
                  </div>
                ) : (
                  <button
                    onClick={() => {
                      setAddingChallengeToGameId(game.id)
                      setExpandedGameId(game.id)
                    }}
                    className="w-full mt-2 p-3 rounded-lg border-2 border-dashed border-dark-600 text-gray-400 hover:text-neon-400 hover:border-neon-500/30 transition-all flex items-center justify-center gap-2"
                  >
                    <Plus className="w-4 h-4" />
                    {isOrganizer ? 'Добавить задание вручную' : 'Предложить задание'}
                  </button>
                )
              )}
            </>
          )}
        </div>
      )}
    </div>
  )

  return (
    <div className="max-w-4xl mx-auto">
      {/* Back button */}
      <Link
        to={`/marathons/${id}`}
        className="inline-flex items-center gap-2 text-gray-400 hover:text-neon-400 mb-6 transition-colors group"
      >
        <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
        К марафону
      </Link>

      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white mb-1">{marathon.title}</h1>
          <p className="text-gray-400">
            {isOrganizer
              ? 'Настройка - Добавьте игры и сгенерируйте задания'
              : 'Предложите игры для марафона'}
          </p>
        </div>

        {isOrganizer && (
          <div className="flex gap-2">
            <NeonButton
              variant="ghost"
              onClick={() => setShowSettings(true)}
              className="!text-gray-400 hover:!bg-dark-600"
              icon={<Settings className="w-4 h-4" />}
            />
            <NeonButton
              onClick={handleStartMarathon}
              isLoading={isStarting}
              disabled={approvedGames.length === 0}
              icon={<Play className="w-4 h-4" />}
            >
              Запустить марафон
            </NeonButton>
          </div>
        )}
      </div>

      {/* Stats */}
      {isOrganizer && (
        <div className="grid grid-cols-2 gap-4 mb-8">
          <StatsCard
            label="Игр одобрено"
            value={approvedGames.length}
            icon={<Gamepad2 className="w-6 h-6" />}
            color="neon"
          />
          <StatsCard
            label="Заданий"
            value={totalChallenges}
            icon={<Sparkles className="w-6 h-6" />}
            color="purple"
          />
        </div>
      )}

      {/* Pending games for moderation */}
      {isOrganizer && pendingGames.length > 0 && (
        <GlassCard className="mb-8 border-yellow-500/30">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-yellow-500/20 flex items-center justify-center">
              <Clock className="w-5 h-5 text-yellow-400" />
            </div>
            <div>
              <h3 className="font-semibold text-yellow-400">На модерации</h3>
              <p className="text-sm text-gray-400">{pendingGames.length} игр ожидают</p>
            </div>
          </div>
          <div className="space-y-3">
            {pendingGames.map((game) => renderGameCard(game, true))}
          </div>
        </GlassCard>
      )}

      {/* Proposed challenges for moderation */}
      {isOrganizer && proposedChallenges.length > 0 && (
        <GlassCard className="mb-8 border-accent-500/30">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-accent-500/20 flex items-center justify-center">
              <Sparkles className="w-5 h-5 text-accent-400" />
            </div>
            <div>
              <h3 className="font-semibold text-accent-400">Предложенные задания</h3>
              <p className="text-sm text-gray-400">{proposedChallenges.length} заданий ожидают</p>
            </div>
          </div>
          <div className="space-y-3">
            {proposedChallenges.map((challenge) => (
              <div
                key={challenge.id}
                className="p-4 bg-dark-700/50 rounded-xl border border-dark-600"
              >
                {editingProposedId === challenge.id ? (
                  // Edit form
                  <div className="space-y-3">
                    <span className="text-xs px-2 py-0.5 rounded-lg bg-dark-600 text-gray-400">
                      {challenge.game.title}
                    </span>
                    <Input
                      placeholder="Название задания"
                      value={editChallenge.title}
                      onChange={(e) => setEditChallenge(prev => ({ ...prev, title: e.target.value }))}
                    />
                    <textarea
                      placeholder="Описание"
                      value={editChallenge.description}
                      onChange={(e) => setEditChallenge(prev => ({ ...prev, description: e.target.value }))}
                      className="input w-full resize-none"
                      rows={2}
                    />
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Тип</label>
                        <select
                          value={editChallenge.type}
                          onChange={(e) => setEditChallenge(prev => ({ ...prev, type: e.target.value }))}
                          className="input w-full"
                        >
                          <option value="completion">Прохождение</option>
                          <option value="no_death">Без смертей</option>
                          <option value="speedrun">Спидран</option>
                          <option value="collection">Коллекция</option>
                          <option value="achievement">Достижение</option>
                          <option value="challenge_run">Челлендж-ран</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Сложность</label>
                        <select
                          value={editChallenge.difficulty}
                          onChange={(e) => setEditChallenge(prev => ({ ...prev, difficulty: e.target.value }))}
                          className="input w-full"
                        >
                          <option value="easy">Легко</option>
                          <option value="medium">Средне</option>
                          <option value="hard">Сложно</option>
                        </select>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Очки</label>
                        <Input
                          type="number"
                          value={editChallenge.points}
                          onChange={(e) => setEditChallenge(prev => ({ ...prev, points: parseInt(e.target.value) || 0 }))}
                          min={1}
                        />
                      </div>
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Тип пруфа</label>
                        <select
                          value={editChallenge.proof_type}
                          onChange={(e) => setEditChallenge(prev => ({ ...prev, proof_type: e.target.value }))}
                          className="input w-full"
                        >
                          <option value="screenshot">Скриншот</option>
                          <option value="video">Видео</option>
                          <option value="steam">Steam</option>
                        </select>
                      </div>
                    </div>
                    <div>
                      <label className="text-xs text-gray-400 mb-1 block">Подсказка для пруфа</label>
                      <Input
                        placeholder="Что именно должно быть на скриншоте/видео"
                        value={editChallenge.proof_hint}
                        onChange={(e) => setEditChallenge(prev => ({ ...prev, proof_hint: e.target.value }))}
                      />
                    </div>
                    <div className="flex gap-2">
                      <NeonButton
                        size="sm"
                        onClick={() => handleUpdateProposedChallenge(challenge.id)}
                        isLoading={isUpdatingChallenge}
                        icon={<Check className="w-4 h-4" />}
                      >
                        Сохранить
                      </NeonButton>
                      <NeonButton
                        variant="outline"
                        size="sm"
                        onClick={() => setEditingProposedId(null)}
                      >
                        Отмена
                      </NeonButton>
                    </div>
                    {challenge.proposed_by && (
                      <p className="text-xs text-gray-500 flex items-center gap-1">
                        <User className="w-3 h-3" /> Предложил: {challenge.proposed_by.nickname}
                      </p>
                    )}
                  </div>
                ) : (
                  // Display
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2 flex-wrap">
                        <span className="text-xs px-2 py-0.5 rounded-lg bg-dark-600 text-gray-400">
                          {challenge.game.title}
                        </span>
                        <span className={`text-xs px-2 py-0.5 rounded-lg border ${
                          challenge.difficulty === 'easy' ? 'bg-green-500/20 text-green-400 border-green-500/30' :
                          challenge.difficulty === 'medium' ? 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30' :
                          'bg-red-500/20 text-red-400 border-red-500/30'
                        }`}>
                          {challenge.difficulty === 'easy' ? 'Легко' :
                           challenge.difficulty === 'medium' ? 'Средне' : 'Сложно'}
                        </span>
                        <span className="text-xs text-neon-400 font-semibold">
                          +{challenge.points}
                        </span>
                      </div>
                      <h4 className="font-medium text-white mb-1">{challenge.title}</h4>
                      <p className="text-sm text-gray-400 mb-2">{challenge.description}</p>
                      {challenge.proof_hint && (
                        <p className="text-xs text-gray-500 mb-2">Пруф: {challenge.proof_hint}</p>
                      )}
                      {challenge.proposed_by && (
                        <p className="text-xs text-gray-500 flex items-center gap-1">
                          <User className="w-3 h-3" /> Предложил: {challenge.proposed_by.nickname}
                        </p>
                      )}
                    </div>
                    <div className="flex gap-2 shrink-0">
                      <button
                        onClick={() => handleStartEditProposed(challenge)}
                        className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-dark-600 transition-colors"
                      >
                        <Edit2 className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleApproveChallenge(challenge.id)}
                        disabled={approvingChallengeId === challenge.id}
                        className="p-2 rounded-lg text-green-400 hover:bg-green-500/10 transition-colors disabled:opacity-50"
                      >
                        {approvingChallengeId === challenge.id ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <CheckCircle className="w-4 h-4" />
                        )}
                      </button>
                      <button
                        onClick={() => handleRejectChallenge(challenge.id)}
                        disabled={approvingChallengeId === challenge.id}
                        className="p-2 rounded-lg text-red-400 hover:bg-red-500/10 transition-colors disabled:opacity-50"
                      >
                        <XCircle className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </GlassCard>
      )}

      {/* My proposed challenges (for non-organizers) */}
      {!isOrganizer && myProposedChallenges.length > 0 && (
        <GlassCard className="mb-8 border-neon-500/30">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-neon-500/20 flex items-center justify-center">
              <Sparkles className="w-5 h-5 text-neon-400" />
            </div>
            <div>
              <h3 className="font-semibold text-neon-400">Мои предложения</h3>
              <p className="text-sm text-gray-400">{myProposedChallenges.length} заданий</p>
            </div>
          </div>
          <div className="space-y-3">
            {myProposedChallenges.map((challenge) => (
              <div
                key={challenge.id}
                className="flex items-start justify-between gap-3 p-4 bg-dark-700/50 rounded-xl border border-dark-600"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-2 flex-wrap">
                    <span className="text-xs px-2 py-0.5 rounded-lg bg-dark-600 text-gray-400">
                      {challenge.game.title}
                    </span>
                    {getStatusBadge(challenge.status)}
                    <span className={`text-xs px-2 py-0.5 rounded-lg border ${
                      challenge.difficulty === 'easy' ? 'bg-green-500/20 text-green-400 border-green-500/30' :
                      challenge.difficulty === 'medium' ? 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30' :
                      'bg-red-500/20 text-red-400 border-red-500/30'
                    }`}>
                      {challenge.difficulty === 'easy' ? 'Легко' :
                       challenge.difficulty === 'medium' ? 'Средне' : 'Сложно'}
                    </span>
                    <span className="text-xs text-neon-400 font-semibold">
                      +{challenge.points}
                    </span>
                  </div>
                  <h4 className="font-medium text-white mb-1">{challenge.title}</h4>
                  <p className="text-sm text-gray-400">{challenge.description}</p>
                  {challenge.proof_hint && (
                    <p className="text-xs text-gray-500 mt-1">Пруф: {challenge.proof_hint}</p>
                  )}
                </div>
                {challenge.status === 'pending' && (
                  <button
                    onClick={() => handleDeleteMyProposedChallenge(challenge.id)}
                    className="p-2 rounded-lg text-red-400 hover:bg-red-500/10 transition-colors shrink-0"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                )}
              </div>
            ))}
          </div>
        </GlassCard>
      )}

      {/* Generate challenges */}
      {isOrganizer && approvedGames.length > 0 && !previewChallenges && (
        <GlassCard className="mb-8">
          <div className="flex items-center justify-between gap-4 flex-wrap mb-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-accent-500/20 flex items-center justify-center">
                <Zap className="w-5 h-5 text-accent-400" />
              </div>
              <div>
                <h3 className="font-semibold text-white">Генерация заданий</h3>
                <p className="text-sm text-gray-400">
                  {showGenerateSelection
                    ? `Выбрано: ${selectedGamesForGeneration.length} из ${approvedGames.length}`
                    : 'Выберите игры для генерации'}
                </p>
              </div>
            </div>
            <div className="flex gap-2">
              {showGenerateSelection ? (
                <>
                  <NeonButton
                    onClick={() => {
                      setShowGenerateSelection(false)
                      clearGameSelection()
                      setGenerateSearchQuery('')
                      setGenerateFilterProposer('all')
                      setGenerateFilterChallenges('all')
                    }}
                    variant="secondary"
                    size="sm"
                  >
                    Отмена
                  </NeonButton>
                  <NeonButton
                    onClick={handleGenerateChallenges}
                    isLoading={isGenerating}
                    color="purple"
                    size="sm"
                    icon={<Sparkles className="w-4 h-4" />}
                    disabled={selectedGamesForGeneration.length === 0}
                  >
                    Сгенерировать ({selectedGamesForGeneration.length})
                  </NeonButton>
                </>
              ) : (
                <NeonButton
                  onClick={() => setShowGenerateSelection(true)}
                  variant="outline"
                  color="purple"
                  icon={<Sparkles className="w-4 h-4" />}
                >
                  Выбрать игры
                </NeonButton>
              )}
            </div>
          </div>

          {/* Game selection */}
          {showGenerateSelection && (
            <div className="space-y-3">
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                <input
                  type="text"
                  placeholder="Поиск игры..."
                  value={generateSearchQuery}
                  onChange={(e) => setGenerateSearchQuery(e.target.value)}
                  className="input w-full pl-10 pr-10 py-2 text-sm"
                />
                {generateSearchQuery && (
                  <button
                    onClick={() => setGenerateSearchQuery('')}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300 transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
              {/* Filters */}
              <div className="flex gap-2">
                <select
                  value={generateFilterProposer === 'all' ? 'all' : generateFilterProposer}
                  onChange={(e) => setGenerateFilterProposer(e.target.value === 'all' ? 'all' : parseInt(e.target.value))}
                  className="input py-2 text-sm flex-1"
                >
                  <option value="all">Все участники</option>
                  {uniqueProposers.map(u => (
                    <option key={u.id} value={u.id}>{u.nickname}</option>
                  ))}
                </select>
                <select
                  value={generateFilterChallenges}
                  onChange={(e) => setGenerateFilterChallenges(e.target.value as 'all' | 'with' | 'without')}
                  className="input py-2 text-sm flex-1"
                >
                  <option value="all">Все игры</option>
                  <option value="with">С заданиями</option>
                  <option value="without">Без заданий</option>
                </select>
              </div>
              {(() => {
                // Compute filtered games
                let filteredGames = approvedGames

                // Apply proposer filter
                if (generateFilterProposer !== 'all') {
                  filteredGames = filteredGames.filter(g => g.proposed_by?.id === generateFilterProposer)
                }

                // Apply challenges filter
                if (generateFilterChallenges === 'with') {
                  filteredGames = filteredGames.filter(g => {
                    const count = gameChallenges[g.id]?.length ?? g.challenges_count
                    return count > 0
                  })
                } else if (generateFilterChallenges === 'without') {
                  filteredGames = filteredGames.filter(g => {
                    const count = gameChallenges[g.id]?.length ?? g.challenges_count
                    return count === 0
                  })
                }

                // Apply search filter
                if (generateSearchQuery) {
                  filteredGames = fuzzyFilter(filteredGames, generateSearchQuery, (g) => g.title + ' ' + (g.genre || ''))
                }

                return (
                  <>
                    <div className="flex items-center justify-between text-sm">
                      <button
                        onClick={() => setSelectedGamesForGeneration(filteredGames.map(g => g.id))}
                        className="text-neon-400 hover:text-neon-300 transition-colors"
                      >
                        Выбрать все ({filteredGames.length})
                      </button>
                      <button
                        onClick={clearGameSelection}
                        className="text-gray-400 hover:text-gray-300 transition-colors"
                      >
                        Снять выбор
                      </button>
                    </div>
                    <div className="grid gap-2 max-h-64 overflow-y-auto custom-scrollbar">
                      {filteredGames.length === 0 ? (
                        <p className="text-center text-gray-500 py-4 text-sm">
                          Ничего не найдено
                        </p>
                      ) : (
                        filteredGames.map((game) => {
                          const isSelected = selectedGamesForGeneration.includes(game.id)
                          const challengeCount = gameChallenges[game.id]?.length ?? game.challenges_count
                          return (
                            <button
                              key={game.id}
                              onClick={() => toggleGameSelection(game.id)}
                              className={`flex items-center gap-3 p-3 rounded-lg border transition-all text-left ${
                                isSelected
                                  ? 'bg-accent-500/20 border-accent-500/50'
                                  : 'bg-dark-700/50 border-dark-600 hover:border-dark-500'
                              }`}
                            >
                              <div className={`w-5 h-5 rounded flex items-center justify-center border-2 transition-colors ${
                                isSelected
                                  ? 'bg-accent-500 border-accent-500'
                                  : 'border-gray-500'
                              }`}>
                                {isSelected && <Check className="w-3 h-3 text-white" />}
                              </div>
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2">
                                  <p className="text-white font-medium truncate">{game.title}</p>
                                  {game.proposed_by && (
                                    <span className="text-xs text-gray-500 shrink-0">от {game.proposed_by.nickname}</span>
                                  )}
                                </div>
                                <p className="text-xs text-gray-400">
                                  {challengeCount > 0 ? `${challengeCount} заданий` : 'Нет заданий'}
                                </p>
                              </div>
                            </button>
                          )
                        })
                      )}
                    </div>
                  </>
                )
              })()}
            </div>
          )}

          {generateMessage && (
            <p className="mt-4 text-sm text-neon-400 p-3 bg-neon-500/10 rounded-lg border border-neon-500/20">
              {generateMessage}
            </p>
          )}
        </GlassCard>
      )}

      {/* Challenge preview */}
      {previewChallenges && previewChallenges.length > 0 && (
        <GlassCard className="mb-8 border-accent-500/30">
          <div className="flex items-center justify-between mb-4 flex-wrap gap-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-accent-500/20 flex items-center justify-center">
                <Eye className="w-5 h-5 text-accent-400" />
              </div>
              <div>
                <h3 className="font-semibold text-white">Предпросмотр заданий</h3>
                <p className="text-sm text-gray-400">{previewChallenges.length} заданий</p>
              </div>
            </div>
            <div className="flex gap-2">
              <NeonButton onClick={handleCancelPreview} variant="outline" size="sm" icon={<X className="w-4 h-4" />}>
                Отмена
              </NeonButton>
              <NeonButton onClick={handleSaveChallenges} isLoading={isSaving} size="sm" icon={<Save className="w-4 h-4" />}>
                Сохранить все
              </NeonButton>
            </div>
          </div>
          <div className="space-y-3 max-h-[60vh] overflow-y-auto custom-scrollbar">
            {previewChallenges.map((challenge, index) => (
              <div
                key={index}
                className="p-4 bg-dark-700/50 rounded-xl border border-dark-600"
              >
                {editingIndex === index ? (
                  <div className="space-y-3">
                    <span className="text-xs px-2 py-0.5 rounded-lg bg-dark-600 text-gray-400">
                      {challenge.game_title}
                    </span>
                    <Input
                      value={challenge.title}
                      onChange={(e) => handleUpdatePreviewChallenge(index, 'title', e.target.value)}
                      placeholder="Название"
                    />
                    <textarea
                      value={challenge.description}
                      onChange={(e) => handleUpdatePreviewChallenge(index, 'description', e.target.value)}
                      placeholder="Описание"
                      className="input w-full resize-none"
                      rows={2}
                    />
                    <div className="grid grid-cols-3 gap-2">
                      <select
                        value={challenge.difficulty}
                        onChange={(e) => handleUpdatePreviewChallenge(index, 'difficulty', e.target.value)}
                        className="input"
                      >
                        <option value="easy">Легко</option>
                        <option value="medium">Средне</option>
                        <option value="hard">Сложно</option>
                      </select>
                      <Input
                        type="number"
                        value={challenge.points}
                        onChange={(e) => handleUpdatePreviewChallenge(index, 'points', parseInt(e.target.value) || 0)}
                        placeholder="Очки"
                      />
                      <select
                        value={challenge.proof_type}
                        onChange={(e) => handleUpdatePreviewChallenge(index, 'proof_type', e.target.value)}
                        className="input"
                      >
                        <option value="screenshot">Скриншот</option>
                        <option value="video">Видео</option>
                        <option value="steam">Steam</option>
                      </select>
                    </div>
                    <Input
                      value={challenge.proof_hint || ''}
                      onChange={(e) => handleUpdatePreviewChallenge(index, 'proof_hint', e.target.value)}
                      placeholder="Подсказка для пруфа"
                    />
                    <div className="flex gap-2">
                      <NeonButton size="sm" onClick={() => setEditingIndex(null)} icon={<Check className="w-4 h-4" />}>
                        Готово
                      </NeonButton>
                      <NeonButton
                        variant="outline"
                        size="sm"
                        onClick={() => handleRemovePreviewChallenge(index)}
                        className="text-red-400 border-red-500/30 hover:bg-red-500/10"
                        icon={<Trash2 className="w-4 h-4" />}
                      >
                        Удалить
                      </NeonButton>
                    </div>
                  </div>
                ) : (
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1 flex-wrap">
                        <span className="text-xs px-2 py-0.5 rounded-lg bg-dark-600 text-gray-400">
                          {challenge.game_title}
                        </span>
                        <span className={`text-xs px-2 py-0.5 rounded-lg border ${
                          challenge.difficulty === 'easy' ? 'bg-green-500/20 text-green-400 border-green-500/30' :
                          challenge.difficulty === 'medium' ? 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30' :
                          'bg-red-500/20 text-red-400 border-red-500/30'
                        }`}>
                          {challenge.difficulty === 'easy' ? 'Легко' :
                           challenge.difficulty === 'medium' ? 'Средне' : 'Сложно'}
                        </span>
                        <span className="text-xs text-neon-400 font-semibold">
                          +{challenge.points} очков
                        </span>
                      </div>
                      <h4 className="font-medium text-white mb-1">{challenge.title}</h4>
                      <p className="text-sm text-gray-400">{challenge.description}</p>
                      {challenge.proof_hint && (
                        <p className="text-xs text-gray-500 mt-2">
                          Пруф: {challenge.proof_hint}
                        </p>
                      )}
                    </div>
                    <div className="flex gap-1 shrink-0">
                      <button
                        onClick={() => setEditingIndex(index)}
                        className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-dark-600 transition-colors"
                      >
                        <Edit2 className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleRemovePreviewChallenge(index)}
                        className="p-2 rounded-lg text-red-400 hover:bg-red-500/10 transition-colors"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </GlassCard>
      )}

      {/* Games list */}
      <GlassCard>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-neon-500/20 flex items-center justify-center">
              <Gamepad2 className="w-5 h-5 text-neon-400" />
            </div>
            <h3 className="font-semibold text-white">Игры</h3>
          </div>
          {(marathon.game_proposal_mode === 'all_participants' || isOrganizer) && (
            <NeonButton
              size="sm"
              onClick={() => setShowAddGame(!showAddGame)}
              icon={<Plus className="w-4 h-4" />}
            >
              {isOrganizer ? 'Добавить' : 'Предложить'}
            </NeonButton>
          )}
        </div>

        {/* Search and filters */}
        <div className="space-y-3 mb-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="text"
              placeholder="Поиск игры..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="input w-full pl-10 pr-10"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300 transition-colors"
              >
                <X className="w-4 h-4" />
              </button>
            )}
          </div>
          <div className="flex gap-2">
            <select
              value={filterProposer === 'all' ? 'all' : filterProposer}
              onChange={(e) => setFilterProposer(e.target.value === 'all' ? 'all' : parseInt(e.target.value))}
              className="input py-2 text-sm flex-1"
            >
              <option value="all">Все участники</option>
              {allGamesProposers.map(u => (
                <option key={u.id} value={u.id}>{u.nickname}</option>
              ))}
            </select>
            <select
              value={filterChallenges}
              onChange={(e) => setFilterChallenges(e.target.value as 'all' | 'with' | 'without')}
              className="input py-2 text-sm flex-1"
            >
              <option value="all">Все игры</option>
              <option value="with">С заданиями</option>
              <option value="without">Без заданий</option>
            </select>
          </div>
        </div>

        {/* Add game form */}
        {showAddGame && (
          <div className="mb-6 p-4 glass rounded-xl space-y-3 border border-neon-500/20">
            <Input
              placeholder="Название игры"
              value={gameTitle}
              onChange={(e) => setGameTitle(e.target.value)}
            />
            <Input
              placeholder="Ссылка для скачивания (https://...)"
              value={gameUrl}
              onChange={(e) => handleGameUrlChange(e.target.value)}
              error={gameUrlError || undefined}
            />
            <Input
              placeholder="Жанр (необязательно)"
              value={gameGenre}
              onChange={(e) => setGameGenre(e.target.value)}
            />

            {/* Game type selector */}
            <div>
              <label className="text-xs text-gray-400 mb-1 block">Тип игры</label>
              <select
                value={gameType}
                onChange={(e) => setGameType(e.target.value as GameType)}
                className="input w-full"
              >
                <option value="challenges">Челленджи — случайный челлендж при спине</option>
                <option value="playthrough">Прохождение — основная задача + бонусные челленджи</option>
              </select>
            </div>

            {/* Playthrough fields */}
            {gameType === 'playthrough' && (
              <div className="space-y-3 p-3 bg-accent-500/10 rounded-lg border border-accent-500/20">
                <p className="text-xs text-accent-400 font-medium">Настройки прохождения</p>
                <textarea
                  placeholder="Что нужно сделать для прохождения (например: пройти игру до финальных титров)"
                  value={playthroughDescription}
                  onChange={(e) => setPlaythroughDescription(e.target.value)}
                  className="input w-full resize-none"
                  rows={2}
                />
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label className="text-xs text-gray-400 mb-1 block">Очки за прохождение</label>
                    <Input
                      type="number"
                      value={playthroughPoints}
                      onChange={(e) => setPlaythroughPoints(parseInt(e.target.value) || 50)}
                      min={1}
                    />
                  </div>
                  <div>
                    <label className="text-xs text-gray-400 mb-1 block">Тип пруфа</label>
                    <select
                      value={playthroughProofType}
                      onChange={(e) => setPlaythroughProofType(e.target.value as ProofType)}
                      className="input w-full"
                    >
                      <option value="screenshot">Скриншот</option>
                      <option value="video">Видео</option>
                      <option value="steam">Steam</option>
                    </select>
                  </div>
                </div>
                <Input
                  placeholder="Подсказка для пруфа (необязательно)"
                  value={playthroughProofHint}
                  onChange={(e) => setPlaythroughProofHint(e.target.value)}
                />
                <p className="text-xs text-gray-500">
                  Все челленджи этой игры станут бонусными (опциональными)
                </p>
              </div>
            )}

            <div className="flex gap-2">
              <NeonButton
                onClick={handleAddGame}
                isLoading={isAddingGame}
                disabled={!gameTitle || !gameUrl || !!gameUrlError || (gameType === 'playthrough' && !playthroughDescription)}
              >
                {isOrganizer ? 'Добавить' : 'Предложить'}
              </NeonButton>
              <NeonButton variant="outline" onClick={() => { setShowAddGame(false); setGameUrlError(null); setGameType('challenges') }}>
                Отмена
              </NeonButton>
            </div>
            {!isOrganizer && (
              <p className="text-xs text-gray-500">
                Игра будет отправлена на модерацию организаторам
              </p>
            )}
          </div>
        )}

        {/* Games */}
        {(() => {
          let filteredGames = isOrganizer
            ? games.filter(g => g.status !== 'pending')
            : games.filter(g => g.status === 'approved' || (g.status === 'pending' && g.proposed_by?.id === user?.id))

          // Apply proposer filter
          if (filterProposer !== 'all') {
            filteredGames = filteredGames.filter(g => g.proposed_by?.id === filterProposer)
          }

          // Apply challenges filter
          if (filterChallenges === 'with') {
            filteredGames = filteredGames.filter(g => {
              const count = gameChallenges[g.id]?.length ?? g.challenges_count
              return count > 0
            })
          } else if (filterChallenges === 'without') {
            filteredGames = filteredGames.filter(g => {
              const count = gameChallenges[g.id]?.length ?? g.challenges_count
              return count === 0
            })
          }

          // Apply search filter
          if (searchQuery) {
            filteredGames = fuzzyFilter(filteredGames, searchQuery, (g) => g.title + ' ' + (g.genre || ''))
          }

          const hasFilters = searchQuery || filterProposer !== 'all' || filterChallenges !== 'all'

          return filteredGames.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-dark-700 flex items-center justify-center">
                {hasFilters ? (
                  <Search className="w-8 h-8 text-gray-600" />
                ) : (
                  <Gamepad2 className="w-8 h-8 text-gray-600" />
                )}
              </div>
              <p className="text-gray-400">
                {hasFilters
                  ? 'Ничего не найдено по заданным фильтрам'
                  : isOrganizer
                    ? 'Пока нет игр. Добавьте игры, чтобы начать!'
                    : 'Пока нет одобренных игр. Предложите свою!'}
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {filteredGames.map((game) => renderGameCard(game, false))}
            </div>
          )
        })()}
      </GlassCard>

      {/* Settings Modal */}
      {marathon && (
        <MarathonSettingsModal
          marathon={marathon}
          isOpen={showSettings}
          onClose={() => setShowSettings(false)}
          onUpdate={setMarathon}
        />
      )}

      {/* Edit Game Modal */}
      {editingGame && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
          <div className="glass rounded-2xl border border-neon-500/20 w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl font-bold text-white">Редактировать игру</h3>
                <button
                  onClick={closeEditModal}
                  className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-dark-600 transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="space-y-4">
                <Input
                  placeholder="Название игры"
                  value={editTitle}
                  onChange={(e) => setEditTitle(e.target.value)}
                />
                <Input
                  placeholder="Ссылка для скачивания"
                  value={editUrl}
                  onChange={(e) => setEditUrl(e.target.value)}
                />
                <Input
                  placeholder="Жанр (необязательно)"
                  value={editGenre}
                  onChange={(e) => setEditGenre(e.target.value)}
                />

                {/* Game type selector */}
                <div>
                  <label className="text-xs text-gray-400 mb-1 block">Тип игры</label>
                  <select
                    value={editGameType}
                    onChange={(e) => setEditGameType(e.target.value as GameType)}
                    className="input w-full"
                  >
                    <option value="challenges">Челленджи</option>
                    <option value="playthrough">Прохождение</option>
                  </select>
                </div>

                {/* Playthrough fields */}
                {editGameType === 'playthrough' && (
                  <div className="space-y-3 p-3 bg-accent-500/10 rounded-lg border border-accent-500/20">
                    <p className="text-xs text-accent-400 font-medium">Настройки прохождения</p>
                    <textarea
                      placeholder="Описание прохождения"
                      value={editPlaythroughDescription}
                      onChange={(e) => setEditPlaythroughDescription(e.target.value)}
                      className="input w-full resize-none"
                      rows={2}
                    />
                    <div className="grid grid-cols-2 gap-2">
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Очки</label>
                        <Input
                          type="number"
                          value={editPlaythroughPoints}
                          onChange={(e) => setEditPlaythroughPoints(parseInt(e.target.value) || 50)}
                          min={1}
                        />
                      </div>
                      <div>
                        <label className="text-xs text-gray-400 mb-1 block">Тип пруфа</label>
                        <select
                          value={editPlaythroughProofType}
                          onChange={(e) => setEditPlaythroughProofType(e.target.value as ProofType)}
                          className="input w-full"
                        >
                          <option value="screenshot">Скриншот</option>
                          <option value="video">Видео</option>
                          <option value="steam">Steam</option>
                        </select>
                      </div>
                    </div>
                    <Input
                      placeholder="Подсказка для пруфа (необязательно)"
                      value={editPlaythroughProofHint}
                      onChange={(e) => setEditPlaythroughProofHint(e.target.value)}
                    />
                  </div>
                )}

                <div className="flex gap-3 pt-2">
                  <NeonButton
                    className="flex-1"
                    onClick={handleEditGame}
                    isLoading={isEditingGame}
                    disabled={!editTitle.trim() || !editUrl.trim() || (editGameType === 'playthrough' && !editPlaythroughDescription.trim())}
                    icon={<Save className="w-4 h-4" />}
                  >
                    Сохранить
                  </NeonButton>
                  <NeonButton variant="outline" onClick={closeEditModal}>
                    Отмена
                  </NeonButton>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
