"use client";
import {
useEffect,
useRef,
useState,
useSyncExternalStore,
type FormEvent,
} from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import {
ArrowUpRight,
Camera,
Check,
Globe2,
Send,
} from "lucide-react";
import SiteShell from "./SiteShell";
import AvatarSelfieModal, {
type SelfieCapturePayload,
} from "./AvatarSelfieModal";
import { PageIntro } from "./SocialUI";
import { useSocialConfig } from "./SocialExperience";
import { socialApi } from "@social/lib/api";
import { isSocialAvatarFaceCheckEnabled } from "@social/lib/avatarFaceCheck";
import { getSocialLive } from "@social/lib/socialLive";
import { useCaptureCapability } from "@social/lib/useCaptureCapability";
import {
getLivenessState,
isFaceOk,
isLivenessVerified,
clearFaceOk,
getLivenessServerSnapshot,
getLivenessSnapshot,
markFaceOk,
markLivenessVerified,
subscribeLivenessState,
} from "@social/lib/livenessGate";
import {
JOIN_AVAILABILITY_OPTIONS,
JOIN_GENDER_OPTIONS,
JOIN_INTENT_OPTIONS,
JOIN_LIVENESS_RETURN,
JOIN_PROFILE_RETURN,
isJoinPaid,
clearJoinProfileDone,
isJoinProfileDone,
markJoinProfileDone,
type JoinProfileDraft,
} from "@social/lib/joinFlow";
import { archiveJoinLead } from "@social/lib/joinArchive";
import { flagOpenJoinModalSoon, openSocialJoinModal } from "@social/lib/joinModal";
import { setRosterPublished } from "@social/lib/discoveryRoster";
import { loadJson, saveJson } from "@social/lib/storage";
import { useLocalState } from "@social/lib/useLocalState";
import { socialPath } from "@social/lib/socialPath";
import { useSocialI18n } from "@social/lib/useSocialI18n";
import { socialTx } from "@social/lib/socialTx";
import type { SocialRosterProfile } from "@social/lib/types";
export function CommunityFeedback() {
const [draft, setDraft] = useLocalState<{
kind: "反馈" | "建议";
text: string;
contact: string;
}>("feedback-draft", { kind: "建议", text: "", contact: "" });
const [delivery, setDelivery] = useLocalState("feedback-delivery", "draft");
const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false);
const lock = useRef(false);
const update = (key: keyof typeof draft, value: string) => {
setDraft((current) => ({ ...current, [key]: value }));
setDelivery("draft");
setStatus("");
};
const reset = () => {
setDraft({ kind: "建议", text: "", contact: "" });
setDelivery("draft");
setStatus("");
};
const submit = async (event: FormEvent) => {
event.preventDefault();
if (!draft.text.trim() || lock.current || delivery === "sent") return;
lock.current = true;
setBusy(true);
try {
const { collectFeedbackClientMeta } = await import(
"@social/lib/feedbackMeta"
);
await socialApi.postFeedback({
...draft,
text: draft.text.trim(),
contact: draft.contact.trim(),
meta: collectFeedbackClientMeta({ ui: "feedback-page" }),
});
setDelivery("sent");
setStatus(socialTx("已提交,感谢反馈。"));
} catch (e) {
// 草稿仍在本机表单里;不要再装成「没网」——多数是服务端挂了
setDelivery("local");
const msg = e instanceof Error ? e.message : "";
setStatus(
msg && msg.length < 120
? socialTx(`提交失败:${msg}。内容还在表单里,修好后点重试。`)
: socialTx("提交失败。内容还在表单里,请稍后点重试。"),
);
} finally {
lock.current = false;
setBusy(false);
}
};
return (
{socialTx("说说你的想法")}
{socialTx("哪里用得不顺手?告诉我们")}
{socialTx("我们会看,但不保证马上回复。提交成功后会清空表单。")}
{delivery === "sent" ? (
{status || socialTx("已提交")}
{socialTx("回社区首页")}
) : (
)}
);
}
const EMPTY_JOIN_PROFILE: JoinProfileDraft = {
name: "",
avatar: "",
gender: "",
phone: "",
wechat: "",
city: "",
title: "",
skills: "",
education: "",
graduation: "",
relationship: "",
intents: [],
availability: "",
status: "online",
linktree: "",
bio: "",
};
type JoinStep = "pay" | "profile" | "liveness" | "done";
/** URL-only — must match SSR; localStorage flags applied after mount. */
function stepFromParam(param: string | null): JoinStep {
if (param === "profile") return "profile";
if (param === "liveness") return "liveness";
if (param === "done") return "done";
return "pay";
}
function resolveJoinStep(param: string | null): JoinStep {
// Unpaid users cannot skip into profile / liveness / done via URL.
if (!isJoinPaid()) {
if (param === "profile" || param === "liveness" || param === "done") {
return "pay";
}
}
// Explicit URL steps win only after paid (re-fill / QA).
if (param === "profile") return "profile";
if (param === "liveness") return isJoinProfileDone() ? "liveness" : "profile";
if (param === "done") {
if (isLivenessVerified() && isJoinProfileDone()) return "done";
if (isJoinProfileDone()) return "liveness";
return "profile";
}
if (isLivenessVerified() && isJoinProfileDone() && isJoinPaid()) return "done";
if (isJoinProfileDone() && isJoinPaid()) return "liveness";
if (isJoinPaid()) return "profile";
return "pay";
}
function JoinStepMark({ active }: { active: 2 | 3 | 4 }) {
const label =
active === 2
? socialTx("资料")
: active === 3
? socialTx("确认本人")
: socialTx("完成");
return (
{String(active).padStart(2, "0")}
/
04
{label}
);
}
function JoinProfileForm({ onDone }: { onDone: () => void }) {
const { locale } = useSocialI18n();
const config = useSocialConfig();
const faceCheckOn = isSocialAvatarFaceCheckEnabled(config);
const liveUx = getSocialLive(config);
const livenessOn = liveUx.livenessGate;
const capture = useCaptureCapability();
const nameRef = useRef(null);
const avatarInputRef = useRef(null);
const captureInputRef = useRef(null);
// Empty seed for SSR — hydrate from localStorage after mount (avoids mismatch).
const [draft, setDraft] = useState(EMPTY_JOIN_PROFILE);
const [busy, setBusy] = useState(false);
const [avatarBusy, setAvatarBusy] = useState(false);
const [avatarErr, setAvatarErr] = useState("");
const [selfieOpen, setSelfieOpen] = useState(false);
const [faceOk, setFaceOk] = useState(false);
const [liveOk, setLiveOk] = useState(false);
const [err, setErr] = useState("");
const lock = useRef(false);
useEffect(() => {
const s = getLivenessState();
setFaceOk(s.faceOk);
setLiveOk(s.livenessStatus === "verified");
}, []);
/** Step 1: always prefer album / clear face photo */
const openPrimaryCapture = () => {
avatarInputRef.current?.click();
};
const avatarHint = (() => {
if (avatarBusy) return socialTx("上传中…");
if (!capture.ready) return socialTx("准备中…");
if (liveOk && (draft.avatar || "").trim()) {
return socialTx("头像和自拍都好了,可以去认识朋友");
}
if (liveOk) return socialTx("请上传一张头像");
// Face-copy only when admin switch is on — otherwise never mention 人脸/正面.
if (faceCheckOn && faceOk) {
return socialTx("照片看起来不错。再拍张自拍,确认是你本人");
}
if (faceCheckOn) {
return socialTx("请先上传一张清晰的正面照片,再拍张自拍确认本人");
}
return socialTx("上传一张头像就可以");
})();
useEffect(() => {
const saved = loadJson>(
"join-profile",
EMPTY_JOIN_PROFILE,
);
const nickLs =
typeof window !== "undefined"
? localStorage.getItem("userName") || ""
: "";
const nick =
(nickLs && !nickLs.includes("@") ? nickLs : "") ||
loadJson("nick", "") ||
saved.name ||
"";
const genderRaw =
typeof saved.gender === "string" ? saved.gender.trim() : "";
setDraft({
...EMPTY_JOIN_PROFILE,
...saved,
intents: Array.isArray(saved.intents) ? saved.intents : [],
availability:
typeof saved.availability === "string" ? saved.availability : "",
status:
typeof saved.status === "string" && saved.status
? saved.status
: "online",
// Only 男/女 — drop legacy nb / empty placeholders
gender: genderRaw === "m" || genderRaw === "f" ? genderRaw : "",
relationship: "",
name: typeof nick === "string" ? nick : "",
avatar:
typeof saved.avatar === "string" && !saved.avatar.startsWith("blob:")
? saved.avatar
: "",
});
nameRef.current?.focus();
}, []);
const update = (
key: K,
value: JoinProfileDraft[K],
) => {
setDraft((current) => ({ ...current, [key]: value }));
setErr("");
};
const onAvatarPick = async (file: File | null) => {
if (!file || avatarBusy) return;
const mime = (file.type || "").toLowerCase();
const okMime =
!mime ||
mime.startsWith("image/") ||
/\.(jpe?g|png|webp|gif)$/i.test(file.name);
if (!okMime) {
setAvatarErr(socialTx("请选择图片文件"));
return;
}
if (file.size > 8 * 1024 * 1024) {
setAvatarErr(socialTx("头像不能超过 8MB"));
return;
}
setAvatarBusy(true);
setAvatarErr("");
setErr("");
// Instant local preview while uploading / face-checking
const localUrl = URL.createObjectURL(file);
setDraft((current) => ({ ...current, avatar: localUrl }));
try {
const uploaded = await socialApi.uploadAvatar(file, "avatar");
const url = (uploaded?.url || "").trim();
if (!url) throw new Error(socialTx("头像上传失败"));
setDraft((current) => {
const next = { ...current, avatar: url };
saveJson("join-profile", next);
const roster = loadJson("roster", {
name: "",
title: "",
city: "",
phone: "",
linktree: "",
skills: "",
bio: "",
avatar: "",
});
saveJson("roster", { ...roster, avatar: url });
return next;
});
// faceOk is server-side only for display gates; never lecture the user unless switch on.
if (uploaded.faceOk) {
markFaceOk();
setFaceOk(true);
setAvatarErr("");
} else {
clearFaceOk();
setFaceOk(false);
if (faceCheckOn) {
setAvatarErr(socialTx("没看清脸,请上传一张清晰的正面照"));
} else {
setAvatarErr("");
}
}
requestAnimationFrame(() => URL.revokeObjectURL(localUrl));
if (
faceCheckOn &&
uploaded.faceOk &&
!isLivenessVerified() &&
capture.mode === "live-modal"
) {
setErr("");
}
} catch (e) {
setDraft((current) => ({ ...current, avatar: "" }));
URL.revokeObjectURL(localUrl);
const raw =
e instanceof Error ? e.message.slice(0, 160).trim() : "";
// Soft-upload never throws face errors; hard gate (switch on) may.
const facey =
/脸|人脸|正面|face|liveness|selfie/i.test(raw);
if (facey && !faceCheckOn) {
setAvatarErr(socialTx("头像上传失败"));
} else {
const msg =
raw && !/^upload failed|^no url|^上传失败 HTTP/i.test(raw)
? socialTx(raw)
: socialTx("头像上传失败");
setAvatarErr(msg || socialTx("头像上传失败"));
}
} finally {
setAvatarBusy(false);
}
};
const onSelfieChallenge = async (payload: SelfieCapturePayload) => {
// Live capture = liveness gate only — never replace album/selfie avatar
setAvatarBusy(true);
setAvatarErr("");
setErr("");
try {
const uploaded = await socialApi.uploadAvatarChallenge(
payload.front,
payload.turn,
payload.video,
payload.videoMime,
);
// Live audit ≠ album avatar / faceOk
markLivenessVerified({ videoUrl: uploaded.videoUrl || "" });
setLiveOk(true);
setAvatarErr("");
if (!(draft.avatar || "").trim()) {
setAvatarErr(
faceCheckOn
? socialTx("自拍已通过。请再选一张正面照片当头像。")
: socialTx("自拍已通过。请再上传一张头像。"),
);
}
} catch (e) {
const raw =
e instanceof Error ? e.message.slice(0, 160).trim() : "";
setAvatarErr(
raw ? socialTx(raw) || raw : socialTx("自拍没通过,请再试一次"),
);
throw e instanceof Error ? e : new Error(socialTx("自拍没通过,请再试一次"));
} finally {
setAvatarBusy(false);
}
};
const toggleIntent = (value: string) => {
setDraft((current) => {
const has = current.intents.includes(value);
return {
...current,
intents: has
? current.intents.filter((item) => item !== value)
: [...current.intents, value],
};
});
};
const submit = async (event: FormEvent) => {
event.preventDefault();
if (lock.current) return;
const name = draft.name.trim();
if (!name) {
setErr(socialTx("请填写怎么称呼你"));
nameRef.current?.focus();
return;
}
if (draft.gender !== "m" && draft.gender !== "f") {
setErr(socialTx("请选择性别"));
return;
}
if (!draft.intents.length) {
setErr(socialTx("请至少选一个「想认识 / 想做什么」"));
return;
}
const avatarUrl =
draft.avatar.startsWith("blob:") ? "" : draft.avatar.trim();
if (!avatarUrl) {
setErr(socialTx("请先上传头像"));
return;
}
if (faceCheckOn && !faceOk && !isFaceOk()) {
setErr(socialTx("请先上传一张清楚的正面头像"));
return;
}
if (draft.linktree.trim() && !/^https?:\/\//i.test(draft.linktree.trim())) {
setErr(socialTx("作品链接请以 https:// 或 http:// 开头。"));
return;
}
lock.current = true;
setBusy(true);
setErr("");
const intentLabels = draft.intents
.map(
(id) =>
JOIN_INTENT_OPTIONS.find((opt) => opt.value === id)?.[
locale === "en" ? "labelEn" : "labelZh"
] || id,
)
.filter(Boolean);
const availLabel =
JOIN_AVAILABILITY_OPTIONS.find((o) => o.value === draft.availability)?.[
locale === "en" ? "labelEn" : "labelZh"
] || draft.availability;
const lookingFor = intentLabels.join(" · ");
const avatar = avatarUrl;
const roster: SocialRosterProfile = {
name,
title: draft.title.trim(),
city: draft.city.trim(),
phone: draft.phone.trim(),
linktree: draft.linktree.trim(),
skills: draft.skills.trim(),
bio: draft.bio.trim(),
avatar,
intents: draft.intents.join(","),
availability: availLabel || draft.availability,
status: draft.status || "online",
lookingFor,
gender: draft.gender,
updatedAt: new Date().toISOString(),
};
try {
saveJson("roster", roster);
saveJson("nick", name);
saveJson("join-profile", draft);
setRosterPublished(true);
await socialApi.saveRoster({
name: roster.name,
title: roster.title,
city: roster.city,
phone: roster.phone,
linktree: roster.linktree,
skills: roster.skills,
bio: roster.bio,
avatar: roster.avatar || "",
gender: draft.gender,
relationship: draft.relationship,
education: draft.education,
graduation: draft.graduation.trim(),
wechat: draft.wechat.trim(),
intents: draft.intents.join(","),
availability: roster.availability || "",
status: roster.status || "online",
lookingFor,
discoverable: "1",
updatedAt: roster.updatedAt || "",
email:
(typeof localStorage !== "undefined"
? localStorage.getItem("userEmail") || ""
: "") || "",
});
} catch {
// Offline / API fail: keep local draft; still mark profile done so UX continues
}
markJoinProfileDone();
void archiveJoinLead("profile_done", {
name: roster.name,
city: roster.city,
avatar: roster.avatar || "",
intents: draft.intents,
});
lock.current = false;
setBusy(false);
onDone();
};
const summaryName = draft.name.trim() || socialTx("你的名字");
const summaryTitle = draft.title.trim() || socialTx("职业待写");
const summaryBio =
draft.bio.trim() || socialTx("自我介绍会出现在这里");
const summaryInitial = (draft.name.trim()[0] || "N").toUpperCase();
const summaryGender =
JOIN_GENDER_OPTIONS.find((opt) => opt.value === draft.gender)?.[
locale === "en" ? "labelEn" : "labelZh"
] || "";
const summaryIntents = draft.intents
.map(
(id) =>
JOIN_INTENT_OPTIONS.find((opt) => opt.value === id)?.[
locale === "en" ? "labelEn" : "labelZh"
] || id,
)
.slice(0, 6);
const filled = [
draft.name,
draft.avatar && !draft.avatar.startsWith("blob:") ? draft.avatar : "",
draft.title,
draft.bio,
draft.intents.length ? "1" : "",
].filter((v) => v.trim()).length;
return (
{capture.mode === "live-modal" ? (
setSelfieOpen(false)}
onCaptured={onSelfieChallenge}
/>
) : null}
);
}
function JoinLivenessForm({ onDone }: { onDone: () => void }) {
const capture = useCaptureCapability();
const [selfieOpen, setSelfieOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
const liveSnap = useSyncExternalStore(
subscribeLivenessState,
getLivenessSnapshot,
getLivenessServerSnapshot,
);
const liveOk =
(JSON.parse(liveSnap) as { livenessStatus?: string }).livenessStatus ===
"verified";
const onSelfieChallenge = async (payload: SelfieCapturePayload) => {
setBusy(true);
setErr("");
try {
const uploaded = await socialApi.uploadAvatarChallenge(
payload.front,
payload.turn,
payload.video,
payload.videoMime,
);
// Do not markFaceOk — album avatar is separate from live audit frames
markLivenessVerified({ videoUrl: uploaded.videoUrl || "" });
void archiveJoinLead("liveness_verified", {
videoUrl: uploaded.videoUrl || "",
frontUrl: uploaded.frontUrl || "",
turnUrl: uploaded.turnUrl || "",
avatarUrl: uploaded.avatarUrl || uploaded.url || "",
storage: uploaded.storage || "",
auditId: uploaded.auditId || "",
});
onDone();
} catch (e) {
const raw =
e instanceof Error ? e.message.slice(0, 160).trim() : "";
setErr(raw ? socialTx(raw) || raw : socialTx("自拍没通过,请再试一次"));
void archiveJoinLead("liveness_failed", { error: raw });
throw e instanceof Error ? e : new Error(socialTx("自拍没通过,请再试一次"));
} finally {
setBusy(false);
}
};
return (
{liveOk ? (
{socialTx("自拍已通过")}
) : (
{socialTx(
"请拍张自拍。拍完就能畅聊、开视频、一起做事。",
)}
)}
{err ? (
{err}
) : null}
{liveOk ? (
) : (
)}
{capture.mode === "live-modal" ? (
setSelfieOpen(false)}
onCaptured={onSelfieChallenge}
/>
) : null}
);
}
export function CommunityJoin() {
const searchParams = useSearchParams();
const router = useRouter();
const stepParam = searchParams.get("step");
const [step, setStep] = useState(() => stepFromParam(stepParam));
useEffect(() => {
const next = resolveJoinStep(stepParam);
// Bare /join or pay step: no dedicated page — bounce home + open modal.
if (next === "pay") {
flagOpenJoinModalSoon();
router.replace(socialPath("/"));
return;
}
setStep(next);
if (next === "profile") {
void archiveJoinLead("profile_started");
}
// Never invent "paid" here — only /paid (or localhost skip) may markJoinPaid.
if (next === "profile") {
if (stepParam === "profile" && isJoinPaid()) {
// Explicit re-fill — clear done so form is writable
clearJoinProfileDone();
}
if (stepParam !== "profile") {
router.replace(JOIN_PROFILE_RETURN);
}
}
if (next === "liveness" && stepParam !== "liveness") {
router.replace(JOIN_LIVENESS_RETURN);
}
}, [stepParam, router]);
const goLiveness = () => {
setStep("liveness");
router.replace(JOIN_LIVENESS_RETURN);
};
const goDone = () => {
setStep("done");
// 只有真人核验通过才算「加入完成」;跳过自拍停在 liveness_skipped
if (isLivenessVerified()) {
void archiveJoinLead("join_done", { liveness: "verified" });
}
router.replace(`${socialPath("/join")}?step=done`);
};
const focusMode =
step === "profile" || step === "liveness" || step === "done";
const liveSnap = useSyncExternalStore(
subscribeLivenessState,
getLivenessSnapshot,
getLivenessServerSnapshot,
);
const liveOk =
(JSON.parse(liveSnap) as { livenessStatus?: string }).livenessStatus ===
"verified";
// Pay landing removed — redirect handles it; avoid flash of page UI.
if (step === "pay") {
return (
{socialTx("正在打开加入…")}
);
}
return (
{step === "profile" ? (
) : null}
{step === "liveness" ? (
) : null}
{step === "done" ? (
{liveOk ? (
{socialTx("进群聊")}
) : (
{socialTx("去拍自拍")}
)}
{socialTx("完善介绍")}
) : null}
);
}
export function CommunityMembership() {
const config = useSocialConfig();
const rawMemFen = Number(config.copy.vipPriceFen);
const memFen =
Number.isFinite(rawMemFen) && rawMemFen >= 0 ? Math.round(rawMemFen) : 0;
const price = (memFen / 100).toLocaleString("zh-CN", {
maximumFractionDigits: 2,
});
const benefits = [
"更好地展示自己的介绍",
"更方便认识想见的人",
"视频见面与同城活动更新提醒",
"找搭子做事时优先沟通",
];
return (
{socialTx("会员通行证")}
{socialTx("游民会员")}
{socialTx("开通后能更方便参与社区。具体权益以支付页说明为准。")}
{benefits.map((item) => (
-
{item}
))}
{config.flags.payEnabled ? (
{config.copy.vipCta || "开通会员"}
) : (
{socialTx("暂时还不能购买")}
)}
{[
{ title: "我的介绍", href: socialPath("/roster") },
{ title: "认识一下", href: socialPath("/date") },
{ title: "城市 / 咖啡馆", href: socialPath("/places") },
{ title: "大家聊天", href: socialPath("/chat") },
].map((item) => (
{item.title}
{socialTx("打开")}
))}
);
}