import { useCallback, useEffect, useState, useRef } from "react"
import { useNavigate } from "react-router-dom"
import { StatusBar } from "@/components/StatusBar"
import { FarmGrid } from "@/components/FarmGrid"
import type { LandData } from "@/components/FarmGrid"
import { LogPanel } from "@/components/LogPanel"
import { ShopPanel } from "@/components/ShopPanel"
import { WarehousePanel } from "@/components/WarehousePanel"
import { SystemMonitor } from "@/components/SystemMonitor"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Cloud, Heart, Star, LogOut, QrCode, RefreshCw, Sprout, Settings, Trophy, ClipboardList, CheckCircle2, Circle, Shovel, Gift, Leaf, PawPrint, Sparkles, Package } from "lucide-react"
import logo from "@/assets/logo.png"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"

interface FarmStatus {
  nickname: string
  level: number
  exp: number
  nextLevelExp: number
  gold: number
  tickets: number
  normalFertilizerHours: number
  organicFertilizerHours: number
  status: 'running' | 'stopped' | 'error'
  avatarUrl?: string
  freeMallClaimed?: boolean
}

interface User {
  email: string
  hasCode: boolean
  code?: string
}

type SeedStrategy = 'default' | 'forceLowest'
type IdleStrategy = 'task' | 'exp'

interface BotSettings {
  farmIntervalSec: number
  friendIntervalSec: number
  seedStrategy: SeedStrategy
  enableFriendOps: boolean
  enableSteal: boolean
  allowTicketFertilizerPurchase: boolean
  enableNormalFertilize: boolean
  enableOrganicFertilize: boolean
  enableAutoSell: boolean
  allowBuySeeds: boolean
  allowRemove: boolean
  idleStrategy: IdleStrategy
}

interface UnluckyItem {
  name: string
  count: number
}

type PaidMallCategory = 'daily' | 'organic' | 'fertilizer' | 'dog'

interface PaidMallItem {
  id: number
  name: string
  currency?: string
  price?: number
  discount?: string
  items: { name: string; count: number }[]
  category: PaidMallCategory
}

const paidMallItems: PaidMallItem[] = [
  {
    id: 1001,
    name: "每日福利",
    items: [{ name: "化肥(1小时)", count: 1 }],
    category: 'daily'
  },
  {
    id: 1002,
    name: "10小时有机化肥",
    currency: "点券",
    price: 42,
    discount: "9.1折",
    items: [
      { name: "有机化肥(1小时)", count: 2 },
      { name: "有机化肥(8小时)", count: 1 }
    ],
    category: 'organic'
  },
  {
    id: 1003,
    name: "10小时化肥",
    currency: "点券",
    price: 34,
    discount: "9.4折",
    items: [
      { name: "化肥(1小时)", count: 2 },
      { name: "化肥(8小时)", count: 1 }
    ],
    category: 'fertilizer'
  },
  {
    id: 1004,
    name: "20小时有机化肥",
    currency: "钻石",
    price: 80,
    discount: "9.1折",
    items: [
      { name: "有机化肥(8小时)", count: 1 },
      { name: "有机化肥(12小时)", count: 1 }
    ],
    category: 'organic'
  },
  {
    id: 1005,
    name: "20小时化肥",
    currency: "钻石",
    price: 64,
    discount: "9.4折",
    items: [
      { name: "化肥(8小时)", count: 1 },
      { name: "化肥(12小时)", count: 1 }
    ],
    category: 'fertilizer'
  },
  {
    id: 1006,
    name: "狗粮礼包",
    currency: "点券",
    price: 33,
    items: [
      { name: "1天狗粮", count: 1 },
      { name: "3天狗粮", count: 1 },
      { name: "5天狗粮", count: 1 }
    ],
    category: 'dog'
  },
  {
    id: 1007,
    name: "有机化肥(1小时)",
    currency: "钻石",
    price: 5,
    items: [{ name: "有机化肥(1小时)", count: 1 }],
    category: 'organic'
  },
  {
    id: 1008,
    name: "有机化肥(4小时)",
    currency: "钻石",
    price: 19,
    items: [{ name: "有机化肥(4小时)", count: 1 }],
    category: 'organic'
  },
  {
    id: 1009,
    name: "有机化肥(8小时)",
    currency: "钻石",
    price: 36,
    items: [{ name: "有机化肥(8小时)", count: 1 }],
    category: 'organic'
  },
  {
    id: 1010,
    name: "有机化肥(12小时)",
    currency: "钻石",
    price: 52,
    items: [{ name: "有机化肥(12小时)", count: 1 }],
    category: 'organic'
  },
  {
    id: 1011,
    name: "化肥(1小时)",
    currency: "钻石",
    price: 4,
    items: [{ name: "化肥(1小时)", count: 1 }],
    category: 'fertilizer'
  },
  {
    id: 1012,
    name: "化肥(4小时)",
    currency: "钻石",
    price: 15,
    items: [{ name: "化肥(4小时)", count: 1 }],
    category: 'fertilizer'
  },
  {
    id: 1013,
    name: "化肥(8小时)",
    currency: "钻石",
    price: 28,
    items: [{ name: "化肥(8小时)", count: 1 }],
    category: 'fertilizer'
  },
  {
    id: 1014,
    name: "化肥(12小时)",
    currency: "钻石",
    price: 40,
    items: [{ name: "化肥(12小时)", count: 1 }],
    category: 'fertilizer'
  },
  {
    id: 1015,
    name: "1天狗粮",
    currency: "钻石",
    price: 4,
    items: [{ name: "1天狗粮", count: 1 }],
    category: 'dog'
  },
  {
    id: 1016,
    name: "3天狗粮",
    currency: "钻石",
    price: 11,
    items: [{ name: "3天狗粮", count: 1 }],
    category: 'dog'
  },
  {
    id: 1017,
    name: "5天狗粮",
    currency: "钻石",
    price: 18,
    items: [{ name: "5天狗粮", count: 1 }],
    category: 'dog'
  }
]

function getPaidMallIcon(category: PaidMallCategory) {
  if (category === 'daily') return <Gift className="h-7 w-7 text-amber-500" />
  if (category === 'organic') return <Leaf className="h-7 w-7 text-emerald-500" />
  if (category === 'dog') return <PawPrint className="h-7 w-7 text-rose-400" />
  return <Package className="h-7 w-7 text-slate-500" />
}

interface TaskReward {
  id: number
  count: number
}

type TaskCategory = 'growth' | 'daily' | 'normal'

interface TaskItem {
  id: number
  desc: string
  progress: number
  totalProgress: number
  isClaimed: boolean
  isUnlocked: boolean
  shareMultiple: number
  rewards: TaskReward[]
  category: TaskCategory
}

