"use client"

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useAuth } from '@/contexts/AuthContext'
import { useLocale, useTranslations } from 'next-intl'
import ProtectedRoute from '@/components/ProtectedRoute'
import Header from '@/components/Header'
import { authFetch } from '@/lib/fetchAuth'
import { Button } from '@/components/ui/button'
import PlayerVehicles from '@/components/PlayerVehicles'
import MoneyLeaderboard from '@/components/MoneyLeaderboard'
import SkinAvatar from '@/components/SkinAvatar'

import { 
  User, 
  Mail, 
  Calendar, 
  Globe, 
  LogOut, 
  Settings, 
  Shield, 
  ShieldCheck,
  Gamepad2,
  Trophy,
  Star,
  Users,
  Activity,
  Hash,
  DollarSign,
  Camera,
  X,
  Eye,
  EyeOff,
  ExternalLink,
  Heart,
  CalendarClock,
  Phone as PhoneIcon,
  Menu,
  ChevronRight,
  Zap,
  TrendingUp,
  Clock,
  MapPin,
  Bell,
  Plus,
  Search,
  Filter,
  MoreHorizontal,
  Home,
  BarChart3,
  CreditCard,
  UserCheck,
  Play,
  Pause,
  Volume2,
  Wifi,
  Battery,
  Signal,
  Ban,
  AlertTriangle,
  FileText,
  Coins,
  Lock,
  RefreshCw
} from 'lucide-react'
import { connectToGameServer } from '@/lib/mtaServer'
import { MAX_CHARACTERS_PER_ACCOUNT } from '@/lib/characterCreation'

interface UserProfile {
  id: number
  username: string
  email: string
  registerdate: string
  lastlogin: string
  ip: string
  gameData?: any
  points?: number
  totalMoney?: number
  totalBankMoney?: number
  characterCount?: number
  characters?: any[]
  profilePhoto?: string | null
  banStatus?: number
  banReason?: string | null
  banDate?: string | null
  bannedBy?: string | null
  certified?: boolean
  certificationRequired?: boolean
}

interface CharacterItem {
  id: number
  name: string
  health: number
  skin: number
  gender: 'male' | 'female'
  age: number
  cityId?: number
  city?: string
  walkStyle?: number
  walkStyleName?: string
  biography?: string
  cash: number
  bank: number
  phone: string | null
  avatar: string
  posX?: number
  posY?: number
  posZ?: number
  MiembroFaccion?: number | null
  LiderFaccion?: number | null
  banStatus?: number
  banReason?: string | null
  banDate?: string | null
  bannedBy?: string | null
  banDuration?: string | null
}

// Faction ID to name map (partial list; extend as needed)
const FACTION_NAMES: Record<number, string> = {
  1: 'Los Santos Police Department'
}

const getFactionName = (id?: number | null) => {
  if (!id || !Number.isFinite(id)) return 'Civilian'
  return FACTION_NAMES[id] || `Faction #${id}`
}

// Safe numeric parser: handles numbers, numeric strings, and strings with commas/symbols
const parseNumeric = (value: any): number => {
  if (typeof value === 'number') return isFinite(value) ? value : 0
  if (value == null) return 0
  const cleaned = String(value).replace(/[^0-9.-]/g, '')
  const n = Number(cleaned)
  return Number.isFinite(n) ? n : 0
}

// Safe formatter for MySQL DATETIME/DATE strings (e.g., '2025-10-07 00:00:00')
const formatMySqlDate = (input: string): string => {
  if (!input) return '—'
  const raw = String(input).trim()

  // Pattern: 'HH:mm:ss - DD/MM/YYYY' or just 'DD/MM/YYYY'
  const dmY = raw.match(/(?:\d{2}:\d{2}:\d{2}\s*-\s*)?(\d{2})\/(\d{2})\/(\d{4})$/)
  if (dmY) {
    const [_, dd, mm, yyyy] = dmY
    const dt = new Date(Number(yyyy), Number(mm) - 1, Number(dd))
    return isNaN(dt.getTime()) ? `${dd}/${mm}/${yyyy}` : dt.toLocaleDateString()
  }

  // Pattern: 'YYYY-MM-DD HH:mm:ss' or 'YYYY-MM-DD'
  const yMd = raw.match(/^(\d{4})-(\d{2})-(\d{2})(?:\s+\d{2}:\d{2}:\d{2})?$/)
  if (yMd) {
    const [_, yyyy, mm, dd] = yMd
    const dt = new Date(Number(yyyy), Number(mm) - 1, Number(dd))
    return isNaN(dt.getTime()) ? `${dd}/${mm}/${yyyy}` : dt.toLocaleDateString()
  }

  // Fallback: try Date.parse
  const t = Date.parse(raw)
  if (!Number.isNaN(t)) {
    return new Date(t).toLocaleDateString()
  }

  return '—'
}

// Enhanced Stats Overview Card
const StatsOverviewCard = ({ icon, title, value, subtitle, color }: { 
  icon: React.ReactNode, 
  title: string, 
  value: string, 
  subtitle?: string,
  color: string
}) => {
  return (
    <div className={`bg-gradient-to-br ${color} rounded-2xl p-6 text-white hover:scale-105 transition-all duration-300 shadow-lg hover:shadow-xl hover:shadow-current/25 group cursor-pointer animate-fade-in`}>
      <div className="flex items-center justify-between mb-4">
        <div className="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm group-hover:bg-white/30 transition-all duration-300 group-hover:scale-110">
          {icon}
        </div>
        <div className="opacity-0 group-hover:opacity-100 transition-opacity duration-300">
          <div className="w-2 h-2 bg-white rounded-full animate-pulse"></div>
        </div>
      </div>
      <div>
        <h3 className="text-2xl font-bold mb-1 group-hover:text-white/90 transition-colors">{value}</h3>
        <p className="text-sm opacity-90 group-hover:opacity-100 transition-opacity">{title}</p>
        {subtitle && <p className="text-xs opacity-75 mt-1 group-hover:opacity-90 transition-opacity">{subtitle}</p>}
      </div>
    </div>
  )
}

