All files / src/components/shared/QuickViewModal index.tsx

4.7% Statements 17/361
100% Branches 0/0
0% Functions 0/1
4.7% Lines 17/361

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3611x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
"use client";
import React, { useEffect, useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { useModalContext } from "@/contexts";
import { clientLogger } from '@/lib/logging/clientLogger';
import { AppDispatch, useAppSelector } from "@/redux/store";
import { updateQuickView } from "@/redux/features/quickViewSlice";
import { useDispatch } from "react-redux";
import Image from "next/image";
import { usePreviewSlider } from "@/contexts";
import { updateProductDetails } from "@/redux/features/productDetails";
import { Icon } from "@/components/ui/icons";
import { StarRating, PriceDisplay, DiscountBadge, Button } from "@/components/ui";
import { WishlistButton } from "@/components/features/product/WishlistButton";
import { useFunnelSteps } from "@/hooks/useFunnelTracking";
import { useProductActionsWithoutToast } from "@/hooks/useProductActions";
 
export default function QuickViewModal() {
  const router = useRouter();
  const { isModalOpen, closeModal, previewProductId } = useModalContext();
  const { openPreviewModal } = usePreviewSlider();
  const [quantity, setQuantity] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const { trackStep } = useFunnelSteps();
  const trackedProductRef = useRef<number | null>(null);

  const dispatch = useDispatch<AppDispatch>();

  // get the product data from Redux
  const product = useAppSelector((state) => state.quickViewReducer.value);

  // Use the product actions hook for proper API integration
  const { addToCart } = useProductActionsWithoutToast(product);

  const [activePreview, setActivePreview] = useState(0);

  // Fetch product data when modal opens via URL (page reload with ?preview=id)
  useEffect(() => {
    const fetchProductForPreview = async () => {
      if (isModalOpen && previewProductId && (!product?.id || product.id !== previewProductId)) {
        setIsLoading(true);
        try {
          const response = await fetch(`/api/products/${previewProductId}`);
          if (response.ok) {
            const json = await response.json();
            // API wraps response in { success: true, data: ... }
            const data = json.data || json;
            // Transform API response to match expected product format
            const transformedProduct = {
              id: data.id,
              title: data.title,
              description: data.description,
              price: data.price,
              discountedPrice: data.discountedPrice,
              stock: data.stock,
              rating: data.averageRating || 0,
              reviews: data.reviews || 0,
              imgs: data.imgs || {
                thumbnails: [],
                previews: [],
              },
            };
            dispatch(updateQuickView(transformedProduct));
          }
        } catch (error) {
          clientLogger.error('Failed to fetch product for preview', error instanceof Error ? error : new Error(String(error)), { previewProductId });
        } finally {
          setIsLoading(false);
        }
      }
    };

    fetchProductForPreview();
  }, [isModalOpen, previewProductId, product?.id, dispatch]);

  // Track view_item when quick view modal opens with a product
  useEffect(() => {
    if (isModalOpen && product?.id && trackedProductRef.current !== product.id) {
      trackStep('checkout', 'view_item', {
        product_id: product.id,
        product_name: product.title,
        price: product.discountedPrice,
        source: 'quick_view'});
      trackedProductRef.current = product.id;
    }
    // Reset tracking when modal closes
    if (!isModalOpen) {
      trackedProductRef.current = null;
    }
  }, [isModalOpen, product, trackStep]);

  // Image navigation handlers
  const totalImages = product?.imgs?.previews?.length || 0;
  const hasMultipleImages = totalImages > 1;

  const handlePrevImage = () => {
    if (!hasMultipleImages) return;
    setActivePreview((prev) => (prev === 0 ? totalImages - 1 : prev - 1));
  };

  const handleNextImage = () => {
    if (!hasMultipleImages) return;
    setActivePreview((prev) => (prev === totalImages - 1 ? 0 : prev + 1));
  };

  // Calculate discount percentage
  const discountPercentage = product.price && product.discountedPrice
    ? Math.round(((product.price - product.discountedPrice) / product.price) * 100)
    : 0;

  // preview modal
  const handlePreviewSlider = () => {
    dispatch(updateProductDetails(product));

    openPreviewModal();
  };

  // add to cart - uses the hook which handles both Redux state and API call
  const handleAddToCart = async () => {
    await addToCart(quantity);

    // Track add_to_cart funnel step for quick view specific tracking
    trackStep('checkout', 'add_to_cart', {
      product_id: product.id,
      product_name: product.title,
      price: product.discountedPrice,
      quantity,
      source: 'quick_view'});

    closeModal();
  };

  useEffect(() => {
    // closing modal while clicking outside
    function handleClickOutside(event: MouseEvent) {
      if (!(event.target as Element).closest(".modal-content")) {
        closeModal();
      }
    }

    if (isModalOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      setQuantity(1);
    };
  }, [isModalOpen, closeModal]);

  return (
    <div
      className={`${isModalOpen ? "z-99999" : "hidden"
        } fixed top-0 left-0 overflow-y-auto no-scrollbar w-full h-screen sm:py-20 xl:py-25 2xl:py-[230px] bg-dark/70 sm:px-8 px-4 py-5`}
    >
      <div className="flex items-center justify-center ">
        <div className="w-full max-w-[1100px] rounded-xl shadow-3 bg-white dark:bg-gray-800 p-7.5 relative modal-content">
          <Button
            onClick={() => closeModal()}
            aria-label="Close quick view modal"
            variant="ghost"
            size="sm"
            className="absolute top-0 right-0 sm:top-6 sm:right-6 w-10 h-10 rounded-full bg-meta dark:bg-gray-700 text-body dark:text-gray-400 hover:text-dark dark:hover:text-gray-200"
          >
            <Icon name="close" size={26} />
          </Button>

          {isLoading ? (
            <div className="flex items-center justify-center min-h-[400px] w-full">
              <div className="flex flex-col items-center gap-4">
                <div className="w-12 h-12 border-4 border-blue border-t-transparent rounded-full animate-spin" />
                <p className="text-gray-600 dark:text-gray-400">Loading product...</p>
              </div>
            </div>
          ) : (
          <div className="flex flex-wrap items-center gap-12.5">
            <div className="max-w-[526px] w-full">
              <div className="flex gap-5">
                <div className="flex flex-col gap-5">
                  {product?.imgs?.thumbnails?.map((img, key) => (
                    <Button
                      onClick={() => setActivePreview(key)}
                      key={key}
                      variant="ghost"
                      size="sm"
                      className={`w-20 h-20 overflow-hidden rounded-lg bg-gray-1 dark:bg-gray-700 hover:border-2 hover:border-blue ${activePreview === key && "border-2 border-blue"
                        }`}
                    >
                      <Image
                        src={img || ""}
                        alt="thumbnail"
                        width={61}
                        height={61}
                        className="aspect-square"
                      />
                    </Button>
                  ))}
                </div>

                <div className="relative z-1 overflow-hidden flex items-center justify-center w-full sm:min-h-[508px] bg-gray-1 dark:bg-gray-700 rounded-lg border border-gray-3 dark:border-gray-600">
                  <div>
                    <Button
                      onClick={handlePreviewSlider}
                      aria-label="Zoom product image"
                      variant="ghost"
                      size="sm"
                      className="gallery__Image w-10 h-10 rounded-[5px] bg-white dark:bg-gray-600 shadow-1 absolute top-4 lg:top-8 right-4 lg:right-8 z-50"
                    >
                      <Icon name="expand" size={22} />
                    </Button>
                    {product?.imgs?.previews?.[activePreview] &&
                      <Image
                        src={product?.imgs?.previews?.[activePreview]}
                        alt="products-details"
                        width={400}
                        height={400}
                      />
                    }
                  </div>

                  {/* Arrow Navigation Buttons */}
                  {hasMultipleImages && (
                    <>
                      <Button
                        onClick={handlePrevImage}
                        aria-label="Previous image"
                        variant="ghost"
                        size="sm"
                        className="absolute left-2 lg:left-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white dark:bg-gray-600 shadow-1 hover:bg-gray-2 dark:hover:bg-gray-500 z-50 flex items-center justify-center"
                      >
                        <Icon name="chevron-left" size={24} />
                      </Button>
                      <Button
                        onClick={handleNextImage}
                        aria-label="Next image"
                        variant="ghost"
                        size="sm"
                        className="absolute right-2 lg:right-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white dark:bg-gray-600 shadow-1 hover:bg-gray-2 dark:hover:bg-gray-500 z-50 flex items-center justify-center"
                      >
                        <Icon name="chevron-right" size={24} />
                      </Button>
                    </>
                  )}
                </div>
              </div>
            </div>

            <div className="max-w-[445px] w-full relative z-10">
              {discountPercentage > 0 && (
                <div className="mb-6.5">
                  <DiscountBadge percentage={discountPercentage} />
                </div>
              )}

              <h3 className="font-semibold text-xl xl:text-heading-5 text-dark dark:text-gray-100 mb-4">
                {product.title}
              </h3>

              <div className="flex flex-wrap items-center gap-5 mb-6">
                <button
                  type="button"
                  onClick={() => {
                    closeModal();
                    router.push(`/product/${product.id}#reviews`);
                  }}
                  className="cursor-pointer hover:opacity-80 transition-opacity"
                >
                  <StarRating
                    rating={product.rating || 0}
                    reviewCount={product.reviews || 0}
                    showCount={true}
                    size="sm"
                  />
                </button>

                <div className="flex items-center gap-2">
                  {product.stock && product.stock > 0 ? (
                    <>
                      <Icon name="check-circle" size={20} style={{ color: "#22AD5C" }} />
                      <span className="font-medium text-dark dark:text-gray-200"> In Stock ({product.stock} available) </span>
                    </>
                  ) : (
                    <span className="font-medium text-red dark:text-red-400"> Out of Stock </span>
                  )}
                </div>
              </div>

              <p className="text-dark-3 dark:text-gray-300">
                {product.description || 'No description available for this product.'}
              </p>

              <div className="flex flex-wrap justify-between gap-5 mt-6 mb-7.5">
                <div>
                  <h4 className="font-semibold text-lg text-dark dark:text-gray-100 mb-3.5">
                    Price
                  </h4>

                  <PriceDisplay
                    price={product.price}
                    discountedPrice={product.discountedPrice}
                    size="lg"
                  />
                </div>

                <div>
                  <h4 className="font-semibold text-lg text-dark dark:text-gray-100 mb-3.5">
                    Quantity
                  </h4>

                  <div className="flex items-center gap-3">
                    <Button
                      onClick={() => quantity > 1 && setQuantity(quantity - 1)}
                      aria-label="Decrease quantity"
                      variant="secondary"
                      size="sm"
                      className="w-10 h-10 rounded-[5px]"
                      disabled={quantity < 0 && true}
                    >
                      <Icon name="minus" size={16} />
                    </Button>

                    <span
                      className="flex items-center justify-center w-20 h-10 rounded-[5px] border border-gray-4 dark:border-gray-600 bg-white dark:bg-gray-700 font-medium text-dark dark:text-gray-200"
                      x-text="quantity"
                    >
                      {quantity}
                    </span>

                    <Button
                      onClick={() => setQuantity(quantity + 1)}
                      aria-label="Increase quantity"
                      variant="secondary"
                      size="sm"
                      className="w-10 h-10 rounded-[5px]"
                    >
                      <Icon name="plus" size={16} />
                    </Button>
                  </div>
                </div>
              </div>

              <div className="flex flex-wrap items-center gap-4">
                <Button
                  disabled={quantity === 0 && true}
                  onClick={() => handleAddToCart()}
                  variant="primary"
                  size="md"
                >
                  Add to Cart
                </Button>

                <WishlistButton product={product} variant="button" />
              </div>
            </div>
          </div>
          )}
        </div>
      </div>
    </div>
  );
}