import { useState, useEffect } from "react"
import { useSession } from "next-auth/react"
import { useRouter } from "next/router"

// Copa do Mundo 2026 - Grupos e Classificação (48 seleções, 12 grupos de 4)
const worldCupGroups = {
  A: [
    { team: "Canadá", flag: "🇨🇦", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "México", flag: "🇲🇽", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Estados Unidos", flag: "🇺🇸", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  B: [
    { team: "Argentina", flag: "🇦🇷", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Paraguai", flag: "🇵🇾", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Chile", flag: "🇨🇱", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  C: [
    { team: "Brasil", flag: "🇧🇷", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Colômbia", flag: "🇨🇴", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Uruguai", flag: "🇺🇾", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  D: [
    { team: "França", flag: "🇫🇷", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Portugal", flag: "🇵🇹", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Espanha", flag: "🇪🇸", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  E: [
    { team: "Alemanha", flag: "🇩🇪", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Inglaterra", flag: "🇬🇧", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Itália", flag: "🇮🇹", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  F: [
    { team: "Holanda", flag: "🇳🇱", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Bélgica", flag: "🇧🇪", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Croácia", flag: "🇭🇷", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  G: [
    { team: "Marrocos", flag: "🇲🇦", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Senegal", flag: "🇸🇳", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Tunísia", flag: "🇹🇳", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  H: [
    { team: "Japão", flag: "🇯🇵", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Coreia do Sul", flag: "🇰🇷", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Austrália", flag: "🇦🇺", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  I: [
    { team: "Irã", flag: "🇮🇷", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Arábia Saudita", flag: "🇸🇦", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Catar", flag: "🇶🇦", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  J: [
    { team: "Nigéria", flag: "🇳🇬", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Gana", flag: "🇬🇭", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Camarões", flag: "🇨🇲", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  K: [
    { team: "Equador", flag: "🇪🇨", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Peru", flag: "🇵🇪", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Venezuela", flag: "🇻🇪", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
  L: [
    { team: "Polônia", flag: "🇵🇱", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Sérvia", flag: "🇷🇸", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "Suíça", flag: "🇨🇭", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
    { team: "TBD (Repescagem)", flag: "🏳️", played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, gd: 0, points: 0 },
  ],
}

// Últimas notícias da Copa 2026 (simuladas - RSS/API pública)
const worldCupNews = [
  { id: 1, category: "PREPARAÇÃO", title: "FIFA Confirma 16 Cidades-Sede para Copa 2026", summary: "Estados Unidos (11), México (3) e Canadá (2) receberão jogos. Final será no MetLife Stadium, Nova Jersey.", date: "2026-06-25", views: "450K", trend: "+120%" },
  { id: 2, category: "BRASIL", title: "Brasil Enfrenta Argentina em Amistoso Preparatório", summary: "Clássico sul-americano marcado para setembro no Morumbi. Dorival Jr. testa nova formação com Endrick e Vini Jr.", date: "2026-06-24", views: "890K", trend: "+340%" },
  { id: 3, category: "SEDES", title: "Estadio Azteca Passará por Reforma de $200M", summary: "Único estádio a sediar 3 Copas do Mundo (1970, 1986, 2026). Modernização inclui nova tecnologia de gramado híbrido.", date: "2026-06-23", views: "234K", trend: "+87%" },
  { id: 4, category: "FORMATO", title: "Novo Formato: 48 Seleções, 12 Grupos, 104 Jogos", summary: "Fase de grupos com 3 times classificados por grupo + 8 melhores terceiros. Oitavas de final expandidas.", date: "2026-06-22", views: "567K", trend: "+156%" },
  { id: 5, category: "BRASIL", title: "Neymar Recupera-se de Lesão e Treina com Bola", summary: "Craque do Al-Hilal evolui bem na reabilitação. Médicos otimistas para disputa da Copa 2026 aos 34 anos.", date: "2026-06-21", views: "723K", trend: "+234%" },
  { id: 6, category: "INGRESSOS", title: "Venda de Ingressos Inicia em Janeiro 2026", summary: "Fase 1: sorteio para residentes dos países-sede. Preços variam de $50 a $1.600. Demanda prevista: 5M ingressos.", date: "2026-06-20", views: "389K", trend: "+98%" },
  { id: 7, category: "TECNOLOGIA", title: "VAR 2.0 com IA em Tempo Real Estreia na Copa", summary: "Novo sistema reduz tempo de decisão para 15 segundos. Câmeras 4K + sensores na bola detectam impedimento milimétrico.", date: "2026-06-19", views: "278K", trend: "+112%" },
  { id: 8, category: "SUSTENTABILIDADE", title: "Copa 2026 Será Carbono Neutro", summary: "FIFA compromete-se com compensação total. Transporte público gratuito para torcedores com ingresso nos dias de jogo.", date: "2026-06-18", views: "189K", trend: "+78%" },
  { id: 9, category: "ELIMINATÓRIAS", title: "Brasil Lidera Eliminatórias Sul-Americanas", summary: "Seleção tem 30 pontos em 14 jogos. Argentina e Uruguai completam top 3. Próximos jogos: Bolívia (casa) e Peru (fora).", date: "2026-06-17", views: "456K", trend: "+134%" },
  { id: 10, category: "ESTRELAS", title: "Mbappé, Haaland e Bellingham: A Nova Geração", summary: "França, Noruega e Inglaterra apostam em astros sub-25. Copa 2026 pode ser última de Messi e Cristiano Ronaldo.", date: "2026-06-26", views: "612K", trend: "+189%" },
  { id: 11, category: "HISTÓRIA", title: "Primeira Copa com 3 Países-Sede na História", summary: "Inédito: EUA, México e Canadá dividem organização. México será único a sediar 3 Copas (1970, 1986, 2026).", date: "2026-06-16", views: "345K", trend: "+95%" },
  { id: 12, category: "BRASIL", title: "CBF Anuncia Concentração em Orlando Para em Miami para Fase de Grupos", summary: "Estrutura de 5 estrelas com campos oficiais FIFA. Climas similares aos das cidades-sede americanas.", date: "2026-06-15", views: "298K", trend: "+103%" },
]

export default function WorldCup2026() {
  const { data: session } = useSession()
  const router = useRouter()
  const [selectedGroup, setSelectedGroup] = useState("TODOS")
  const [selectedCategory, setSelectedCategory] = useState("TODAS")
  const [filteredNews, setFilteredNews] = useState(worldCupNews)

  useEffect(() => {
    if (selectedCategory === "TODAS") {
      setFilteredNews(worldCupNews)
    } else {
      setFilteredNews(worldCupNews.filter(n => n.category === selectedCategory))
    }
  }, [selectedCategory])

  const groups = ["TODOS", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
  const newsCategories = ["TODAS", "PREPARAÇÃO", "BRASIL", "SEDES", "FORMATO", "INGRESSOS", "TECNOLOGIA", "SUSTENTABILIDADE", "ELIMINATÓRIAS", "ESTRELAS", "HISTÓRIA"]

  // Ordenar times por pontos, saldo, gols pró
  const sortStandings = (teams) => {
    return [...teams].sort((a, b) => {
      if (b.points !== a.points) return b.points - a.points
      if (b.gd !== a.gd) return b.gd - a.gd
      return b.gf - a.gf
    })
  }

  const getGroupsToShow = () => {
    if (selectedGroup === "TODOS") return Object.keys(worldCupGroups)
    return [selectedGroup]
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <nav className="bg-white shadow-lg p-4 sticky top-0 z-10 flex items-center justify-between">
        <button 
          onClick={() => router.push("/dashboard")}
          className="text-blue-600 hover:text-blue-800 font-medium"
        >
          ← Voltar
        </button>
        <div>
          <h1 className="text-2xl font-bold text-center bg-gradient-to-r from-green-600 to-blue-600 bg-clip-text text-transparent">
            Copa do Mundo 2026
          </h1>
          <p className="text-center text-sm text-gray-500 mt-1">48 Seleções • 12 Grupos • 104 Jogos • EUA/México/Canadá</p>
        </div>
        <div className="w-16"></div>
      </nav>

      <div className="max-w-4xl mx-auto p-4">
        {/* Filtros de Grupo */}
        <div className="flex flex-wrap gap-2 justify-center mb-6">
          {groups.map(grp => (
            <button
              key={grp}
              onClick={() => setSelectedGroup(grp)}
              className={`px-3 py-1 rounded-full text-xs font-medium transition-all ${
                selectedGroup === grp
                  ? "bg-green-600 text-white"
                  : "bg-gray-200 text-gray-700 hover:bg-gray-300"
              }`}
            >
              {grp === "TODOS" ? "TODOS" : `Grupo ${grp}`}
            </button>
          ))}
        </div>

        {/* Tabelas de Classificação por Grupo */}
        <div className="space-y-6 mb-8">
          {getGroupsToShow().map(groupKey => {
            const teams = sortStandings(worldCupGroups[groupKey])
            return (
              <div key={groupKey} className="bg-white rounded-lg shadow-md overflow-hidden">
                <div className="bg-gradient-to-r from-green-600 to-green-800 text-white p-4">
                  <h2 className="text-xl font-bold">Grupo {groupKey}</h2>
                </div>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-100">
                      <tr>
                        <th className="p-3 text-left font-semibold text-gray-700 w-8">#</th>
                        <th className="p-3 text-left font-semibold text-gray-700 w-40">Seleção</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">J</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">V</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">E</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">D</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">GP</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">GC</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">SG</th>
                        <th className="p-3 text-center font-semibold text-gray-700 w-16">Pts</th>
                      </tr>
                    </thead>
                    <tbody>
                      {teams.map((team, idx) => (
                        <tr key={`${groupKey}-${team.team}`} className={`${idx < 2 ? "bg-green-50" : ""} border-t border-gray-100 hover:bg-gray-50`}>
                          <td className="p-3 font-bold text-gray-800">{idx + 1}</td>
                          <td className="p-3 font-medium">
                            <span className="text-lg mr-2">{team.flag}</span>
                            {team.team}
                          </td>
                          <td className="p-3 text-center text-gray-600">{team.played}</td>
                          <td className="p-3 text-center text-green-600 font-medium">{team.won}</td>
                          <td className="p-3 text-center text-yellow-600 font-medium">{team.drawn}</td>
                          <td className="p-3 text-center text-red-600 font-medium">{team.lost}</td>
                          <td className="p-3 text-center text-gray-600">{team.gf}</td>
                          <td className="p-3 text-center text-gray-600">{team.ga}</td>
                          <td className="p-3 text-center font-bold text-blue-600">{team.gd >= 0 ? "+" : ""}{team.gd}</td>
                          <td className="p-3 text-center font-bold text-green-700">{team.points}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div className="p-3 text-xs text-gray-500 bg-gray-50 border-t border-gray-100">
                  Top 2 classificam direto • 8 melhores terceiros avançam • J = Jogos, V = Vitórias, E = Empates, D = Derrotas, GP = Gols Pró, GC = Gols Contra, SG = Saldo, Pts = Pontos
                </div>
              </div>
            )
          })}
        </div>

        {/* Separador Notícias */}
        <div className="my-8">
          <h2 className="text-xl font-bold text-center text-gray-800 mb-4">Últimas Notícias da Copa 2026</h2>
        </div>

        {/* Filtros de Categoria Notícias */}
        <div className="flex flex-wrap gap-2 justify-center mb-6">
          {newsCategories.map(cat => (
            <button
              key={cat}
              onClick={() => setSelectedCategory(cat)}
              className={`px-3 py-1 rounded-full text-xs font-medium transition-all ${
                selectedCategory === cat
                  ? "bg-blue-600 text-white"
                  : "bg-gray-200 text-gray-700 hover:bg-gray-300"
              }`}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Grid de Notícias - 2 colunas */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {filteredNews.length > 0 ? (
            filteredNews.map((news, idx) => (
              <div key={news.id} className="bg-white rounded-lg p-4 shadow-md hover:shadow-lg transition-shadow">
                <div className="flex items-start justify-between mb-2">
                  <span className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full font-semibold">
                    {news.category}
                  </span>
                  <div className="flex items-center gap-2 text-xs">
                    <span className="text-green-600 font-bold">{news.trend}</span>
                    <span className="text-gray-500">{news.views} views</span>
                  </div>
                </div>
                
                <h2 className="text-lg font-bold text-gray-800 mb-2">
                  #{idx + 1} {news.title}
                </h2>
                
                <p className="text-gray-600 text-sm leading-relaxed">
                  {news.summary}
                </p>
                
                <div className="mt-3 text-xs text-gray-500">
                  {new Date(news.date).toLocaleDateString('pt-BR', { 
                    weekday: 'short', 
                    month: 'short', 
                    day: 'numeric' 
                  })}
                </div>
              </div>
            ))
          ) : (
            <div className="text-center py-12">
              <p className="text-gray-500">Nenhuma notícia nesta categoria</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="mt-8 text-center text-xs text-gray-400">
          <p>Copa do Mundo FIFA 2026 • 48 Seleções • 12 Grupos • 104 Jogos</p>
          <p className="mt-1">Sedes: EUA (11), México (3), Canadá (2) • Junho/Julho 2026</p>
          <p className="mt-1">Mostrando {filteredNews.length} de {worldCupNews.length} notícias • Grupos: fase inicial (0 jogos)</p>
        </div>
      </div>
    </div>
  )
}