// New Component: Ranking Card
const RankingCard = ({ rank, player, money, avatar, characterName, isCurrentUser = false }: {
  rank: number,
  player: string,
  money: number,
  avatar: string,
  characterName: string,
  isCurrentUser?: boolean
}) => (
  <div className={`flex items-center space-x-4 p-4 rounded-xl transition-all duration-200 ${
    isCurrentUser 
      ? 'bg-gradient-to-r from-[#0087FF]/20 to-[#8ab4ff]/20 border border-[#0087FF]/30' 
      : 'bg-[#0c1320]/60 hover:bg-[#0c1320]/80 border border-[#0087FF]/15'
  }`}>
    <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm ${
      rank === 1 ? 'bg-gradient-to-r from-yellow-400 to-yellow-500 text-black' :
      rank === 2 ? 'bg-gradient-to-r from-gray-300 to-gray-400 text-black' :
      rank === 3 ? 'bg-gradient-to-r from-orange-400 to-orange-500 text-black' :
      'bg-[#0087FF]/20 text-[#8ab4ff]'
    }`}>
      {rank}
    </div>
    <img 
      src={avatar} 
      alt={player} 
      className="w-10 h-10 rounded-xl object-cover border border-[#0087FF]/30" 
    />
    <div className="flex-1">
      <h4 className={`font-medium ${isCurrentUser ? 'text-[#8ab4ff]' : 'text-white'}`}>{player}</h4>
      <p className="text-sm text-gray-400">{characterName}</p>
    </div>
    <div className="text-right">
      <p className="font-bold text-emerald-400">${money.toLocaleString()}</p>
      <p className="text-xs text-gray-400">money</p>
    </div>
  </div>
)

// Minimal Character Card (avatar + name)
const CharacterCard = ({ character, href, t }: { character: CharacterItem, href: string, t: any }) => {
  const isBanned = character.banStatus && character.banStatus > 0
  
  return (
    <Link
      href={href}
      className={`group relative bg-gradient-to-br from-[#0f1620] to-[#0c1320] rounded-2xl p-5 border transition-all duration-300 hover:shadow-xl hover:-translate-y-0.5 focus:outline-none focus:ring-2 w-full text-left block ${
        isBanned 
          ? 'border-red-500/50 hover:border-red-500/70 hover:shadow-red-500/20 focus:ring-red-500/40' 
          : 'border-[#0087FF]/20 hover:border-[#0087FF]/40 hover:shadow-[#0087FF]/20 focus:ring-[#0087FF]/40'
      }`}
      aria-label={`Open ${character.name}`}
    >
      <div className="flex items-center gap-4">
        <div className="relative">
          <SkinAvatar
            src={character.avatar}
            alt={character.gender}
            gender={character.gender}
            className={`w-16 h-16 md:w-18 md:h-18 rounded-2xl border-2 transition-all ${
              isBanned
                ? 'border-red-500/50 group-hover:border-red-400'
                : 'border-[#0087FF]/30 group-hover:border-[#8ab4ff]'
            }`}
          />
          {isBanned && (
            <div className="absolute -top-1 -right-1 w-6 h-6 bg-red-500 rounded-full flex items-center justify-center border-2 border-[#0f1620]">
              <Ban className="w-3 h-3 text-white" />
            </div>
          )}
        </div>
        <div className="min-w-0">
          <h4 className={`text-lg font-bold truncate transition-colors ${
            isBanned ? 'text-red-300 group-hover:text-red-200' : 'text-white group-hover:text-[#8ab4ff]'
          }`}>
            {character.name}
          </h4>
          <p className="text-xs text-gray-400">{t('characters.id', { id: character.id })}</p>
          {isBanned && (
            <span className="inline-flex items-center gap-1 text-xs text-red-400 mt-1">
              <AlertTriangle className="w-3 h-3" />
              {t('characters.banned')}
            </span>
          )}
        </div>
      </div>
      <div className={`absolute inset-0 rounded-2xl transition-opacity pointer-events-none ${
        isBanned 
          ? 'bg-gradient-to-br from-red-500/5 to-transparent opacity-0 group-hover:opacity-100' 
          : 'bg-gradient-to-br from-[#0087FF]/5 to-transparent opacity-0 group-hover:opacity-100'
      }`} />
    </Link>
  )
}

// New Component: Notification System
const NotificationToast = ({ type, message, onClose }: {
  type: 'success' | 'error' | 'info',
  message: string,
  onClose: () => void
}) => {
  const colors = {
    success: 'bg-gradient-to-r from-emerald-500 to-emerald-600 border-emerald-400/50',
    error: 'bg-gradient-to-r from-red-500 to-red-600 border-red-400/50',
    info: 'bg-gradient-to-r from-blue-500 to-blue-600 border-blue-400/50'
  }

  const icons = {
    success: <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center"><div className="w-3 h-3 bg-white rounded-full"></div></div>,
    error: <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center"><X className="w-4 h-4 text-white" /></div>,
    info: <div className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center"><div className="w-3 h-3 bg-white rounded-full"></div></div>
  }

  return (
    <div className={`fixed top-6 right-6 z-50 ${colors[type]} backdrop-blur-sm rounded-2xl p-4 border shadow-2xl animate-slide-in`}>
      <div className="flex items-center space-x-3">
        {icons[type]}
        <p className="text-white font-semibold">{message}</p>
        <button 
          onClick={onClose}
          className="ml-2 text-white/80 hover:text-white transition-colors p-1 hover:bg-white/10 rounded-lg"
        >
          <X className="w-4 h-4" />
        </button>
      </div>
    </div>
  )
}

// Enhanced Profile Photo Component
const EnhancedProfilePhoto = ({ 
  profilePhoto, 
  onPhotoUpload, 
  onPhotoRemove,
  onNotification,
  t
}: {
  profilePhoto: string | null,
  onPhotoUpload: (file: File) => void,
  onPhotoRemove: () => void,
  onNotification: (type: 'success' | 'error', message: string) => void,
  t: any
}) => {
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      // Validate file type
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
      if (!allowedTypes.includes(file.type)) {
        onNotification('error', t('notifications.invalidFileType'))
        return
      }

      // Validate file size (max 5MB)
      const maxSize = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSize) {
        onNotification('error', t('notifications.fileTooLarge'))
        return
      }

      onPhotoUpload(file)
      onNotification('success', t('notifications.photoUploadSuccess'))
    }
  }

  const handleRemove = () => {
    onPhotoRemove()
    onNotification('success', t('notifications.photoRemoveSuccess'))
  }

  return (
    <div className="relative group">
      {/* Outer container allows the X button to sit slightly outside */}
      <div className="relative w-14 h-14 sm:w-16 sm:h-16 md:w-20 md:h-20 lg:w-24 lg:h-24 xl:w-28 xl:h-28">
        {/* Inner circle clips the image and overlay */}
        <div className="relative w-full h-full rounded-full overflow-hidden">
          <img 
            src={profilePhoto || '/images/logo.webp'} 
            alt="Profile" 
            className="w-full h-full rounded-full object-cover border-2 border-[#0087FF]/20 group-hover:border-[#0087FF]/40 transition-colors duration-200" 
          />

          {/* Clean hover ring (no blur) */}
          <div className="absolute inset-0 rounded-full border-2 border-[#0087FF]/40 opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none" />

          {/* Subtle hover veil with tiny blur */}
          <div className="absolute inset-0 rounded-full bg-black/20 backdrop-blur-[1px] opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none" />

          {/* Green online dot (always visible) */}
          <div className="absolute bottom-1 right-1 w-3 h-3 sm:w-3.5 sm:h-3.5 bg-gradient-to-r from-emerald-400 to-emerald-500 rounded-full ring-2 ring-[#0f1620] z-30" aria-hidden="true" />
          
          {/* Center camera label (upload) – smaller, crisp; hidden until hover */}
          <label
            className="absolute inset-0 flex items-center justify-center cursor-pointer z-30 focus:outline-none opacity-0 group-hover:opacity-100 transition-opacity duration-150"
            aria-label="Upload profile photo"
            tabIndex={0}
          >
            <div className="w-7 h-7 sm:w-8 sm:h-8 rounded-full bg-[#0087FF] hover:bg-[#0072d1] shadow-md flex items-center justify-center transition-transform transition-colors duration-200 ease-out ring-2 ring-white/60">
              <Camera className="w-3.5 h-3.5 text-white" />
            </div>
            <input
              type="file"
              accept="image/jpeg,image/png,image/gif"
              onChange={handleFileChange}
              className="hidden"
            />
          </label>
        </div>

        {/* Remove button – smaller, sits just outside */}
        {profilePhoto && (
          <button 
            onClick={(e) => { e.preventDefault(); e.stopPropagation(); handleRemove() }}
            type="button"
            aria-label="Remove profile photo"
            className="absolute -right-2 -top-1.5 w-6 h-6 sm:w-6.5 sm:h-6.5 rounded-full bg-red-500 hover:bg-red-600 shadow-md flex items-center justify-center transition-transform transition-colors duration-200 ease-out cursor-pointer z-30 focus:outline-none ring-2 ring-white/70 opacity-0 group-hover:opacity-100"
          >
            <X className="w-3.5 h-3.5 text-white" />
          </button>
        )}
      </div>
    </div>
  )
}

// New Component: Integrated Profile & Account Section
const ProfileAccountSection = ({ 
  profilePhoto, 
  onPhotoUpload, 
  onPhotoRemove, 
  profile, 
  showIP, 
  setShowIP, 
  formatDate, 
  maskIP,
  onNotification,
  t
}: {
  profilePhoto: string | null,
  onPhotoUpload: (file: File) => void,
  onPhotoRemove: () => void,
  profile: UserProfile,
  showIP: boolean,
  setShowIP: (show: boolean) => void,
  formatDate: (date: string) => string,
  maskIP: (ip: string) => string,
  onNotification: (type: 'success' | 'error', message: string) => void,
  t: any
}) => {
  const vipTier = Number((profile as any).vip || 0)
  const vipMap: Record<number, { label: string, classes: string }> = {
    0: { label: t('vip.noVip'), classes: 'text-gray-300 border-gray-600/50 bg-gradient-to-r from-gray-800/40 to-gray-700/30' },
    1: { label: t('vip.silver'), classes: 'text-slate-200 border-slate-400/40 bg-gradient-to-r from-slate-600/40 to-slate-700/30' },
    2: { label: t('vip.gold'), classes: 'text-amber-200 border-amber-400/40 bg-gradient-to-r from-amber-600/30 to-amber-500/20' },
    3: { label: t('vip.diamond'), classes: 'text-cyan-200 border-cyan-400/40 bg-gradient-to-r from-cyan-600/30 to-blue-600/20' },
  }
  const vip = vipMap[vipTier] || vipMap[0]

  return (
    <div className="bg-gradient-to-br from-[#0f1620] to-[#0c1320] rounded-2xl p-6 border border-[#0087FF]/20 shadow-lg">
      {/* Enhanced Profile Photo Section */}
      <div className="flex items-center space-x-6 mb-6">
        <EnhancedProfilePhoto 
          profilePhoto={profilePhoto}
          onPhotoUpload={onPhotoUpload}
          onPhotoRemove={onPhotoRemove}
          onNotification={onNotification}
          t={t}
        />
        
        <div className="flex-1">
          <div className="flex items-center gap-3 flex-wrap">
            <h3 className="text-xl font-bold text-white mb-1">{profile.username}</h3>
            <span className={`inline-flex items-center gap-2 px-3 py-1 rounded-xl text-xs font-semibold border ${vip.classes}`}>
              <svg viewBox="0 0 24 24" className={`w-4 h-4 ${vipTier===2?'text-amber-300':vipTier===3?'text-cyan-300':'text-slate-200'}`} fill="currentColor">
                <path d="M12 2l3 6 6 .9-4.5 4.3L17 20l-5-2.6L7 20l1.5-6.8L4 8.9 10 8l2-6z"/>
              </svg>
              {vip.label}
            </span>
          </div>
          <p className="text-gray-400 text-sm">{t('profile.playerId', { id: profile.id })}</p>
          <p className="text-gray-400 text-sm">{t('profile.memberSince', { date: formatDate(profile.registerdate) })}</p>
          <p className="text-[11px] text-gray-500 mt-2">{t('profile.allowedFormats')}</p>
        </div>
      </div>

      {/* Enhanced Account Details Grid */}
      <div className="grid grid-cols-1 gap-4">
        <div className="flex items-center justify-between p-4 bg-gradient-to-r from-[#0c1320]/60 to-[#0c1320]/40 rounded-xl border border-[#0087FF]/15 hover:border-[#0087FF]/30 transition-all duration-200 hover:shadow-lg hover:shadow-[#0087FF]/10">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-gradient-to-r from-[#0087FF]/10 to-[#8ab4ff]/10 rounded-xl flex items-center justify-center border border-[#0087FF]/20">
              <Mail className="w-5 h-5 text-[#8ab4ff]" />
            </div>
            <div>
              <p className="text-xs text-gray-400 font-medium">{t('account.email')}</p>
              <p className="text-sm text-white font-semibold">{profile.email}</p>
            </div>
          </div>
          <button 
            onClick={(e) => {
              e.preventDefault()
              e.stopPropagation()
              navigator.clipboard.writeText(profile.email)
              onNotification('success', t('account.copySuccess'))
            }}
            className="p-2 text-gray-300 hover:text-white bg-[#0c1320]/60 hover:bg-[#0c1320]/80 rounded-full border border-[#0087FF]/25 transition-all duration-200 cursor-pointer"
            type="button"
          >
            <ExternalLink className="w-4 h-4" />
          </button>
        </div>

        <div className="flex items-center justify-between p-4 bg-gradient-to-r from-[#0c1320]/60 to-[#0c1320]/40 rounded-xl border border-[#0087FF]/15 hover:border-[#0087FF]/30 transition-all duration-200 hover:shadow-lg hover:shadow-[#0087FF]/10">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-gradient-to-r from-[#0087FF]/10 to-[#8ab4ff]/10 rounded-xl flex items-center justify-center border border-[#0087FF]/20">
              <Globe className="w-5 h-5 text-[#8ab4ff]" />
            </div>
            <div>
              <p className="text-xs text-gray-400 font-medium">{t('account.ipAddress')}</p>
              <p className="text-sm text-white font-semibold">{showIP ? profile.ip : maskIP(profile.ip)}</p>
            </div>
          </div>
          <button
            onClick={(e) => {
              e.preventDefault()
              e.stopPropagation()
              setShowIP(!showIP)
            }}
            className="p-2 text-gray-300 hover:text-white bg-[#0c1320]/60 hover:bg-[#0c1320]/80 rounded-full border border-[#0087FF]/25 transition-all duration-200 cursor-pointer"
            type="button"
            aria-label={showIP ? t('account.hideIp') : t('account.showIp')}
          >
            {showIP ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
          </button>
        </div>

        <div className="flex items-center justify-between p-4 bg-gradient-to-r from-[#0c1320]/60 to-[#0c1320]/40 rounded-xl border border-[#0087FF]/15 hover:border-[#0087FF]/30 transition-all duration-200 hover:shadow-lg hover:shadow-[#0087FF]/10">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-gradient-to-r from-[#0087FF]/10 to-[#8ab4ff]/10 rounded-xl flex items-center justify-center border border-[#0087FF]/20">
              <Clock className="w-5 h-5 text-[#8ab4ff]" />
            </div>
            <div>
              <p className="text-xs text-gray-400 font-medium">{t('account.lastLogin')}</p>
              <p className="text-sm text-white font-semibold">{formatDate(profile.lastlogin)}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Ban Status Section */}
      {profile.banStatus !== undefined && profile.banStatus > 0 && (
        <div className="mt-6 p-6 bg-gradient-to-br from-red-900/30 via-red-800/20 to-red-900/30 rounded-2xl border-2 border-red-500/50 shadow-lg shadow-red-500/20 animate-pulse">
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 bg-red-500/20 rounded-xl flex items-center justify-center border border-red-500/50 flex-shrink-0">
              <Ban className="w-6 h-6 text-red-400" />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-2">
                <AlertTriangle className="w-5 h-5 text-red-400" />
                <h4 className="text-lg font-bold text-red-300">{t('ban.title')}</h4>
              </div>
              
              <div className="space-y-3">
                {profile.banReason && (
                  <div className="flex items-start gap-3">
                    <FileText className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                    <div>
                      <p className="text-xs text-gray-400 font-medium">{t('ban.reason')}</p>
                      <p className="text-sm text-red-200 font-semibold">{profile.banReason}</p>
                    </div>
                  </div>
                )}
                
                {profile.bannedBy && (
                  <div className="flex items-start gap-3">
                    <User className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                    <div>
                      <p className="text-xs text-gray-400 font-medium">{t('ban.bannedBy')}</p>
                      <p className="text-sm text-red-200 font-semibold">{profile.bannedBy}</p>
                    </div>
                  </div>
                )}
                
                {profile.banDate && (
                  <div className="flex items-start gap-3">
                    <Calendar className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                    <div>
                      <p className="text-xs text-gray-400 font-medium">{t('ban.banDate')}</p>
                      <p className="text-sm text-red-200 font-semibold">{formatDate(profile.banDate)}</p>
                    </div>
                  </div>
                )}
                
                <div className="flex items-start gap-3">
                  <Shield className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                  <div>
                    <p className="text-xs text-gray-400 font-medium">{t('ban.banType')}</p>
                    <p className="text-sm text-red-200 font-semibold">
                      {profile.banStatus === 1 ? t('ban.temporary') : profile.banStatus === 2 ? t('ban.permanent') : t('ban.banned')}
                    </p>
                  </div>
                </div>
              </div>
              
              <p className="mt-4 text-xs text-red-300/80 bg-red-500/10 px-4 py-2 rounded-2xl border border-red-500/20">
                {t('ban.contactAdmin')}
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// Helper function for Discord avatar URL
const getDiscordAvatarUrl = (discordId: string, avatarHash: string) => {
  return `https://cdn.discordapp.com/avatars/${discordId}/${avatarHash}.png`
}

