create-nextblock 0.15.5 → 0.15.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/package.json +50 -26
  2. package/templates/nextblock-template/app/ToasterProvider.tsx +26 -17
  3. package/templates/nextblock-template/app/actions/contactSellerActions.test.ts +280 -0
  4. package/templates/nextblock-template/app/actions/contactSellerActions.ts +222 -0
  5. package/templates/nextblock-template/app/actions/email-retry.test.ts +62 -0
  6. package/templates/nextblock-template/app/actions/email.ts +241 -110
  7. package/templates/nextblock-template/app/actions/formActions.ts +245 -116
  8. package/templates/nextblock-template/app/actions/interactions.ts +489 -396
  9. package/templates/nextblock-template/app/actions/threadActions.ts +166 -0
  10. package/templates/nextblock-template/app/api/checkout/route.ts +162 -146
  11. package/templates/nextblock-template/app/api/cron/reset-sandbox/route.ts +14 -0
  12. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +664 -1
  13. package/templates/nextblock-template/app/checkout/page.tsx +57 -52
  14. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +552 -529
  15. package/templates/nextblock-template/app/cms/blocks/editors/FormBlockEditor.tsx +304 -181
  16. package/templates/nextblock-template/app/cms/components/ContactReminderBanner.tsx +75 -0
  17. package/templates/nextblock-template/app/cms/components/PaymentsReminderBanner.tsx +58 -0
  18. package/templates/nextblock-template/app/cms/components/VisibilityControl.tsx +542 -528
  19. package/templates/nextblock-template/app/cms/inquiries/actions.ts +66 -0
  20. package/templates/nextblock-template/app/cms/inquiries/page.tsx +12 -0
  21. package/templates/nextblock-template/app/cms/interactions/page.tsx +12 -51
  22. package/templates/nextblock-template/app/cms/layout.tsx +101 -73
  23. package/templates/nextblock-template/app/cms/messages/MessagesClient.tsx +661 -0
  24. package/templates/nextblock-template/app/cms/messages/actions.ts +404 -0
  25. package/templates/nextblock-template/app/cms/messages/loadInbox.ts +333 -0
  26. package/templates/nextblock-template/app/cms/messages/page.tsx +87 -0
  27. package/templates/nextblock-template/app/cms/messages/require-admin.ts +37 -0
  28. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +370 -362
  29. package/templates/nextblock-template/app/cms/revisions/service.ts +20 -0
  30. package/templates/nextblock-template/app/cms/settings/email/components/EmailForm.tsx +227 -185
  31. package/templates/nextblock-template/app/layout.tsx +671 -667
  32. package/templates/nextblock-template/app/lib/seo.ts +319 -311
  33. package/templates/nextblock-template/app/product/[slug]/page.tsx +502 -482
  34. package/templates/nextblock-template/app/providers.tsx +96 -96
  35. package/templates/nextblock-template/app/thread/ThreadView.tsx +164 -0
  36. package/templates/nextblock-template/app/thread/[token]/route.ts +57 -0
  37. package/templates/nextblock-template/app/thread/layout.tsx +15 -0
  38. package/templates/nextblock-template/app/thread/page.tsx +98 -0
  39. package/templates/nextblock-template/components/BlockRenderer.tsx +312 -296
  40. package/templates/nextblock-template/components/ContactSellerSection.tsx +188 -0
  41. package/templates/nextblock-template/components/PostCommentsSection.tsx +378 -369
  42. package/templates/nextblock-template/components/ProductReviewsSection.tsx +426 -419
  43. package/templates/nextblock-template/components/StaffReplies.tsx +102 -0
  44. package/templates/nextblock-template/components/blocks/renderers/CartBlockRenderer.tsx +18 -17
  45. package/templates/nextblock-template/components/blocks/renderers/CheckoutBlockRenderer.tsx +20 -19
  46. package/templates/nextblock-template/components/blocks/renderers/FeaturedProductBlockRenderer.tsx +25 -22
  47. package/templates/nextblock-template/components/blocks/renderers/FormBlockRenderer.tsx +385 -381
  48. package/templates/nextblock-template/components/blocks/renderers/ProductDetailsBlockRenderer.tsx +157 -92
  49. package/templates/nextblock-template/components/blocks/renderers/ProductGridBlockRenderer.tsx +34 -31
  50. package/templates/nextblock-template/components/blocks/renderers/SectionBlockRenderer.tsx +612 -600
  51. package/templates/nextblock-template/components/commerce/PaymentReadinessBoundary.tsx +32 -0
  52. package/templates/nextblock-template/docs/05-DEVELOPER-GUIDE.md +25 -19
  53. package/templates/nextblock-template/docs/06-CLI-AND-SCAFFOLDING.md +1 -1
  54. package/templates/nextblock-template/docs/08-NEXTBLOCK-CORTEX-AI-ARCHITECTURE.md +2 -2
  55. package/templates/nextblock-template/docs/12-VERCEL-DEPLOYMENT.md +32 -9
  56. package/templates/nextblock-template/docs/14-MESSAGES-INBOX.md +309 -0
  57. package/templates/nextblock-template/docs/README.md +42 -41
  58. package/templates/nextblock-template/docs/TECHNICAL_SPECIFICATION.md +540 -542
  59. package/templates/nextblock-template/docs/assets/lighthouse-scores.png +0 -0
  60. package/templates/nextblock-template/lib/blocks/blockColors.test.ts +22 -2
  61. package/templates/nextblock-template/lib/blocks/blockColors.ts +44 -1
  62. package/templates/nextblock-template/lib/blocks/blockRegistry.ts +761 -753
  63. package/templates/nextblock-template/lib/cms/contact-reminder.ts +64 -0
  64. package/templates/nextblock-template/lib/cms/payments-reminder.ts +98 -0
  65. package/templates/nextblock-template/lib/cms/unread-messages.ts +42 -0
  66. package/templates/nextblock-template/lib/commerce/seller-contact.ts +162 -0
  67. package/templates/nextblock-template/lib/config/email-settings.ts +323 -254
  68. package/templates/nextblock-template/lib/config/email-tls.test.ts +57 -0
  69. package/templates/nextblock-template/lib/email/placeholder-address.test.ts +59 -0
  70. package/templates/nextblock-template/lib/email/placeholder-address.ts +39 -0
  71. package/templates/nextblock-template/lib/messages/thread-reference.test.ts +70 -0
  72. package/templates/nextblock-template/lib/messages/thread-token.test.ts +93 -0
  73. package/templates/nextblock-template/lib/messages/thread-token.ts +157 -0
  74. package/templates/nextblock-template/lib/messages/threads.ts +579 -0
  75. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +20 -0
  76. package/templates/nextblock-template/lib/site-url.test.ts +89 -0
  77. package/templates/nextblock-template/lib/site-url.ts +102 -48
  78. package/templates/nextblock-template/package.json +14 -1
  79. package/templates/nextblock-template/public/assets/nextblock-banner.jpg +0 -0
