"use client";

import { Link } from "@/i18n/navigation";
import { CTA_CONFIG } from "@/config/course";
import { useAuthAndVip } from "@/app/lib/useAuthAndVip";
import { getStoredToken, getStoredUser } from "@/app/lib/pocketbase";
import AuthModal from "@/app/components/AuthModal";
import {
  getPayEnv,
  redirectToPay,
  getDeviceFromEnv,
} from "@/app/lib/payment";
import { useState } from "react";

export function CTASection() {
  const { user, vip, refetch } = useAuthAndVip();
  const paid = !!user && vip;
  const [authOpen, setAuthOpen] = useState(false);
  const [payRedirecting, setPayRedirecting] = useState(false);

  const startPay = (userId: string) => {
    const env = getPayEnv();
    const channel = "wxpay";
    const device = getDeviceFromEnv(env);
    const returnUrl = `${window.location.origin}/`;

    redirectToPay({
      user_id: userId,
      return_url: returnUrl,
      channel,
      device,
      type: "video",
      useJoinConfig: true,
    });
  };

  const handleEnroll = async () => {
    if (payRedirecting) return;
    setPayRedirecting(true);

    try {
      // 先验证登录态
      let meRes = await fetch("/api/auth/me", { credentials: "include" });
      let meData = await meRes.json().catch(() => ({}));
      if (meData?.user?.id) {
        // 已登录：先校验 VIP，已是 VIP 则无需支付
        const vipRes = await fetch(`/api/vip/check?email=${encodeURIComponent(meData.user.email)}`, { credentials: "include" });
        const vipData = await vipRes.json().catch(() => ({}));
        if (vipData?.vip) {
          await refetch();
          return;
        }
        startPay(meData.user.id);
        return;
      }

      const storedUser = getStoredUser();
      const storedToken = getStoredToken();
      if (storedUser?.id && storedToken) {
        await fetch("/api/auth/sync-session", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token: storedToken, record: storedUser }),
          credentials: "include",
        }).catch(() => null);
        meRes = await fetch("/api/auth/me", { credentials: "include" });
        meData = await meRes.json().catch(() => ({}));
        if (meData?.user?.id) {
          const vipRes = await fetch(`/api/vip/check?email=${encodeURIComponent(meData.user.email)}`, { credentials: "include" });
          const vipData = await vipRes.json().catch(() => ({}));
          if (vipData?.vip) {
            await refetch();
            return;
          }
          startPay(meData.user.id);
          return;
        }
      }

      setAuthOpen(true);
    } finally {
      setPayRedirecting(false);
    }
  };

  return (
    <section className="border-t border-[var(--border)] py-16 sm:py-20 md:py-24">
      <div className="mx-auto max-w-3xl px-4 text-center sm:px-6">
        <h2 className="mb-4 text-xl font-bold sm:text-2xl md:text-3xl">{CTA_CONFIG.title}</h2>
        <p className="mb-6 text-[var(--muted-foreground)] sm:mb-8">{CTA_CONFIG.subtitle}</p>
        <div className="mb-8 flex flex-wrap justify-center gap-4 text-sm text-[var(--muted-foreground)] sm:mb-10 sm:gap-6">
          {CTA_CONFIG.badges.map((b, i) => (
            <span
              key={b}
              className="animate-float-badge rounded-full border border-[var(--border)] bg-[var(--card)] px-4 py-2"
              style={{ animationDelay: `${i * 0.2}s` }}
            >
              {b}
            </span>
          ))}
        </div>
        {paid ? (
          <Link
            href="/course/0/0"
            className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition-all duration-300 hover:scale-105 hover:opacity-95 hover:shadow-xl hover:shadow-[var(--accent)]/30 sm:px-10"
          >
            开始学习 →
          </Link>
        ) : (
          <button
            type="button"
            onClick={handleEnroll}
            disabled={payRedirecting}
            className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition hover:opacity-95 disabled:opacity-70 sm:px-10"
          >
            {payRedirecting ? "跳转支付中..." : "立即报名 →"}
          </button>
        )}
      </div>
      <AuthModal
        isOpen={authOpen}
        onClose={() => setAuthOpen(false)}
        onSuccess={() => {
          setAuthOpen(false);
          void refetch();
        }}
      />
    </section>
  );
}