// New Component: Discord Section (locked when certification pending)
const DiscordSectionLocked = ({ t, onGoCertification }: {
  t: any,
  onGoCertification: () => void
}) => (
  <div className="bg-[#0f1620]/70 backdrop-blur-sm rounded-2xl p-6 border border-amber-400/20">
    <h3 className="text-lg font-bold text-white mb-4">{t('discord.title')}</h3>
    <div className="text-center">
      <div className="w-12 h-12 bg-amber-500/10 rounded-xl flex items-center justify-center mx-auto mb-3 border border-amber-400/20">
        <Lock className="w-6 h-6 text-amber-300" />
      </div>
      <p className="text-amber-200 font-medium text-sm mb-1">{t('discord.lockedTitle')}</p>
      <p className="text-gray-400 text-sm mb-4">{t('discord.lockedText')}</p>
      <button
        type="button"
        onClick={onGoCertification}
        className="w-full px-4 py-2 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white rounded-xl transition-colors text-sm"
      >
        <ShieldCheck className="w-4 h-4 mr-2 inline" />
        {t('discord.lockedAction')}
      </button>
    </div>
  </div>
)

// New Component: Discord Section
const DiscordSection = ({ discordInfo, onLinkDiscord, onUnlinkDiscord, onSyncRole, syncingRole, t }: {
  discordInfo: any,
  onLinkDiscord: () => void,
  onUnlinkDiscord: () => void,
  onSyncRole?: () => void,
  syncingRole?: boolean,
  t: any
}) => (
  <div className="bg-[#0f1620]/70 backdrop-blur-sm rounded-2xl p-6 border border-[#0087FF]/20">
    <h3 className="text-lg font-bold text-white mb-4">{t('discord.title')}</h3>
    {discordInfo ? (
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <img 
            src={discordInfo.avatar ? getDiscordAvatarUrl(discordInfo.id, discordInfo.avatar) : '/images/logo.webp'} 
            alt="Discord Avatar" 
            className="w-10 h-10 rounded-xl object-cover border border-[#0087FF]/30" 
            onError={(e) => { (e.currentTarget as HTMLImageElement).src = '/images/logo.webp' }}
          />
          <div className="flex-1 min-w-0">
            <p className="text-white font-medium text-sm truncate">{discordInfo.username || 'Discord User'}</p>
            <p className="text-xs text-gray-400 truncate">ID: {discordInfo.id}</p>
          </div>
        </div>
        <div className="space-y-2">
          {onSyncRole && (
            <button
              type="button"
              onClick={onSyncRole}
              disabled={syncingRole}
              className="w-full px-3 py-2 bg-[#0087FF]/20 hover:bg-[#0087FF]/30 text-[#8ab4ff] rounded-xl transition-colors text-sm border border-[#0087FF]/30 disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 mr-2 inline ${syncingRole ? 'animate-spin' : ''}`} />
              {t('discord.syncRole')}
            </button>
          )}
          <button
            type="button"
            onClick={onUnlinkDiscord}
            className="w-full px-3 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-xl transition-colors text-sm border border-red-400/20"
          >
            <X className="w-4 h-4 mr-2 inline" />
            {t('discord.unlink')}
          </button>
        </div>
      </div>
    ) : (
      <div className="text-center">
        <div className="w-12 h-12 bg-[#0087FF]/10 rounded-xl flex items-center justify-center mx-auto mb-3 border border-[#0087FF]/20">
          <svg viewBox="0 0 24 24" fill="currentColor" className="w-6 h-6 text-[#8ab4ff]">
            <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.127.094.253.194.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.419-.019 1.333-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1568 2.4189Z"/>
          </svg>
        </div>
        <p className="text-gray-400 text-sm mb-3">{t('discord.connect')}</p>
        <button 
          onClick={onLinkDiscord}
          className="w-full px-4 py-2 bg-[#0087FF] hover:bg-[#0072d1] text-white rounded-xl transition-colors text-sm"
        >
          <ExternalLink className="w-4 h-4 mr-2 inline" />
          {t('discord.link')}
        </button>
      </div>
    )}
  </div>
)

