feat: improve profile navigation and responsive privacy UX

This commit is contained in:
2026-09-29 15:26:28 +03:30
parent 61698ccbd9
commit bbf924c22d
25 changed files with 1353 additions and 764 deletions

File diff suppressed because it is too large Load Diff

431
src/views/ProfileEdit.tsx Normal file
View File

@@ -0,0 +1,431 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Camera, Check, CircleAlert, Eye, Loader2, LockKeyhole, Trash2, UserRound } from "lucide-react";
import AsyncSearchableCombobox from "@/components/AsyncSearchableCombobox";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { Helmet } from "@/lib/helmet";
import { Link, Navigate, useNavigate } from "@/lib/router";
import { buildAuthPath } from "@/lib/auth-return";
import { api } from "@/lib/api";
import { toEnglishDigits } from "@/lib/digits";
import type * as Types from "@/lib/types";
import { resolveErrorMessage, toPersianDigits } from "@/lib/utils";
type EditForm = Omit<Types.UserUpdateSchema, "email">;
const BIO_MAX_LENGTH = 500;
const USERNAME_MIN_LENGTH = 5;
const USERNAME_MAX_LENGTH = 150;
const USERNAME_PATTERN = /^[A-Za-z0-9_]+$/;
const persianNumberFormatter = new Intl.NumberFormat("fa-IR", { useGrouping: false });
type UsernameAvailability = "checking" | "available" | "taken" | "error";
const emptyForm: EditForm = {
username: "",
first_name: "",
last_name: "",
bio: "",
year_of_study: null,
major: null,
university: null,
student_id: "",
show_public_profile_details: false,
};
const editorSections = [
{ id: "identity", label: "اطلاعات فردی", icon: UserRound },
{ id: "academic", label: "اطلاعات دانشگاهی", icon: LockKeyhole },
{ id: "about", label: "درباره من", icon: Camera },
{ id: "visibility", label: "پروفایل عمومی", icon: Eye },
] as const;
export default function ProfileEdit() {
const { isAuthenticated, loading, setUser } = useAuth();
const queryClient = useQueryClient();
const { toast } = useToast();
const navigate = useNavigate();
const [form, setForm] = useState<EditForm>(emptyForm);
const [pictureFile, setPictureFile] = useState<File | null>(null);
const [picturePreview, setPicturePreview] = useState<string | null>(null);
const [removePicture, setRemovePicture] = useState(false);
const [saving, setSaving] = useState(false);
const [dirty, setDirty] = useState(false);
const [usernameCheck, setUsernameCheck] = useState<{ username: string; status: UsernameAvailability } | null>(null);
const profileQuery = useQuery({
queryKey: ["profile"],
queryFn: () => api.getProfile(),
enabled: isAuthenticated,
});
const profile = profileQuery.data;
const currentUsername = profile?.username;
useEffect(() => {
if (!profile) return;
setForm({
username: profile.username,
first_name: profile.first_name ?? "",
last_name: profile.last_name ?? "",
bio: profile.bio ?? "",
year_of_study: typeof profile.year_of_study === "number" ? profile.year_of_study : null,
major: profile.major_code ?? null,
university: profile.university_code ?? null,
student_id: toEnglishDigits(profile.student_id ?? ""),
show_public_profile_details: profile.show_public_profile_details ?? false,
});
}, [profile]);
useEffect(() => {
if (!currentUsername) return;
const username = (form.username ?? "").trim();
if (
username === currentUsername
|| username.length < USERNAME_MIN_LENGTH
|| username.length > USERNAME_MAX_LENGTH
|| !USERNAME_PATTERN.test(username)
) {
setUsernameCheck(null);
return;
}
let active = true;
setUsernameCheck({ username, status: "checking" });
const timeout = window.setTimeout(() => {
void api.checkUsername(username).then((result) => {
if (active) setUsernameCheck({ username, status: result.exists ? "taken" : "available" });
}).catch(() => {
if (active) setUsernameCheck({ username, status: "error" });
});
}, 350);
return () => {
active = false;
window.clearTimeout(timeout);
};
}, [form.username, currentUsername]);
useEffect(() => () => {
if (picturePreview) URL.revokeObjectURL(picturePreview);
}, [picturePreview]);
useEffect(() => {
if (!dirty) return;
const warnBeforeLeaving = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = "";
};
window.addEventListener("beforeunload", warnBeforeLeaving);
return () => window.removeEventListener("beforeunload", warnBeforeLeaving);
}, [dirty]);
const loadMajors = useCallback(async (params: { search: string; limit: number; offset: number }) => {
const result = await api.getMajorsPaged(params);
return { count: result.count, results: result.results.map((item) => ({ value: String(item.code), label: item.label })) };
}, []);
const loadUniversities = useCallback(async (params: { search: string; limit: number; offset: number }) => {
const result = await api.getUniversitiesPaged(params);
return { count: result.count, results: result.results.map((item) => ({ value: String(item.code), label: item.label })) };
}, []);
const fullName = useMemo(
() => [form.first_name, form.last_name].filter(Boolean).join(" ").trim() || profile?.username || "کاربر",
[form.first_name, form.last_name, profile?.username],
);
const avatarFallback = `${form.first_name?.[0] ?? ""}${form.last_name?.[0] ?? ""}` || profile?.username?.[0] || "؟";
const currentPicture = picturePreview || (removePicture ? undefined : profile?.profile_picture_preview_url || profile?.profile_picture);
const bioLength = (form.bio ?? "").length;
const bioHasError = bioLength > BIO_MAX_LENGTH;
const yearOfStudyHasError = form.year_of_study != null
&& (!Number.isInteger(form.year_of_study) || form.year_of_study < 1300 || form.year_of_study > 1600);
const bioLengthLabel = persianNumberFormatter.format(bioLength);
const bioMaxLengthLabel = persianNumberFormatter.format(BIO_MAX_LENGTH);
const usernameValue = (form.username ?? "").trim();
const usernameChanged = Boolean(profile && usernameValue !== profile.username);
const usernameCheckStatus = !usernameChanged
? "unchanged"
: usernameValue.length < USERNAME_MIN_LENGTH
? "too-short"
: usernameValue.length > USERNAME_MAX_LENGTH
? "too-long"
: !USERNAME_PATTERN.test(usernameValue)
? "invalid-format"
: usernameCheck?.username !== usernameValue
? "checking"
: usernameCheck.status;
const usernameCanSave = usernameCheckStatus === "unchanged" || usernameCheckStatus === "available";
const usernameFeedback = {
"too-short": "نام کاربری باید حداقل ۵ نویسه داشته باشد.",
"too-long": "نام کاربری بیش از حد مجاز طولانی است.",
"invalid-format": "فقط حروف انگلیسی، عدد و زیرخط (_) مجاز است.",
checking: "در حال بررسی نام کاربری...",
available: "این نام کاربری در دسترس است.",
taken: "این نام کاربری قبلاً انتخاب شده است.",
error: "بررسی نام کاربری انجام نشد؛ دوباره تلاش کنید.",
}[usernameCheckStatus];
const usernameHasError = usernameChanged && ["too-short", "too-long", "invalid-format", "taken", "error"].includes(usernameCheckStatus);
if (!loading && !isAuthenticated) return <Navigate to={buildAuthPath("/profile/edit")} replace />;
if ((loading || profileQuery.isLoading) && !profile) {
return <main className="flex min-h-[70vh] items-center justify-center text-muted-foreground" dir="rtl">در حال دریافت اطلاعات...</main>;
}
if (!profile) {
return <main className="container mx-auto max-w-4xl px-4 py-16 text-center" dir="rtl"><p role="alert" className="text-destructive">اطلاعات پروفایل دریافت نشد. صفحه را دوباره بارگذاری کنید.</p></main>;
}
const updateForm = <K extends keyof EditForm>(key: K, value: EditForm[K]) => {
setDirty(true);
setForm((current) => ({ ...current, [key]: value }));
};
const handlePictureSelection = (file?: File) => {
if (!file) return;
if (picturePreview) URL.revokeObjectURL(picturePreview);
setPicturePreview(URL.createObjectURL(file));
setPictureFile(file);
setRemovePicture(false);
setDirty(true);
};
const handleSave = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const username = (form.username ?? "").trim();
const usernameChanged = username !== profile.username;
const bio = form.bio ?? "";
const bioChanged = bio !== (profile.bio ?? "");
if (!usernameCanSave) {
toast({ title: "نام کاربری را بررسی کنید", description: usernameFeedback, variant: "destructive" });
return;
}
if (bioHasError) {
toast({ title: "معرفی بیش از حد مجاز است", description: `معرفی پروفایل باید حداکثر ${BIO_MAX_LENGTH} نویسه باشد.`, variant: "destructive" });
return;
}
if (yearOfStudyHasError) {
toast({ title: "سال ورود نامعتبر است", description: "سال ورود باید بین ۱۳۰۰ تا ۱۶۰۰ باشد.", variant: "destructive" });
return;
}
setSaving(true);
try {
const updates: Types.UserUpdateSchema = {};
if (usernameChanged) updates.username = username;
if ((form.first_name ?? "") !== profile.first_name) updates.first_name = form.first_name ?? "";
if ((form.last_name ?? "") !== profile.last_name) updates.last_name = form.last_name ?? "";
if (bioChanged) updates.bio = bio;
if ((form.year_of_study ?? null) !== (profile.year_of_study ?? null)) updates.year_of_study = form.year_of_study == null ? null : Number(form.year_of_study);
if ((form.major ?? null) !== (profile.major_code ?? null)) updates.major = form.major || null;
if ((form.university ?? null) !== (profile.university_code ?? null)) updates.university = form.university || null;
const studentId = toEnglishDigits(form.student_id ?? "");
const currentStudentId = toEnglishDigits(profile.student_id ?? "");
if (studentId !== currentStudentId) updates.student_id = studentId || null;
if (Boolean(form.show_public_profile_details) !== Boolean(profile.show_public_profile_details)) {
updates.show_public_profile_details = Boolean(form.show_public_profile_details);
}
if (Object.keys(updates).length) await api.updateProfile(updates);
if (pictureFile) await api.uploadProfilePicture(pictureFile);
else if (removePicture && profile.profile_picture) await api.deleteProfilePicture();
const updated = await api.getProfile();
queryClient.setQueryData(["profile"], updated);
setUser(updated);
setDirty(false);
toast({ title: "تغییرات پروفایل ذخیره شد", variant: "success" });
navigate("/profile");
} catch (error) {
toast({ title: "ذخیره پروفایل انجام نشد", description: resolveErrorMessage(error, "دوباره تلاش کنید"), variant: "destructive" });
} finally {
setSaving(false);
}
};
const handleCancel = () => {
if (dirty && !window.confirm("تغییرات ذخیره‌نشده کنار گذاشته شوند؟")) return;
navigate("/profile");
};
return (
<>
<Helmet>
<title>ویرایش پروفایل | انجمن علمی مهندسی کامپیوتر</title>
<meta name="robots" content="noindex, nofollow" />
</Helmet>
<main className="min-h-[70vh] w-full min-w-0 overflow-x-clip bg-muted/15 px-4 py-6 md:py-12" dir="rtl">
<div className="container mx-auto w-full min-w-0 max-w-5xl">
<div className="mb-6 min-w-0 text-right">
<p className="text-sm text-muted-foreground">حساب کاربری / پروفایل</p>
<h1 className="mt-1 text-2xl font-bold md:text-3xl">ویرایش پروفایل</h1>
</div>
<form onSubmit={handleSave} className="min-w-0 space-y-5">
<Card className="min-w-0 border-border/70 shadow-sm">
<CardContent className="flex min-w-0 flex-col items-center gap-5 p-4 text-center sm:flex-row sm:items-center sm:p-6 sm:text-right">
<Avatar className="h-24 w-24 border-2 border-background shadow-sm">
<AvatarImage src={currentPicture || undefined} alt={fullName} />
<AvatarFallback className="text-2xl">{avatarFallback}</AvatarFallback>
</Avatar>
<div className="min-w-0 w-full flex-1 text-right">
<p className="font-semibold">تصویر پروفایل</p>
<p className="mt-1 text-sm text-muted-foreground">تصویر دلخواه خود را بارگذاری کنید. حداکثر حجم فایل ۵ مگابایت است.</p>
<div className="mt-3 grid w-full grid-cols-1 gap-2 sm:grid-cols-2">
<Label htmlFor="profile-picture" className="inline-flex min-h-10 w-full cursor-pointer items-center justify-center rounded-xl border border-border px-4 text-sm font-medium transition-colors hover:bg-muted focus-within:ring-2 focus-within:ring-ring">
<Camera className="ml-2 h-4 w-4" />انتخاب تصویر
</Label>
<Input id="profile-picture" type="file" accept="image/*" className="sr-only" onChange={(event) => handlePictureSelection(event.currentTarget.files?.[0])} />
{profile.profile_picture || pictureFile ? (
<Button type="button" variant="ghost" size="sm" className="w-full" onClick={() => { setPicturePreview(null); setPictureFile(null); setRemovePicture(true); setDirty(true); }}>
<Trash2 className="ml-2 h-4 w-4" />حذف تصویر
</Button>
) : null}
{removePicture ? <Button type="button" variant="outline" size="sm" className="w-full" onClick={() => { setRemovePicture(false); setDirty(true); }}>بازگردانی تصویر فعلی</Button> : null}
</div>
</div>
</CardContent>
</Card>
<div className="grid min-w-0 gap-5 lg:grid-cols-[minmax(0,220px)_minmax(0,1fr)]">
<nav className="hidden min-w-0 self-start lg:sticky lg:top-24 lg:flex lg:flex-col lg:gap-2 lg:rounded-2xl lg:border lg:border-border/70 lg:bg-card lg:p-2" aria-label="بخش‌های ویرایش پروفایل">
{editorSections.map(({ id, label, icon: Icon }) => (
<a key={id} href={`#${id}`} className="inline-flex min-h-11 min-w-0 items-center justify-center gap-2 rounded-xl px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:justify-start sm:px-3 sm:text-sm">
<Icon className="h-4 w-4" aria-hidden="true" />{label}
</a>
))}
</nav>
<div className="min-w-0 space-y-5">
<Card id="identity" className="scroll-mt-24 min-w-0 border-border/70 shadow-sm">
<CardHeader className="text-right">
<CardTitle>اطلاعات فردی</CardTitle>
<CardDescription>نامی که در سایت و پروفایل عمومی شما نمایش داده می‌شود</CardDescription>
</CardHeader>
<CardContent className="grid min-w-0 gap-4 sm:grid-cols-2">
<div className="min-w-0"><Label htmlFor="first_name">نام</Label><Input id="first_name" autoComplete="given-name" value={form.first_name ?? ""} onChange={(event) => updateForm("first_name", event.target.value)} className="mt-2 w-full min-w-0 text-right" /></div>
<div className="min-w-0"><Label htmlFor="last_name">نام خانوادگی</Label><Input id="last_name" autoComplete="family-name" value={form.last_name ?? ""} onChange={(event) => updateForm("last_name", event.target.value)} className="mt-2 w-full min-w-0 text-right" /></div>
<div className="min-w-0 sm:col-span-2">
<Label htmlFor="username">نام کاربری</Label>
<Input
id="username"
autoComplete="username"
autoCapitalize="none"
spellCheck={false}
maxLength={USERNAME_MAX_LENGTH}
required
aria-invalid={usernameHasError}
aria-describedby={usernameChanged ? "username-help username-warning username-feedback" : "username-help"}
value={form.username ?? ""}
onChange={(event) => updateForm("username", event.target.value)}
className={`mt-2 text-left ${usernameHasError ? "border-destructive focus-visible:ring-destructive" : ""}`}
dir="ltr"
/>
{usernameChanged ? (
<div id="username-warning" role="note" className="mt-2 flex items-start gap-2 rounded-lg border border-amber-300/70 bg-amber-50/80 px-3 py-2 text-xs leading-5 text-amber-950 dark:border-amber-900/70 dark:bg-amber-950/20 dark:text-amber-100">
<CircleAlert className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
<span>با تغییر نام کاربری، نشانی پروفایل عمومی شما عوض می‌شود و پیوندهای قبلی از دسترس خارج می‌شوند.</span>
</div>
) : null}
<p id="username-help" className="mt-1 text-xs leading-5 text-muted-foreground">نام کاربری در نشانی پروفایل عمومی شما استفاده می‌شود.</p>
{usernameChanged ? (
<p id="username-feedback" aria-live="polite" className={`mt-1 text-xs ${usernameCheckStatus === "available" ? "text-emerald-700 dark:text-emerald-400" : usernameCheckStatus === "checking" ? "text-muted-foreground" : "text-destructive"}`}>
{usernameCheckStatus === "checking" ? <Loader2 className="ml-1 inline h-3 w-3 animate-spin" aria-hidden="true" /> : null}
{usernameFeedback}
</p>
) : null}
</div>
</CardContent>
</Card>
<Card id="academic" className="scroll-mt-24 min-w-0 border-border/70 shadow-sm">
<CardHeader className="text-right">
<CardTitle>اطلاعات دانشگاهی</CardTitle>
<CardDescription>با فعال‌کردن نمایش جزئیات پروفایل عمومی، این اطلاعات برای همه قابل مشاهده می‌شوند.</CardDescription>
</CardHeader>
<CardContent className="grid min-w-0 gap-4 sm:grid-cols-2">
<div className="min-w-0"><Label htmlFor="university">دانشگاه</Label><div className="mt-2 min-w-0"><AsyncSearchableCombobox id="university" value={form.university || null} selectedLabel={profile.university} onChange={(value) => updateForm("university", value)} loadOptions={loadUniversities} placeholder="انتخاب دانشگاه" /></div></div>
<div className="min-w-0"><Label htmlFor="major">رشته</Label><div className="mt-2 min-w-0"><AsyncSearchableCombobox id="major" value={form.major || null} selectedLabel={profile.major} onChange={(value) => updateForm("major", value)} loadOptions={loadMajors} placeholder="انتخاب رشته" /></div></div>
<div className="min-w-0">
<Label htmlFor="year_of_study">سال ورود</Label>
<Input
id="year_of_study"
type="text"
inputMode="numeric"
maxLength={4}
value={form.year_of_study == null ? "" : toPersianDigits(form.year_of_study)}
onChange={(event) => {
const digits = toEnglishDigits(event.target.value).replace(/\D/g, "").slice(0, 4);
updateForm("year_of_study", digits ? Number(digits) : null);
}}
aria-invalid={yearOfStudyHasError || undefined}
aria-describedby={yearOfStudyHasError ? "year_of_study-error" : undefined}
className={`mt-2 w-full min-w-0 text-right ${yearOfStudyHasError ? "border-destructive focus-visible:ring-destructive" : ""}`}
/>
{yearOfStudyHasError ? <p id="year_of_study-error" className="mt-1 text-xs text-destructive">سال ورود باید بین ۱۳۰۰ تا ۱۶۰۰ باشد.</p> : null}
</div>
<div className="min-w-0">
<Label htmlFor="student_id">شماره دانشجویی</Label>
<Input id="student_id" autoComplete="off" value={toPersianDigits(form.student_id ?? "")} onChange={(event) => updateForm("student_id", toEnglishDigits(event.target.value))} className="mt-2 w-full min-w-0 text-right" />
</div>
</CardContent>
</Card>
<Card id="about" className="scroll-mt-24 min-w-0 border-border/70 shadow-sm">
<CardHeader className="text-right"><CardTitle>درباره من</CardTitle><CardDescription>یک معرفی کوتاه و ساده بنویسید. متن در پروفایل عمومی بدون قالب‌بندی نمایش داده می‌شود.</CardDescription></CardHeader>
<CardContent>
<Label htmlFor="bio">معرفی کوتاه</Label>
<Textarea
id="bio"
value={form.bio ?? ""}
onChange={(event) => updateForm("bio", event.target.value)}
className={`mt-2 min-h-28 resize-y text-right leading-7 ${bioHasError ? "border-destructive focus-visible:ring-destructive" : ""}`}
maxLength={BIO_MAX_LENGTH}
aria-invalid={bioHasError}
aria-describedby="bio-count"
/>
<p id="bio-count" aria-live="polite" className={`mt-2 text-xs ${bioHasError ? "text-destructive" : "text-muted-foreground"}`}>
{bioLengthLabel} از {bioMaxLengthLabel} نویسه{bioHasError ? " — برای ذخیره، متن را کوتاه کنید." : ""}
</p>
</CardContent>
</Card>
<Card id="visibility" className="scroll-mt-24 min-w-0 border-border/70 shadow-sm">
<CardHeader className="text-right"><CardTitle>پروفایل عمومی</CardTitle><CardDescription>پروفایل عمومی رویدادهایی را که در آن‌ها شرکت کرده‌اید نشان می‌دهد. این گزینه، جزئیات پروفایل را هم در اختیار بازدیدکنندگان قرار می‌دهد.</CardDescription></CardHeader>
<CardContent className="space-y-5">
<div className="flex min-w-0 items-start justify-between gap-4 rounded-2xl border border-border/70 p-4">
<div className="min-w-0 flex-1 text-right">
<div className="flex flex-wrap items-center gap-2">
<Label htmlFor="show-public-details" className="cursor-pointer text-sm font-semibold">نمایش جزئیات پروفایل برای همه</Label>
<span aria-live="polite" className={`rounded-full px-2 py-0.5 text-xs font-semibold ${form.show_public_profile_details ? "bg-primary/15 text-primary" : "bg-muted text-muted-foreground"}`}>{form.show_public_profile_details ? "فعال" : "غیرفعال"}</span>
</div>
<p id="public-details-description" className="mt-1 max-w-xl text-sm leading-6 text-muted-foreground">با فعال‌کردن این گزینه، شماره موبایل، شماره دانشجویی، دانشگاه، رشته و سال ورود در پروفایل عمومی دیده می‌شوند.</p>
</div>
<Switch id="show-public-details" checked={Boolean(form.show_public_profile_details)} onCheckedChange={(checked) => updateForm("show_public_profile_details", checked)} aria-label="نمایش جزئیات پروفایل برای همه" aria-describedby="public-details-description" className="shrink-0 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-foreground/40" />
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div><Label htmlFor="mobile">شماره موبایل</Label><Input id="mobile" value={profile.mobile ? toPersianDigits(profile.mobile) : "ثبت نشده"} readOnly aria-readonly="true" className="mt-2 text-right read-only:cursor-not-allowed read-only:bg-muted/40" /><p className="mt-1 text-xs text-muted-foreground">تغییر شماره موبایل از این صفحه امکان‌پذیر نیست. برای به‌روزرسانی آن، روند تأیید شماره را دنبال کنید.</p></div>
<div><Label htmlFor="email">ایمیل</Label><Input id="email" value={profile.email ?? "ثبت نشده"} readOnly aria-readonly="true" className="mt-2 text-right read-only:cursor-not-allowed read-only:bg-muted/40" /><p className="mt-1 text-xs text-muted-foreground">تغییر ایمیل از این صفحه امکان‌پذیر نیست.</p></div>
</div>
</CardContent>
</Card>
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
<Button type="button" variant="outline" onClick={handleCancel} disabled={saving}>انصراف</Button>
<Button type="submit" disabled={saving || bioHasError || !usernameCanSave} className="min-w-36">
{saving ? <Loader2 className="ml-2 h-4 w-4 animate-spin" /> : <Check className="ml-2 h-4 w-4" />}
{saving ? "در حال ذخیره..." : "ذخیره تغییرات"}
</Button>
</div>
</div>
</div>
</form>
</div>
</main>
</>
);
}

