"use client"; import { useCallback, useState, useEffect, type FormEvent } from "react"; import { createPortal } from "react-dom"; import { useLocale } from "@/i18n/navigation"; import { getPayEnv, redirectToPay, getDeviceFromEnv, } from "@/app/lib/payment"; import type { PayChannel, PayEnv } from "@/app/lib/payment"; import { apiUrl } from "@/app/lib/api-client"; import { googleLogin } from "@/app/lib/pocketbase"; import GoogleLoginButton from "./GoogleLoginButton"; interface JoinModalProps { isOpen: boolean; onClose: () => void; initialEmail?: string; /** 仅登录(已有 VIP 用户直接邮箱登录,不跳转支付) */ vipOnly?: boolean; } const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || ""; export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly = false }: JoinModalProps) { const locale = useLocale(); const [email, setEmail] = useState(initialEmail); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (isOpen) { setEmail(initialEmail); setError(null); } }, [isOpen, initialEmail]); const saveAuth = useCallback(async (token: string, record: Record) => { const { pbSaveAuth } = await import("@/app/lib/pocketbase"); pbSaveAuth(token, record as { id: string; email: string; [key: string]: unknown }); try { await fetch(apiUrl("/api/auth/sync-session"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token, record }), credentials: "include", }); } catch { /* local auth is already saved; backend cookie will be retried by the navbar */ } if (typeof window !== "undefined") { window.dispatchEvent(new CustomEvent("auth:updated")); } }, []); const continueAfterAuth = useCallback((userId: string) => { if (vipOnly) { onClose(); return; } const returnUrl = typeof window !== "undefined" ? `${window.location.origin}/${locale}/join/paid` : "/zh/join/paid"; const env = getPayEnv(); const channel: PayChannel = "wxpay"; redirectToPay({ user_id: userId, return_url: returnUrl, channel, device: getDeviceFromEnv(env), useJoinConfig: true, }); }, [locale, onClose, vipOnly]); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); if (loading) return; const em = email.trim(); if (!em) { setError(locale === "zh" ? "请输入邮箱" : "Please enter your email"); return; } setError(null); setLoading(true); try { const res = await fetch(apiUrl("/api/meetup/ensure-user"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: em }), credentials: "include", }); const data = await res.json(); if (!res.ok || !data?.ok) { throw new Error(data?.error || (locale === "zh" ? "操作失败" : "Operation failed")); } await saveAuth(data.token, data.record); continueAfterAuth(String(data.user_id)); } catch (err) { setError(err instanceof Error ? err.message : "操作失败"); } finally { setLoading(false); } }; const handleGoogleCredential = useCallback(async (credential: string) => { if (loading) return; setError(null); setLoading(true); try { const result = await googleLogin(credential); await saveAuth(result.token, result.record); continueAfterAuth(result.record.id); } catch (err) { setError(err instanceof Error ? err.message : "Google 登录失败"); } finally { setLoading(false); } }, [continueAfterAuth, loading, saveAuth]); const [mounted, setMounted] = useState(false); useEffect(() => setMounted(true), []); if (!isOpen || !mounted) return null; const modalContent = (

{vipOnly ? (locale === "zh" ? "邮箱登录" : "Email login") : (locale === "zh" ? "加入游牧中国" : "Join Nomad China")}

{ setEmail(e.target.value); setError(null); }} placeholder={locale === "zh" ? "输入你的邮箱..." : "Enter your email..."} required className="w-full rounded-lg border border-gray-200 px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:border-[#ff4d4f] focus:outline-none focus:ring-1 focus:ring-[#ff4d4f] dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100" />
{error && (

{error}

)}
{GOOGLE_CLIENT_ID && ( <>
or
)}
); return createPortal(modalContent, document.body); }