// New Component: Character Preview Card
const CharacterPreviewCard = ({ character, onClick, t }: { character: CharacterItem, onClick: () => void, t: any }) => (
  <div
    onClick={onClick}
    className="group relative bg-gradient-to-br from-slate-800 to-slate-900 rounded-3xl p-6 border border-slate-700 hover:border-emerald-500/50 transition-all duration-300 cursor-pointer hover:shadow-2xl hover:shadow-emerald-500/10"
  >
    <div className="absolute top-4 right-4 opacity-0 group-hover:opacity-100 transition-opacity">
      <div className="w-2 h-2 bg-emerald-500 rounded-full"></div>
    </div>
    
    <div className="flex items-center space-x-4 mb-4">
      <div className="relative">
        <SkinAvatar
          src={character.avatar}
          alt={character.gender}
          gender={character.gender}
          className="w-14 h-14 rounded-2xl border-2 border-slate-600 group-hover:border-emerald-500 transition-colors"
        />
        <div className="absolute -bottom-1 -right-1 w-5 h-5 bg-emerald-500 rounded-full border-2 border-slate-800"></div>
      </div>
      <div className="flex-1">
        <h4 className="text-lg font-bold text-white group-hover:text-emerald-400 transition-colors">{character.name}</h4>
        <p className="text-sm text-gray-400">{t('characters.details.level', { level: Math.floor(character.age / 10) + 1 })}</p>
      </div>
    </div>
    
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-400 flex items-center gap-2"><Heart className="w-4 h-4 text-red-400" /> {t('characters.details.health')}</span>
        <div className="flex items-center space-x-2">
          <div className="w-16 h-2 bg-slate-700 rounded-full overflow-hidden">
            <div 
              className="h-full bg-gradient-to-r from-red-500 to-red-400 rounded-full transition-all duration-500"
              style={{ width: `${Math.min(100, (character.health / 100) * 100)}%` }}
            ></div>
          </div>
          <span className="text-xs text-gray-300">{character.health}</span>
        </div>
      </div>
      
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-400 flex items-center gap-2"><DollarSign className="w-4 h-4 text-emerald-400" /> {t('characters.details.cash')}</span>
        <span className="text-sm font-semibold text-emerald-400">${character.cash.toLocaleString()}</span>
      </div>
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-400 flex items-center gap-2"><CreditCard className="w-4 h-4 text-blue-300" /> {t('characters.details.bank')}</span>
        <span className="text-sm font-semibold text-blue-300">${character.bank.toLocaleString()}</span>
      </div>
    </div>
  </div>
)

