import { useRef, useState } from "react"
import { Toaster, toast } from "sonner"
import {
  calcGamePrice,
  createHttpOrder,
  fetchGameCities,
  fetchGameLineCount,
  fetchGameList,
  fetchHttpBalance,
} from "@/api/http"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import Wrap from "@/components/wrap"
import type { GameCity, GameItem, GameOrderData } from "@/lib/models/http"
import { cn } from "@/lib/utils"
import alipay from "../_assets/alipay.svg"
import wechat from "../_assets/wechat.svg"

const TABS = [
  { id: "prepaid", label: "预储值" },
  { id: "unlimited", label: "短效无限量" },
  { id: "daily", label: "短效包天" },
  { id: "volume", label: "短效包量" },
  { id: "game", label: "长效游戏" },
]

const PREPAID_PLANS = [
  { amount: 200, bonus: "5%", total: 210, tag: "送 ￥5%" },
  { amount: 500, bonus: "10%", total: 550, tag: "送 ￥10%" },
  { amount: 1000, bonus: "15%", total: 1150, tag: "送 ￥15%" },
]

const PREPAID_PLANS_LARGE = [
  { amount: 2000, bonus: "20%", total: 2400, tag: "多送20%" },
  { amount: 5000, bonus: "25%", total: 6250, tag: "多送25%" },
  { amount: 10000, bonus: "30%", total: 13000, tag: "多送30%" },
]

const DURATION_OPTIONS = [
  { value: "5", label: "1~5分钟" },
  { value: "25", label: "5~25分钟" },
  { value: "180", label: "25分钟~3小时" },
  { value: "360", label: "3小时~6小时" },
]

const PERIOD_OPTIONS = [
  { value: "1", label: "按天" },
  { value: "7", label: "按周" },
  { value: "30", label: "按月" },
  { value: "90", label: "按季" },
]

const IP_AMOUNT_OPTIONS = [
  { value: 5000, label: "每日最多使用 5,000 个IP" },
  { value: 10000, label: "每日最多使用 10,000 个IP" },
  { value: 30000, label: "每日最多使用 30,000 个IP" },
  { value: 50000, label: "每日最多使用 50,000 个IP" },
  { value: 100000, label: "每日最多使用 100,000 个IP" },
]

const VOLUME_AMOUNTS = [1, 10, 20, 50, 80, 100, 200, 500, 1000]

const BANDWIDTH_OPTIONS = [
  { value: 1, label: "1M" },
  { value: 2, label: "2M" },
  { value: 5, label: "5M" },
  { value: 10, label: "10M" },
]

const GAME_PERIOD_OPTIONS = [
  { value: 1, label: "按天", unit: "天" },
  { value: 7, label: "按周", unit: "周" },
  { value: 30, label: "按月", unit: "月" },
  { value: 90, label: "按季", unit: "季" },
]

const DEFAULT_GAME: GameOrderData = {
  isAbroad: 0,
  isRelayed: 0,
  shareType: 1,
  gameId: 0,
  lineType: 1,
  bandwidth: 1,
  cityCode: 0,
  isp: 0,
  ipAmount: 1,
  periodType: 1,
  periodAmount: 1,
}