function TaskPanel({ email }: { email: string }) {
  const [tasks, setTasks] = useState<TaskItem[]>([])
  const [loading, setLoading] = useState(false)
  const [claimingId, setClaimingId] = useState<number | null>(null)
  const [showCompleted, setShowCompleted] = useState(false)
  const [error, setError] = useState("")
  const [lastClaim, setLastClaim] = useState<{ claimedCount: number; failed: number } | null>(null)
  const inflightRef = useRef(false)
  const claimedCacheRef = useRef<Map<string, TaskItem>>(new Map())
  const autoCompleteRef = useRef(false)

  const getTaskKey = useCallback((task: TaskItem) => {
    return `${(task.desc || '').trim()}|${task.totalProgress}`
  }, [])

  const mergeWithClaimedCache = useCallback((nextTasks: TaskItem[]) => {
    const resultMap = new Map<string, TaskItem>()
    for (const task of nextTasks) {
      const key = getTaskKey(task)
      resultMap.set(key, task)
      if (task.isClaimed) {
        claimedCacheRef.current.set(key, task)
      }
    }
    for (const [key, cached] of claimedCacheRef.current.entries()) {
      const current = resultMap.get(key)
      if (!current || (cached.isClaimed && !current.isClaimed)) {
        resultMap.set(key, cached)
      }
    }
    return Array.from(resultMap.values())
  }, [getTaskKey])

  const fetchTasks = useCallback(async (withClaim: boolean) => {
    if (!email) return
    if (inflightRef.current) return
    inflightRef.current = true
    setLoading(true)
    setError("")
    try {
      if (withClaim) {
        const res = await fetch('/api/tasks/claim', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email })
        })
        if (!res.ok) throw new Error('claim failed')
        const data = await res.json()
        const list = Array.isArray(data.tasks) ? data.tasks : []
        setTasks(mergeWithClaimedCache(list))
        const failed = Array.isArray(data.failed) ? data.failed.length : 0
        setLastClaim({ claimedCount: Number(data.claimedCount) || 0, failed })
      } else {
        const res = await fetch(`/api/tasks?email=${encodeURIComponent(email)}`)
        if (!res.ok) throw new Error('fetch failed')
        const data = await res.json()
        const list = Array.isArray(data.tasks) ? data.tasks : []
        setTasks(mergeWithClaimedCache(list))
      }
    } catch {
      setError("任务获取失败")
    } finally {
      setLoading(false)
      inflightRef.current = false
    }
  }, [email, mergeWithClaimedCache])

  const claimSingle = useCallback(async (task: TaskItem) => {
    if (!email) return
    if (claimingId !== null) return
    setClaimingId(task.id)
    setError("")
    try {
      const res = await fetch('/api/tasks/claim-one', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, taskId: task.id, doShared: task.shareMultiple > 1 })
      })
      if (!res.ok) throw new Error('claim failed')
      const data = await res.json()
      const list = Array.isArray(data.tasks) ? data.tasks : []
      const claimedTask = { ...task, isClaimed: true }
      claimedCacheRef.current.set(getTaskKey(claimedTask), claimedTask)
      setTasks(mergeWithClaimedCache(list))
      const claimedCount = Number(data.claimedCount) || 0
      const failedCount = Number(data.failedCount) || 0
      if (claimedCount > 0 || failedCount > 0) {
        setLastClaim({ claimedCount, failed: failedCount })
      }
    } catch {
      setError("任务完成失败")
    } finally {
      setClaimingId(null)
    }
  }, [claimingId, email, getTaskKey, mergeWithClaimedCache])

  const autoCompleteNext = useCallback(() => {
    if (autoCompleteRef.current) return
    const nextTask = tasks.find((task) => {
      if (task.isClaimed) return false
      if (!task.isUnlocked) return false
      if (task.totalProgress <= 0) return false
      return task.progress >= task.totalProgress
    })
    if (!nextTask) return
    autoCompleteRef.current = true
    claimSingle(nextTask).finally(() => {
      autoCompleteRef.current = false
    })
  }, [claimSingle, tasks])

  useEffect(() => {
    if (!email) return
    fetchTasks(false)
    const timer = setInterval(() => fetchTasks(false), 15000)
    return () => clearInterval(timer)
  }, [email, fetchTasks])

  useEffect(() => {
    autoCompleteNext()
  }, [autoCompleteNext])

  const completedCount = tasks.filter(task => task.isClaimed).length
  const visibleTasks = showCompleted ? tasks : tasks.filter(task => !task.isClaimed)
  const buckets: Record<TaskCategory, TaskItem[]> = { growth: [], daily: [], normal: [] }
  for (const task of visibleTasks) {
    if (task.category === 'growth' || task.category === 'daily' || task.category === 'normal') {
      buckets[task.category].push(task)
    } else {
      buckets.normal.push(task)
    }
  }

  const categoryMeta: Array<{ key: TaskCategory; label: string; badge: string }> = [
    { key: 'growth', label: '成长', badge: 'bg-indigo-50 text-indigo-600 border-indigo-100' },
    { key: 'daily', label: '日常', badge: 'bg-emerald-50 text-emerald-600 border-emerald-100' },
    { key: 'normal', label: '普通', badge: 'bg-slate-50 text-slate-600 border-slate-200' }
  ]

  return (
    <div className="bg-white/60 backdrop-blur-md rounded-[2.5rem] p-6 shadow-sm border border-white/50 space-y-4">
      <div className="flex items-center justify-between">
        <div className="space-y-1">
          <div className="text-sm font-semibold text-slate-700 flex items-center gap-2">
            <ClipboardList className="h-4 w-4 text-indigo-400" />
            当前任务
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            className="rounded-full border-white/60 bg-white/60 text-slate-600 hover:bg-white"
            onClick={() => setShowCompleted(prev => !prev)}
          >
            {showCompleted ? "隐藏已完成" : `显示已完成(${completedCount})`}
          </Button>
          <Button
            variant="outline"
            size="sm"
            className="rounded-full border-white/60 bg-white/60 text-slate-600 hover:bg-white"
            onClick={() => fetchTasks(false)}
            disabled={loading}
          >
            {loading ? "更新中" : "刷新"}
          </Button>
        </div>
      </div>

      {lastClaim && (lastClaim.claimedCount > 0 || lastClaim.failed > 0) && (
        <div className="text-xs text-slate-500">
          已完成 {lastClaim.claimedCount} 个任务 {lastClaim.failed > 0 ? `，失败 ${lastClaim.failed} 个` : ''}
        </div>
      )}

      {error && (
        <div className="text-xs text-rose-500">{error}</div>
      )}

      {visibleTasks.length === 0 && !loading ? (
        <div className="text-sm text-slate-400 text-center py-6">暂无任务</div>
      ) : (
        <div className="space-y-4">
          {categoryMeta.map(({ key, label, badge }) => {
            const items = buckets[key]
            if (items.length === 0) return null
            return (
              <div key={key} className="space-y-2">
                <div className="flex items-center gap-2 text-xs font-semibold">
                  <span className={`px-2 py-0.5 rounded-full border ${badge}`}>{label}</span>
                  <span className="text-slate-400">{items.length} 项</span>
                </div>
                <div className="space-y-2">
                  {items.map(task => {
                    const claimable = task.isUnlocked && !task.isClaimed && task.totalProgress > 0 && task.progress >= task.totalProgress
                    const progressText = task.totalProgress > 0 ? `${task.progress}/${task.totalProgress}` : "-"
                    const progressPercent = task.totalProgress > 0 ? Math.min(100, Math.round((task.progress / task.totalProgress) * 100)) : 0
                    return (
                      <div key={task.id} className="bg-white/70 border border-white/60 rounded-2xl px-4 py-3 space-y-2">
                        <div className="flex items-start justify-between gap-3">
                          <div className="flex items-start gap-2">
                            {task.isClaimed ? (
                              <CheckCircle2 className="h-4 w-4 text-emerald-500 mt-0.5" />
                            ) : claimable ? (
                              <Circle className="h-4 w-4 text-indigo-400 mt-0.5" />
                            ) : (
                              <Circle className="h-4 w-4 text-slate-300 mt-0.5" />
                            )}
                            <div className="space-y-1">
                              <div className="text-sm font-medium text-slate-700">{task.desc || `任务#${task.id}`}</div>
                              <div className="text-xs text-slate-400">
                                进度 {progressText}
                                {task.shareMultiple > 1 ? ` · 分享翻倍 x${task.shareMultiple}` : ''}
                              </div>
                            </div>
                          </div>
                        <div className="flex items-center gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            className="h-7 px-3 rounded-full border-white/60 bg-white/70 text-slate-600 hover:bg-white"
                            onClick={() => claimSingle(task)}
                            disabled={loading || claimingId === task.id || !claimable}
                          >
                            {claimingId === task.id ? "完成中" : "完成"}
                          </Button>
                          <div className={`text-xs font-semibold ${task.isClaimed ? "text-emerald-500" : claimable ? "text-indigo-500" : "text-slate-400"}`}>
                            {task.isClaimed ? "已完成" : "进行中"}
                          </div>
                        </div>
                        </div>
                        <div className="h-2 rounded-full bg-slate-100 overflow-hidden">
                          <div
                            className={`h-full rounded-full ${task.isClaimed ? "bg-emerald-400" : claimable ? "bg-indigo-400" : "bg-slate-300"}`}
                            style={{ width: `${progressPercent}%` }}
                          />
                        </div>
                      </div>
                    )
                  })}
                </div>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}

const defaultSettings: BotSettings = {
  farmIntervalSec: 1,
  friendIntervalSec: 10,
  seedStrategy: 'default',
  enableFriendOps: true,
  enableSteal: true,
  allowTicketFertilizerPurchase: false,
  enableNormalFertilize: false,
  enableOrganicFertilize: false,
  enableAutoSell: true,
  allowBuySeeds: true,
  allowRemove: true,
  idleStrategy: 'exp'
}

export default function Dashboard() {
  const navigate = useNavigate()
  const [user, setUser] = useState<User | null>(null)
  const [farmStatus, setFarmStatus] = useState<FarmStatus>({
    nickname: "加载中...",
    level: 1,
    exp: 0,
    nextLevelExp: 100,
    gold: 0,
    tickets: 0,
    normalFertilizerHours: 0,
    organicFertilizerHours: 0,
    status: 'stopped',
    freeMallClaimed: false
  })
  const [warehouseRefreshKey, setWarehouseRefreshKey] = useState(0)
  const [lands, setLands] = useState<LandData[]>([])
  const [removeMode, setRemoveMode] = useState(false)
  const [selectedLandIds, setSelectedLandIds] = useState<number[]>([])
  const [isRemoving, setIsRemoving] = useState(false)
  const [unlockingLandIds, setUnlockingLandIds] = useState<number[]>([])
  const [showBindDialog, setShowBindDialog] = useState(false)
  const [isStarting, setIsStarting] = useState(false)
  const [settings, setSettings] = useState<BotSettings>(defaultSettings)
  const [isSavingSettings, setIsSavingSettings] = useState(false)
  const [settingsHint, setSettingsHint] = useState("")
  const [unluckyList, setUnluckyList] = useState<UnluckyItem[]>([])
  const [announcementMessage, setAnnouncementMessage] = useState("")
  const [announcementOpen, setAnnouncementOpen] = useState(false)
  const unluckyLoadingRef = useRef(false)
  const [activePage, setActivePage] = useState<'farm' | 'shop' | 'paymall' | 'settings' | 'task' | 'leaderboard'>('farm')
  const [navOpen, setNavOpen] = useState(false)
  const [payMallDialogOpen, setPayMallDialogOpen] = useState(false)
  const [payMallSelected, setPayMallSelected] = useState<PaidMallItem | null>(null)
  const [payMallCount, setPayMallCount] = useState(1)
  const [payMallMessage, setPayMallMessage] = useState("")
  const [payMallBuying, setPayMallBuying] = useState(false)
  const isPayMallClaimed = payMallSelected?.id === 1001 && farmStatus.freeMallClaimed === true
  
  // QR Code States
  const [qrCodeUrl, setQrCodeUrl] = useState("")
  const [qrSig, setQrSig] = useState("")
  const [qrStatus, setQrStatus] = useState<string>("init") // init, waiting, scanned, success, expired
  const [qrMsg, setQrMsg] = useState("")
  
  // Ref to track current status for stale closure prevention in setInterval
  const statusRef = useRef(farmStatus.status)

  // Sync ref with state
  useEffect(() => {
    statusRef.current = farmStatus.status
  }, [farmStatus.status])

  useEffect(() => {
    if (removeMode) return
    if (selectedLandIds.length === 0) return
    setSelectedLandIds([])
  }, [removeMode, selectedLandIds.length])
  
  // Initialize user from local storage
  useEffect(() => {
    const storedUser = localStorage.getItem('farm_user')
    if (!storedUser) {
      navigate('/login')
      return
    }
    const userData = JSON.parse(storedUser)
    setUser(userData)
    
    // Check if user needs to bind farm
    if (!userData.hasCode && !userData.code) {
      setShowBindDialog(true)
    }
  }, [navigate])

  useEffect(() => {
    if (!user) return
    let cancelled = false
    const loadAnnouncement = async () => {
      try {
        const res = await fetch('/api/announcement')
        if (!res.ok) return
        const data = await res.json()
        const message = String(data?.message || '').trim()
        if (!message) return
        if (cancelled) return
        setAnnouncementMessage(message)
        setAnnouncementOpen(true)
      } catch {
        return
      }
    }
    loadAnnouncement()
    return () => {
      cancelled = true
    }
  }, [user])

  const normalizeSettings = useCallback((value: BotSettings): BotSettings => {
    const farmIntervalSec = Math.max(1, Math.floor(Number(value.farmIntervalSec) || 1))
    const friendIntervalSec = Math.max(1, Math.floor(Number(value.friendIntervalSec) || 1))
    const seedStrategy: SeedStrategy = value.seedStrategy === 'forceLowest' ? 'forceLowest' : 'default'
    const enableFriendOps = value.enableFriendOps !== false
    const enableSteal = value.enableSteal !== false
    const allowTicketFertilizerPurchase = value.allowTicketFertilizerPurchase === true
    const enableNormalFertilize = value.enableNormalFertilize === true
    const enableOrganicFertilize = value.enableOrganicFertilize === true
    const enableAutoSell = value.enableAutoSell !== false
    const allowBuySeeds = value.allowBuySeeds !== false
    const allowRemove = value.allowRemove !== false
    const idleStrategy: IdleStrategy = value.idleStrategy === 'task' ? 'task' : 'exp'
    return { farmIntervalSec, friendIntervalSec, seedStrategy, enableFriendOps, enableSteal, allowTicketFertilizerPurchase, enableNormalFertilize, enableOrganicFertilize, enableAutoSell, allowBuySeeds, allowRemove, idleStrategy }
  }, [])

  const openPayMallDialog = useCallback((item: PaidMallItem) => {
    setPayMallSelected(item)
    setPayMallCount(1)
    setPayMallMessage("")
    setPayMallDialogOpen(true)
  }, [])

  const handlePayMallBuy = useCallback(async () => {
    if (!payMallSelected) return
    if (!user?.email) {
      setPayMallMessage("请先登录")
      return
    }
    if (isPayMallClaimed) {
      setPayMallMessage("今日已领取")
      return
    }
    if (payMallBuying) return
    setPayMallBuying(true)
    setPayMallMessage("")
    try {
      const res = await fetch('/api/paymall/buy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: user.email,
          itemId: payMallSelected.id,
          count: payMallCount
        })
      })
      const json = await res.json()
      if (json.success) {
        setPayMallMessage("购买成功")
        if (payMallSelected.id === 1001) {
          setFarmStatus(prev => ({ ...prev, freeMallClaimed: true }))
        }
        setTimeout(() => {
          setPayMallDialogOpen(false)
        }, 1200)
        return
      }
      setPayMallMessage(`购买失败: ${json.error || '未知错误'}`)
    } catch {
      setPayMallMessage("网络错误")
    } finally {
      setPayMallBuying(false)
    }
  }, [isPayMallClaimed, payMallBuying, payMallCount, payMallSelected, user?.email])

  useEffect(() => {
    const storedSettings = localStorage.getItem('farm_settings')
    if (!storedSettings) return
    try {
      const parsed = JSON.parse(storedSettings)
      const next = normalizeSettings({ ...defaultSettings, ...parsed })
      setSettings(next)
    } catch {
      setSettings(defaultSettings)
    }
  }, [normalizeSettings])

  const fetchStatus = useCallback(async () => {
    if (!user) return

    try {
      const res = await fetch(`/api/status?email=${user.email}`)
      const data = await res.json()
      
      if (data.status === 'stopped') {
        // Detect disconnect: if we were running but now stopped, prompt rebind
        if (statusRef.current === 'running') {
          setQrStatus('init')
          setShowBindDialog(true)
        }
        setFarmStatus(prev => ({ ...prev, status: 'stopped' }))
      } else {
        setFarmStatus({
            nickname: data.user?.nickname || 'Farmer',
            level: data.user?.level || 1,
            exp: data.user?.exp || 0,
            nextLevelExp: data.user?.nextLevelExp || 100,
            gold: data.user?.gold || 0,
            tickets: data.user?.tickets || 0,
            normalFertilizerHours: data.user?.normalFertilizerHours || 0,
            organicFertilizerHours: data.user?.organicFertilizerHours || 0,
            status: 'running',
            avatarUrl: data.user?.avatarUrl,
            freeMallClaimed: data.user?.freeMallClaimed === true
        })
      }
    } catch (error) {
      console.error("Failed to fetch status", error)
    }
  }, [user])

  const fetchLands = useCallback(async () => {
    if (!user || farmStatus.status !== 'running') return
    
    try {
      const res = await fetch(`/api/lands?email=${user.email}`)
      if (res.ok) {
        const data = await res.json()
        setLands(data.lands || [])
      }
    } catch (error) {
      console.error("Failed to fetch lands", error)
    }
  }, [farmStatus.status, user])

  const handleWarehouseRefresh = useCallback(() => {
    setWarehouseRefreshKey(prev => prev + 1)
    fetchStatus()
    fetchLands()
  }, [fetchLands, fetchStatus])

  const handleLandClick = useCallback((land: LandData) => {
    if (!removeMode) return
    if (land.type !== 'planted') return
    setSelectedLandIds(prev => {
      if (prev.includes(land.id)) {
        return prev.filter(id => id !== land.id)
      }
      return [...prev, land.id]
    })
  }, [removeMode])

  const handleRemoveSelected = useCallback(async () => {
    if (!user) return
    if (isRemoving) return
    if (selectedLandIds.length === 0) return
    setIsRemoving(true)
    try {
      const res = await fetch('/api/lands/remove', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: user.email, landIds: selectedLandIds })
      })
      if (!res.ok) throw new Error('remove failed')
      await fetchLands()
      setSelectedLandIds([])
      setRemoveMode(false)
    } catch (error) {
      console.error("Remove plants failed", error)
    } finally {
      setIsRemoving(false)
    }
  }, [fetchLands, isRemoving, selectedLandIds, user])

  const handleUnlockLand = useCallback(async (land: LandData) => {
    if (!user) return
    if (unlockingLandIds.includes(land.id)) return
    setUnlockingLandIds(prev => prev.includes(land.id) ? prev : [...prev, land.id])
    try {
      const res = await fetch('/api/lands/unlock', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: user.email, landId: land.id })
      })
      if (!res.ok) throw new Error('unlock failed')
      await Promise.all([fetchLands(), fetchStatus()])
    } catch (error) {
      console.error("Unlock land failed", error)
    } finally {
      setUnlockingLandIds(prev => prev.filter(id => id !== land.id))
    }
  }, [fetchLands, fetchStatus, unlockingLandIds, user])

  // QR Code Logic
  const generateQRCode = useCallback(async () => {
    setQrStatus("waiting")
    setQrMsg("正在获取二维码...")
    try {
      const res = await fetch('/api/qr/create', { method: 'POST' })
      const data = await res.json()
      if (data.success) {
        setQrCodeUrl(data.qrcode)
        setQrSig(data.qrsig)
        setQrMsg("请使用手机QQ扫码")
      } else {
        setQrStatus("error")
        setQrMsg("获取二维码失败")
      }
    } catch (error) {
      console.error("Generate QR error", error)
      setQrStatus("error")
      setQrMsg("网络错误")
    }
  }, [])

  const handleBindSuccess = useCallback(async (code: string) => {
    if (!user) return
    setIsStarting(true)
    
    try {
      const normalizedSettings = normalizeSettings(settings)
      // Start bot
      const res = await fetch('/api/bot/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: user.email, code, settings: normalizedSettings })
      })
      
      const data = await res.json()
      if (data.success) {
        // Update local user state
        const newUser = { ...user, hasCode: true, code }
        setUser(newUser)
        localStorage.setItem('farm_user', JSON.stringify(newUser))
        
        setShowBindDialog(false)
        fetchStatus()
      } else {
        setQrMsg(`启动失败: ${data.error}`)
      }
    } catch (error) {
      console.error("Bind error", error)
      setQrMsg("启动服务失败")
    } finally {
      setIsStarting(false)
    }
  }, [fetchStatus, normalizeSettings, settings, user])

  useEffect(() => {
    let timer: ReturnType<typeof setInterval> | undefined
    if (showBindDialog && qrStatus === 'init') {
      generateQRCode()
    }
    
    if (showBindDialog && qrStatus === 'waiting' && qrSig) {
      timer = setInterval(async () => {
        try {
          const res = await fetch('/api/qr/check', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ qrsig: qrSig })
          })
          const data = await res.json()
          
          if (data.success) {
             if (data.status === 'OK') {
               setQrStatus('success')
               setQrMsg('登录成功！正在绑定...')
               clearInterval(timer)
               
               // Start bot with new code
               await handleBindSuccess(data.code)
             } else if (data.status === 'Used') {
               setQrStatus('expired')
               setQrMsg('二维码已失效，请刷新')
               clearInterval(timer)
             }
          }
        } catch (error) {
          console.error("Check QR error", error)
        }
      }, 3000)
    }
    
    return () => {
      if (timer) clearInterval(timer)
    }
  }, [generateQRCode, handleBindSuccess, qrSig, qrStatus, showBindDialog])

  useEffect(() => {
    if (!user) return
    
    // Initial fetch
    fetchStatus()
    
    // Poll status every 5 seconds
    const statusTimer = setInterval(fetchStatus, 5000)
    
    return () => clearInterval(statusTimer)
  }, [fetchStatus, user])

  useEffect(() => {
    if (farmStatus.status === 'running') {
      fetchLands()
      const landTimer = setInterval(fetchLands, 10000)
      return () => clearInterval(landTimer)
    }
  }, [farmStatus.status, fetchLands])

  const handleLogout = () => {
    localStorage.removeItem('farm_user')
    navigate('/login')
  }

  const handleStartBot = async () => {
    if (!user) return
    setIsStarting(true)
    try {
      const normalizedSettings = normalizeSettings(settings)
      const res = await fetch('/api/bot/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: user.email, settings: normalizedSettings })
      })
      const data = await res.json()
      if (data.success) {
        fetchStatus()
      } else {
        console.error(data.error || 'Failed to start bot')
      }
    } catch (e) {
      console.error('Failed to start bot', e)
    } finally {
      setIsStarting(false)
    }
  }

  const handleSaveSettings = async () => {
    if (isSavingSettings) return
    setIsSavingSettings(true)
    const normalizedSettings = normalizeSettings(settings)
    setSettings(normalizedSettings)
    localStorage.setItem('farm_settings', JSON.stringify(normalizedSettings))
    setSettingsHint("已保存，下次启动生效")
    setTimeout(() => setSettingsHint(""), 2500)
    setIsSavingSettings(false)
  }

  const fetchUnlucky = useCallback(async () => {
    if (!user) return
    if (unluckyLoadingRef.current) return
    unluckyLoadingRef.current = true
    try {
      const res = await fetch(`/api/leaderboard/unlucky?email=${encodeURIComponent(user.email)}`)
      if (!res.ok) return
      const data = await res.json()
      setUnluckyList(Array.isArray(data.items) ? data.items : [])
    } catch (error) {
      console.error("Failed to fetch unlucky list", error)
    } finally {
      unluckyLoadingRef.current = false
    }
  }, [user])

  useEffect(() => {
    if (!user) return
    fetchUnlucky()
    const timer = setInterval(fetchUnlucky, 10000)
    return () => clearInterval(timer)
  }, [fetchUnlucky, user])

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-pink-50 to-purple-50 p-4 md:p-8 font-sans overflow-hidden relative">
      {/* Decorative Background Elements */}
      <div className="absolute top-20 left-20 text-blue-200 animate-bounce delay-1000 duration-3000 pointer-events-none">
        <Cloud size={64} fill="currentColor" className="opacity-50" />
      </div>
      <div className="absolute bottom-40 right-20 text-pink-200 animate-pulse delay-700 pointer-events-none">
        <Heart size={48} fill="currentColor" className="opacity-50" />
      </div>
      <div className="absolute top-1/3 right-1/4 text-yellow-100 animate-spin-slow pointer-events-none">
        <Star size={32} fill="currentColor" className="opacity-60" />
      </div>

      <div className="max-w-7xl mx-auto space-y-6 relative z-30">
        <SystemMonitor />
        <div className="space-y-6">
          <header className="flex flex-wrap items-center justify-between gap-4 bg-white/40 backdrop-blur-sm p-4 rounded-3xl border border-white/40 shadow-sm relative z-30">
            <div className="flex items-center gap-2">
              <div className="h-10 w-10 rounded-full flex items-center justify-center overflow-hidden">
                <img src={logo} alt="Logo" className="h-full w-full object-contain" />
              </div>
              <h1 className="text-2xl font-bold text-slate-700 tracking-tight">谢尔达莱群岛</h1>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <div className="relative">
                <button
                  className="flex items-center gap-2 px-3 py-2 rounded-2xl bg-white/70 border border-white/70 text-slate-700 shadow-sm hover:bg-white transition"
                  onClick={() => setNavOpen(prev => !prev)}
                  title="点击切换页面"
                >
                  <span className="text-xs text-slate-500">当前：</span>
                  <span className="text-sm font-semibold">
                    {activePage === 'farm' ? '农场' : activePage === 'shop' ? '仓库商店' : activePage === 'paymall' ? '付费商城' : activePage === 'settings' ? '设置' : activePage === 'task' ? '任务' : '榜单'}
                  </span>
                  <span className={`text-slate-500 transition-transform ${navOpen ? "rotate-180" : ""}`}>▾</span>
                </button>
                {navOpen && (
                  <div className="absolute right-0 mt-2 w-44 bg-white/90 backdrop-blur-md border border-white/70 rounded-2xl shadow-lg p-2 z-40">
                    <button
                      className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-semibold transition ${activePage === 'farm' ? "bg-white text-slate-700 shadow-sm" : "text-slate-600 hover:bg-white/70"}`}
                      onClick={() => {
                        setActivePage('farm')
                        setNavOpen(false)
                      }}
                    >
                      <Sprout className="h-4 w-4" />
                      农场
                    </button>
                    <button
                      className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-semibold transition ${activePage === 'shop' ? "bg-white text-slate-700 shadow-sm" : "text-slate-600 hover:bg-white/70"}`}
                      onClick={() => {
                        setActivePage('shop')
                        setNavOpen(false)
                      }}
                    >
                      <ClipboardList className="h-4 w-4" />
                      仓库商店
                    </button>
                    <button
                      className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-semibold transition ${activePage === 'paymall' ? "bg-white text-slate-700 shadow-sm" : "text-slate-600 hover:bg-white/70"}`}
                      onClick={() => {
                        setActivePage('paymall')
                        setNavOpen(false)
                      }}
                    >
                      <Sparkles className="h-4 w-4" />
                      付费商城
                    </button>
                    <button
                      className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-semibold transition ${activePage === 'settings' ? "bg-white text-slate-700 shadow-sm" : "text-slate-600 hover:bg-white/70"}`}
                      onClick={() => {
                        setActivePage('settings')
                        setNavOpen(false)
                      }}
                    >
                      <Settings className="h-4 w-4" />
                      设置
                    </button>
                    <button
                      className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-semibold transition ${activePage === 'task' ? "bg-white text-slate-700 shadow-sm" : "text-slate-600 hover:bg-white/70"}`}
                      onClick={() => {
                        setActivePage('task')
                        setNavOpen(false)
                      }}
                    >
                      <ClipboardList className="h-4 w-4" />
                      任务
                    </button>
                    <button
                      className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-semibold transition ${activePage === 'leaderboard' ? "bg-white text-slate-700 shadow-sm" : "text-slate-600 hover:bg-white/70"}`}
                      onClick={() => {
                        setActivePage('leaderboard')
                        setNavOpen(false)
                      }}
                    >
                      <Trophy className="h-4 w-4" />
                      榜单
                    </button>
                  </div>
                )}
              </div>
              {farmStatus.status !== 'running' && user?.hasCode && (
                <Button 
                  className="gap-2 rounded-xl bg-gradient-to-r from-green-400 to-emerald-500 hover:from-green-500 hover:to-emerald-600 text-white shadow-lg shadow-green-200/50 border-0 transition-all active:scale-95"
                  onClick={handleStartBot}
                  disabled={isStarting}
                >
                  <Sprout className="h-4 w-4" />
                  {isStarting ? "启动中..." : "开始挂机"}
                </Button>
              )}
              <Button 
                variant="outline" 
                className="gap-2 rounded-xl border-white/60 bg-white/50 hover:bg-white text-slate-600 shadow-sm"
                onClick={() => setShowBindDialog(true)}
              >
                <QrCode className="h-4 w-4" />
                {user?.hasCode ? '重新绑定' : '绑定农场'}
              </Button>
              <Button 
                variant="ghost" 
                className="gap-2 rounded-xl text-slate-500 hover:text-red-500 hover:bg-red-50/50"
                onClick={handleLogout}
              >
                <LogOut className="h-4 w-4" />
                退出
              </Button>
            </div>
          </header>
          <StatusBar 
            nickname={farmStatus.nickname}
            level={farmStatus.level}
            exp={farmStatus.exp}
            nextLevelExp={farmStatus.nextLevelExp}
            gold={farmStatus.gold}
            tickets={farmStatus.tickets}
              normalFertilizerHours={farmStatus.normalFertilizerHours}
              organicFertilizerHours={farmStatus.organicFertilizerHours}
            status={farmStatus.status}
            avatarUrl={farmStatus.avatarUrl}
          />

            {activePage === 'farm' && (
              <div className="space-y-6">
                <div className="flex flex-col lg:block relative">
                  <div className="w-full lg:w-[66%] flex flex-col space-y-4">
                    <div className="flex items-center justify-between px-2">
                      <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                        <span className="w-2 h-6 bg-yellow-300 rounded-full shadow-sm"></span>
                        我的土地
                      </h2>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setRemoveMode(prev => !prev)}
                          className="rounded-full border-white/60 bg-white/70 text-slate-600 hover:bg-white"
                        >
                          <Shovel className="h-4 w-4 mr-1" />
                          {removeMode ? "取消铲除" : "铲除"}
                        </Button>
                        {removeMode && (
                          <Button
                            size="sm"
                            className="rounded-full bg-rose-500 hover:bg-rose-600 text-white shadow-lg shadow-rose-200/50"
                            onClick={handleRemoveSelected}
                            disabled={isRemoving || selectedLandIds.length === 0}
                          >
                            {isRemoving ? "铲除中" : `确认铲除(${selectedLandIds.length})`}
                          </Button>
                        )}
                        <Button variant="ghost" size="sm" onClick={fetchLands} className="text-slate-400 hover:text-slate-600 hover:bg-white/30 rounded-lg">
                          <RefreshCw className="h-4 w-4 mr-1" /> 刷新
                        </Button>
                      </div>
                    </div>
                    {removeMode && (
                      <div className="px-2 text-xs text-rose-500">
                        铲除模式已开启，点击已种植土地进行多选
                      </div>
                    )}
                    <div className="bg-white/60 backdrop-blur-md rounded-[2.5rem] p-6 shadow-sm border border-white/50">
                      <FarmGrid
                        lands={lands}
                        isLoading={farmStatus.status !== 'running'}
                        onLandClick={handleLandClick}
                        onLandUnlock={handleUnlockLand}
                        selectionEnabled={removeMode}
                        selectedLandIds={selectedLandIds}
                        userLevel={farmStatus.level}
                        userGold={farmStatus.gold}
                        unlockingLandIds={unlockingLandIds}
                      />
                    </div>
                  </div>

                  <div className="mt-6 lg:mt-0 w-full lg:w-[32%] lg:absolute lg:right-0 lg:top-0 lg:bottom-0 flex flex-col space-y-4">
                    <div className="flex items-center justify-between px-2">
                      <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                        <span className="w-2 h-6 bg-blue-300 rounded-full shadow-sm"></span>
                        运行日志
                      </h2>
                    </div>
                    <LogPanel className="flex-1 h-full min-h-[260px] max-h-[50vh] lg:min-h-0 lg:max-h-none" email={user?.email} />
                  </div>
                </div>

              </div>
            )}

            {activePage === 'shop' && (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div className="flex items-center justify-between px-2">
                    <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                      <span className="w-2 h-6 bg-amber-300 rounded-full shadow-sm"></span>
                      商店
                    </h2>
                  </div>
                  <div className="bg-white/60 backdrop-blur-md rounded-[2.5rem] p-6 shadow-sm border border-white/50 h-[600px]">
                    <ShopPanel email={user?.email || ''} refreshKey={farmStatus.gold} />
                  </div>
                </div>
                <div className="space-y-4">
                  <div className="flex items-center justify-between px-2">
                    <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                      <span className="w-2 h-6 bg-orange-300 rounded-full shadow-sm"></span>
                      仓库
                    </h2>
                  </div>
                  <WarehousePanel
                    email={user?.email || ''}
                    refreshKey={farmStatus.gold + warehouseRefreshKey}
                    onRefresh={handleWarehouseRefresh}
                  />
                </div>
              </div>
            )}

            {activePage === 'paymall' && (
              <div className="space-y-6">
                <div className="flex items-center justify-between px-2">
                  <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                    <span className="w-2 h-6 bg-rose-300 rounded-full shadow-sm"></span>
                    付费商城
                  </h2>
                  <div className="text-xs text-slate-400">共 {paidMallItems.length} 件</div>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
                  {paidMallItems.map((item) => {
                    const isDailyFree = item.id === 1001
                    const isClaimed = isDailyFree && farmStatus.freeMallClaimed === true
                    return (
                    <div key={item.id} className="bg-white/60 backdrop-blur-md rounded-[2.5rem] p-5 shadow-sm border border-white/50 flex flex-col gap-3">
                      <div className="flex items-start justify-between">
                        <div className="h-14 w-14 rounded-2xl bg-white/80 border border-white/70 flex items-center justify-center">
                          {getPaidMallIcon(item.category)}
                        </div>
                        {isClaimed ? (
                          <span className="text-[11px] font-semibold text-emerald-600 bg-emerald-50 border border-emerald-100 px-2 py-0.5 rounded-full">
                            已领取
                          </span>
                        ) : item.discount && (
                          <span className="text-[11px] font-semibold text-rose-500 bg-rose-50 border border-rose-100 px-2 py-0.5 rounded-full">
                            {item.discount}
                          </span>
                        )}
                      </div>
                      <div className="space-y-1">
                        <div className="text-base font-bold text-slate-700">{item.name}</div>
                        <div className="text-xs text-slate-400">
                          {item.items.map((sub) => (
                            <span key={`${item.id}-${sub.name}`} className="mr-2">
                              {sub.name} x{sub.count}
                            </span>
                          ))}
                        </div>
                      </div>
                      <div className="flex items-center justify-between pt-2">
                        <div className="text-sm font-semibold text-slate-700">
                          {item.price ? `${item.price} ${item.currency || ''}` : "免费"}
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          className="rounded-full border-white/60 bg-white/70 text-slate-600 hover:bg-white"
                          disabled={isClaimed}
                          onClick={() => {
                            if (isClaimed) return
                            openPayMallDialog(item)
                          }}
                        >
                          {isClaimed ? '已领取' : '购买'}
                        </Button>
                      </div>
                    </div>
                  )})}
                </div>
              </div>
            )}

            <Dialog open={payMallDialogOpen} onOpenChange={setPayMallDialogOpen}>
              <DialogContent className="sm:max-w-md rounded-3xl border-0 shadow-2xl">
                <DialogHeader className="text-center pb-4">
                  <DialogTitle className="text-2xl font-bold text-slate-700">购买 {payMallSelected?.name}</DialogTitle>
                  <DialogDescription>
                    {payMallSelected?.price ? `${payMallSelected.price} ${payMallSelected.currency || ''}` : '免费'}
                  </DialogDescription>
                </DialogHeader>
                <div className="py-2 flex flex-col gap-4">
                  <div className="flex items-center justify-center gap-4">
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => setPayMallCount(Math.max(1, payMallCount - 1))}
                    >
                      -
                    </Button>
                    <div className="text-xl font-bold w-12 text-center">{payMallCount}</div>
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => setPayMallCount(payMallCount + 1)}
                    >
                      +
                    </Button>
                  </div>
                  <div className="text-center text-sm text-slate-500">
                    {payMallSelected?.price
                      ? `合计 ${payMallSelected.price * payMallCount} ${payMallSelected.currency || ''}`
                      : '合计 免费'}
                  </div>
                  {payMallMessage && (
                    <div className={`text-center text-sm ${payMallMessage.includes('成功') ? 'text-emerald-500' : 'text-rose-500'}`}>
                      {payMallMessage}
                    </div>
                  )}
                </div>
                <div className="flex items-center justify-center gap-2">
                  <Button
                    onClick={handlePayMallBuy}
                    disabled={payMallBuying || isPayMallClaimed}
                    className="rounded-full px-6"
                  >
                    {isPayMallClaimed ? '已领取' : payMallBuying ? '购买中...' : '确认购买'}
                  </Button>
                </div>
              </DialogContent>
            </Dialog>

          {activePage === 'settings' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between px-2">
                  <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                    <span className="w-2 h-6 bg-emerald-300 rounded-full shadow-sm"></span>
                    设置
                  </h2>
                </div>
                <div className="bg-white/60 backdrop-blur-md rounded-[2.5rem] p-6 shadow-sm border border-white/50 space-y-5">
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-slate-600">自己农场巡查间隔（秒）</label>
                    <Input
                      type="number"
                      min={1}
                      step={1}
                      value={settings.farmIntervalSec}
                      onChange={(e) => setSettings(prev => ({ ...prev, farmIntervalSec: Number(e.target.value) }))}
                      className="h-11 rounded-2xl bg-white/70 border-white/60 focus:border-emerald-200 focus:ring-emerald-100"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-slate-600">好友巡查间隔（秒）</label>
                    <Input
                      type="number"
                      min={1}
                      step={1}
                      value={settings.friendIntervalSec}
                      onChange={(e) => setSettings(prev => ({ ...prev, friendIntervalSec: Number(e.target.value) }))}
                      disabled={!settings.enableFriendOps}
                      className={`h-11 rounded-2xl bg-white/70 border-white/60 focus:border-emerald-200 focus:ring-emerald-100 ${settings.enableFriendOps ? "" : "opacity-60 cursor-not-allowed"}`}
                    />
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">是否帮忙（好友相关）</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.enableFriendOps ? "default" : "outline"}
                        className={settings.enableFriendOps ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableFriendOps: true }))}
                      >
                        开启帮忙
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.enableFriendOps ? "default" : "outline"}
                        className={!settings.enableFriendOps ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableFriendOps: false }))}
                      >
                        关闭帮忙
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">是否偷菜</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.enableSteal ? "default" : "outline"}
                        className={settings.enableSteal ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableSteal: true }))}
                        disabled={!settings.enableFriendOps}
                      >
                        允许偷菜
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.enableSteal ? "default" : "outline"}
                        className={!settings.enableSteal ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableSteal: false }))}
                        disabled={!settings.enableFriendOps}
                      >
                        禁止偷菜
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">肥料使用</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.enableNormalFertilize ? "default" : "outline"}
                        className={settings.enableNormalFertilize ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableNormalFertilize: true }))}
                      >
                        使用普通肥
                      </Button>
                      <Button
                        type="button"
                        variant={settings.enableOrganicFertilize ? "default" : "outline"}
                        className={settings.enableOrganicFertilize ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableOrganicFertilize: true }))}
                      >
                        使用有机肥
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.enableNormalFertilize ? "default" : "outline"}
                        className={!settings.enableNormalFertilize ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableNormalFertilize: false }))}
                      >
                        关闭普通肥
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.enableOrganicFertilize ? "default" : "outline"}
                        className={!settings.enableOrganicFertilize ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableOrganicFertilize: false }))}
                      >
                        关闭有机肥
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">是否使用点券购买肥料</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.allowTicketFertilizerPurchase ? "default" : "outline"}
                        className={settings.allowTicketFertilizerPurchase ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, allowTicketFertilizerPurchase: true }))}
                      >
                        允许点券购买
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.allowTicketFertilizerPurchase ? "default" : "outline"}
                        className={!settings.allowTicketFertilizerPurchase ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, allowTicketFertilizerPurchase: false }))}
                      >
                        禁止点券购买
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">种子策略</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.seedStrategy === 'default' ? "default" : "outline"}
                        className={settings.seedStrategy === 'default' ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, seedStrategy: 'default' }))}
                      >
                        默认策略
                      </Button>
                      <Button
                        type="button"
                        variant={settings.seedStrategy === 'forceLowest' ? "default" : "outline"}
                        className={settings.seedStrategy === 'forceLowest' ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, seedStrategy: 'forceLowest' }))}
                      >
                        强制最低
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">挂机逻辑</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.idleStrategy === 'task' ? "default" : "outline"}
                        className={settings.idleStrategy === 'task' ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, idleStrategy: 'task' }))}
                      >
                        任务优先
                      </Button>
                      <Button
                        type="button"
                        variant={settings.idleStrategy === 'exp' ? "default" : "outline"}
                        className={settings.idleStrategy === 'exp' ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, idleStrategy: 'exp' }))}
                      >
                        经验优先
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">是否出售</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.enableAutoSell ? "default" : "outline"}
                        className={settings.enableAutoSell ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableAutoSell: true }))}
                      >
                        开启出售
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.enableAutoSell ? "default" : "outline"}
                        className={!settings.enableAutoSell ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, enableAutoSell: false }))}
                      >
                        关闭出售
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">仓库无种子时自动购买</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.allowBuySeeds ? "default" : "outline"}
                        className={settings.allowBuySeeds ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, allowBuySeeds: true }))}
                      >
                        开启自动购买
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.allowBuySeeds ? "default" : "outline"}
                        className={!settings.allowBuySeeds ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, allowBuySeeds: false }))}
                      >
                        关闭自动购买
                      </Button>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <div className="text-sm font-medium text-slate-600">允许铲除</div>
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        type="button"
                        variant={settings.allowRemove ? "default" : "outline"}
                        className={settings.allowRemove ? "rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, allowRemove: true }))}
                      >
                        允许铲除
                      </Button>
                      <Button
                        type="button"
                        variant={!settings.allowRemove ? "default" : "outline"}
                        className={!settings.allowRemove ? "rounded-2xl bg-slate-600 hover:bg-slate-700 text-white" : "rounded-2xl bg-white/70 border-white/60 text-slate-600 hover:bg-white"}
                        onClick={() => setSettings(prev => ({ ...prev, allowRemove: false }))}
                      >
                        禁止铲除
                      </Button>
                    </div>
                  </div>
                  <div className="flex items-center justify-between">
                    <div className="text-xs text-slate-400">{settingsHint}</div>
                    <Button
                      type="button"
                      onClick={handleSaveSettings}
                      disabled={isSavingSettings}
                      className="gap-2 rounded-xl bg-emerald-500 hover:bg-emerald-600 text-white shadow-lg shadow-emerald-200/50 border-0"
                    >
                      <Settings className="h-4 w-4" />
                      保存设置
                    </Button>
                  </div>
              </div>
            </div>
          )}

          {activePage === 'task' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between px-2">
                <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                  <span className="w-2 h-6 bg-indigo-300 rounded-full shadow-sm"></span>
                  任务
                </h2>
              </div>
              <TaskPanel email={user?.email || ''} />
            </div>
          )}

          {activePage === 'leaderboard' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between px-2">
                <h2 className="text-lg font-bold text-slate-700 flex items-center gap-2">
                  <span className="w-2 h-6 bg-blue-300 rounded-full shadow-sm"></span>
                  榜单
                </h2>
                <span className="text-xs font-semibold text-blue-500 bg-blue-50 border border-blue-100 px-2 py-1 rounded-full">已偷榜</span>
              </div>
              <div className="bg-white/60 backdrop-blur-md rounded-[2.5rem] p-6 shadow-sm border border-white/50">
                {unluckyList.length === 0 ? (
                  <div className="text-sm text-slate-400 text-center py-6">暂无数据</div>
                ) : (
                  <div className="space-y-3">
                    {unluckyList.slice(0, 10).map((item, index) => (
                      <div key={`${item.name}-${index}`} className="flex items-center justify-between bg-white/70 border border-white/60 rounded-2xl px-4 py-2">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 rounded-full bg-amber-100 text-amber-600 flex items-center justify-center text-xs font-bold">
                            {index + 1}
                          </div>
                          <span className="text-sm font-medium text-slate-700">{item.name}</span>
                        </div>
                        <div className="flex items-center gap-2 text-sm text-slate-500">
                          <Trophy className="h-4 w-4 text-amber-400" />
                          <span>{item.count} 次</span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>

      <Dialog open={announcementOpen} onOpenChange={setAnnouncementOpen}>
        <DialogContent className="w-[92vw] sm:max-w-3xl rounded-3xl border-0 shadow-2xl">
          <DialogHeader className="text-center pb-4">
            <DialogTitle className="text-2xl font-bold text-slate-700">公告</DialogTitle>
            <div
              className="whitespace-pre-line text-slate-500 text-sm"
              dangerouslySetInnerHTML={{ __html: announcementMessage }}
            />
          </DialogHeader>
          <div className="flex items-center justify-center">
            <Button onClick={() => setAnnouncementOpen(false)} className="rounded-full px-6">
              我知道了
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Bind Farm Dialog */}
      <Dialog open={showBindDialog} onOpenChange={setShowBindDialog}>
        <DialogContent className="sm:max-w-md rounded-3xl border-0 shadow-2xl">
          <DialogHeader className="text-center pb-4">
            <DialogTitle className="text-2xl font-bold text-slate-700">绑定 QQ 农场</DialogTitle>
            <DialogDescription>
              请使用手机 QQ 扫描下方二维码进行登录
            </DialogDescription>
          </DialogHeader>
          
          <div className="flex flex-col items-center justify-center p-6 bg-slate-50 rounded-2xl border border-slate-100">
            {qrStatus === 'waiting' && qrCodeUrl ? (
               <div className="relative group">
                 <img src={qrCodeUrl} alt="Scan QR Code" className="w-48 h-48 rounded-xl shadow-sm mix-blend-multiply" />
                 <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-white/80 backdrop-blur-sm rounded-xl">
                   <span className="text-slate-600 font-medium">请扫码</span>
                 </div>
               </div>
            ) : qrStatus === 'success' ? (
              <div className="w-48 h-48 flex flex-col items-center justify-center text-green-500 animate-in zoom-in duration-300">
                 <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4">
                   <QrCode className="w-8 h-8" />
                 </div>
                 <span className="font-bold">扫码成功</span>
              </div>
            ) : (
              <div className="w-48 h-48 flex items-center justify-center">
                 <Button onClick={generateQRCode} variant="outline" className="rounded-full">
                   <RefreshCw className="mr-2 h-4 w-4" /> 获取二维码
                 </Button>
              </div>
            )}

            <p className="mt-4 text-sm font-medium text-slate-500 animate-pulse">
              {qrMsg || "等待操作..."}
            </p>
          </div>
        </DialogContent>
      </Dialog>
      {isStarting && (
        <div className="fixed inset-0 z-[100] bg-black/50 flex items-center justify-center">
            <div className="bg-white p-6 rounded-2xl flex flex-col items-center gap-4 animate-in zoom-in-95">
                <RefreshCw className="h-8 w-8 animate-spin text-blue-500" />
                <span className="font-medium text-slate-600">正在启动农场...</span>
            </div>
        </div>
      )}
    </div>
  )
}