// Character Detail Modal (animated)
const CharacterDetailModal = ({ character, onClose, t }: { character: CharacterItem, onClose: () => void, t: any }) => (
  <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
    <div className="absolute inset-0 bg-black/80 backdrop-blur-sm animate-fade-in" onClick={onClose}></div>
    <div className="relative bg-gradient-to-br from-slate-800 to-slate-900 rounded-3xl border border-slate-700 p-6 md:p-8 max-w-4xl w-full max-h-[90vh] overflow-y-auto animate-slide-in">
      <button
        onClick={onClose}
        className="absolute top-4 right-4 p-2 text-gray-400 hover:text-white hover:bg-slate-700 rounded-xl transition-colors"
        aria-label="Close"
      >
        <X className="w-5 h-5" />
      </button>
      {/* Header */}
      <div className="flex items-start gap-4 md:gap-6 mb-6">
        <SkinAvatar
          src={character.avatar}
          alt={character.gender}
          gender={character.gender}
          className="w-20 h-20 md:w-24 md:h-24 rounded-2xl border-2 border-slate-600"
        />
        <div className="min-w-0 flex-1">
          <h2 className="text-2xl md:text-3xl font-bold text-white mb-1 truncate">{character.name}</h2>
          <div className="flex items-center gap-3 text-xs text-gray-300 flex-wrap">
            <span className="inline-flex items-center gap-1"><Hash className="w-3 h-3" /> ID #{character.id}</span>
            <span className="inline-flex items-center gap-1"><Shield className="w-3 h-3" /> {getFactionName(character.MiembroFaccion)}</span>
            {character.LiderFaccion ? <span className="text-amber-400">{t('characters.details.leader')}</span> : null}
            <span className="inline-flex items-center gap-1"><MapPin className="w-3 h-3" />
              X: {typeof character.posX === 'number' ? character.posX.toFixed(2) : '—'},
              Y: {typeof character.posY === 'number' ? character.posY.toFixed(2) : '—'},
              Z: {typeof character.posZ === 'number' ? character.posZ.toFixed(2) : '—'}
            </span>
          </div>
        </div>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-6">
        <div className="rounded-xl border border-slate-600 bg-slate-700/40 p-4">
          <p className="text-sm text-gray-300 mb-1">{t('characters.details.cash')}</p>
          <p className="text-2xl font-bold text-emerald-400">${character.cash.toLocaleString()}</p>
        </div>
        <div className="rounded-xl border border-slate-600 bg-slate-700/40 p-4">
          <p className="text-sm text-gray-300 mb-1">{t('characters.details.bank')}</p>
          <p className="text-2xl font-bold text-blue-300">${character.bank.toLocaleString()}</p>
        </div>
        <div className="rounded-xl border border-slate-600 bg-slate-700/40 p-4">
          <p className="text-sm text-gray-300 mb-1">{t('characters.details.netWorth')}</p>
          <p className="text-2xl font-bold text-white">${(character.cash + character.bank).toLocaleString()}</p>
        </div>
      </div>

      {/* Status bars */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
        <div>
          <div className="flex items-center justify-between text-sm text-gray-300 mb-2">
            <span className="inline-flex items-center gap-2"><Heart className="w-4 h-4 text-red-400" /> {t('characters.details.health')}</span>
            <span className="text-white font-semibold">{character.health}</span>
          </div>
          <div className="h-2 rounded-full bg-slate-700 overflow-hidden">
            <div className="h-full bg-gradient-to-r from-red-500 to-red-400" style={{ width: `${Math.min(100, (character.health / 100) * 100)}%` }}></div>
          </div>
        </div>
        {/* Placeholder second bar (can be extended when hunger/thirst is available) */}
        <div className="opacity-70">
          <div className="flex items-center justify-between text-sm text-gray-300 mb-2">
            <span className="inline-flex items-center gap-2"><CalendarClock className="w-4 h-4 text-blue-400" /> {t('characters.details.age')}</span>
            <span className="text-white font-semibold">{character.age}</span>
          </div>
          <div className="h-2 rounded-full bg-slate-700 overflow-hidden">
            <div className="h-full bg-gradient-to-r from-blue-500 to-blue-400" style={{ width: `${Math.min(100, (character.age / 100) * 100)}%` }}></div>
          </div>
        </div>
      </div>

      {/* Character Details */}
      <div className="mb-2">
        <h4 className="text-white font-semibold mb-3">{t('characters.details.title')}</h4>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-3">
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.fullName')}</span>
            <span className="text-white text-sm font-medium truncate">{character.name}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.phoneNumber')}</span>
            <span className="text-white text-sm font-medium">{character.phone || '—'}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.bank')}</span>
            <span className="text-white text-sm font-medium">${character.bank.toLocaleString()}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.cash')}</span>
            <span className="text-white text-sm font-medium">${character.cash.toLocaleString()}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.faction')}</span>
            <span className="text-white text-sm font-medium">{getFactionName(character.MiembroFaccion)}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.leader')}</span>
            <span className="text-white text-sm font-medium">{character.LiderFaccion ? t('characters.details.yes') : t('characters.details.no')}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.coordinates')}</span>
            <span className="text-white text-sm font-medium">{typeof character.posX === 'number' && typeof character.posY === 'number' && typeof character.posZ === 'number' ? `${character.posX.toFixed(2)}, ${character.posY.toFixed(2)}, ${character.posZ.toFixed(2)}` : '—'}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.gender')}</span>
            <span className="text-white text-sm font-medium">{character.gender === 'female' ? t('characters.details.female') : t('characters.details.male')}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.skin')}</span>
            <span className="text-white text-sm font-medium">#{character.skin}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.city')}</span>
            <span className="text-white text-sm font-medium">{character.city || '—'}</span>
          </div>
          <div className="flex items-center justify-between border-b border-white/10 py-2">
            <span className="text-gray-400 text-sm">{t('characters.details.walkStyle')}</span>
            <span className="text-white text-sm font-medium">{character.walkStyleName || '—'}</span>
          </div>
        </div>
        {character.biography ? (
          <div className="mt-4 rounded-xl border border-[#0087FF]/15 bg-[#0c1320]/50 p-4">
            <span className="text-gray-400 text-sm block mb-2">{t('characters.details.biography')}</span>
            <p className="text-white text-sm leading-relaxed">{character.biography}</p>
          </div>
        ) : null}
      </div>

      {/* Character Ban Status */}
      {character.banStatus && character.banStatus > 0 && (
        <div className="mt-6 p-6 bg-gradient-to-br from-red-900/30 via-red-800/20 to-red-900/30 rounded-2xl border-2 border-red-500/50 shadow-lg shadow-red-500/20">
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 bg-red-500/20 rounded-xl flex items-center justify-center border border-red-500/50 flex-shrink-0">
              <Ban className="w-6 h-6 text-red-400" />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-3">
                <AlertTriangle className="w-5 h-5 text-red-400" />
                <h4 className="text-lg font-bold text-red-300">{t('characters.bannedTitle')}</h4>
              </div>
              
              <div className="space-y-2">
                {character.banReason && (
                  <div className="flex items-start gap-2 text-sm">
                    <FileText className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                    <div>
                      <span className="text-gray-400">{t('characters.bannedReason')}: </span>
                      <span className="text-red-200 font-semibold">{character.banReason}</span>
                    </div>
                  </div>
                )}
                
                {character.bannedBy && (
                  <div className="flex items-start gap-2 text-sm">
                    <User className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                    <div>
                      <span className="text-gray-400">{t('characters.bannedBy')}: </span>
                      <span className="text-red-200 font-semibold">{character.bannedBy}</span>
                    </div>
                  </div>
                )}
                
                {character.banDate && (
                  <div className="flex items-start gap-2 text-sm">
                    <Calendar className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                    <div>
                      <span className="text-gray-400">{t('characters.bannedDate')}: </span>
                      <span className="text-red-200 font-semibold">{formatMySqlDate(character.banDate)}</span>
                    </div>
                  </div>
                )}
                
                <div className="flex items-start gap-2 text-sm">
                  <Shield className="w-4 h-4 text-red-300 mt-0.5 flex-shrink-0" />
                  <div>
                    <span className="text-gray-400">{t('ban.banType')}: </span>
                    <span className="text-red-200 font-semibold">
                      {character.banStatus === 1 ? t('ban.temporary') : character.banStatus === 2 ? t('ban.permanent') : t('characters.banned')}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  </div>
)

// Confirm Modal
const ConfirmModal = ({ open, title, description, confirmText = 'Confirm', cancelText = 'Cancel', onConfirm, onCancel }: {
  open: boolean,
  title: string,
  description: string,
  confirmText?: string,
  cancelText?: string,
  onConfirm: () => void,
  onCancel: () => void
}) => {
  if (!open) return null
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/70" onClick={onCancel}></div>
      <div className="relative w-full max-w-md bg-gradient-to-br from-[#0f1620] to-[#0c1320] border border-[#0087FF]/20 rounded-2xl p-6 shadow-2xl">
        <h4 className="text-xl font-bold text-white mb-2">{title}</h4>
        <p className="text-sm text-gray-300 mb-5">{description}</p>
        <div className="flex items-center justify-end gap-3">
          <button onClick={onCancel} className="px-4 py-2 rounded-xl border border-[#0087FF]/20 text-[#8ab4ff] hover:bg-[#0087FF]/10">{cancelText}</button>
          <button onClick={onConfirm} className="px-4 py-2 rounded-xl bg-red-600 text-white hover:bg-red-500">{confirmText}</button>
        </div>
      </div>
    </div>
  )
}

export default function DashboardPage() {
  const { user, logout, loading: authLoading, showCertReminder, clearCertReminder } = useAuth()
  const router = useRouter()
  const locale = useLocale()
  const t = useTranslations('dashboard')
  const [profile, setProfile] = useState<UserProfile | null>(null)
  const [loading, setLoading] = useState(true)
  const [profilePhoto, setProfilePhoto] = useState<string | null>(null)
  const [showIP, setShowIP] = useState(false)
  const [discordInfo, setDiscordInfo] = useState<any>(null)
  const [discordSyncLoading, setDiscordSyncLoading] = useState(false)
  const [isAdmin, setIsAdmin] = useState(false)
  const [characters, setCharacters] = useState<CharacterItem[]>([])
  const [maxCharacters, setMaxCharacters] = useState(MAX_CHARACTERS_PER_ACCOUNT)
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [totalCharacterMoney, setTotalCharacterMoney] = useState(0)
  const [totalCash, setTotalCash] = useState(0)
  const [totalBank, setTotalBank] = useState(0)
  const [notification, setNotification] = useState<{type: 'success' | 'error' | 'info', message: string} | null>(null)
  const [characterQuery, setCharacterQuery] = useState('')
  const [unlinkConfirmOpen, setUnlinkConfirmOpen] = useState(false)
  const [certificationEnabled, setCertificationEnabled] = useState(false)

  const isCertified = user?.certified === true || profile?.certified === true
  const needsCertification =
    certificationEnabled && profile?.certificationRequired && !isCertified
  const canLinkDiscord = isCertified || !certificationEnabled

  const canCreateCharacter =
    !needsCertification && characters.length < maxCharacters

  const filteredCharacters = characters.filter((character) => {
    const query = characterQuery.trim().toLowerCase()
    if (!query) return true
    return (
      character.name.toLowerCase().includes(query) ||
      String(character.id).includes(query)
    )
  })

  // Notification handler
  const handleNotification = (type: 'success' | 'error' | 'info', message: string) => {
    setNotification({ type, message })
    setTimeout(() => setNotification(null), 4000)
  }

  useEffect(() => {
    authFetch('/api/user/certification/config')
      .then((res) => res.json())
      .then((data) => setCertificationEnabled(Boolean(data.enabled)))
      .catch(() => setCertificationEnabled(false))
  }, [])

  useEffect(() => {
    if (showCertReminder && needsCertification) {
      handleNotification('info', t('certification.loginReminder'))
      clearCertReminder()
    }
  }, [showCertReminder, needsCertification, clearCertReminder, t])

  useEffect(() => {
    if (typeof window === 'undefined') return
    const params = new URLSearchParams(window.location.search)
    if (params.get('certified') === '1') {
      handleNotification('success', t('certification.passed'))
      setProfile((prev) => (prev ? { ...prev, certified: true } : prev))
      window.history.replaceState({}, document.title, window.location.pathname)
    }
    if (params.get('characterCreated') === '1') {
      handleNotification('success', t('createCharacter.success'))
      window.history.replaceState({}, document.title, window.location.pathname)
    }
    if (params.get('error') === 'discord_certification_required') {
      handleNotification('error', t('discord.certificationRequired'))
      window.history.replaceState({}, document.title, window.location.pathname)
    }
  }, [t])

  useEffect(() => {
    // Wait for auth to finish loading before checking user state
    if (authLoading) return
    
    if (!user) {
      router.push(`/${locale}/login`)
      return
    }

    fetchUserProfile()
    fetchCharacters()

    const urlParams = new URLSearchParams(window.location.search)
    if (urlParams.get('discord_linked') === 'true') {
      handleNotification('success', t('discord.linkedSuccess'))
      if (urlParams.get('discord_role_failed') === '1') {
        handleNotification('error', t('discord.syncRoleError'))
      }
      fetchDiscordInfo()
      window.history.replaceState({}, document.title, window.location.pathname)
    }
  }, [user, router, authLoading])

  // Refetch profile photo when user changes
  useEffect(() => {
    if (user && !authLoading) {
      fetchProfilePhoto()
      fetchDiscordInfo()
      checkAdmin()
    }
  }, [user, authLoading])

  const checkAdmin = async () => {
    try {
      if (!user) return
      const res = await authFetch(`/api/admin/is-admin`)
      if (res.ok) {
        const data = await res.json()
        setIsAdmin(!!data?.isAdmin)
      }
    } catch {}
  }

  const fetchCharacters = async () => {
    try {
      if (!user) return
      const res = await authFetch(`/api/user/characters`)
      if (res.ok) {
        const data = await res.json()
        const charactersData = Array.isArray(data.characters) ? data.characters : []
        const normalized: CharacterItem[] = charactersData.map((c: any) => {
          const banStatusValue = c?.banStatus ?? 0
          return {
            id: c.id,
            name: c.name,
            health: parseNumeric(c?.health ?? c?.Vida ?? 0),
            skin: parseNumeric(c?.skin ?? c?.Skin ?? 0),
            gender: c.gender,
            age: parseNumeric(c?.age ?? c?.Edad ?? 0),
            cityId: c?.cityId != null ? parseNumeric(c.cityId) : undefined,
            city: c?.city || undefined,
            walkStyle: c?.walkStyle != null ? parseNumeric(c.walkStyle) : undefined,
            walkStyleName: c?.walkStyleName || undefined,
            biography: c?.biography || '',
            cash: parseNumeric(c?.BolosUwU ?? c?.money ?? c?.cash ?? 0),
            bank: parseNumeric(c?.BanescoOwO ?? c?.bank ?? c?.bankMoney ?? 0),
            phone: c.phone || c.Telefono || null,
            avatar: c.avatar,
            posX: c?.PosicionX != null ? parseNumeric(c.PosicionX) : (c?.posX != null ? parseNumeric(c.posX) : undefined),
            posY: c?.PosicionY != null ? parseNumeric(c.PosicionY) : (c?.posY != null ? parseNumeric(c.posY) : undefined),
            posZ: c?.PosicionZ != null ? parseNumeric(c.PosicionZ) : (c?.posZ != null ? parseNumeric(c.posZ) : undefined),
            MiembroFaccion: c?.MiembroFaccion != null ? parseNumeric(c.MiembroFaccion) : null,
            LiderFaccion: c?.LiderFaccion != null ? parseNumeric(c.LiderFaccion) : null,
            banStatus: banStatusValue > 0 ? banStatusValue : undefined,
            banReason: banStatusValue > 0 ? (c?.banReason || null) : undefined,
            banDate: banStatusValue > 0 ? (c?.banDate || null) : undefined,
            bannedBy: banStatusValue > 0 ? (c?.bannedBy || null) : undefined,
            banDuration: banStatusValue > 0 ? (c?.banDuration || null) : undefined,
          }
        })
        setCharacters(normalized)
        setMaxCharacters(
          Number(data.maxCharacters) > 0
            ? Number(data.maxCharacters)
            : MAX_CHARACTERS_PER_ACCOUNT
        )
        
        // Calculate totals
        const cashSum = normalized.reduce((sum: number, c: CharacterItem) => sum + (c.cash || 0), 0)
        const bankSum = normalized.reduce((sum: number, c: CharacterItem) => sum + (c.bank || 0), 0)
        setTotalCash(cashSum)
        setTotalBank(bankSum)
        setTotalCharacterMoney(cashSum + bankSum)
      }
    } catch {}
  }

  const fetchUserProfile = async () => {
    try {
      if (!user) return
      
      const response = await authFetch(`/api/user/profile`)
      if (response.ok) {
        const data = await response.json()

        setProfile(data)
      } else {
        console.error('Failed to fetch profile')
      }
    } catch (error) {
      console.error('Failed to fetch profile:', error)
    } finally {
      setLoading(false)
    }
  }

  const fetchDiscordInfo = async () => {
    if (!user) return
    
    try {
      const response = await authFetch(`/api/user/discord-info`)
      if (response.ok) {
        const data = await response.json()
        setDiscordInfo(data.discord)
      }
    } catch (error) {
      console.error('Error fetching Discord info:', error)
    }
  }

  const handleUnlinkDiscord = async () => {
    if (!user || !discordInfo) return

    try {
      const response = await authFetch(`/api/user/link-discord`, {
        method: 'DELETE'
      })

      if (response.ok) {
        setDiscordInfo(null)
        handleNotification('success', t('discord.unlinkedSuccess'))
        // Optional refresh
        fetchDiscordInfo()
      } else {
        const errorData = await response.json()
        console.error('Failed to unlink Discord account:', errorData.error)
        handleNotification('error', t('discord.unlinkError'))
      }
    } catch (error) {
      console.error('Error unlinking Discord account:', error)
      handleNotification('error', t('discord.unlinkError'))
    }
  }

  const handleSyncDiscordRole = async () => {
    if (!user || !discordInfo) return

    setDiscordSyncLoading(true)
    try {
      const response = await authFetch('/api/user/discord-sync-role', { method: 'POST' })
      const data = await response.json().catch(() => ({}))

      if (response.ok) {
        handleNotification('success', t('discord.syncRoleSuccess'))
      } else {
        handleNotification('error', data.error || t('discord.syncRoleError'))
      }
    } catch {
      handleNotification('error', t('discord.syncRoleError'))
    } finally {
      setDiscordSyncLoading(false)
    }
  }

  const startDiscordOAuth = async () => {
    if (!canLinkDiscord) {
      handleNotification('error', t('discord.certificationRequired'))
      return
    }
    try {
      const stateResponse = await authFetch('/api/auth/discord/state')
      if (!stateResponse.ok) {
        handleNotification('error', t('discord.error'))
        return
      }
      const { state } = await stateResponse.json()
      const clientId = process.env.NEXT_PUBLIC_DISCORD_CLIENT_ID || ''
      const baseUrl =
        (typeof window !== 'undefined' && window.location?.origin) ||
        process.env.NEXT_PUBLIC_BASE_URL ||
        'https://urbangamers.es'
      const redirectUri = encodeURIComponent(`${baseUrl}/api/auth/discord/callback`)
      const scope = encodeURIComponent('identify guilds.join')
      window.location.href = `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${encodeURIComponent(state)}`
    } catch {
      handleNotification('error', t('discord.error'))
    }
  }

  const getDiscordAvatarUrl = (discordId: string, avatarHash: string) => {
    return `https://cdn.discordapp.com/avatars/${discordId}/${avatarHash}.png`
  }

  const fetchProfilePhoto = async () => {
    try {
      if (!user) return

      const response = await authFetch(`/api/user/upload-photo`)
      if (response.ok) {
        const data = await response.json()
        if (data?.photo?.data && data?.photo?.type) {
          const photoUrl = `data:${data.photo.type};base64,${data.photo.data}`
          setProfilePhoto(photoUrl)
          } else {
            setProfilePhoto(null)
        }
      }
    } catch (error) {
      console.error('Error fetching profile photo:', error)
    }
  }

  if (loading) {
    return (
      <ProtectedRoute>
      <>
        <Header />
          <main className="min-h-screen pt-16 bg-gradient-to-b from-[#1E1E2E] via-[#002647] to-[#1E1E2E]">
            <div className="container mx-auto px-6 py-12">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 animate-pulse">
                <div className="md:col-span-1 space-y-4">
                  <div className="h-28 bg-white/5 rounded-2xl border border-white/10" />
                  <div className="h-40 bg-white/5 rounded-2xl border border-white/10" />
            </div>
                <div className="md:col-span-2 space-y-4">
                  <div className="h-12 bg-white/5 rounded-2xl border border-white/10" />
                  <div className="h-64 bg-white/5 rounded-2xl border border-white/10" />
                  <div className="h-40 bg-white/5 rounded-2xl border border-white/10" />
          </div>
              </div>
              <div className="mt-8 flex items-center justify-center">
                <div className="h-10 w-10 rounded-full border-2 border-[#0087FF]/30 border-t-[#0087FF] animate-spin" aria-label="Loading" />
            </div>
          </div>
        </main>
      </>
      </ProtectedRoute>
    )
  }

  if (!profile) {
    return (
      <ProtectedRoute>
      <>
        <Header />
          <main className="min-h-screen pt-16 bg-gradient-to-b from-[#1E1E2E] via-[#002647] to-[#1E1E2E]">
            <div className="container mx-auto px-6 py-16 text-center">
              <h1 className="text-3xl font-bold text-white mb-2">{t('profileNotFound.title')}</h1>
              <p className="text-gray-400">{t('profileNotFound.message')}</p>
          </div>
        </main>
      </>
      </ProtectedRoute>
    )
  }

  return (
    <ProtectedRoute>
      <>
        <Header />
        <main className="min-h-screen pt-16 bg-gradient-to-b from-[#1E1E2E] via-[#002647] to-[#1E1E2E]">
          {notification && (
            <NotificationToast
              type={notification.type}
              message={notification.message}
              onClose={() => setNotification(null)}
            />
          )}
          <ConfirmModal 
            open={unlinkConfirmOpen}
            title={t('discord.unlinkConfirm.title')}
            description={t('discord.unlinkConfirm.description')}
            confirmText={t('discord.unlinkConfirm.confirm')}
            cancelText={t('discord.unlinkConfirm.cancel')}
            onConfirm={() => { setUnlinkConfirmOpen(false); handleUnlinkDiscord() }}
            onCancel={() => { setUnlinkConfirmOpen(false) }}
          />
          <section className="container mx-auto px-6 py-8">
            <div className="mb-8">
              <h2 className="text-4xl font-bold text-white mb-2">{t('welcome', { username: profile.username })}</h2>
              <p className="text-gray-400 text-lg">{t('subtitle')}</p>
            </div>

            {needsCertification && (
              <div className="mb-8 p-4 rounded-2xl border border-amber-400/30 bg-amber-500/10 flex items-start gap-3">
                <AlertTriangle className="w-5 h-5 text-amber-300 mt-0.5 shrink-0" />
                <div>
                  <p className="text-amber-200 font-semibold">{t('certification.bannerTitle')}</p>
                  <p className="text-amber-100/80 text-sm mt-1">{t('certification.bannerText')}</p>
                </div>
              </div>
            )}

            {/* Stats — oculto temporalmente
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
              <StatsOverviewCard icon={<Hash className="w-6 h-6 text-white" />} title={t('stats.playerId')} value={profile.id.toString()} color="from-blue-500 to-blue-600" />
              <StatsOverviewCard icon={<DollarSign className="w-6 h-6 text-white" />} title={t('stats.totalMoney')} value={`$${totalCharacterMoney.toLocaleString()}`} subtitle={t('stats.subtitle', { cash: totalCash.toLocaleString(), bank: totalBank.toLocaleString(), count: characters.length, plural: characters.length !== 1 ? 's' : '' })} color="from-emerald-500 to-emerald-600" />
              <StatsOverviewCard icon={<Users className="w-6 h-6 text-white" />} title={t('stats.characters')} value={characters.length.toString()} color="from-purple-500 to-purple-600" />
              <StatsOverviewCard icon={<Coins className="w-6 h-6 text-white" />} title={t('stats.points')} value={(profile.points || 0).toLocaleString()} color="from-yellow-500 to-yellow-600" />
            </div>
            */}
                
            {/* Main content grid */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
              {/* Left column - Profile & Account */}
              <div className="lg:col-span-1 space-y-6">
                <ProfileAccountSection 
                  profilePhoto={profilePhoto}
                  onPhotoUpload={async (file: File) => {
                    // Show preview immediately
                    const objectUrl = URL.createObjectURL(file)
                    setProfilePhoto(objectUrl)
                    try {
                      if (!user) return
                      // Convert to base64 (strip the prefix)
                      const toBase64 = (f: File) => new Promise<string>((resolve, reject) => {
                        const reader = new FileReader()
                        reader.onload = () => resolve(String(reader.result).split(',')[1] || '')
                        reader.onerror = reject
                        reader.readAsDataURL(f)
                      })
                      const base64 = await toBase64(file)
                      await authFetch(`/api/user/upload-photo`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ photoData: base64, photoType: file.type, fileSize: file.size })
                      })
                      // Refresh from server (ensures persistence & future loads)
                      fetchProfilePhoto()
                    } catch (e) {
                      console.error('Upload failed', e)
                    }
                  }}
                  onPhotoRemove={async () => {
                    if (!user) return
                    await authFetch(`/api/user/upload-photo`, { method: 'DELETE' })
                    setProfilePhoto(null)
                    fetchProfilePhoto()
                  }}
                  profile={profile}
                  showIP={showIP}
                  setShowIP={setShowIP}
                  formatDate={formatMySqlDate}
                  maskIP={(ip: string) => (ip ? ip.replace(/\d/g, 'x') : '')}
                  onNotification={handleNotification}
                  t={t}
                />
                {canLinkDiscord ? (
                  discordInfo ? (
                    <DiscordSection
                      discordInfo={discordInfo}
                      onLinkDiscord={startDiscordOAuth}
                      onUnlinkDiscord={() => setUnlinkConfirmOpen(true)}
                      onSyncRole={handleSyncDiscordRole}
                      syncingRole={discordSyncLoading}
                      t={t}
                    />
                  ) : (
                    <DiscordSection discordInfo={null} onLinkDiscord={startDiscordOAuth} onUnlinkDiscord={() => setUnlinkConfirmOpen(true)} t={t} />
                  )
                ) : (
                  <DiscordSectionLocked
                    t={t}
                    onGoCertification={() => router.push(`/${locale}/dashboard/certification`)}
                  />
                )}

                {/* Quick Actions */}
                <div className="bg-[#0f1620]/70 backdrop-blur-sm rounded-2xl p-4 border border-[#0087FF]/20">
                  <h3 className="text-lg font-bold text-white mb-3">{t('quickActions.title')}</h3>
                  <div className="space-y-2">
                    {needsCertification && (
                      <button
                        type="button"
                        onClick={() => router.push(`/${locale}/dashboard/certification`)}
                        className="w-full flex items-center justify-center gap-2 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white font-medium py-2 rounded-xl text-sm transition-colors"
                      >
                        <ShieldCheck className="w-4 h-4" />
                        {t('quickActions.certifyAccount')}
                      </button>
                    )}
                        <button
                       onClick={() => connectToGameServer()}
                       className="w-full flex items-center justify-center gap-2 bg-[#0087FF] hover:bg-[#0072d1] text-white font-medium py-2 rounded-xl text-sm transition-colors"
                     >
                       <Play className="w-4 h-4" />
                       {t('quickActions.joinServer')}
                        </button>
                      <button
                       onClick={() => window.open('https://discord.gg/6rjeA3TPBn', '_blank')}
                       className="w-full flex items-center justify-center gap-2 border border-[#0087FF]/30 text-[#8ab4ff] hover:bg-[#0087FF]/10 hover:text-white rounded-xl py-2 text-sm transition-colors"
                     >
                       {/* small discord glyph */}
                       <svg viewBox="0 0 24 24" fill="currentColor" className="w-4 h-4">
                         <path d="M20.317 4.37a19.79 19.79 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.127.094.253.194.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.419-.019 1.333-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1568 2.4189Z"/>
                          </svg>
                       {t('quickActions.joinDiscord')}
                     </button>
                    {isAdmin && (
                       <button
                        onClick={() => router.push(`/${locale}/admin`)}
                         className="w-full flex items-center justify-center gap-2 bg-gradient-to-r from-emerald-600 to-emerald-500 hover:from-emerald-700 hover:to-emerald-600 text-white font-medium py-2 rounded-xl text-sm transition-all duration-300 shadow-lg hover:shadow-emerald-500/25"
                      >
                         <Shield className="w-4 h-4" />
                        {t('quickActions.adminPanel')}
                       </button>
                     )}
                  </div>
                </div>

              {/* Close left column and start right column */}
              </div>

              {/* Right column - Characters and content */}
              <div className="lg:col-span-2 space-y-8">
                <div className="bg-[#0f1620]/70 backdrop-blur-sm rounded-2xl border border-[#0087FF]/20 p-6">
                  <div className="flex items-center justify-between mb-6 gap-3 flex-wrap">
                              <div>
                      <h3 className="text-2xl font-bold text-white">{t('characters.title')}</h3>
                      <p className="text-gray-400">{t('characters.subtitle')}</p>
                    </div>
                    <div className="flex items-center gap-2">
                      {canCreateCharacter && (
                        <Link
                          href={`/${locale}/dashboard/create-character`}
                          className="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-sm font-medium border border-[#0087FF]/30 text-[#8ab4ff] hover:text-white hover:bg-[#0087FF]/10 transition-colors"
                        >
                          <Plus className="w-4 h-4" />
                          {t('createCharacter.button')}
                        </Link>
                      )}
                      <div className="relative">
                        <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                        <input
                          type="text"
                          value={characterQuery}
                          onChange={(e) => setCharacterQuery(e.target.value)}
                          placeholder={t('characters.searchPlaceholder')}
                          aria-label="Search characters"
                          className="pl-10 pr-4 py-2 bg-[#0c1320]/80 border border-[#0087FF]/20 rounded-xl text-white placeholder-gray-400 focus:outline-none focus:border-[#0087FF] focus:ring-0"
                        />
                  </div>
                    </div>
                  </div>

                  {filteredCharacters.length > 0 ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {filteredCharacters.map((character) => (
                        <CharacterCard key={character.id} character={character} href={`/${locale}/dashboard/characters/${character.id}`} t={t} />
                      ))}
                    </div>
                  ) : characters.length === 0 ? (
                    <div className="text-center py-16">
                      <Users className="w-20 h-20 text-gray-600 mx-auto mb-4" />
                      <h4 className="text-xl font-semibold text-gray-300 mb-2">{t('characters.emptyTitle')}</h4>
                      <p className="text-gray-500 mb-6">{t('characters.emptySubtitle')}</p>
                      {canCreateCharacter && (
                        <Link
                          href={`/${locale}/dashboard/create-character`}
                          className="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium bg-[#0087FF]/15 border border-[#0087FF]/30 text-[#8ab4ff] hover:text-white hover:bg-[#0087FF]/25 transition-colors"
                        >
                          <Plus className="w-4 h-4" />
                          {t('createCharacter.button')}
                        </Link>
                      )}
                    </div>
                  ) : (
                    <div className="text-center py-16">
                      <Users className="w-20 h-20 text-gray-600 mx-auto mb-4" />
                      <h4 className="text-xl font-semibold text-gray-300 mb-2">{t('characters.noMatch')}</h4>
                      <p className="text-gray-500">{t('characters.tryDifferent')}</p>
                  </div>
                )}
                </div>

                {profile && (
                  <PlayerVehicles userId={profile.id} characters={characters.map(c => ({ id: c.id, name: c.name }))} />
                )}

                {/* Money Leaderboard - Below Vehicles & Interiors */}
                <div className="mt-6">
                  <MoneyLeaderboard limit={5} />
              </div>
            </div>
          </div>
          </section>

        </main>
      </>
    </ProtectedRoute>
  )
}