export default function HttpPage() {
  const [activeTab, setActiveTab] = useState("prepaid")
  const [customAmount, setCustomAmount] = useState("")
  const [customIpAmount, setCustomIpAmount] = useState("")

  const [duration, setDuration] = useState(DURATION_OPTIONS[0].value)
  const [period, setPeriod] = useState(PERIOD_OPTIONS[0].value)
  const [periodCount, setPeriodCount] = useState(1)
  const [whitelistCount, setWhitelistCount] = useState(1)
  const [ipAmount, setIpAmount] = useState(5000)
  const [volumeAmount, setVolumeAmount] = useState(1)

  // 长效游戏
  const [game, _setGame] = useState<GameOrderData>(DEFAULT_GAME)
  const gameRef = useRef(game)
  const [cities, setCities] = useState<GameCity[]>([])
  const [games, setGames] = useState<GameItem[]>([])
  const [lineCount, _setLineCount] = useState(100)
  const lineCountRef = useRef(100)
  const [gamePrice, setGamePrice] = useState(0)
  const [gamePriceLoading, setGamePriceLoading] = useState(false)
  const gameSeqRef = useRef(0)

  // 支付弹窗状态
  const [payDialogOpen, setPayDialogOpen] = useState(false)
  const [payAmount, setPayAmount] = useState(0)
  const [payMethod, setPayMethod] = useState("2")
  const isRecharge = true
  const [isLoading, setIsLoading] = useState(false)

  // 长效游戏支付（H币）
  const [gamePayOpen, setGamePayOpen] = useState(false)
  const [balance, setBalance] = useState(0)
  const [gamePaying, setGamePaying] = useState(false)
  const alipayBoxRef = useRef<HTMLDivElement>(null)

  const setGame = (next: GameOrderData) => {
    gameRef.current = next
    _setGame(next)
  }

  const setLineCountValue = (next: number) => {
    lineCountRef.current = next
    _setLineCount(next)
  }

  const isCurrent = (seq: number) => seq === gameSeqRef.current

  const loadGamePrice = async (g: GameOrderData, seq: number) => {
    if (lineCountRef.current <= 0) {
      toast.error("可用IP为0！")
      return
    }
    setGamePriceLoading(true)
    const res = await calcGamePrice({
      order_type: 5,
      money: 1,
      pay_type: 1,
      data: g,
    })
    if (!isCurrent(seq)) return
    setGamePriceLoading(false)
    if (!res.success) {
      toast.error(res.message)
      return
    }
    setGamePrice(Number((g.periodAmount * g.ipAmount * res.data).toFixed(2)))
  }

  // 更新游戏参数：拉取线路数量并重置IP数量为1，随后重新计算价格
  const applyGame = async (
    next: GameOrderData,
    opts: { fetchCities?: boolean; fetchGames?: boolean } = {},
  ) => {
    const seq = gameSeqRef.current + 1
    gameSeqRef.current = seq
    setGame(next)

    if (opts.fetchCities) {
      const cityRes = await fetchGameCities(next)
      if (!isCurrent(seq)) return
      if (cityRes.success) {
        setCities(cityRes.data)
      } else {
        toast.error(cityRes.message)
      }
    }

    let finalGame = next
    if (opts.fetchGames) {
      const gameRes = await fetchGameList(next)
      if (!isCurrent(seq)) return
      if (!gameRes.success) {
        toast.error(gameRes.message)
        return
      }
      setGames(gameRes.data)
      finalGame = { ...next, gameId: gameRes.data[0]?.id ?? 0 }
      setGame(finalGame)
    }

    const lineRes = await fetchGameLineCount(finalGame)
    if (!isCurrent(seq)) return
    if (!lineRes.success) {
      toast.error(lineRes.message)
      return
    }
    setLineCountValue(lineRes.data)
    finalGame = { ...finalGame, ipAmount: 1 }
    setGame(finalGame)

    await loadGamePrice(finalGame, seq)
  }

  // 仅重新计算价格（不影响线路数量）
  const refreshGamePrice = (next: GameOrderData) => {
    const seq = gameSeqRef.current + 1
    gameSeqRef.current = seq
    setGame(next)
    void loadGamePrice(next, seq)
  }

  const selectAbroad = (isAbroad: number) => {
    void applyGame(
      {
        ...gameRef.current,
        isAbroad,
        shareType: 1,
        lineType: 1,
        gameId: 0,
      },
      { fetchCities: true },
    )
  }

  const selectShareType = (shareType: number) => {
    if (shareType === 1) {
      void applyGame({
        ...gameRef.current,
        shareType,
        lineType: 1,
        gameId: 0,
      })
    } else {
      void applyGame({ ...gameRef.current, shareType }, { fetchGames: true })
    }
  }

  const changeRelay = (isRelayed: number) => {
    void applyGame({ ...gameRef.current, isRelayed })
  }

  const changeIsp = (isp: number) => {
    void applyGame({ ...gameRef.current, isp })
  }

  const changeCity = (cityCode: number) => {
    void applyGame({ ...gameRef.current, cityCode })
  }

  const changeGameId = (gameId: number) => {
    void applyGame({ ...gameRef.current, gameId })
  }

  const openGamePay = async () => {
    if (lineCountRef.current <= 0) {
      toast.error("可用IP为0！")
      return
    }
    if (gamePrice <= 0) {
      toast.error("价格获取失败，请稍后重试")
      return
    }
    const res = await fetchHttpBalance()
    if (!res.success) {
      toast.error(res.message)
      return
    }
    setBalance(res.data)
    setGamePayOpen(true)
  }

  const payGameOrder = async () => {
    setGamePaying(true)
    const res = await createHttpOrder({
      order_type: 5,
      money: gamePrice,
      pay_type: 1,
      data: gameRef.current,
    })
    if (!res.success) {
      toast.error(res.message)
      setGamePaying(false)
      return
    }
    const result = res.data
    if (result.code === 1) {
      setGamePayOpen(false)
      toast.success(result.msg || "支付成功")
    } else if (result.code === 2) {
      if (result.data && alipayBoxRef.current) {
        alipayBoxRef.current.innerHTML = result.data
        alipayBoxRef.current.querySelector("form")?.submit()
        setGamePayOpen(false)
      } else {
        toast.error(result.msg || "支付宝支付数据异常")
      }
    } else {
      toast.error(result.msg || "支付失败")
    }
    setGamePaying(false)
  }

  const handleTabClick = (id: string) => {
    setActiveTab(id)
    if (id === "game") {
      void applyGame(
        { ...gameRef.current, periodType: 1 },
        {
          fetchCities: true,
        },
      )
    }
  }

  // 计算价格
  const calculatePrice = () => {
    // 根据不同的 tab 计算价格
    let price = 0
    switch (activeTab) {
      case "prepaid":
        price = Number(customAmount) || 1
        break
      case "unlimited":
        price = whitelistCount * periodCount * 0.5
        break
      case "daily":
        price = ipAmount * periodCount * 0.01
        break
      case "volume":
        price = volumeAmount || Number(customAmount) || 0
        break
      default:
        price = 0
    }
    return Number(price.toFixed(2))
  }

  const totalPrice = calculatePrice()

  // 处理支付
  const handlePay = () => {
    setIsLoading(true)
    // 模拟支付请求
    setTimeout(() => {
      setIsLoading(false)
      setPayDialogOpen(false)
      toast.success(`支付成功！支付金额：¥${payAmount.toFixed(2)}`)
    }, 1500)
  }

  // 打开支付弹窗
  const openPayDialog = (amount?: number) => {
    const effectivePrice = Number(amount ?? totalPrice)
    if (effectivePrice <= 0) {
      toast.error("请输入有效的充值金额")
      return
    }
    setPayAmount(effectivePrice)
    setPayDialogOpen(true)
  }

  return (
    <>
      <Toaster position="top-center" richColors />
      <Wrap className="bg-white">
        <section className="py-20">
          <div className="text-center mb-6">
            <h2 className="text-2xl font-bold text-gray-800">
              <span className="block">
                套餐多元，自主选择，城市覆盖广性价比高，服务态度都说好
              </span>
              <span className="block text-xl font-normal text-muted-foreground mt-2">
                预存享超值优惠 海量IP池随心用
              </span>
            </h2>
          </div>

          <div className="max-w-6xl mx-auto px-4">
            <ul className="flex gap-2 justify-center flex-wrap mb-6">
              {TABS.map(tab => (
                <li key={tab.id}>
                  <button
                    onClick={() => handleTabClick(tab.id)}
                    className={cn(
                      "px-6 py-2.5 rounded-md text-sm font-bold transition-all cursor-pointer",
                      activeTab === tab.id
                        ? "bg-linear-to-r from-blue-500 to-cyan-400 text-white shadow-sm"
                        : "bg-gray-100 text-gray-600 hover:bg-gray-200",
                    )}
                  >
                    {tab.label}
                  </button>
                </li>
              ))}
            </ul>

            {activeTab === "prepaid" && (
              <div>
                <h3 className="text-center text-lg font-bold text-gray-700 mb-2">
                  充的越多送的越多
                </h3>
                <p className="text-center mb-8">
                  <a
                    href="https://lanhuip.com"
                    target="_blank"
                    rel="noreferrer"
                    className="text-blue-500 hover:text-blue-600 underline"
                  >
                    点击前往购买新http/socks5产品、IP池更大、网速更快
                  </a>
                </p>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-6 mt-8">
                  <PrepaidCardCustom
                    amount={customAmount}
                    onAmountChange={setCustomAmount}
                    onPay={openPayDialog}
                  />
                  {PREPAID_PLANS.map(plan => (
                    <PrepaidCard
                      key={plan.amount}
                      plan={plan}
                      onPay={openPayDialog}
                    />
                  ))}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  {PREPAID_PLANS_LARGE.map(plan => (
                    <PrepaidCardLarge
                      key={plan.amount}
                      plan={plan}
                      onPay={openPayDialog}
                    />
                  ))}
                </div>
              </div>
            )}

            {activeTab === "unlimited" && (
              <div className="max-w-3xl mx-auto flex flex-col gap-3">
                <p className="text-center text-sm  mb-4">
                  适用于每天需要大量高匿IP的用户使用，支持HTTP(S)、S5协议，IP可通过API获得集成在程序或软件中使用
                </p>
                <p className="text-center">
                  <a
                    href="https://lanhuip.com"
                    target="_blank"
                    rel="noreferrer"
                    className="text-blue-500 hover:text-blue-600 underline"
                  >
                    点击前往购买新http/socks5产品、IP池更大、网速更快
                  </a>
                </p>

                <OptionBox label="有效时长">
                  <div className="flex flex-wrap gap-3">
                    {DURATION_OPTIONS.map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={duration === opt.value}
                        onClick={() => setDuration(opt.value)}
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="套餐周期">
                  <div className="flex flex-wrap gap-3">
                    {PERIOD_OPTIONS.map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={period === opt.value}
                        onClick={() => setPeriod(opt.value)}
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="购买时长">
                  <Stepper
                    value={periodCount}
                    unit="小时"
                    onChange={setPeriodCount}
                  />
                </OptionBox>

                <OptionBox label="白名单数量">
                  <div className="flex items-center gap-4 flex-wrap">
                    <Stepper
                      value={whitelistCount}
                      unit=""
                      onChange={v => setWhitelistCount(v)}
                      min={1}
                      max={1000}
                    />
                    <span className="text-sm text-muted-foreground">
                      您的白名单上限{whitelistCount}个，
                      {whitelistCount === 1 ? (
                        <span className="text-red-500">
                          价格<span className="font-medium">无折扣</span>
                        </span>
                      ) : whitelistCount <= 5 ? (
                        <span className="text-red-500 font-medium">
                          {11 - whitelistCount}折
                        </span>
                      ) : (
                        <span className="text-red-500 font-medium">6折</span>
                      )}
                    </span>
                  </div>
                </OptionBox>

                <PriceBar price={totalPrice} onPay={openPayDialog} />
              </div>
            )}

            {activeTab === "daily" && (
              <div className="max-w-3xl mx-auto flex flex-col gap-3">
                <p className="text-center text-sm">
                  适用于每天需要大量高匿IP的用户使用，支持HTTP(S)、S5协议，IP可通过API获得集成在程序或软件中使用
                </p>
                <p className="text-center">
                  <a
                    href="https://lanhuip.com"
                    target="_blank"
                    rel="noreferrer"
                    className="text-blue-500 hover:text-blue-600 underline"
                  >
                    点击前往购买新http/socks5产品、IP池更大、网速更快
                  </a>
                </p>

                <OptionBox label="选择每日可使用IP数">
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                    {IP_AMOUNT_OPTIONS.map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={ipAmount === opt.value}
                        onClick={() => setIpAmount(opt.value)}
                        className="justify-center"
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                  <div className="mt-4 flex items-center gap-3 flex-wrap">
                    <span className="inline-flex items-center gap-2 px-4 py-2 rounded-full border bg-white text-sm">
                      每日最多使用
                      <Input
                        type="number"
                        value={customIpAmount}
                        onChange={e => setCustomIpAmount(e.target.value)}
                        placeholder="IP数"
                        className="w-28 h-7 inline-block text-center"
                      />
                      个IP
                    </span>
                  </div>
                </OptionBox>

                <OptionBox label="有效时长">
                  <div className="flex flex-wrap gap-3">
                    {DURATION_OPTIONS.map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={duration === opt.value}
                        onClick={() => setDuration(opt.value)}
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="套餐周期">
                  <div className="flex flex-wrap gap-3">
                    {PERIOD_OPTIONS.slice(0, 3).map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={period === opt.value}
                        onClick={() => setPeriod(opt.value)}
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="购买时长">
                  <Stepper
                    value={periodCount}
                    unit="天"
                    onChange={setPeriodCount}
                  />
                </OptionBox>

                <PriceBar price={totalPrice} onPay={openPayDialog} />
              </div>
            )}

            {activeTab === "volume" && (
              <div className="max-w-3xl mx-auto">
                <h3 className="text-center text-lg font-bold text-gray-700">
                  提取免费，使用才扣费。节约成本，按使用次数扣费
                </h3>
                <p className="text-center p-3">
                  <a
                    href="https://lanhuip.com"
                    target="_blank"
                    rel="noreferrer"
                    className="text-blue-500 hover:text-blue-600 underline"
                  >
                    点击前往购买新http/socks5产品、IP池更大、网速更快
                  </a>
                </p>

                <OptionBox label="充值金额">
                  <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
                    {VOLUME_AMOUNTS.map(amount => (
                      <OptionBtn
                        key={amount}
                        active={volumeAmount === amount}
                        onClick={() => setVolumeAmount(amount)}
                        className="justify-center"
                      >
                        {amount}元
                      </OptionBtn>
                    ))}
                  </div>
                  <div className="mt-4 flex items-center gap-3 flex-wrap">
                    <span className="inline-flex items-center gap-2 px-4 py-2 rounded-full border bg-white text-sm">
                      自定义
                      <Input
                        type="number"
                        value={customAmount}
                        onChange={e => setCustomAmount(e.target.value)}
                        placeholder="金额"
                        className="w-28 h-7 inline-block text-center"
                      />
                      元
                    </span>
                  </div>
                </OptionBox>

                <OptionBox label="有效时长">
                  <div className="flex flex-wrap gap-3">
                    {DURATION_OPTIONS.map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={duration === opt.value}
                        onClick={() => setDuration(opt.value)}
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="IP数量">
                  <div className="text-sm text-muted-foreground">
                    可使用{" "}
                    <span className="text-xl font-bold text-blue-500">
                      {Math.floor(
                        (volumeAmount || customAmount
                          ? Number(customAmount || volumeAmount)
                          : 0) * 100,
                      )}
                    </span>{" "}
                    个IP，有效期1年，提取免费，使用才扣费。
                  </div>
                </OptionBox>

                <PriceBar price={totalPrice} onPay={openPayDialog} />
              </div>
            )}

            {activeTab === "game" && (
              <div className="max-w-3xl mx-auto space-y-5">
                <h3 className="text-center text-lg font-bold text-gray-700">
                  高匿 · 高质 · 长效 · 稳定 · HTTP · SOCKS5
                </h3>

                <OptionBox label="类型">
                  <div className="flex flex-wrap gap-3">
                    <OptionBtn
                      active={game.isAbroad === 0}
                      onClick={() => selectAbroad(0)}
                    >
                      国内游戏
                    </OptionBtn>
                    <OptionBtn
                      active={game.isAbroad === 1}
                      onClick={() => selectAbroad(1)}
                    >
                      国际游戏
                    </OptionBtn>
                  </div>
                </OptionBox>

                <OptionBox label="模式">
                  <div className="flex flex-wrap gap-3">
                    <OptionBtn
                      active={game.shareType === 1}
                      onClick={() => selectShareType(1)}
                    >
                      共享线路
                    </OptionBtn>
                    <OptionBtn
                      active={game.shareType === 2}
                      onClick={() => selectShareType(2)}
                    >
                      独享游戏
                    </OptionBtn>
                  </div>
                </OptionBox>

                {game.isAbroad === 1 && (
                  <OptionBox label="中继选择">
                    <div className="flex flex-wrap gap-3">
                      <OptionBtn
                        active={game.isRelayed === 0}
                        onClick={() => changeRelay(0)}
                      >
                        直连
                      </OptionBtn>
                      <OptionBtn
                        active={game.isRelayed === 1}
                        onClick={() => changeRelay(1)}
                      >
                        中继
                      </OptionBtn>
                    </div>
                  </OptionBox>
                )}

                {game.shareType === 2 && (
                  <OptionBox label="线路质量">
                    <div className="flex flex-wrap gap-3">
                      <OptionBtn
                        active={game.lineType === 1}
                        onClick={() =>
                          refreshGamePrice({ ...game, lineType: 1 })
                        }
                      >
                        普通线路
                      </OptionBtn>
                      <OptionBtn
                        active={game.lineType === 2}
                        onClick={() =>
                          refreshGamePrice({ ...game, lineType: 2 })
                        }
                      >
                        优质线路
                      </OptionBtn>
                    </div>
                  </OptionBox>
                )}

                {game.shareType === 2 && games.length > 0 && (
                  <OptionBox label="独享游戏">
                    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
                      {games.map(item => (
                        <OptionBtn
                          key={item.id}
                          active={game.gameId === item.id}
                          onClick={() => changeGameId(item.id)}
                          className="justify-center"
                        >
                          {item.name}
                        </OptionBtn>
                      ))}
                    </div>
                  </OptionBox>
                )}

                {game.isAbroad === 0 && (
                  <OptionBox label="运营商选择">
                    <div className="flex flex-wrap gap-3">
                      <OptionBtn
                        active={game.isp === 0}
                        onClick={() => changeIsp(0)}
                      >
                        普通线路
                      </OptionBtn>
                      <OptionBtn
                        active={game.isp === 2}
                        onClick={() => changeIsp(2)}
                      >
                        电信
                      </OptionBtn>
                      <OptionBtn
                        active={game.isp === 3}
                        onClick={() => changeIsp(3)}
                      >
                        移动
                      </OptionBtn>
                      <OptionBtn
                        active={game.isp === 4}
                        onClick={() => changeIsp(4)}
                      >
                        联通
                      </OptionBtn>
                    </div>
                  </OptionBox>
                )}

                <OptionBox label="地区选择">
                  <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
                    <OptionBtn
                      active={game.cityCode === 0}
                      onClick={() => changeCity(0)}
                      className="justify-center"
                    >
                      随机地区
                    </OptionBtn>
                    {cities.map(city => (
                      <OptionBtn
                        key={city.code}
                        active={game.cityCode === city.code}
                        onClick={() => changeCity(city.code)}
                        className="justify-center"
                      >
                        {city.name}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="IP数量">
                  <div className="flex items-center gap-4 flex-wrap">
                    <Stepper
                      value={game.ipAmount}
                      unit="个"
                      onChange={v => refreshGamePrice({ ...game, ipAmount: v })}
                      min={1}
                      max={lineCount}
                    />
                    <span className="text-sm text-muted-foreground">
                      最大可选数量：{lineCount}
                    </span>
                  </div>
                </OptionBox>

                <OptionBox label="带宽">
                  <div className="flex flex-wrap gap-3">
                    {BANDWIDTH_OPTIONS.map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={game.bandwidth === opt.value}
                        onClick={() =>
                          refreshGamePrice({ ...game, bandwidth: opt.value })
                        }
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="套餐周期">
                  <div className="flex flex-wrap gap-3">
                    {GAME_PERIOD_OPTIONS.map(opt => (
                      <OptionBtn
                        key={opt.value}
                        active={game.periodType === opt.value}
                        onClick={() =>
                          refreshGamePrice({ ...game, periodType: opt.value })
                        }
                      >
                        {opt.label}
                      </OptionBtn>
                    ))}
                  </div>
                </OptionBox>

                <OptionBox label="购买时长">
                  <Stepper
                    value={game.periodAmount}
                    unit={
                      GAME_PERIOD_OPTIONS.find(
                        opt => opt.value === game.periodType,
                      )?.unit ?? "天"
                    }
                    onChange={v =>
                      refreshGamePrice({ ...game, periodAmount: v })
                    }
                    min={1}
                  />
                </OptionBox>

                <PriceBar
                  price={gamePrice}
                  loading={gamePriceLoading}
                  onPay={() => void openGamePay()}
                />
              </div>
            )}
          </div>
        </section>

        {/* 支付弹窗 */}
        <Dialog open={payDialogOpen} onOpenChange={setPayDialogOpen}>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle className="text-center">
                待支付：¥{payAmount.toFixed(2)}元
              </DialogTitle>
            </DialogHeader>

            <div className="py-4">
              {isRecharge ? (
                <>
                  <p className="text-sm text-gray-600 mb-4">选择支付方式：</p>
                  <RadioGroup
                    value={payMethod}
                    onValueChange={setPayMethod}
                    className="flex justify-center gap-8 py-4"
                  >
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="2" id="alipay" />
                      <Label
                        htmlFor="alipay"
                        className="flex items-center gap-2 cursor-pointer"
                      >
                        <img src={alipay} alt="支付宝" className="w-6 h-6" />
                        支付宝支付
                      </Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="3" id="wechat" />
                      <Label
                        htmlFor="wechat"
                        className="flex items-center gap-2 cursor-pointer"
                      >
                        <img src={wechat} alt="微信" className="w-6 h-6" />
                        微信支付
                      </Label>
                    </div>
                  </RadioGroup>
                </>
              ) : (
                <div className="text-center py-6">
                  <p className="text-gray-600">
                    个人剩余H币：{payAmount.toFixed(2)}
                    <a
                      href="/product/http"
                      className="text-blue-500 hover:underline ml-2"
                    >
                      去充值
                    </a>
                  </p>
                  <p className="text-gray-600 mt-2">
                    本次支付H币：{payAmount.toFixed(2)}
                  </p>
                </div>
              )}
            </div>

            <DialogFooter>
              <Button
                onClick={handlePay}
                disabled={isLoading}
                className="w-full bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90 py-3"
              >
                {isLoading ? "支付中..." : "立即支付"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* 长效游戏支付弹窗（H币支付） */}
        <Dialog open={gamePayOpen} onOpenChange={setGamePayOpen}>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle className="text-center">
                待支付：¥{gamePrice.toFixed(2)}元
              </DialogTitle>
            </DialogHeader>

            <div className="py-4">
              <div className="text-center py-6">
                <p className="text-gray-600">
                  个人剩余H币：
                  <span className="text-orange-500 font-medium ml-1">
                    {balance.toFixed(2)}
                  </span>
                  <a
                    href="/product/http"
                    className="text-blue-500 hover:underline ml-2"
                  >
                    去充值
                  </a>
                </p>
                <p className="text-gray-600 mt-2">
                  本次支付H币：{gamePrice.toFixed(2)}
                </p>
              </div>
            </div>

            <DialogFooter>
              <Button
                onClick={() => void payGameOrder()}
                disabled={gamePaying}
                className="w-full bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90 py-3"
              >
                {gamePaying ? "支付中..." : "立即支付"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* 支付宝表单渲染容器 */}
        <div ref={alipayBoxRef} className="hidden" />
      </Wrap>
    </>
  )
}

function PrepaidCardCustom({
  amount,
  onAmountChange,
  onPay,
}: {
  amount: string
  onAmountChange: (v: string) => void
  onPay: (amount: number) => void
}) {
  return (
    <Card className="relative text-center border-0 shadow-md overflow-visible">
      <CardContent className="pt-6 space-y-4">
        <div className="text-3xl font-bold">
          ￥
          <Input
            type="number"
            value={amount || "1"}
            onChange={e => onAmountChange(e.target.value)}
            className="inline-block w-24 h-auto text-2xl font-bold text-center border-0 border-b-2 border-blue-200 rounded-none focus-visible:ring-0 px-0 mx-1"
            placeholder="金额"
            min="1"
          />
        </div>
        <div className="py-3 px-4 bg-blue-50 rounded-lg">
          <span className="text-blue-600 font-bold">
            实到{amount || "1"}H币
          </span>
        </div>
        <ul className="space-y-1 text-sm text-muted-foreground">
          <li>国内长效月卡低至9.9元</li>
          <li>国际长效月卡低至10元</li>
          <li>多充多送更超值</li>
          <li>省时省力更方便</li>
          <li>支持购买任意套餐</li>
        </ul>
        <Button
          onClick={() => onPay(Number(amount) || 1)}
          className="w-full rounded-md bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90"
        >
          自定义充值
        </Button>
      </CardContent>
    </Card>
  )
}
function PrepaidCard({
  plan,
  onPay,
}: {
  plan: { amount: number; bonus: string; total: number; tag: string }
  onPay: (amount: number) => void
}) {
  return (
    <Card className="relative text-center border-0 shadow-md overflow-visible">
      <Badge className="absolute -top-3 right-4 bg-yellow-400 text-white hover:bg-yellow-400 border-0 text-xs px-3 py-0.5 z-10">
        {plan.tag}
      </Badge>
      <CardContent className="pt-8 space-y-4">
        <div className="text-3xl font-bold">￥{plan.amount}</div>
        <div className="py-3 px-4 bg-blue-50 rounded-lg">
          <span className="text-blue-600 font-bold">实到{plan.total}H币</span>
        </div>
        <ul className="space-y-1 text-sm text-muted-foreground">
          <li>国内长效月卡低至9.9元</li>
          <li>国际长效月卡低至10元</li>
          <li>多充多送更超值</li>
          <li>省时省力更方便</li>
          <li>支持购买任意套餐</li>
        </ul>
        <Button
          onClick={() => onPay(plan.amount)}
          className="w-full rounded-md bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90"
        >
          立即充值
        </Button>
      </CardContent>
    </Card>
  )
}

function PrepaidCardLarge({
  plan,
  onPay,
}: {
  plan: { amount: number; bonus: string; total: number; tag: string }
  onPay: (amount: number) => void
}) {
  return (
    <Card className="relative text-center border-0 shadow-md bg-white overflow-visible">
      <Badge className="absolute -top-3 right-4 bg-yellow-400 text-white hover:bg-yellow-400 border-0 text-xs px-3 py-0.5 z-10">
        {plan.tag}
      </Badge>
      <CardContent className="pt-8 pb-6 flex flex-col items-center gap-3">
        <div className="text-3xl font-bold">￥{plan.amount}</div>
        <p className="text-sm text-muted-foreground">实到{plan.total}H币</p>
        <Button
          onClick={() => onPay(plan.amount)}
          className="rounded-md bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90 px-10"
        >
          立即充值
        </Button>
      </CardContent>
    </Card>
  )
}

function OptionBox({
  label,
  children,
}: {
  label: string
  children: React.ReactNode
}) {
  return (
    <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
      <div className="p-5">
        <h5 className="text-sm font-medium text-gray-700 mb-4">{label}</h5>
        {children}
      </div>
    </div>
  )
}

function OptionBtn({
  active = false,
  onClick,
  className,
  children,
}: {
  active?: boolean
  onClick?: () => void
  className?: string
  children: React.ReactNode
}) {
  return (
    <Button
      variant={active ? "default" : "outline"}
      size="sm"
      onClick={onClick}
      className={cn(
        "rounded-md text-sm font-medium transition-all",
        active &&
          "bg-linear-to-r from-blue-500 to-cyan-400 text-white border-transparent shadow-sm hover:opacity-90",
        !active &&
          "border-gray-200 bg-white text-gray-600 hover:border-blue-300 hover:text-blue-500",
        className,
      )}
    >
      {children}
    </Button>
  )
}

function Stepper({
  value,
  unit,
  onChange,
  min = 1,
  max,
}: {
  value: number
  unit: string
  onChange: (v: number) => void
  min?: number
  max?: number
}) {
  return (
    <span className="inline-flex items-center rounded-md border overflow-hidden">
      <button
        onClick={() => onChange(Math.max(min, value - 1))}
        disabled={value <= min}
        className="px-3 py-2 bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90 disabled:opacity-40 transition-opacity cursor-pointer"
      >
        -
      </button>
      <span className="px-5 py-2 text-sm font-medium tabular-nums bg-white min-w-20 text-center">
        {value}
        {unit}
      </span>
      <button
        onClick={() => onChange(max ? Math.min(max, value + 1) : value + 1)}
        disabled={max !== undefined && value >= max}
        className="px-3 py-2 bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90 disabled:opacity-40 transition-opacity cursor-pointer"
      >
        +
      </button>
    </span>
  )
}

function PriceBar({
  price,
  onPay,
  loading = false,
}: {
  price: number
  onPay: () => void
  loading?: boolean
}) {
  return (
    <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
      <div className="p-5 flex items-center justify-between gap-4 flex-wrap">
        <span className="text-sm font-medium text-gray-700">
          价格：
          <span className="text-lg font-bold">
            {loading ? "计算中..." : `¥${price.toFixed(2)}`}
          </span>
        </span>
        <Button
          onClick={onPay}
          size="lg"
          disabled={loading}
          className="rounded-md bg-linear-to-r from-blue-500 to-cyan-400 text-white hover:opacity-90"
        >
          实付 ¥{price.toFixed(2)}
        </Button>
      </div>
    </div>
  )
}