@@ -1,419 +1,426 @@
1
- "use client";
2
-
3
- import React, { useState, useEffect, useTransition, useOptimistic } from "react";
4
- import { createClient } from "@nextblock-cms/db";
5
- import { Button } from "@nextblock-cms/ui";
6
- import { Textarea } from "@nextblock-cms/ui";
7
- import { Avatar, AvatarFallback, AvatarImage } from "@nextblock-cms/ui";
8
- import { submitInteraction, toggleReaction } from "../app/actions/interactions";
9
- import { cn, useTranslations } from "@nextblock-cms/utils";
10
- import { MessageSquare, ThumbsUp, Star, Loader2, PenTool } from "lucide-react";
11
-
12
- interface ProductReviewsSectionProps {
13
- productId: string;
14
- }
15
-
16
- export default function ProductReviewsSection({ productId }: ProductReviewsSectionProps) {
17
- const { t, lang } = useTranslations();
18
- const [reviews, setReviews] = useState<any[]>([]);
19
- const [loading, setLoading] = useState(true);
20
- const [page, setPage] = useState(0);
21
- const [hasMore, setHasMore] = useState(true);
22
- const [user, setUser] = useState<any>(null);
23
-
24
- // Form states
25
- const [isFormOpen, setIsFormOpen] = useState(false);
26
- const [rating, setRating] = useState(5);
27
- const [hoverRating, setHoverRating] = useState(0);
28
- const [content, setContent] = useState("");
29
- const [submitting, setSubmitting] = useState(false);
30
- const [error, setError] = useState<string | null>(null);
31
- const [success, setSuccess] = useState<string | null>(null);
32
-
33
- // Liked interactions tracking
34
- const [likedIds, setLikedIds] = useState<string[]>([]);
35
- const [, startTransition] = useTransition();
36
-
37
- // Optimistic reviews list
38
- const [optimisticReviews, setOptimisticReviews] = useOptimistic(
39
- reviews,
40
- (state, { reviewId, hasReacted, count }: { reviewId: string; hasReacted: boolean; count: number }) =>
41
- state.map((r) => {
42
- if (r.id === reviewId) {
43
- const reactions = { ...((r.reactions as Record<string, number>) || {}) };
44
- reactions.likes = count;
45
- return { ...r, reactions, tempHasReacted: hasReacted };
46
- }
47
- return r;
48
- })
49
- );
50
-
51
- useEffect(() => {
52
- // 1. Fetch user
53
- const supabase = createClient();
54
- supabase.auth.getUser().then(({ data: { user } }) => {
55
- setUser(user);
56
- });
57
-
58
- // 2. Read liked interactions from cookies
59
- const match = document.cookie.match(/reacted_interactions=([^;]+)/);
60
- if (match) {
61
- try {
62
- setLikedIds(JSON.parse(decodeURIComponent(match[1])));
63
- } catch (err) {
64
- console.warn("Failed to parse liked interactions cookie:", err);
65
- }
66
- }
67
-
68
- // 3. Load initial reviews
69
- fetchReviews(0, true);
70
- }, [productId]);
71
-
72
- const fetchReviews = async (pageNum: number, isInitial = false) => {
73
- setLoading(true);
74
- const supabase = createClient();
75
- const limit = 5;
76
- const start = pageNum * limit;
77
- const end = start + limit - 1;
78
-
79
- try {
80
- const { data, error: dbError } = await supabase
81
- .from("cms_interactions" as any)
82
- .select("*, profiles(full_name, avatar_url)")
83
- .eq("product_id", productId)
84
- .eq("type", "review")
85
- .eq("status", "approved")
86
- .order("created_at", { ascending: false })
87
- .range(start, end);
88
-
89
- if (dbError) throw dbError;
90
-
91
- if (data) {
92
- if (isInitial) {
93
- setReviews(data);
94
- setPage(0);
95
- } else {
96
- setReviews((prev) => [...prev, ...data]);
97
- setPage(pageNum);
98
- }
99
- setHasMore(data.length === limit);
100
- }
101
- } catch (err) {
102
- console.error("Error fetching reviews:", err);
103
- } finally {
104
- setLoading(false);
105
- }
106
- };
107
-
108
- const handleLoadMore = () => {
109
- fetchReviews(page + 1);
110
- };
111
-
112
- const handleLike = async (reviewId: string) => {
113
- const isLiked = likedIds.includes(reviewId);
114
- const review = reviews.find((r) => r.id === reviewId);
115
- if (!review) return;
116
-
117
- const currentLikes = (review.reactions as Record<string, number>)?.likes || 0;
118
- const nextCount = isLiked ? Math.max(0, currentLikes - 1) : currentLikes + 1;
119
-
120
- startTransition(async () => {
121
- // Apply optimistic update
122
- setOptimisticReviews({ reviewId, hasReacted: !isLiked, count: nextCount });
123
-
124
- const res = await toggleReaction(reviewId);
125
- if (res.success) {
126
- // Update liked cookie state locally
127
- if (isLiked) {
128
- setLikedIds((prev) => prev.filter((id) => id !== reviewId));
129
- } else {
130
- setLikedIds((prev) => [...prev, reviewId]);
131
- }
132
- // Sync actual state
133
- setReviews((prev) =>
134
- prev.map((r) => {
135
- if (r.id === reviewId) {
136
- const reactions = { ...((r.reactions as Record<string, number>) || {}) };
137
- reactions.likes = res.count ?? nextCount;
138
- return { ...r, reactions };
139
- }
140
- return r;
141
- })
142
- );
143
- }
144
- });
145
- };
146
-
147
- const handleSubmitReview = async (e: React.FormEvent) => {
148
- e.preventDefault();
149
- if (!user) {
150
- setError(t("reviews.login_to_write"));
151
- return;
152
- }
153
-
154
- if (content.trim().length < 5) {
155
- setError(lang === "fr" ? "Votre avis doit faire au moins 5 caractères." : "Your review must be at least 5 characters long.");
156
- return;
157
- }
158
-
159
- setSubmitting(true);
160
- setError(null);
161
- setSuccess(null);
162
-
163
- const res = await submitInteraction({
164
- type: "review",
165
- content: content.trim(),
166
- rating,
167
- productId,
168
- });
169
-
170
- setSubmitting(false);
171
-
172
- if (res.error) {
173
- setError(res.error);
174
- } else {
175
- setSuccess(t("reviews.success_pending"));
176
- setContent("");
177
- setRating(5);
178
- // Close form after a brief delay
179
- setTimeout(() => {
180
- setIsFormOpen(false);
181
- setSuccess(null);
182
- }, 3000);
183
- }
184
- };
185
-
186
- const getInitials = (profile: any) => {
187
- if (profile?.full_name) {
188
- return profile.full_name
189
- .split(" ")
190
- .map((n: string) => n[0])
191
- .join("")
192
- .toUpperCase()
193
- .slice(0, 2);
194
- }
195
- return "U";
196
- };
197
-
198
- return (
199
- <div className="space-y-8 max-w-4xl mx-auto px-4">
200
- {/* Header */}
201
- <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b pb-6 gap-4">
202
- <div>
203
- <h2 className="text-2xl font-bold tracking-tight text-foreground flex items-center gap-2">
204
- <MessageSquare className="h-6 w-6 text-primary" />
205
- {t("reviews.customer_reviews")}
206
- </h2>
207
- <p className="text-sm text-muted-foreground mt-1 text-left">
208
- {t("reviews.share_thoughts")}
209
- </p>
210
- </div>
211
-
212
- {user ? (
213
- <Button
214
- onClick={() => setIsFormOpen(!isFormOpen)}
215
- className="flex items-center gap-2 transition-all"
216
- variant={isFormOpen ? "outline" : "default"}
217
- >
218
- <PenTool className="h-4 w-4" />
219
- {isFormOpen ? t("reviews.cancel_review") : t("reviews.write_review")}
220
- </Button>
221
- ) : (
222
- <p className="text-sm text-muted-foreground italic">
223
- {t("reviews.login_to_write")}
224
- </p>
225
- )}
226
- </div>
227
-
228
- {/* Submission Form */}
229
- {isFormOpen && (
230
- <form
231
- onSubmit={handleSubmitReview}
232
- className="bg-card/50 border border-border/80 rounded-2xl p-6 shadow-sm space-y-4 animate-in fade-in slide-in-from-top-4 duration-300"
233
- >
234
- <h3 className="text-lg font-semibold text-foreground">{t("reviews.write_your_review")}</h3>
235
-
236
- {/* Stars Selection */}
237
- <div className="space-y-1.5">
238
- <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block">
239
- {t("reviews.rating")}
240
- </label>
241
- <div className="flex items-center gap-1.5">
242
- {Array.from({ length: 5 }).map((_, i) => {
243
- const starVal = i + 1;
244
- const isActive = starVal <= (hoverRating || rating);
245
- return (
246
- <button
247
- key={i}
248
- type="button"
249
- onClick={() => setRating(starVal)}
250
- onMouseEnter={() => setHoverRating(starVal)}
251
- onMouseLeave={() => setHoverRating(0)}
252
- className="transition-transform active:scale-95 focus:outline-none"
253
- aria-label={`Rate ${starVal} stars`}
254
- >
255
- <Star
256
- className={cn(
257
- "h-7 w-7 transition-colors",
258
- isActive
259
- ? "text-amber-500 fill-amber-500"
260
- : "text-slate-300 dark:text-slate-700"
261
- )}
262
- />
263
- </button>
264
- );
265
- })}
266
- </div>
267
- </div>
268
-
269
- {/* Text Area */}
270
- <div className="space-y-1.5">
271
- <label
272
- htmlFor="review-content"
273
- className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block"
274
- >
275
- {t("reviews.description")}
276
- </label>
277
- <Textarea
278
- id="review-content"
279
- placeholder={t("reviews.description_placeholder")}
280
- value={content}
281
- onChange={(e) => setContent(e.target.value)}
282
- className="min-h-[120px] focus:ring-1 focus:ring-primary"
283
- disabled={submitting}
284
- required
285
- />
286
- </div>
287
-
288
- {error && <div className="text-sm font-semibold text-destructive">{error}</div>}
289
- {success && <div className="text-sm font-semibold text-emerald-600">{success}</div>}
290
-
291
- <div className="flex justify-end gap-3 pt-2">
292
- <Button
293
- type="button"
294
- variant="ghost"
295
- onClick={() => setIsFormOpen(false)}
296
- disabled={submitting}
297
- >
298
- {t("reviews.cancel")}
299
- </Button>
300
- <Button type="submit" disabled={submitting} className="min-w-[120px]">
301
- {submitting ? (
302
- <>
303
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
304
- {t("reviews.submitting")}
305
- </>
306
- ) : (
307
- t("reviews.submit_review")
308
- )}
309
- </Button>
310
- </div>
311
- </form>
312
- )}
313
-
314
- {/* Reviews List */}
315
- <div className="space-y-6">
316
- {optimisticReviews.length > 0 ? (
317
- optimisticReviews.map((review) => {
318
- const hasLiked = likedIds.includes(review.id) || review.tempHasReacted;
319
- const likeCount = (review.reactions as Record<string, number>)?.likes || 0;
320
- const reviewerName = review.profiles?.full_name || "Anonymous";
321
- const dateStr = new Date(review.created_at).toLocaleDateString(lang, {
322
- year: "numeric",
323
- month: "long",
324
- day: "numeric",
325
- });
326
-
327
- return (
328
- <div
329
- key={review.id}
330
- className="bg-card border border-border/60 rounded-2xl p-5 shadow-sm space-y-4 hover:border-border/100 transition-all duration-300"
331
- >
332
- {/* Reviewer Header */}
333
- <div className="flex items-center justify-between gap-4">
334
- <div className="flex items-center gap-3">
335
- <Avatar className="h-10 w-10 border">
336
- <AvatarImage src={review.profiles?.avatar_url || undefined} alt={reviewerName} />
337
- <AvatarFallback className="bg-primary/5 text-primary text-xs font-semibold">
338
- {getInitials(review.profiles)}
339
- </AvatarFallback>
340
- </Avatar>
341
- <div>
342
- <h4 className="text-sm font-semibold text-foreground leading-none">
343
- {reviewerName}
344
- </h4>
345
- <span className="text-[10px] text-muted-foreground mt-1.5 block" suppressHydrationWarning>
346
- {dateStr}
347
- </span>
348
- </div>
349
- </div>
350
-
351
- {/* Rating Stars */}
352
- <div className="flex items-center gap-0.5 text-amber-500">
353
- {Array.from({ length: 5 }).map((_, i) => (
354
- <Star
355
- key={i}
356
- className={cn(
357
- "h-4 w-4",
358
- i < review.rating ? "fill-amber-500 text-amber-500" : "text-slate-200 dark:text-slate-800"
359
- )}
360
- />
361
- ))}
362
- </div>
363
- </div>
364
-
365
- {/* Review Content */}
366
- <p className="text-sm text-slate-600 dark:text-slate-350 leading-relaxed whitespace-pre-line text-left">
367
- {review.content}
368
- </p>
369
-
370
- {/* Reaction Actions */}
371
- <div className="flex items-center pt-2">
372
- <button
373
- onClick={() => handleLike(review.id)}
374
- className={cn(
375
- "flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-full border transition-all active:scale-95",
376
- hasLiked
377
- ? "bg-primary/5 border-primary/20 text-primary"
378
- : "bg-background border-border text-muted-foreground hover:text-foreground hover:border-border/100"
379
- )}
380
- >
381
- <ThumbsUp className={cn("h-3.5 w-3.5", hasLiked && "fill-current")} />
382
- <span>{t("reviews.helpful")}</span>
383
- {likeCount > 0 && <span className="font-semibold ml-0.5">{likeCount}</span>}
384
- </button>
385
- </div>
386
- </div>
387
- );
388
- })
389
- ) : (
390
- !loading && (
391
- <div className="text-center py-12 border border-dashed rounded-2xl bg-slate-50/50 dark:bg-slate-900/10">
392
- <Star className="mx-auto h-8 w-8 text-slate-300 dark:text-slate-700" />
393
- <h3 className="mt-4 text-sm font-semibold text-foreground">{t("reviews.no_reviews")}</h3>
394
- <p className="mt-1 text-xs text-muted-foreground">
395
- {t("reviews.be_the_first")}
396
- </p>
397
- </div>
398
- )
399
- )}
400
-
401
- {/* Loading Spinner */}
402
- {loading && (
403
- <div className="flex justify-center py-6">
404
- <Loader2 className="h-6 w-6 animate-spin text-primary" />
405
- </div>
406
- )}
407
-
408
- {/* Load More */}
409
- {hasMore && !loading && (
410
- <div className="flex justify-center pt-2">
411
- <Button variant="outline" size="sm" onClick={handleLoadMore}>
412
- {t("reviews.load_more")}
413
- </Button>
414
- </div>
415
- )}
416
- </div>
417
- </div>
418
- );
419
- }
1
+ "use client";
2
+
3
+ import React, { useState, useEffect, useTransition, useOptimistic } from "react";
4
+ import { createClient } from "@nextblock-cms/db";
5
+ import { Button } from "@nextblock-cms/ui";
6
+ import { Textarea } from "@nextblock-cms/ui";
7
+ import { Avatar, AvatarFallback, AvatarImage } from "@nextblock-cms/ui";
8
+ import { submitInteraction, toggleReaction } from "../app/actions/interactions";
9
+ import { cn, useTranslations } from "@nextblock-cms/utils";
10
+ import { MessageSquare, ThumbsUp, Star, Loader2, PenTool } from "lucide-react";
11
+ import { StaffReplies, useStaffReplies } from "./StaffReplies";
12
+
13
+ interface ProductReviewsSectionProps {
14
+ productId: string;
15
+ }
16
+
17
+ export default function ProductReviewsSection({ productId }: ProductReviewsSectionProps) {
18
+ const { t, lang } = useTranslations();
19
+ const [reviews, setReviews] = useState<any[]>([]);
20
+ const [loading, setLoading] = useState(true);
21
+ const [page, setPage] = useState(0);
22
+ const [hasMore, setHasMore] = useState(true);
23
+ const [user, setUser] = useState<any>(null);
24
+
25
+ // Form states
26
+ const [isFormOpen, setIsFormOpen] = useState(false);
27
+ const [rating, setRating] = useState(5);
28
+ const [hoverRating, setHoverRating] = useState(0);
29
+ const [content, setContent] = useState("");
30
+ const [submitting, setSubmitting] = useState(false);
31
+ const [error, setError] = useState<string | null>(null);
32
+ const [success, setSuccess] = useState<string | null>(null);
33
+
34
+ // Liked interactions tracking
35
+ const [likedIds, setLikedIds] = useState<string[]>([]);
36
+ const [, startTransition] = useTransition();
37
+
38
+ // Optimistic reviews list
39
+ const [optimisticReviews, setOptimisticReviews] = useOptimistic(
40
+ reviews,
41
+ (state, { reviewId, hasReacted, count }: { reviewId: string; hasReacted: boolean; count: number }) =>
42
+ state.map((r) => {
43
+ if (r.id === reviewId) {
44
+ const reactions = { ...((r.reactions as Record<string, number>) || {}) };
45
+ reactions.likes = count;
46
+ return { ...r, reactions, tempHasReacted: hasReacted };
47
+ }
48
+ return r;
49
+ })
50
+ );
51
+
52
+ // Staff answers for the parents currently on screen. Keyed off the base list, not the
53
+ // optimistic one: a like never changes which replies exist.
54
+ const staffReplies = useStaffReplies(reviews.map((item: any) => item.id));
55
+
56
+ useEffect(() => {
57
+ // 1. Fetch user
58
+ const supabase = createClient();
59
+ supabase.auth.getUser().then(({ data: { user } }) => {
60
+ setUser(user);
61
+ });
62
+
63
+ // 2. Read liked interactions from cookies
64
+ const match = document.cookie.match(/reacted_interactions=([^;]+)/);
65
+ if (match) {
66
+ try {
67
+ setLikedIds(JSON.parse(decodeURIComponent(match[1])));
68
+ } catch (err) {
69
+ console.warn("Failed to parse liked interactions cookie:", err);
70
+ }
71
+ }
72
+
73
+ // 3. Load initial reviews
74
+ fetchReviews(0, true);
75
+ }, [productId]);
76
+
77
+ const fetchReviews = async (pageNum: number, isInitial = false) => {
78
+ setLoading(true);
79
+ const supabase = createClient();
80
+ const limit = 5;
81
+ const start = pageNum * limit;
82
+ const end = start + limit - 1;
83
+
84
+ try {
85
+ const { data, error: dbError } = await supabase
86
+ .from("cms_interactions" as any)
87
+ .select("*, profiles(full_name, avatar_url)")
88
+ .eq("product_id", productId)
89
+ .eq("type", "review")
90
+ .eq("status", "approved")
91
+ .order("created_at", { ascending: false })
92
+ .range(start, end);
93
+
94
+ if (dbError) throw dbError;
95
+
96
+ if (data) {
97
+ if (isInitial) {
98
+ setReviews(data);
99
+ setPage(0);
100
+ } else {
101
+ setReviews((prev) => [...prev, ...data]);
102
+ setPage(pageNum);
103
+ }
104
+ setHasMore(data.length === limit);
105
+ }
106
+ } catch (err) {
107
+ console.error("Error fetching reviews:", err);
108
+ } finally {
109
+ setLoading(false);
110
+ }
111
+ };
112
+
113
+ const handleLoadMore = () => {
114
+ fetchReviews(page + 1);
115
+ };
116
+
117
+ const handleLike = async (reviewId: string) => {
118
+ const isLiked = likedIds.includes(reviewId);
119
+ const review = reviews.find((r) => r.id === reviewId);
120
+ if (!review) return;
121
+
122
+ const currentLikes = (review.reactions as Record<string, number>)?.likes || 0;
123
+ const nextCount = isLiked ? Math.max(0, currentLikes - 1) : currentLikes + 1;
124
+
125
+ startTransition(async () => {
126
+ // Apply optimistic update
127
+ setOptimisticReviews({ reviewId, hasReacted: !isLiked, count: nextCount });
128
+
129
+ const res = await toggleReaction(reviewId);
130
+ if (res.success) {
131
+ // Update liked cookie state locally
132
+ if (isLiked) {
133
+ setLikedIds((prev) => prev.filter((id) => id !== reviewId));
134
+ } else {
135
+ setLikedIds((prev) => [...prev, reviewId]);
136
+ }
137
+ // Sync actual state
138
+ setReviews((prev) =>
139
+ prev.map((r) => {
140
+ if (r.id === reviewId) {
141
+ const reactions = { ...((r.reactions as Record<string, number>) || {}) };
142
+ reactions.likes = res.count ?? nextCount;
143
+ return { ...r, reactions };
144
+ }
145
+ return r;
146
+ })
147
+ );
148
+ }
149
+ });
150
+ };
151
+
152
+ const handleSubmitReview = async (e: React.FormEvent) => {
153
+ e.preventDefault();
154
+ if (!user) {
155
+ setError(t("reviews.login_to_write"));
156
+ return;
157
+ }
158
+
159
+ if (content.trim().length < 5) {
160
+ setError(lang === "fr" ? "Votre avis doit faire au moins 5 caractères." : "Your review must be at least 5 characters long.");
161
+ return;
162
+ }
163
+
164
+ setSubmitting(true);
165
+ setError(null);
166
+ setSuccess(null);
167
+
168
+ const res = await submitInteraction({
169
+ type: "review",
170
+ content: content.trim(),
171
+ rating,
172
+ productId,
173
+ });
174
+
175
+ setSubmitting(false);
176
+
177
+ if (res.error) {
178
+ setError(res.error);
179
+ } else {
180
+ setSuccess(t("reviews.success_pending"));
181
+ setContent("");
182
+ setRating(5);
183
+ // Close form after a brief delay
184
+ setTimeout(() => {
185
+ setIsFormOpen(false);
186
+ setSuccess(null);
187
+ }, 3000);
188
+ }
189
+ };
190
+
191
+ const getInitials = (profile: any) => {
192
+ if (profile?.full_name) {
193
+ return profile.full_name
194
+ .split(" ")
195
+ .map((n: string) => n[0])
196
+ .join("")
197
+ .toUpperCase()
198
+ .slice(0, 2);
199
+ }
200
+ return "U";
201
+ };
202
+
203
+ return (
204
+ <div className="space-y-8 max-w-4xl mx-auto px-4">
205
+ {/* Header */}
206
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b pb-6 gap-4">
207
+ <div>
208
+ <h2 className="text-2xl font-bold tracking-tight text-foreground flex items-center gap-2">
209
+ <MessageSquare className="h-6 w-6 text-primary" />
210
+ {t("reviews.customer_reviews")}
211
+ </h2>
212
+ <p className="text-sm text-muted-foreground mt-1 text-left">
213
+ {t("reviews.share_thoughts")}
214
+ </p>
215
+ </div>
216
+
217
+ {user ? (
218
+ <Button
219
+ onClick={() => setIsFormOpen(!isFormOpen)}
220
+ className="flex items-center gap-2 transition-all"
221
+ variant={isFormOpen ? "outline" : "default"}
222
+ >
223
+ <PenTool className="h-4 w-4" />
224
+ {isFormOpen ? t("reviews.cancel_review") : t("reviews.write_review")}
225
+ </Button>
226
+ ) : (
227
+ <p className="text-sm text-muted-foreground italic">
228
+ {t("reviews.login_to_write")}
229
+ </p>
230
+ )}
231
+ </div>
232
+
233
+ {/* Submission Form */}
234
+ {isFormOpen && (
235
+ <form
236
+ onSubmit={handleSubmitReview}
237
+ className="bg-card/50 border border-border/80 rounded-2xl p-6 shadow-sm space-y-4 animate-in fade-in slide-in-from-top-4 duration-300"
238
+ >
239
+ <h3 className="text-lg font-semibold text-foreground">{t("reviews.write_your_review")}</h3>
240
+
241
+ {/* Stars Selection */}
242
+ <div className="space-y-1.5">
243
+ <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block">
244
+ {t("reviews.rating")}
245
+ </label>
246
+ <div className="flex items-center gap-1.5">
247
+ {Array.from({ length: 5 }).map((_, i) => {
248
+ const starVal = i + 1;
249
+ const isActive = starVal <= (hoverRating || rating);
250
+ return (
251
+ <button
252
+ key={i}
253
+ type="button"
254
+ onClick={() => setRating(starVal)}
255
+ onMouseEnter={() => setHoverRating(starVal)}
256
+ onMouseLeave={() => setHoverRating(0)}
257
+ className="transition-transform active:scale-95 focus:outline-none"
258
+ aria-label={`Rate ${starVal} stars`}
259
+ >
260
+ <Star
261
+ className={cn(
262
+ "h-7 w-7 transition-colors",
263
+ isActive
264
+ ? "text-amber-500 fill-amber-500"
265
+ : "text-slate-300 dark:text-slate-700"
266
+ )}
267
+ />
268
+ </button>
269
+ );
270
+ })}
271
+ </div>
272
+ </div>
273
+
274
+ {/* Text Area */}
275
+ <div className="space-y-1.5">
276
+ <label
277
+ htmlFor="review-content"
278
+ className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block"
279
+ >
280
+ {t("reviews.description")}
281
+ </label>
282
+ <Textarea
283
+ id="review-content"
284
+ placeholder={t("reviews.description_placeholder")}
285
+ value={content}
286
+ onChange={(e) => setContent(e.target.value)}
287
+ className="min-h-[120px] focus:ring-1 focus:ring-primary"
288
+ disabled={submitting}
289
+ required
290
+ />
291
+ </div>
292
+
293
+ {error && <div className="text-sm font-semibold text-destructive">{error}</div>}
294
+ {success && <div className="text-sm font-semibold text-emerald-600">{success}</div>}
295
+
296
+ <div className="flex justify-end gap-3 pt-2">
297
+ <Button
298
+ type="button"
299
+ variant="ghost"
300
+ onClick={() => setIsFormOpen(false)}
301
+ disabled={submitting}
302
+ >
303
+ {t("reviews.cancel")}
304
+ </Button>
305
+ <Button type="submit" disabled={submitting} className="min-w-[120px]">
306
+ {submitting ? (
307
+ <>
308
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
309
+ {t("reviews.submitting")}
310
+ </>
311
+ ) : (
312
+ t("reviews.submit_review")
313
+ )}
314
+ </Button>
315
+ </div>
316
+ </form>
317
+ )}
318
+
319
+ {/* Reviews List */}
320
+ <div className="space-y-6">
321
+ {optimisticReviews.length > 0 ? (
322
+ optimisticReviews.map((review) => {
323
+ const hasLiked = likedIds.includes(review.id) || review.tempHasReacted;
324
+ const likeCount = (review.reactions as Record<string, number>)?.likes || 0;
325
+ const reviewerName = review.profiles?.full_name || "Anonymous";
326
+ const dateStr = new Date(review.created_at).toLocaleDateString(lang, {
327
+ year: "numeric",
328
+ month: "long",
329
+ day: "numeric",
330
+ });
331
+
332
+ return (
333
+ <div
334
+ key={review.id}
335
+ className="bg-card border border-border/60 rounded-2xl p-5 shadow-sm space-y-4 hover:border-border/100 transition-all duration-300"
336
+ >
337
+ {/* Reviewer Header */}
338
+ <div className="flex items-center justify-between gap-4">
339
+ <div className="flex items-center gap-3">
340
+ <Avatar className="h-10 w-10 border">
341
+ <AvatarImage src={review.profiles?.avatar_url || undefined} alt={reviewerName} />
342
+ <AvatarFallback className="bg-primary/5 text-primary text-xs font-semibold">
343
+ {getInitials(review.profiles)}
344
+ </AvatarFallback>
345
+ </Avatar>
346
+ <div>
347
+ <h4 className="text-sm font-semibold text-foreground leading-none">
348
+ {reviewerName}
349
+ </h4>
350
+ <span className="text-[10px] text-muted-foreground mt-1.5 block" suppressHydrationWarning>
351
+ {dateStr}
352
+ </span>
353
+ </div>
354
+ </div>
355
+
356
+ {/* Rating Stars */}
357
+ <div className="flex items-center gap-0.5 text-amber-500">
358
+ {Array.from({ length: 5 }).map((_, i) => (
359
+ <Star
360
+ key={i}
361
+ className={cn(
362
+ "h-4 w-4",
363
+ i < review.rating ? "fill-amber-500 text-amber-500" : "text-slate-200 dark:text-slate-800"
364
+ )}
365
+ />
366
+ ))}
367
+ </div>
368
+ </div>
369
+
370
+ {/* Review Content */}
371
+ <p className="text-sm text-slate-600 dark:text-slate-350 leading-relaxed whitespace-pre-line text-left">
372
+ {review.content}
373
+ </p>
374
+
375
+ {/* Reaction Actions */}
376
+ <div className="flex items-center pt-2">
377
+ <button
378
+ onClick={() => handleLike(review.id)}
379
+ className={cn(
380
+ "flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-full border transition-all active:scale-95",
381
+ hasLiked
382
+ ? "bg-primary/5 border-primary/20 text-primary"
383
+ : "bg-background border-border text-muted-foreground hover:text-foreground hover:border-border/100"
384
+ )}
385
+ >
386
+ <ThumbsUp className={cn("h-3.5 w-3.5", hasLiked && "fill-current")} />
387
+ <span>{t("reviews.helpful")}</span>
388
+ {likeCount > 0 && <span className="font-semibold ml-0.5">{likeCount}</span>}
389
+ </button>
390
+ </div>
391
+
392
+ <StaffReplies replies={staffReplies[review.id]} />
393
+ </div>
394
+ );
395
+ })
396
+ ) : (
397
+ !loading && (
398
+ <div className="text-center py-12 border border-dashed rounded-2xl bg-slate-50/50 dark:bg-slate-900/10">
399
+ <Star className="mx-auto h-8 w-8 text-slate-300 dark:text-slate-700" />
400
+ <h3 className="mt-4 text-sm font-semibold text-foreground">{t("reviews.no_reviews")}</h3>
401
+ <p className="mt-1 text-xs text-muted-foreground">
402
+ {t("reviews.be_the_first")}
403
+ </p>
404
+ </div>
405
+ )
406
+ )}
407
+
408
+ {/* Loading Spinner */}
409
+ {loading && (
410
+ <div className="flex justify-center py-6">
411
+ <Loader2 className="h-6 w-6 animate-spin text-primary" />
412
+ </div>
413
+ )}
414
+
415
+ {/* Load More */}
416
+ {hasMore && !loading && (
417
+ <div className="flex justify-center pt-2">
418
+ <Button variant="outline" size="sm" onClick={handleLoadMore}>
419
+ {t("reviews.load_more")}
420
+ </Button>
421
+ </div>
422
+ )}
423
+ </div>
424
+ </div>
425
+ );
426
+ }