143
src/views/PublicProfile.tsx Normal file
View File

@@ -0,0 +1,143 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import Image from "next/image";
import { CalendarDays, EyeOff, UserRound } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Helmet } from "@/lib/helmet";
import { Link, useParams } from "@/lib/router";
import { api } from "@/lib/api";
import { formatJalali, formatNumberPersian, toPersianDigits } from "@/lib/utils";
import type { PublicProfileEventSchema } from "@/lib/types";
function EventCard({ event }: { event: PublicProfileEventSchema }) {
return (
<Link to={`/events/${event.slug}`} className="group flex min-h-28 gap-4 rounded-2xl border border-border/70 bg-background p-3 text-right transition-colors hover:bg-muted/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{event.image_url ? <Image src={event.image_url} alt="" width={160} height={120} unoptimized className="aspect-[4/3] w-24 shrink-0 rounded-xl object-cover sm:w-32" /> : (
<span className="flex aspect-[4/3] w-24 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary sm:w-32"><CalendarDays className="h-6 w-6" aria-hidden="true" /></span>
)}
<span className="flex min-w-0 flex-1 flex-col gap-2 py-1">
<span className="font-semibold text-foreground group-hover:text-primary">{event.title}</span>
<span className="text-xs text-muted-foreground">{formatJalali(event.start_time, false)}</span>
</span>
</Link>
);
}
export default function PublicProfile() {
const { username: rawUsername } = useParams<{ username: string }>();
const username = Array.isArray(rawUsername) ? rawUsername[0] : rawUsername;
const profileQuery = useQuery({
queryKey: ["public-profile", username],
queryFn: () => api.getPublicProfile(username),
enabled: Boolean(username),
retry: false,
});
const profile = profileQuery.data;
if (profileQuery.isLoading) {
return <main className="flex min-h-[70vh] items-center justify-center text-muted-foreground" dir="rtl">در حال بارگذاری پروفایل عمومی...</main>;
}
if (profileQuery.isError || !profile) {
return (
<main className="container mx-auto max-w-4xl px-4 py-16" dir="rtl">
<Card className="border-border/70 text-center shadow-sm"><CardContent className="p-10">
<UserRound className="mx-auto h-8 w-8 text-muted-foreground" aria-hidden="true" />
<h1 className="mt-4 text-xl font-bold">این پروفایل در دسترس نیست</h1>
<p className="mt-2 text-sm text-muted-foreground">نام کاربری را بررسی کنید یا بعداً دوباره تلاش کنید.</p>
</CardContent></Card>
</main>
);
}
const fallback = `${profile.first_name?.[0] ?? ""}${profile.last_name?.[0] ?? ""}` || profile.username[0];
const maskedDetails = [
{ label: "شماره موبایل", value: profile.mobile },
{ label: "شماره دانشجویی", value: profile.student_id },
{ label: "دانشگاه", value: profile.university },
{ label: "رشته", value: profile.major },
{ label: "سال ورود", value: profile.year_of_study || null },
];
const pageDescription = profile.bio || `پروفایل عمومی ${profile.full_name} و رویدادهای او در انجمن علمی مهندسی کامپیوتر.`;
return (
<>
<Helmet>
<title>{`${profile.full_name} | پروفایل عمومی`}</title>
<meta name="description" content={pageDescription} />
<meta name="robots" content="index, follow" />
</Helmet>
<main className="min-h-screen bg-muted/15 px-4 py-8 md:py-12" dir="rtl">
<div className="container mx-auto max-w-6xl space-y-5">
<div className="grid gap-5 lg:grid-cols-12 lg:items-start">
<aside className="space-y-5 lg:col-span-4">
<Card className="border-border/70 shadow-sm">
<CardContent className="p-6 text-right">
<div className="flex items-center gap-4">
<Avatar className="h-20 w-20 border-2 border-background shadow-sm">
<AvatarImage src={profile.profile_picture || undefined} alt={profile.full_name} />
<AvatarFallback className="text-xl">{fallback}</AvatarFallback>
</Avatar>
<div className="min-w-0">
<h1 className="truncate text-xl font-bold">{profile.full_name}</h1>
<p className="mt-1 text-sm text-muted-foreground">@{profile.username}</p>
</div>
</div>
{profile.bio ? <p className="mt-5 whitespace-pre-wrap text-sm leading-7 text-muted-foreground">{profile.bio}</p> : null}
<div className="mt-5 grid grid-cols-1 gap-3">
<div className="rounded-2xl border border-border/70 bg-muted/45 p-4 text-center shadow-sm dark:bg-background/70"><p className="text-xl font-bold">{formatNumberPersian(profile.events.length)}</p><p className="mt-1 text-xs text-muted-foreground">رویداد</p></div>
</div>
</CardContent>
</Card>
<Card className="border-border/70 shadow-sm">
<CardHeader className="pb-2 text-right"><CardTitle className="text-base">{profile.details_visible ? "اطلاعات بیشتر" : "اطلاعات خصوصی"}</CardTitle></CardHeader>
<CardContent className="space-y-1">
{profile.details_visible ? maskedDetails.map(({ label, value }) => (
<div key={label} className="flex items-center justify-between gap-4 border-b border-border/60 py-3 last:border-0 text-sm">
<span className="shrink-0 text-muted-foreground">{label}</span>
<span className="text-left font-medium">{value ? toPersianDigits(String(value)) : "ثبت نشده"}</span>
</div>
)) : (
<div className="relative isolate overflow-hidden rounded-xl border border-border/70 bg-muted/20 p-5 sm:p-6">
<div aria-hidden="true" className="pointer-events-none select-none space-y-3 opacity-55 blur-[4px]">
{maskedDetails.map(({ label }) => (
<div key={label} className="flex items-center justify-between gap-4 border-b border-border/60 py-3 last:border-0 text-sm">
<span className="shrink-0 text-muted-foreground">{label}</span>
<span className="font-medium">••••••••</span>
</div>
))}
</div>
<div className="absolute inset-0 flex items-center justify-center bg-background/55 p-4 text-center">
<div className="max-w-xs">
<span className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10 text-primary">
<EyeOff className="h-6 w-6" aria-hidden="true" />
</span>
<p className="font-semibold">جزئیات این پروفایل خصوصی است</p>
<p className="mt-1 text-sm leading-6 text-muted-foreground">نمایش اطلاعات تکمیلی به درخواست صاحب حساب غیرفعال شده است.</p>
</div>
</div>
</div>
)}
</CardContent>
</Card>
</aside>
<div className="space-y-5 lg:col-span-8">
<Card className="border-border/70 shadow-sm">
<CardHeader className="text-right">
<CardTitle className="flex items-center gap-2"><CalendarDays className="h-5 w-5 text-primary" aria-hidden="true" />رویدادهای انجمن</CardTitle>
<CardDescription>رویدادهایی که {profile.first_name || profile.username} در آن‌ها شرکت کرده</CardDescription>
</CardHeader>
<CardContent className="h-[70vh] space-y-3 overflow-y-auto overscroll-contain">
{profile.events.length ? profile.events.map((event) => <EventCard key={`${event.slug}-${event.start_time}`} event={event} />) : <p className="rounded-xl bg-muted/30 p-5 text-center text-sm text-muted-foreground">هنوز رویدادی برای نمایش ثبت نشده است.</p>}
</CardContent>
</Card>
</div>
</div>
</div>
</main>
</>
);
}