diff --git a/scripts/verify-product-gallery.mjs b/scripts/verify-product-gallery.mjs new file mode 100644 index 0000000..e489b3a --- /dev/null +++ b/scripts/verify-product-gallery.mjs @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; + +const pagePath = path.join(process.cwd(), 'src/pages/catalog/ShopSinglePage.tsx'); +const src = fs.readFileSync(pagePath, 'utf8'); + +assert.ok(!src.includes('indicator-carousel-dots.svg'), 'Static carousel dots SVG must be removed'); +assert.ok(src.includes('liveProduct.media'), 'Gallery must bind to product.media'); + +const resolveMediaUrl = (u) => (!u ? '' : u.startsWith('http') || u.startsWith('/') ? u : `/${u}`); +function buildSlides(liveProduct, useMockFallback, title = 'Islam in the Bible Book') { + if (liveProduct) { + const slides = (Array.isArray(liveProduct.media) ? liveProduct.media : []) + .slice() + .sort((a, b) => a.sort_order - b.sort_order || a.id - b.id) + .map((m, i) => ({ id: `media-${m.id}-${i}`, src: resolveMediaUrl(m.image_url), alt: m.alt_text || title })) + .filter((s) => Boolean(s.src)); + if (slides.length > 0) return slides; + return [{ id: 'hero-fallback', src: resolveMediaUrl(liveProduct.hero_image_url || liveProduct.primary_image_url) || '/assets/images/product-duffel-bag-hero.png', alt: title }]; + } + return useMockFallback ? ['/assets/images/product-duffel-bag-hero.png', '/assets/images/product-brown-leather-bag.png', '/assets/images/product-boby-backpack.png'].map((s, i) => ({ id: `mock-${i + 1}`, src: s, alt: title })) : []; +} + +// 1. Sorts media by sort_order then id, filters empty URLs, falls back alt_text to title +const sorted = buildSlides({ + media: [ + { id: 9, image_url: 'media/b.jpg', alt_text: 'Side', sort_order: 2 }, + { id: 4, image_url: '', alt_text: 'Empty', sort_order: 0 }, + { id: 5, image_url: '/media/a.jpg', alt_text: '', sort_order: 1 }, + ], +}, false, 'Leather Bag'); +assert.deepEqual(sorted.map((s) => [s.src, s.alt]), [['/media/a.jpg', 'Leather Bag'], ['/media/b.jpg', 'Side']]); + +// 2. Falls back to hero/primary when media[] is empty +const fallback = buildSlides({ media: [], hero_image_url: '', primary_image_url: 'media/p.jpg' }, false, 'Book'); +assert.equal(fallback.length, 1); +assert.equal(fallback[0].src, '/media/p.jpg'); + +// 3. Empty when no liveProduct and mock disabled; 3 slides when mock enabled +assert.equal(buildSlides(null, false).length, 0); +assert.equal(buildSlides(null, true).length, 3); + +console.log('PASS: Product gallery assertions passed.'); diff --git a/scripts/verify-product-reviews.mjs b/scripts/verify-product-reviews.mjs new file mode 100644 index 0000000..082f3bd --- /dev/null +++ b/scripts/verify-product-reviews.mjs @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; + +const singlePage = fs.readFileSync( + path.join(process.cwd(), 'src/pages/catalog/ShopSinglePage.tsx'), + 'utf8' +); +const shopApiSrc = fs.readFileSync( + path.join(process.cwd(), 'src/lib/shopApi.ts'), + 'utf8' +); + +// 1. ShopSinglePage uses reviewsCount backed by liveProduct.reviews_count instead of displayReviews.length +assert.ok(singlePage.includes('liveProduct.reviews_count')); +assert.ok(!singlePage.includes('Review(${displayReviews.length})')); +assert.ok(!singlePage.includes('Customer Reviews (${displayReviews.length})')); +assert.ok(singlePage.includes('resolveMediaUrl(r.image_url)')); +assert.ok(singlePage.includes('review.imageUrl &&')); + +// 2. reviewsCount logic handles >20 cap, seeded count, and fallback +function computeReviewsCount(liveProduct, displayReviewsLen) { + return liveProduct + ? Math.max(liveProduct.reviews_count ?? 0, displayReviewsLen) + : displayReviewsLen; +} +assert.equal(computeReviewsCount({ reviews_count: 47 }, 20), 47); +assert.equal(computeReviewsCount({ reviews_count: 12 }, 0), 12); +assert.equal(computeReviewsCount({ reviews_count: 0 }, 2), 2); +assert.equal(computeReviewsCount(null, 3), 3); + +// 3. createProductReview builds FormData when File is provided and keeps JSON otherwise +assert.ok(shopApiSrc.includes("form.append('image', payload.image)")); +function buildReviewBody(payload) { + if (payload.image) { + const form = new FormData(); + form.append('rating', String(payload.rating)); + form.append('comment', payload.comment); + form.append('image', payload.image); + if (payload.author_name) form.append('author_name', payload.author_name); + return form; + } + return payload; +} +const jsonBody = buildReviewBody({ rating: 5, comment: 'Great!' }); +assert.ok(!(jsonBody instanceof FormData)); +const file = new File([new Uint8Array([137, 80, 78, 71])], 'photo.png', { type: 'image/png' }); +const multipartBody = buildReviewBody({ rating: 4, comment: 'Nice!', image: file, author_name: 'Ali' }); +assert.ok(multipartBody instanceof FormData); +assert.equal(multipartBody.get('rating'), '4'); +assert.equal(multipartBody.get('comment'), 'Nice!'); +assert.equal(multipartBody.get('author_name'), 'Ali'); +assert.equal(multipartBody.get('image')?.name, 'photo.png'); + +console.log('PASS: Product review count & multipart image assertions passed.'); diff --git a/src/context/ShopAppContext.tsx b/src/context/ShopAppContext.tsx index ea12931..bc98bcd 100644 --- a/src/context/ShopAppContext.tsx +++ b/src/context/ShopAppContext.tsx @@ -412,6 +412,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ }, [queryClient]); const refreshCart = useCallback(async () => { + void queryClient.invalidateQueries({ + queryKey: shopKeys.checkoutSummariesAll(), + }); if (!getToken()) { await queryClient.invalidateQueries({ queryKey: shopKeys.cart() }); return; @@ -628,6 +631,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ quantity, }); queryClient.setQueryData(shopKeys.cart(), updated); + void queryClient.invalidateQueries({ + queryKey: shopKeys.checkoutSummariesAll(), + }); void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); showToast('Added to cart'); return updated; @@ -647,6 +653,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ try { const updated = await shopApi.updateCartItem(itemId, quantity); queryClient.setQueryData(shopKeys.cart(), updated); + void queryClient.invalidateQueries({ + queryKey: shopKeys.checkoutSummariesAll(), + }); void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); } catch (err) { showToast(err instanceof Error ? err.message : 'Could not update cart'); @@ -663,6 +672,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ try { const updated = await shopApi.removeCartItem(itemId); queryClient.setQueryData(shopKeys.cart(), updated); + void queryClient.invalidateQueries({ + queryKey: shopKeys.checkoutSummariesAll(), + }); void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); } catch (err) { showToast(err instanceof Error ? err.message : 'Could not remove item'); @@ -678,6 +690,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ try { const updated = await shopApi.clearCart(); queryClient.setQueryData(shopKeys.cart(), updated); + void queryClient.invalidateQueries({ + queryKey: shopKeys.checkoutSummariesAll(), + }); void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); } catch (err) { showToast(err instanceof Error ? err.message : 'Could not clear cart'); diff --git a/src/data/accountData.ts b/src/data/accountData.ts index e68202c..413bbdc 100644 --- a/src/data/accountData.ts +++ b/src/data/accountData.ts @@ -93,11 +93,11 @@ export const SHOP_ACCOUNT_MENU_ROWS: AccountMenuRowItem[] = [ subtitle: 'Name, contact number, email, etc.', subtitleWidth: 155, iconBoxBg: 'rgba(21, 28, 49, 0.1)', - iconSrc: '/assets/images/icon-menu-saved-bookmark.svg', - iconLeft: 9, - iconTop: 7, - iconWidth: 14, - iconHeight: 18, + iconSrc: '/assets/images/standalone-user-filled-icon.svg', + iconLeft: 5, + iconTop: 5, + iconWidth: 24, + iconHeight: 24, rightIconType: 'none', targetRoute: '/provider-requst', }, diff --git a/src/lib/cookies.ts b/src/lib/cookies.ts index 0ddf730..24ab427 100644 --- a/src/lib/cookies.ts +++ b/src/lib/cookies.ts @@ -611,6 +611,16 @@ const FA_DICTIONARY: Record = { 'ثبت تیکت پشتیبانی امکان‌پذیر نیست. لطفاً دوباره تلاش کنید.', 'Ticket Submitted!': 'تیکت ثبت شد!', 'Submit Ticket': 'ثبت تیکت', + 'Submitted Tickets': 'تیکت‌های ثبت‌شده', + Open: 'باز', + Resolved: 'پاسخ داده شده', + 'Support Reply': 'پاسخ پشتیبانی', + 'View attachment': 'مشاهده پیوست', + 'No support tickets submitted yet.': 'هنوز تیکت پشتیبانی ثبت نشده است.', + 'Could not load support tickets. Tap Retry to refresh.': + 'بارگذاری تیکت‌های پشتیبانی امکان‌پذیر نبود. برای تلاش مجدد ضربه بزنید.', + 'Sign in to view your submitted tickets.': + 'برای مشاهده تیکت‌های ثبت‌شده خود وارد حساب کاربری شوید.', // Chat Online: 'آنلاین', @@ -1172,6 +1182,16 @@ const AR_DICTIONARY: Record = { 'تعذر إرسال تذكرة الدعم. يرجى المحاولة مرة أخرى.', 'Ticket Submitted!': 'تم إرسال التذكرة!', 'Submit Ticket': 'إرسال التذكرة', + 'Submitted Tickets': 'التذاكر المرسلة', + Open: 'مفتوحة', + Resolved: 'تم الحل', + 'Support Reply': 'رد الدعم', + 'View attachment': 'عرض المرفق', + 'No support tickets submitted yet.': 'لم يتم إرسال أي تذاكر دعم بعد.', + 'Could not load support tickets. Tap Retry to refresh.': + 'تعذر تحميل تذاكر الدعم. اضغط على إعادة المحاولة للتحديث.', + 'Sign in to view your submitted tickets.': + 'سجل الدخول لعرض تذاكر الدعم المرسلة.', // Chat Online: 'متصل', diff --git a/src/lib/shopApi.ts b/src/lib/shopApi.ts index 0c5d5b1..3d6f871 100644 --- a/src/lib/shopApi.ts +++ b/src/lib/shopApi.ts @@ -138,12 +138,15 @@ export interface ApiCartItem { } export interface ApiCartPricing { + currency?: string; items_count: number; total_quantity: number; total_units?: number; shops_count: number; subtotal: string; formatted_subtotal: string; + compare_subtotal?: string; + formatted_compare_subtotal?: string | null; shipping_fee: string; formatted_shipping_fee: string; total: string; @@ -437,12 +440,27 @@ export const shopApi = { createProductReview: ( idOrSlug: string | number, - payload: { rating: number; comment: string; author_name?: string; image_url?: string } - ) => - shopRequest( + payload: { + rating: number; + comment: string; + author_name?: string; + image?: File; + } + ) => { + let body: BodyInit | Record = payload; + if (payload.image) { + const form = new FormData(); + form.append('rating', String(payload.rating)); + form.append('comment', payload.comment); + form.append('image', payload.image); + if (payload.author_name) form.append('author_name', payload.author_name); + body = form; + } + return shopRequest( `/products/${encodeURIComponent(String(idOrSlug))}/reviews/`, - { method: 'POST', body: payload } - ), + { method: 'POST', body } + ); + }, fetchStores: (q?: string) => shopRequest<{ count: number; results: ApiStoreSummary[] }>('/stores/', { @@ -502,6 +520,7 @@ export const shopApi = { shipping_address?: Record; shipping_method?: string | number; payment_method: string; + confirm_payment?: boolean; notes?: string; }) => shopRequest('/orders/', { method: 'POST', body: payload }), diff --git a/src/lib/shopQueries.ts b/src/lib/shopQueries.ts index aac70ac..5198e82 100644 --- a/src/lib/shopQueries.ts +++ b/src/lib/shopQueries.ts @@ -11,6 +11,7 @@ import { type ApiOrderDetail, type ApiProductCard, type ApiProductDetail, + type ApiSupportTicket, type ApiUserProfile, shopApi, } from './shopApi'; @@ -53,6 +54,9 @@ export const shopKeys = { storeDetail: (idOrSlug: string | number) => ['shop', 'store', String(idOrSlug)] as const, cart: () => ['shop', 'cart'] as const, + checkoutSummariesAll: () => ['shop', 'checkout-summary'] as const, + checkoutSummary: (shippingMethod?: string | number) => + ['shop', 'checkout-summary', String(shippingMethod ?? '')] as const, shippingMethods: () => ['shop', 'shipping-methods'] as const, paymentMethods: () => ['shop', 'payment-methods'] as const, ordersAll: () => ['shop', 'orders'] as const, @@ -108,6 +112,7 @@ export function findCachedCategoryBySlug( } export function clearUserScopedCache(queryClient: QueryClient): void { + queryClient.removeQueries({ queryKey: shopKeys.checkoutSummariesAll() }); queryClient.removeQueries({ queryKey: shopKeys.ordersAll() }); queryClient.removeQueries({ queryKey: shopKeys.orderDetailsAll() }); queryClient.removeQueries({ queryKey: shopKeys.orderReceiptsAll() }); @@ -221,6 +226,17 @@ export function useOrderReceiptQuery(orderNumber: string, enabled = true) { }); } +export function useCheckoutSummaryQuery( + shippingMethod?: string | number, + enabled = true +) { + return useQuery({ + queryKey: shopKeys.checkoutSummary(shippingMethod), + queryFn: () => shopApi.fetchCheckoutSummary(shippingMethod), + enabled, + }); +} + export function usePaymentMethodsQuery(enabled = true) { return useQuery({ queryKey: shopKeys.paymentMethods(), @@ -238,6 +254,14 @@ export function useSupportSubjectsQuery(enabled = true) { }); } +export function useSupportTicketsQuery(enabled = true) { + return useQuery({ + queryKey: shopKeys.supportTickets(), + queryFn: () => shopApi.fetchSupportTickets(), + enabled, + }); +} + export function useChatMessagesQuery( pkOrSlug: string | number, enabled = true @@ -259,12 +283,7 @@ export function useCreateReviewMutation() { }: { productRef: string | number; routeRef?: string | number; - payload: { - rating: number; - comment: string; - author_name?: string; - image_url?: string; - }; + payload: Parameters[1]; }) => shopApi.createProductReview(productRef, payload), onSuccess: (created, variables) => { const refs = new Set( @@ -308,6 +327,9 @@ export function usePlaceOrderMutation() { order ); void queryClient.invalidateQueries({ queryKey: shopKeys.cart() }); + void queryClient.invalidateQueries({ + queryKey: shopKeys.checkoutSummariesAll(), + }); void queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() }); void queryClient.invalidateQueries({ queryKey: shopKeys.orderCounters(), @@ -360,7 +382,20 @@ export function useCreateSupportTicketMutation() { return useMutation({ mutationFn: (payload: Parameters[0]) => shopApi.createSupportTicket(payload), - onSuccess: () => { + onSuccess: (created) => { + queryClient.setQueryData<{ count: number; results: ApiSupportTicket[] }>( + shopKeys.supportTickets(), + (old) => { + if (!old) return { count: 1, results: [created] }; + const filtered = old.results.filter((t) => t.id !== created.id); + return { + ...old, + count: + filtered.length === old.results.length ? old.count + 1 : old.count, + results: [created, ...filtered], + }; + } + ); void queryClient.invalidateQueries({ queryKey: shopKeys.supportTickets(), }); diff --git a/src/pages/catalog/ShopBoothPage.tsx b/src/pages/catalog/ShopBoothPage.tsx index 8240826..5546a44 100644 --- a/src/pages/catalog/ShopBoothPage.tsx +++ b/src/pages/catalog/ShopBoothPage.tsx @@ -72,7 +72,7 @@ export const ShopBoothPage: React.FC = () => { return ( - {/* Top Store Logo Backdrop & Floating Actions */} + {/* Top Banner Calligraphy Image & Floating Actions */}
{ flexShrink: 0, }} > - {isStoreShimmer ? ( - - ) : ( - - )} +
{ const [activeTab, setActiveTab] = useState<'info' | 'review'>('info'); const [reviewRating, setReviewRating] = useState(5); const [reviewComment, setReviewComment] = useState(''); + const [reviewImage, setReviewImage] = useState<{ + file: File; + previewUrl: string; + isObjectUrl: boolean; + } | null>(null); + const [pickingReviewImage, setPickingReviewImage] = useState(false); + const reviewFileInputRef = useRef(null); + + useEffect(() => { + return () => { + if (reviewImage?.isObjectUrl) { + URL.revokeObjectURL(reviewImage.previewUrl); + } + }; + }, [reviewImage]); const resolvedRef = productId || 'islam-in-the-bible-book'; + const [slideState, setSlideState] = useState<{ ref: string; index: number }>({ + ref: resolvedRef, + index: 0, + }); + const [dragOffset, setDragOffset] = useState(0); + const [isDragging, setIsDragging] = useState(false); + const [heroEl, setHeroEl] = useState(null); + const dragStartRef = useRef<{ + id: number; + x: number; + y: number; + lastX: number; + time: number; + locked: 'x' | null; + } | null>(null); + const wheelCooldownRef = useRef(0); const productQuery = useProductDetailQuery(resolvedRef, !isBare); const createReviewMutation = useCreateReviewMutation(); @@ -133,6 +170,62 @@ export const ShopSinglePage: React.FC = () => { } }; + const stageReviewFile = ( + file: File, + previewUrl?: string, + isObjectUrl = false + ) => { + if (file.type && !file.type.startsWith('image/')) { + if (isObjectUrl && previewUrl) URL.revokeObjectURL(previewUrl); + showToast(tr('Failed to upload image. Please try another file.')); + return; + } + if (file.size > MAX_REVIEW_IMAGE_BYTES) { + if (isObjectUrl && previewUrl) URL.revokeObjectURL(previewUrl); + showToast('Image exceeds the 10 MB size limit'); + return; + } + setReviewImage({ + file, + previewUrl: previewUrl || URL.createObjectURL(file), + isObjectUrl: previewUrl ? isObjectUrl : true, + }); + }; + + const handlePickReviewImage = async () => { + if (isBare || submittingReview || pickingReviewImage) return; + if (isInFlutterWebView()) { + setPickingReviewImage(true); + try { + const picked = await pickFileViaFlutterBridge('image'); + if (!picked) return; + if (picked.file) { + stageReviewFile(picked.file, picked.url, Boolean(picked.isObjectUrl)); + return; + } + const resp = await fetch(resolveMediaUrl(picked.url)); + const blob = await resp.blob(); + stageReviewFile( + new File([blob], picked.name || `review-${Date.now()}.jpg`, { + type: blob.type || 'image/jpeg', + }) + ); + } catch { + showToast(tr('Failed to upload image. Please try another file.')); + } finally { + setPickingReviewImage(false); + } + return; + } + reviewFileInputRef.current?.click(); + }; + + const handleReviewFileChange = (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + e.target.value = ''; + if (file) stageReviewFile(file); + }; + const handleSubmitReview = async (e: React.FormEvent) => { e.preventDefault(); if (!reviewComment.trim() || submittingReview) return; @@ -149,19 +242,198 @@ export const ShopSinglePage: React.FC = () => { payload: { rating: reviewRating, comment: reviewComment.trim(), + image: reviewImage?.file, }, }); setReviewComment(''); + setReviewImage(null); showToast('Review submitted'); } catch (err) { showToast(err instanceof Error ? err.message : 'Could not post review'); } }; - const heroImageSrc = liveProduct - ? resolveMediaUrl(liveProduct.hero_image_url || liveProduct.primary_image_url) || - '/assets/images/product-duffel-bag-hero.png' - : '/assets/images/product-duffel-bag-hero.png'; + const productTitle = liveProduct?.title || 'Islam in the Bible Book'; + + const gallerySlides = useMemo(() => { + if (liveProduct) { + const mediaSlides = (Array.isArray(liveProduct.media) ? liveProduct.media : []) + .slice() + .sort((a, b) => a.sort_order - b.sort_order || a.id - b.id) + .map((m, idx) => ({ + id: `media-${m.id}-${idx}`, + src: resolveMediaUrl(m.image_url), + alt: m.alt_text || productTitle, + })) + .filter((s) => Boolean(s.src)); + + if (mediaSlides.length > 0) { + return mediaSlides; + } + + return [ + { + id: 'hero-fallback', + src: + resolveMediaUrl( + liveProduct.hero_image_url || liveProduct.primary_image_url + ) || '/assets/images/product-duffel-bag-hero.png', + alt: productTitle, + }, + ]; + } + + if (!useMockFallback) { + return []; + } + + return [ + { + id: 'mock-1', + src: '/assets/images/product-duffel-bag-hero.png', + alt: productTitle, + }, + { + id: 'mock-2', + src: '/assets/images/product-brown-leather-bag.png', + alt: productTitle, + }, + { + id: 'mock-3', + src: '/assets/images/product-boby-backpack.png', + alt: productTitle, + }, + ]; + }, [liveProduct, productTitle, useMockFallback]); + + const maxSlideIndex = Math.max(0, gallerySlides.length - 1); + const activeSlide = + slideState.ref === resolvedRef + ? Math.min(slideState.index, maxSlideIndex) + : 0; + + const setActiveSlide = (next: number | ((prev: number) => number)) => { + setSlideState((prev) => { + const current = + prev.ref === resolvedRef ? Math.min(prev.index, maxSlideIndex) : 0; + const raw = typeof next === 'function' ? next(current) : next; + return { + ref: resolvedRef, + index: Math.max(0, Math.min(maxSlideIndex, raw)), + }; + }); + }; + + useEffect(() => { + if (!heroEl) return; + // Consume horizontal touchmove so Android WebView / Flutter does not cancel the swipe + const onTouchMove = (e: TouchEvent) => { + if (dragStartRef.current?.locked === 'x' && e.cancelable) { + e.preventDefault(); + } + }; + heroEl.addEventListener('touchmove', onTouchMove, { passive: false }); + return () => { + heroEl.removeEventListener('touchmove', onTouchMove); + }; + }, [heroEl]); + + const handleGalleryPointerDown = (e: React.PointerEvent) => { + if (!e.isPrimary || gallerySlides.length <= 1) return; + if (e.pointerType === 'mouse' && e.button !== 0) return; + dragStartRef.current = { + id: e.pointerId, + x: e.clientX, + y: e.clientY, + lastX: e.clientX, + time: Date.now(), + locked: null, + }; + }; + + const handleGalleryPointerMove = (e: React.PointerEvent) => { + const start = dragStartRef.current; + if (!start || start.id !== e.pointerId) return; + + start.lastX = e.clientX; + const dx = e.clientX - start.x; + const dy = e.clientY - start.y; + + if (!start.locked) { + const absX = Math.abs(dx); + const absY = Math.abs(dy); + if (absX < 6 && absY < 8) return; + if (absY > absX) { + dragStartRef.current = null; + return; + } + start.locked = 'x'; + if (e.pointerType === 'mouse') { + e.currentTarget.setPointerCapture(e.pointerId); + } + setIsDragging(true); + } + + const atEdge = + (activeSlide === 0 && dx > 0) || + (activeSlide === gallerySlides.length - 1 && dx < 0); + setDragOffset(atEdge ? dx * 0.3 : dx); + }; + + const finishGalleryDrag = ( + e: React.PointerEvent, + cancelled = false + ) => { + const start = dragStartRef.current; + if (!start || start.id !== e.pointerId) return; + dragStartRef.current = null; + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + e.currentTarget.releasePointerCapture(e.pointerId); + } + + if (start.locked === 'x' && !cancelled) { + const endX = Number.isFinite(e.clientX) ? e.clientX : start.lastX; + const dx = endX - start.x; + const elapsed = Date.now() - start.time; + const threshold = Math.min(50, (e.currentTarget.clientWidth || 375) * 0.16); + const isQuickFlick = elapsed < 250 && Math.abs(dx) > 20; + + if (dx <= -threshold || (isQuickFlick && dx < 0)) { + setActiveSlide((prev) => prev + 1); + } else if (dx >= threshold || (isQuickFlick && dx > 0)) { + setActiveSlide((prev) => prev - 1); + } + } + + setIsDragging(false); + setDragOffset(0); + }; + + const handleGalleryWheel = (e: React.WheelEvent) => { + if ( + gallerySlides.length <= 1 || + Math.abs(e.deltaX) <= Math.abs(e.deltaY) || + Math.abs(e.deltaX) < 20 + ) { + return; + } + const now = Date.now(); + if (now - wheelCooldownRef.current < 450) return; + wheelCooldownRef.current = now; + setActiveSlide((prev) => (e.deltaX > 0 ? prev + 1 : prev - 1)); + }; + + const handleGalleryKeyDown = (e: React.KeyboardEvent) => { + if (gallerySlides.length <= 1) return; + if (e.key === 'ArrowRight') { + e.preventDefault(); + setActiveSlide((prev) => prev + 1); + } else if (e.key === 'ArrowLeft') { + e.preventDefault(); + setActiveSlide((prev) => prev - 1); + } + }; const displayReviews = !isBare && reviews @@ -171,10 +443,14 @@ export const ShopSinglePage: React.FC = () => { date: r.formatted_date, rating: r.rating, comment: r.comment, + imageUrl: resolveMediaUrl(r.image_url), })) : useMockFallback - ? STATIC_PRODUCT_REVIEWS + ? STATIC_PRODUCT_REVIEWS.map((r) => ({ ...r, imageUrl: '' })) : []; + const reviewsCount = liveProduct + ? Math.max(liveProduct.reviews_count ?? 0, displayReviews.length) + : displayReviews.length; const storeDetail = liveProduct?.store_detail; const storeSlug = storeDetail?.slug || liveProduct?.store_slug || 'al-hujjah-books'; @@ -183,18 +459,70 @@ export const ShopSinglePage: React.FC = () => { return ( - {/* Hero Product Image & Floating Top Controls */} -
+ {/* Hero Product Image Gallery & Floating Top Controls */} +
1 ? 'pan-y' : undefined }} + > {isProductShimmer ? ( - ) : !liveProduct && !useMockFallback ? ( + ) : gallerySlides.length === 0 ? (
) : ( - {liveProduct?.title +
finishGalleryDrag(e)} + onPointerCancel={(e) => finishGalleryDrag(e, true)} + onLostPointerCapture={(e) => { + if (e.target === e.currentTarget) finishGalleryDrag(e, true); + }} + style={{ + direction: 'ltr', + display: 'flex', + width: '100%', + height: '100%', + transform: `translateX(calc(-${activeSlide * 100}% + ${dragOffset}px))`, + transition: isDragging + ? 'none' + : 'transform 380ms cubic-bezier(0.22, 1, 0.36, 1)', + willChange: gallerySlides.length > 1 ? 'transform' : undefined, + touchAction: gallerySlides.length > 1 ? 'pan-y' : undefined, + userSelect: 'none', + cursor: + gallerySlides.length > 1 + ? isDragging + ? 'grabbing' + : 'grab' + : undefined, + }} + > + {gallerySlides.map((slide) => ( +
+ {slide.alt} +
+ ))} +
)} {/* Floating Top Action Row */} @@ -207,6 +535,8 @@ export const ShopSinglePage: React.FC = () => { display: 'flex', alignItems: 'center', justifyContent: 'space-between', + zIndex: 2, + pointerEvents: 'none', }} >
{/* Image Carousel Dots */} - {!isProductShimmer && ( - 1 && ( +
+ > + {gallerySlides.map((slide, idx) => { + const isActive = activeSlide === idx; + return ( + + ); + })} +
)}
@@ -545,8 +909,8 @@ export const ShopSinglePage: React.FC = () => { {tr( isBare ? '0 Reviews' - : `${displayReviews.length} ${ - displayReviews.length === 1 ? 'Review' : 'Reviews' + : `${reviewsCount} ${ + reviewsCount === 1 ? 'Review' : 'Reviews' }` )} @@ -915,7 +1279,7 @@ export const ShopSinglePage: React.FC = () => { transition: 'color 200ms cubic-bezier(0.22, 1, 0.36, 1)', }} > - {isProductShimmer ? tr('Review') : tr(`Review(${displayReviews.length})`)} + {isProductShimmer ? tr('Review') : tr(`Review(${reviewsCount})`)} {/* Active Tab Indicator Bar */} @@ -1053,7 +1417,7 @@ export const ShopSinglePage: React.FC = () => { > {isProductShimmer ? tr('Customer Reviews') - : tr(`Customer Reviews (${displayReviews.length})`)} + : tr(`Customer Reviews (${reviewsCount})`)}
{ ))}
+