"use client"; import { useState, type FormEvent } from "react"; import type { ApiComment } from "@/lib/api"; import { formatDate } from "@/lib/format"; import { customerLoginUrl } from "@/lib/customer"; import { useSession } from "@/lib/session"; import { RichContent } from "./RichContent"; type Props = { productId: string; descriptionHtml?: string | null; comments: ApiComment[]; }; type Tab = { id: "description" | "comments"; fa: string; en: string; }; const tabs: Tab[] = [ { id: "description", fa: "توضیحات محصول", en: "Description" }, { id: "comments", fa: "نظرات", en: "Comments" }, ]; export function ProductTabs({ productId, descriptionHtml, comments: initialComments }: Props) { const [tab, setTab] = useState<"description" | "comments">("description"); const [comments, setComments] = useState(initialComments); const [sent, setSent] = useState(false); const [sending, setSending] = useState(false); const { isAuthenticated: loggedIn, user } = useSession(); const authorName = user?.firstName?.trim() || "کاربر"; async function onSubmit(event: FormEvent) { event.preventDefault(); if (!loggedIn) return; const form = event.currentTarget; const text = String(new FormData(form).get("text") || "").trim(); if (!text) return; setSending(true); try { const response = await fetch("/api/comments", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ entityType: "product", entityId: productId, authorName, text, }), }); if (response.ok) { setSent(true); form.reset(); setComments((current) => [ { id: `local-${Date.now()}`, authorName, text, createdAt: new Date().toISOString(), }, ...current, ]); } } finally { setSending(false); } } return (
{tabs.map((item) => { const active = tab === item.id; const label = item.id === "comments" && comments.length ? `${item.fa} (${comments.length.toLocaleString("fa-IR")})` : item.fa; return ( ); })}
{tab === "description" ? ( descriptionHtml ? ( ) : (

توضیحی برای این محصول ثبت نشده است.

) ) : (
{comments.length ? ( comments.map((comment) => (
{comment.authorName || "کاربر"} {comment.createdAt ? : null}

{comment.text}

)) ) : (

هنوز نظری ثبت نشده است.

)}
{loggedIn ? (
{sent ? (

نظر شما ثبت شد و پس از تایید نمایش داده می‌شود.

) : (
)}
) : (

برای ثبت نظر ابتدا وارد حساب کاربری شوید.

ورود / ثبت نام
)}
)}
); }