Files
2026-06-08 03:06:12 -05:00

494 lines
17 KiB
TypeScript

"use client";
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocale, useTranslation } from "@/i18n/navigation";
import { useSearchParams } from "next/navigation";
import Footer from "@/app/components/Footer";
import { cities } from "@/app/data/cities";
import { fetchAuthMe } from "@/app/lib/api-client";
import IntentTabs from "./components/IntentTabs";
import CityFilter from "./components/CityFilter";
import LikesPanel from "./components/LikesPanel";
import SwipeStack from "./components/SwipeStack";
import MatchModal from "./components/MatchModal";
import AdvancedFilters from "./components/AdvancedFilters";
import SwipeQuota from "./components/SwipeQuota";
import { BADGE_KEYS } from "./constants";
import type { DatingProfile, MatchIntent } from "./types";
import type { MatchQuota } from "./utils";
import {
fetchCandidates,
fetchLikes,
fetchMutualMatches,
fetchQuota,
filterFallbackProfiles,
formatTimeAgo,
saveSwipe,
undoSwipe,
} from "./utils";
function DatingSkeleton() {
return (
<div className="min-h-screen bg-[#fafafa] dark:bg-gray-950">
<div className="mx-auto max-w-md animate-pulse px-4 py-16">
<div className="h-[520px] rounded-2xl bg-gray-200 dark:bg-gray-800" />
</div>
</div>
);
}
function DatingPageInner() {
const { t } = useTranslation("match");
const locale = useLocale();
const searchParams = useSearchParams();
const initialIntent = (searchParams.get("intent") as MatchIntent) || "friends";
const initialCity = searchParams.get("city") || "all";
const [activeTab, setActiveTab] = useState<MatchIntent>(
["friends", "dating", "partner", "roommate", "cofounder", "explore"].includes(initialIntent)
? initialIntent
: "friends"
);
const [cityFilter, setCityFilter] = useState(initialCity);
const [profiles, setProfiles] = useState<DatingProfile[]>([]);
const [likes, setLikes] = useState<DatingProfile[]>([]);
const [mutual, setMutual] = useState<DatingProfile[]>([]);
const [currentIndex, setCurrentIndex] = useState(0);
const [loading, setLoading] = useState(true);
const [usingFallback, setUsingFallback] = useState(false);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isVip, setIsVip] = useState(false);
const [quota, setQuota] = useState<MatchQuota>({ vip: false, limit: 25, used: 0, remaining: 25 });
const [advancedFilters, setAdvancedFilters] = useState({ gender: "all", single: "all" });
const [showLoginPrompt, setShowLoginPrompt] = useState(false);
const [showQuotaPrompt, setShowQuotaPrompt] = useState(false);
const [canUndo, setCanUndo] = useState(false);
const [matchCelebration, setMatchCelebration] = useState<{
profile: DatingProfile;
conversationId?: string;
} | null>(null);
const [mobilePanelOpen, setMobilePanelOpen] = useState(false);
const [dragX, setDragX] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [isAnimatingOut, setIsAnimatingOut] = useState<"left" | "right" | null>(null);
const startXRef = useRef(0);
const swipeLockRef = useRef(false);
const cityOptions = useMemo(
() =>
cities.map((city) => ({
slug: city.slug || city.name,
name: city.name,
nameEn: city.nameEn,
})),
[]
);
const refreshSidePanels = useCallback(async () => {
if (!isLoggedIn) {
setLikes([]);
setMutual([]);
return;
}
try {
const [likesData, mutualData] = await Promise.all([fetchLikes(), fetchMutualMatches()]);
setLikes(likesData);
setMutual(mutualData);
} catch {
setLikes([]);
setMutual([]);
}
}, [isLoggedIn]);
const refreshQuota = useCallback(async () => {
if (!isLoggedIn) return;
try {
const data = await fetchQuota();
setQuota(data);
setIsVip(data.vip);
} catch {
// ignore
}
}, [isLoggedIn]);
const loadCandidates = useCallback(
async (intent: MatchIntent, city: string, advanced = advancedFilters) => {
setLoading(true);
setCurrentIndex(0);
setCanUndo(false);
try {
const items = await fetchCandidates(intent, city, advanced);
if (items.length) {
setProfiles(items);
setUsingFallback(false);
} else {
const fallback = filterFallbackProfiles(intent, city, advanced);
setProfiles(fallback);
setUsingFallback(true);
}
} catch {
const fallback = filterFallbackProfiles(intent, city, advanced);
setProfiles(fallback);
setUsingFallback(true);
} finally {
setLoading(false);
}
},
[advancedFilters]
);
useEffect(() => {
fetchAuthMe().then((data) => setIsLoggedIn(Boolean(data?.user?.id)));
}, []);
useEffect(() => {
if (isLoggedIn) refreshQuota();
}, [isLoggedIn, refreshQuota]);
useEffect(() => {
loadCandidates(activeTab, cityFilter, advancedFilters);
}, [activeTab, cityFilter, advancedFilters, loadCandidates]);
useEffect(() => {
refreshSidePanels();
}, [refreshSidePanels]);
useEffect(() => {
const params = new URLSearchParams();
params.set("intent", activeTab);
if (cityFilter && cityFilter !== "all") params.set("city", cityFilter);
const next = `/dating?${params.toString()}`;
window.history.replaceState(null, "", next);
}, [activeTab, cityFilter]);
const currentProfile = profiles[currentIndex];
const nextProfile = profiles[currentIndex + 1];
const hasMoreProfiles = currentIndex < profiles.length - 1;
const badgeText = t(BADGE_KEYS[activeTab]);
const formatTime = (value?: string) => formatTimeAgo(value, locale);
const advanceProfile = () => {
window.setTimeout(() => {
setCurrentIndex((index) => (hasMoreProfiles ? index + 1 : index));
setDragX(0);
setIsAnimatingOut(null);
swipeLockRef.current = false;
}, 180);
};
const performSwipe = async (action: "like" | "dislike") => {
if (!currentProfile || swipeLockRef.current) return;
if (!isLoggedIn) {
setShowLoginPrompt(true);
setDragX(0);
return;
}
if (!quota.vip && quota.remaining <= 0) {
setShowQuotaPrompt(true);
setDragX(0);
return;
}
swipeLockRef.current = true;
setIsAnimatingOut(action === "like" ? "right" : "left");
setDragX(action === "like" ? 260 : -260);
try {
if (!usingFallback) {
const result = await saveSwipe(currentProfile.id, action, activeTab);
setCanUndo(true);
if (result.matched) {
setMatchCelebration({
profile: currentProfile,
conversationId: result.match?.conversationId,
});
refreshSidePanels();
} else if (action === "like") {
refreshSidePanels();
}
refreshQuota();
} else {
setCanUndo(true);
}
} catch (err) {
const message = err instanceof Error ? err.message : "";
if (message.includes("滑动次数") || message.includes("升级会员")) {
setShowQuotaPrompt(true);
} else {
setShowLoginPrompt(true);
}
swipeLockRef.current = false;
setIsAnimatingOut(null);
setDragX(0);
return;
} finally {
advanceProfile();
}
};
const handleUndo = async () => {
if (!canUndo || currentIndex <= 0) return;
try {
if (!usingFallback) await undoSwipe();
setCurrentIndex((index) => Math.max(0, index - 1));
setCanUndo(false);
refreshQuota();
} catch {
// ignore
}
};
const handleLike = () => performSwipe("like");
const handleDislike = () => performSwipe("dislike");
const beginDrag = (clientX: number) => {
startXRef.current = clientX;
setIsDragging(true);
};
const moveDrag = (clientX: number) => {
if (!isDragging) return;
setDragX(Math.max(-180, Math.min(180, clientX - startXRef.current)));
};
const endDrag = () => {
if (!isDragging) return;
setIsDragging(false);
if (dragX > 90) {
handleLike();
return;
}
if (dragX < -90) {
handleDislike();
return;
}
setDragX(0);
};
const jumpToProfile = (profile: DatingProfile) => {
const index = profiles.findIndex((item) => item.id === profile.id);
if (index >= 0) setCurrentIndex(index);
setMobilePanelOpen(false);
};
return (
<div className="min-h-screen bg-[#fafafa] dark:bg-gray-950">
<div className="border-b border-gray-100 bg-white/80 backdrop-blur dark:border-gray-800 dark:bg-gray-950/80">
<div className="mx-auto flex max-w-7xl items-center justify-between px-4 py-4">
<div>
<h1 className="text-lg font-bold text-gray-900 dark:text-gray-100">{t("heroTitle")}</h1>
<p className="text-xs text-gray-500 dark:text-gray-400">{t("heroSubtitle")}</p>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setMobilePanelOpen(true)}
className="rounded-full border border-gray-200 px-3 py-1.5 text-xs font-semibold text-gray-700 md:hidden dark:border-gray-700 dark:text-gray-200"
>
{t("mobilePanel")} {likes.length + mutual.length > 0 ? `(${likes.length + mutual.length})` : ""}
</button>
<Link
href="/join"
className="rounded-full bg-[#ff4d4f] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-red-600"
>
{t("editProfile")}
</Link>
</div>
</div>
</div>
<IntentTabs activeTab={activeTab} onChange={setActiveTab} t={t} />
<CityFilter value={cityFilter} onChange={setCityFilter} cities={cityOptions} locale={locale} t={t} />
<AdvancedFilters
value={advancedFilters}
onChange={setAdvancedFilters}
isVip={isVip}
t={t}
/>
{isLoggedIn ? <SwipeQuota vip={quota.vip} used={quota.used} limit={quota.limit} remaining={quota.remaining} t={t} /> : null}
{!isLoggedIn ? (
<div className="mx-auto mb-4 max-w-md px-4">
<div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-100">
{t("loginHint")}{" "}
<Link href="/join" className="font-semibold underline">
{t("loginAction")}
</Link>
</div>
</div>
) : null}
{usingFallback ? (
<p className="mx-auto mb-3 max-w-md px-4 text-center text-xs text-gray-400">{t("fallbackHint")}</p>
) : null}
<div className="mx-auto flex max-w-7xl flex-col gap-6 px-4 pb-12 md:flex-row">
<aside className="hidden w-72 flex-shrink-0 md:block">
<div className="sticky top-24">
<LikesPanel
likes={likes}
mutual={mutual}
formatTime={formatTime}
t={t}
onSelectProfile={jumpToProfile}
/>
</div>
</aside>
<main className="flex min-w-0 flex-1 flex-col items-center">
<div className="w-full max-w-md">
{loading ? (
<div className="h-[520px] animate-pulse rounded-2xl bg-gray-200 dark:bg-gray-800" />
) : currentProfile ? (
<>
<SwipeStack
current={currentProfile}
next={nextProfile}
badgeText={badgeText}
dragX={dragX}
isDragging={isDragging}
isAnimatingOut={isAnimatingOut}
onLike={handleLike}
onDislike={handleDislike}
onBeginDrag={beginDrag}
onMoveDrag={moveDrag}
onEndDrag={endDrag}
t={t}
/>
<div className="mt-4 flex items-center justify-center gap-3">
<button
type="button"
onClick={handleUndo}
disabled={!canUndo || currentIndex <= 0}
className="rounded-full border border-gray-200 px-4 py-2 text-xs font-semibold text-gray-600 transition enabled:hover:bg-gray-50 disabled:opacity-40 dark:border-gray-700 dark:text-gray-300"
>
↩ {t("undo")}
</button>
<p className="text-sm text-gray-500 dark:text-gray-400">
{currentIndex + 1} / {profiles.length}
</p>
</div>
<p className="mt-1 text-center text-xs text-gray-400 dark:text-gray-500">{t("keyboardHint")}</p>
</>
) : (
<div className="rounded-2xl border border-dashed border-gray-200 bg-white p-10 text-center dark:border-gray-700 dark:bg-gray-900">
<div className="text-4xl">🌏</div>
<h3 className="mt-4 text-lg font-semibold text-gray-900 dark:text-gray-100">{t("emptyTitle")}</h3>
<p className="mt-2 text-sm text-gray-500 dark:text-gray-400">{t("emptySubtitle")}</p>
<div className="mt-6 flex flex-wrap justify-center gap-2">
<button
type="button"
onClick={() => {
setCityFilter("all");
setActiveTab("friends");
}}
className="rounded-full border border-gray-200 px-4 py-2 text-sm font-medium dark:border-gray-700"
>
{t("resetFilters")}
</button>
<Link
href="/join"
className="rounded-full bg-[#ff4d4f] px-4 py-2 text-sm font-semibold text-white"
>
{t("editProfile")}
</Link>
</div>
</div>
)}
</div>
</main>
<div className="hidden w-72 flex-shrink-0 lg:block" />
</div>
{mobilePanelOpen ? (
<div className="fixed inset-0 z-40 md:hidden">
<button
type="button"
aria-label={t("closePanel")}
className="absolute inset-0 bg-black/40"
onClick={() => setMobilePanelOpen(false)}
/>
<div className="absolute bottom-0 max-h-[80vh] w-full overflow-y-auto rounded-t-3xl bg-[#fafafa] p-4 dark:bg-gray-950">
<div className="mb-4 flex items-center justify-between">
<h2 className="font-semibold text-gray-900 dark:text-gray-100">{t("mobilePanel")}</h2>
<button type="button" onClick={() => setMobilePanelOpen(false)} className="text-sm text-gray-500">
{t("closePanel")}
</button>
</div>
<LikesPanel
likes={likes}
mutual={mutual}
formatTime={formatTime}
t={t}
onSelectProfile={jumpToProfile}
/>
</div>
</div>
) : null}
{showQuotaPrompt ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div className="w-full max-w-sm rounded-2xl bg-white p-6 dark:bg-gray-900">
<h3 className="text-lg font-bold text-gray-900 dark:text-gray-100">{t("quotaExceededTitle")}</h3>
<p className="mt-2 text-sm text-gray-500 dark:text-gray-400">{t("quotaExceededBody")}</p>
<div className="mt-5 flex gap-3">
<Link
href="/pricing"
className="flex-1 rounded-full bg-[#ff4d4f] px-4 py-2 text-center text-sm font-semibold text-white"
>
{t("upgradeVip")}
</Link>
<button
type="button"
onClick={() => setShowQuotaPrompt(false)}
className="flex-1 rounded-full border border-gray-200 px-4 py-2 text-sm font-semibold dark:border-gray-700"
>
{t("closePanel")}
</button>
</div>
</div>
</div>
) : null}
{showLoginPrompt ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div className="w-full max-w-sm rounded-2xl bg-white p-6 dark:bg-gray-900">
<h3 className="text-lg font-bold text-gray-900 dark:text-gray-100">{t("loginRequiredTitle")}</h3>
<p className="mt-2 text-sm text-gray-500 dark:text-gray-400">{t("loginRequiredBody")}</p>
<div className="mt-5 flex gap-3">
<Link
href="/join"
className="flex-1 rounded-full bg-[#ff4d4f] px-4 py-2 text-center text-sm font-semibold text-white"
>
{t("loginAction")}
</Link>
<button
type="button"
onClick={() => setShowLoginPrompt(false)}
className="flex-1 rounded-full border border-gray-200 px-4 py-2 text-sm font-semibold dark:border-gray-700"
>
{t("closePanel")}
</button>
</div>
</div>
</div>
) : null}
<MatchModal
profile={matchCelebration?.profile ?? null}
conversationId={matchCelebration?.conversationId}
onClose={() => setMatchCelebration(null)}
t={t}
/>
<Footer />
</div>
);
}
export default function DatingPage() {
return (
<Suspense fallback={<DatingSkeleton />}>
<DatingPageInner />
</Suspense>
);
}