summaryrefslogtreecommitdiff
path: root/src-migrate/modules/product-detail/components/ProductDetail.tsx
blob: e4ba2b2ff63d227bab16a268f8640734b04e31d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import style from '../styles/product-detail.module.css';

import Link from 'next/link';
import { useRouter } from 'next/router';
import { useEffect, useRef, useState, UIEvent } from 'react';

import { Button } from '@chakra-ui/react';
import {
  AlertCircle,
  AlertTriangle,
  MessageCircleIcon,
  Share2Icon,
} from 'lucide-react';
import { LazyLoadComponent } from 'react-lazy-load-image-component';

import useDevice from '@/core/hooks/useDevice';
import { getAuth } from '~/libs/auth';
import { whatsappUrl } from '~/libs/whatsappUrl';
import ProductPromoSection from '~/modules/product-promo/components/Section';
import { IProductDetail } from '~/types/product';
import { useProductDetail } from '../stores/useProductDetail';
import AddToWishlist from './AddToWishlist';
import Breadcrumb from './Breadcrumb';
import ProductImage from './Image';
import Information from './Information';
import PriceAction from './PriceAction';
import SimilarBottom from './SimilarBottom';
import SimilarSide from './SimilarSide';
import dynamic from 'next/dynamic';

import { gtagProductDetail } from '@/core/utils/googleTag';

type Props = {
  product: IProductDetail;
};

const RWebShare = dynamic(
  () => import('react-web-share').then((m) => m.RWebShare),
  { ssr: false }
);

const SELF_HOST = process.env.NEXT_PUBLIC_SELF_HOST;

