"use client"; import { useEffect, useMemo, useState, useSyncExternalStore } from "react"; import { useAudienceModule } from "~/modules/audience"; import { socialApi } from "./api"; import { MOCK_ROSTER, type SocialRosterMember } from "./rosterMock"; import { cnAvatarForSeed, mapRosterAvatarPack } from "./rosterAvatars"; import { discoveryItemToMember, sortDiscoveryMembers, } from "./rankDiscovery"; import { loadJson, saveJson } from "./storage"; import type { SocialRosterProfile } from "./types"; export const ROSTER_PUBLISH_KEY = "roster-publish"; export const ROSTER_PUBLISH_CHANGED = "social-roster-publish-changed"; export const SELF_MEMBER_ID = "self-local"; const EMPTY: SocialRosterProfile = { name: "", title: "", city: "", phone: "", linktree: "", skills: "", bio: "", avatar: "", intents: "", availability: "", status: "", lookingFor: "", gender: "", }; const STORAGE_CHANGE = "nomadro-social-storage"; function subscribeSocialStorage(cb: () => void) { window.addEventListener("storage", cb); window.addEventListener(STORAGE_CHANGE, cb); window.addEventListener(ROSTER_PUBLISH_CHANGED, cb); return () => { window.removeEventListener("storage", cb); window.removeEventListener(STORAGE_CHANGE, cb); window.removeEventListener(ROSTER_PUBLISH_CHANGED, cb); }; } export function setRosterPublished(published: boolean) { saveJson(ROSTER_PUBLISH_KEY, published); window.dispatchEvent(new Event(STORAGE_CHANGE)); window.dispatchEvent(new Event(ROSTER_PUBLISH_CHANGED)); } export function profileToMember( profile: SocialRosterProfile, avatarPack: "cn" | "intl" = "intl", ): SocialRosterMember | null { const name = profile.name.trim(); if (!name) return null; const tags = profile.skills .split(/[,,、]/) .map((t) => t.trim()) .filter(Boolean) .slice(0, 6); const own = (profile.avatar || "").trim(); const ownOk = own.startsWith("https://") || own.startsWith("http://") || own.startsWith("/api/social/"); const avatar = ownOk ? own : avatarPack === "cn" ? cnAvatarForSeed(name, (profile.gender as "f" | "m") || "f") : `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(name)}`; const status = (profile.status || "online").trim(); const online = status === "online" || status === "here" || status === "available"; return { id: SELF_MEMBER_ID, name, title: profile.title.trim() || "游民", city: profile.city.trim() || "探索中", tags: tags.length ? tags : ["新朋友"], avatar, bio: profile.bio.trim() || "刚写好介绍,想认识同频的人。", vibe: status === "here" ? "同城想出来" : online ? "在线" : "刚出现", online, lookingFor: (profile.lookingFor || "").trim() || (profile.intents || "").replace(/,/g, " · ") || "想认识同频游民", gender: profile.gender === "m" ? "m" : "f", availability: (profile.availability || "").trim() || undefined, }; } function readLocalProfile(): SocialRosterProfile { const raw = loadJson>("roster", EMPTY); const next = { ...EMPTY }; (Object.keys(EMPTY) as (keyof SocialRosterProfile)[]).forEach((key) => { const val = raw?.[key]; if (typeof val === "string") next[key] = val; }); return next; } /** * Discovery list: live API (same-city / online / tags) → merge mock fallback → * optional self card. Ranked for local viewer profile. */ export function useDiscoveryRoster(): SocialRosterMember[] { const { bundle } = useAudienceModule(); const pack = bundle.module.social.rosterAvatarPack; const published = useSyncExternalStore( subscribeSocialStorage, () => loadJson(ROSTER_PUBLISH_KEY, false), () => false, ); const profileSnapshot = useSyncExternalStore( subscribeSocialStorage, () => JSON.stringify(loadJson("roster", EMPTY)), () => JSON.stringify(EMPTY), ); const profile = useMemo(() => { const raw = JSON.parse(profileSnapshot) as Partial | null; const next = { ...EMPTY }; (Object.keys(EMPTY) as (keyof SocialRosterProfile)[]).forEach((key) => { const val = raw?.[key]; if (typeof val === "string") next[key] = val; }); return next; }, [profileSnapshot]); const [remote, setRemote] = useState(null); useEffect(() => { let cancelled = false; void socialApi .discoveryRoster({ limit: 48 }) .then((res) => { if (cancelled || !res?.items?.length) return; setRemote(res.items.map(discoveryItemToMember)); }) .catch(() => { /* offline → keep mock */ }); return () => { cancelled = true; }; }, [profile.city, profile.skills, profile.intents]); const seed = useMemo( () => mapRosterAvatarPack(MOCK_ROSTER, pack), [pack], ); return useMemo(() => { const live = remote || []; const liveIds = new Set(live.map((m) => m.id)); // Prefer real people; pad with mock so empty cities still feel alive const merged = [ ...live, ...seed.filter((m) => !liveIds.has(m.id)), ]; const ranked = sortDiscoveryMembers(merged, profile); const self = published ? profileToMember(profile, pack) : null; if (!self) return ranked; return [self, ...ranked.filter((m) => m.id !== SELF_MEMBER_ID)]; }, [published, profile, seed, pack, remote]); } /** One-shot helper for non-hook call sites. */ export function getLocalViewerProfile(): SocialRosterProfile { return readLocalProfile(); }