const ProductDetail = ({ product }: Props) => {
  const { isDesktop, isMobile } = useDevice();
  const router = useRouter();
  const [auth, setAuth] = useState<any>(null);
  useEffect(() => {
    try {
      setAuth(getAuth() ?? null);
    } catch {}
  }, []);

  const canShare =
    typeof navigator !== 'undefined' &&
    typeof (navigator as any).share === 'function';

  const {
    setAskAdminUrl,
    askAdminUrl,
    activeVariantId,
    setIsApproval,
    isApproval,
    setSelectedVariant,
    setSla,
  } = useProductDetail();

  useEffect(() => {
    gtagProductDetail(product);
  }, [product]);

  useEffect(() => {
    const createdAskUrl = whatsappUrl({
      template: 'product',
      payload: {
        manufacture: product.manufacture.name,
        productName: product.name,
        url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath,
      },
      fallbackUrl: router.asPath,
    });

    setAskAdminUrl(createdAskUrl);
  }, [router.asPath, product.manufacture.name, product.name, setAskAdminUrl]);

  useEffect(() => {
    if (typeof auth === 'object') {
      setIsApproval(auth?.feature?.soApproval);
    }
    const selectedVariant =
      product?.variants?.find((variant) => variant.is_in_bu) ||
      product?.variants?.[0];
    setSelectedVariant(selectedVariant);
  }, []);

  const allImages = (() => {
    const arr: string[] = [];
    if (product?.image) arr.push(product.image);
    if (
      Array.isArray(product?.image_carousel) &&
      product.image_carousel.length
    ) {
      const set = new Set(arr);
      for (const img of product.image_carousel) {
        if (!set.has(img)) {
          arr.push(img);
          set.add(img);
        }
      }
    }
    return arr;
  })();

  const [mainImage, setMainImage] = useState(allImages[0] || '');
  const hasPrice = Number(product?.lowest_price?.price) > 0;

  useEffect(() => {
    if (!allImages.includes(mainImage)) {
      setMainImage(allImages[0] || '');
    }
  }, [allImages]);

  const sliderRef = useRef<HTMLDivElement | null>(null);
  const [currentIdx, setCurrentIdx] = useState(0);

  const handleMobileScroll = (e: UIEvent<HTMLDivElement>) => {
    const el = e.currentTarget;
    if (!el) return;
    const idx = Math.round(el.scrollLeft / el.clientWidth);
    if (idx !== currentIdx) {
      setCurrentIdx(idx);
      setMainImage(allImages[idx] || '');
    }
  };

  const scrollToIndex = (i: number) => {
    const el = sliderRef.current;
    if (!el) return;
    el.scrollTo({ left: i * el.clientWidth, behavior: 'smooth' });
    setCurrentIdx(i);
    setMainImage(allImages[i] || '');
  };

  return (
    <>
      <div className='relative'>
        {isDesktop && !hasPrice && (
          <div className='absolute inset-0 z-[20] flex items-center justify-center pointer-events-none select-none'>
            <img
              src='/images/produk_tidak_tersedia.svg'
              alt='Produk tidak tersedia'
              className='w-[47%] opacity-50 -translate-x-[3%]  -translate-y-[-70%]'
            />
          </div>
        )}
      </div>

      <div className='relative'>
        {isMobile && !hasPrice && (
          <div className='absolute inset-0 z-[50] flex items-center justify-center pointer-events-none select-none'>
            <img
              src='/images/produk_tidak_tersedia.svg'
              alt='Produk tidak tersedia'
              className='w-[100%] opacity-[1000%] -translate-x-[0%]  -translate-y-[-197%]'
            />
          </div>
        )}
      </div>

      <div className='md:flex md:flex-wrap'>
        <div className='w-full mb-4 md:mb-0 px-4 md:px-0'>
          <Breadcrumb id={product.id} name={product.name} />
        </div>

        <div className='md:w-9/12 md:flex md:flex-col md:pr-4 md:pt-6'>
          <div className='md:flex md:flex-wrap'>
            {/* ===== Kolom kiri: gambar ===== */}
            <div className='md:w-4/12'>
              {/* === MOBILE: Slider swipeable, tanpa thumbnail carousel === */}
              {isMobile ? (
                <div className='relative'>
                  <div
                    ref={sliderRef}
                    onScroll={handleMobileScroll}
                    className='flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar'
                    style={{
                      scrollBehavior: 'smooth',
                      msOverflowStyle: 'none',
                      scrollbarWidth: 'none',
                    }}
                  >
                    {allImages.length > 0 ? (
                      allImages.map((img, i) => (
                        <div
                          key={i}
                          className='w-full flex-shrink-0 snap-center flex justify-center items-center'
                        >
                          {/* gambar diperkecil */}
                          <img
                            src={img}
                            alt={`Gambar ${i + 1}`}
                            className='w-[85%] aspect-square object-contain'
                            onError={(e) => {
                              (e.target as HTMLImageElement).src =
                                '/images/noimage.jpeg';
                            }}
                          />
                        </div>
                      ))
                    ) : (
                      <div className='w-full flex-shrink-0 snap-center flex justify-center items-center'>
                        <img
                          src={mainImage || '/images/noimage.jpeg'}
                          alt='Gambar produk'
                          className='w-[85%] aspect-square object-contain'
                        />
                      </div>
                    )}
                  </div>

                  {/* Dots indicator */}
                  {allImages.length > 1 && (
                    <div className='absolute bottom-2 left-0 right-0 flex justify-center gap-2'>
                      {allImages.map((_, i) => (
                        <button
                          key={i}
                          aria-label={`Ke slide ${i + 1}`}
                          className={`w-2 h-2 rounded-full ${
                            currentIdx === i ? 'bg-gray-800' : 'bg-gray-300'
                          }`}
                          onClick={() => scrollToIndex(i)}
                        />
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                <>
                  {/* === DESKTOP: Tetap seperti sebelumnya === */}
                  <ProductImage product={{ ...product, image: mainImage }} />

                  {/* Carousel horizontal (thumbnail) – hanya desktop */}
                  {allImages.length > 0 && (
                    <div className='mt-4 overflow-x-auto'>
                      <div className='flex space-x-3 pb-3'>
                        {allImages.map((img, index) => (
                          <div
                            key={index}
                            className={`flex-shrink-0 w-16 h-16 cursor-pointer border-2 rounded-md transition-colors ${
                              mainImage === img
                                ? 'border-red-500 ring-2 ring-red-200'
                                : 'border-gray-200 hover:border-gray-300'
                            }`}
                            onClick={() => setMainImage(img)}
                          >
                            <img
                              src={img}
                              alt={`Thumbnail ${index + 1}`}
                              className='w-full h-full object-cover rounded-sm'
                              loading='lazy'
                              onError={(e) => {
                                (e.target as HTMLImageElement).src =
                                  '/images/noimage.jpeg';
                              }}
                            />
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>
            {/* <<=== TUTUP kolom kiri */}

            {/* ===== Kolom kanan: info ===== */}
            {isDesktop && (
              <div className='md:w-8/12 px-4 md:pl-6'>
                {!hasPrice && (
                  <div className='bg-red-50 p-2 py-1.5 rounded-lg border border-red-500 flex gap-1 items-center '>
                    <AlertTriangle
                      size={18}
                      className='text-red-600 shrink-0 mx-2'
                    />
                    <h1 className='text-red-600 font-normal text-h-sm'>
                      Maaf untuk saat ini Produk yang anda cari tidak tersedia
                    </h1>
                  </div>
                )}
                <div className='h-6 md:h-0' />
                <h1 className={style['title']}>{product.name}</h1>
                <div className='h-3 md:h-0' />
                <Information product={product} />
                <div className='h-6' />
              </div>
            )}
            {isMobile && (
              <div className='md:w-8/12 px-4 md:pl-6 relative'>
                {!hasPrice && (
                  <div className='bg-red-50 p-2 py-1.5 border-b border-red-500 flex gap-1 items-center w-screen relative left-1/2 right-1/2 -translate-x-1/2'>
                    <AlertTriangle
                      size={18}
                      className='text-red-600 shrink-0 mx-2'
                    />
                    <h1 className='text-red-600 font-normal text-h-sm'>
                      Maaf untuk saat ini Produk yang anda cari tidak tersedia
                    </h1>
                  </div>
                )}
                <h1 className={style['title']}>{product.name}</h1>
                <div className='h-3 md:h-0' />
                <Information product={product} />
                <div className='h-6' />
              </div>
            )}
          </div>

          <div className='h-full'>
            {isMobile && (
              <div className='px-4 pt-6'>
                <PriceAction product={product} />
              </div>
            )}

            <div className='h-4 md:h-10' />
            {!!activeVariantId && !isApproval && (
              <ProductPromoSection
                product={product}
                productId={activeVariantId}
              />
            )}

            <div className='h-0 md:h-6' />

            <div className={style['section-card']}>
              <h2 className={style['heading']}>Informasi Produk</h2>
              <div className='h-4' />
              <div className='overflow-x-auto'>
                <div
                  className={style['description']}
                  dangerouslySetInnerHTML={{
                    __html:
                      !product.description ||
                      product.description == '<p><br></p>'
                        ? 'Belum ada deskripsi'
                        : product.description,
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        {isDesktop && (
          <div className='md:w-3/12'>
            <PriceAction product={product} />
            <div className='flex gap-x-5 items-center justify-center'>
              <Button
                as={Link}
                href={askAdminUrl}
                variant='link'
                target='_blank'
                colorScheme='gray'
                leftIcon={<MessageCircleIcon size={18} />}
                isDisabled={!hasPrice}
              >
                Ask Admin
              </Button>

              <span>|</span>

              <div className={hasPrice ? '' : 'opacity-40 pointer-events-none'}>
                <AddToWishlist productId={product.id} />
              </div>

              <span>|</span>

              {canShare && (
                <RWebShare
                  data={{
                    text: 'Check out this product',
                    title: `${product.name} - Indoteknik.com`,
                    url:
                      (process.env.NEXT_PUBLIC_SELF_HOST || '') +
                      (router?.asPath || '/'),
                  }}
                >
                  <Button
                    variant='link'
                    colorScheme='gray'
                    leftIcon={<Share2Icon size={18} />}
                    isDisabled={!hasPrice}
                  >
                    Share
                  </Button>
                </RWebShare>
              )}
            </div>

            <div className='h-6' />
            <div className={style['heading']}>Produk Serupa</div>

            <div className='h-4' />

            <SimilarSide product={product} />
          </div>
        )}

        <div className='md:w-full pt-4 md:py-10 px-4 md:px-0'>
          <div className={style['heading']}>Kamu Mungkin Juga Suka</div>

          <div className='h-6' />

          <LazyLoadComponent>
            <SimilarBottom product={product} />
          </LazyLoadComponent>
        </div>

        <div className='h-6 md:h-0' />
      </div>
    </>
  );
};

export default ProductDetail;