All files / varjoliitokauppa/pages ProductDetail.tsx

40.49% Statements 49/121
23.52% Branches 40/170
25.64% Functions 10/39
44.23% Lines 46/104

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 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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519                      3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x     3x 3x           3x 3x           3x 3x 2x   1x       3x         3x           3x 3x   2x                   2x 2x       3x 3x     3x   3x 3x         3x 1x       2x 3x 3x 3x   2x     2x 2x 2x       3x         3x 3x   3x                                                 3x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
'use client';
 
import React from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useShop } from '../context/ShopContext';
import { useToast } from '../context/ToastContext';
import { Section } from '../components/Section';
import { ArrowLeft, MessageCircle, HelpCircle, Check, Plus, X, ZoomIn } from 'lucide-react';
 
const ProductDetail: React.FC = () => {
  const params = useParams();
  const idParam = params?.id;
  const id = Array.isArray(idParam) ? idParam[0] : idParam;
  const { products, addToCart, cart } = useShop();
  const { addToast } = useToast();
  const [selectedImageIndex, setSelectedImageIndex] = React.useState(0);
  const [isLightboxOpen, setIsLightboxOpen] = React.useState(false);
  const [selectedColor, setSelectedColor] = React.useState<string | null>(null);
  const [selectedSize, setSelectedSize] = React.useState<string | null>(null);
 
  const product = id ? products.find(p => p.id === id) : undefined;
 
  // Set default color when product loads
  React.useEffect(() => {
    Iif (product?.colors && product.colors.length > 0 && !selectedColor) {
      setSelectedColor(product.colors[0].name);
    }
  }, [product, selectedColor]);
 
  // Set default size when product loads
  React.useEffect(() => {
    Iif (product?.sizes && product.sizes.length > 0 && !selectedSize) {
      setSelectedSize(product.sizes[0].name);
    }
  }, [product, selectedSize]);
 
  // Ensure product has at least one image (use placeholder if empty)
  const productImages = React.useMemo(() => {
    if (product?.images && product.images.length > 0) {
      return product.images;
    }
    return ['/placeholder.svg'];
  }, [product?.images]);
 
  // Carousel navigation - use useCallback to avoid recreating functions
  const goToPrevious = React.useCallback(() => {
    if (!product) return;
    setSelectedImageIndex((prev) => (prev === 0 ? productImages.length - 1 : prev - 1));
  }, [product, productImages]);
 
  const goToNext = React.useCallback(() => {
    if (!product) return;
    setSelectedImageIndex((prev) => (prev === productImages.length - 1 ? 0 : prev + 1));
  }, [product, productImages]);
 
  // Keyboard navigation - ALL HOOKS MUST BE BEFORE EARLY RETURN
  React.useEffect(() => {
    if (!product) return; // Guard against undefined product
 
    const handleKeyDown = (e: KeyboardEvent) => {
      if (isLightboxOpen) {
        if (e.key === 'Escape') setIsLightboxOpen(false);
        if (e.key === 'ArrowLeft') goToPrevious();
        if (e.key === 'ArrowRight') goToNext();
      } else {
        if (e.key === 'ArrowLeft') goToPrevious();
        if (e.key === 'ArrowRight') goToNext();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [product, isLightboxOpen, goToPrevious, goToNext]);
 
  // Prevent body scroll when lightbox is open
  React.useEffect(() => {
    Iif (isLightboxOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isLightboxOpen]);
 
  // Early return AFTER all hooks (Rules of Hooks requirement)
  if (!product) {
    return <Section><p className="text-center py-20 font-bold text-xl">Tuotetta ei löytynyt.</p></Section>;
  }
 
  // Get available stock (considering color and size variants)
  const selectedColorVariant = product.colors?.find(c => c.name === selectedColor);
  const selectedSizeVariant = product.sizes?.find(s => s.name === selectedSize);
  const hasBothVariants = !!(product.colors?.length && product.sizes?.length);
  const availableStock = (() => {
    // Both size + color: use nested colorStocks
    Iif (selectedSizeVariant?.colorStocks && selectedColor) {
      return selectedSizeVariant.colorStocks.find(c => c.colorName === selectedColor)?.stock ?? 0;
    }
    Iif (selectedSizeVariant) return selectedSizeVariant.stock;
    Iif (selectedColorVariant) return selectedColorVariant.stock;
    return product.stock;
  })();
 
  // Calculate if out of stock in cart (triple-key matching)
  const cartItem = cart.find(i =>
    i.id === product.id &&
    (!product.colors || i.selectedColor === selectedColor) &&
    (!product.sizes || i.selectedSize === selectedSize)
  );
  const currentQty = cartItem ? cartItem.quantity : 0;
  const isOutOfStock = currentQty >= availableStock;
 
  const handleAddToCart = () => {
    // Validate color selection
    if (product.colors && product.colors.length > 0 && !selectedColor) {
      addToast("Valitse väri", "error");
      return;
    }
 
    // Validate size selection
    if (product.sizes && product.sizes.length > 0 && !selectedSize) {
      addToast("Valitse koko", "error");
      return;
    }
 
    if (isOutOfStock) {
      addToast("Maksimimäärä varastossa", "error");
      return;
    }
 
    // Add to cart with selected color and size
    const productWithVariants = { ...product, selectedColor: selectedColor || null, selectedSize: selectedSize || null };
    addToCart(productWithVariants);
    const variantInfo = [selectedColor, selectedSize].filter(Boolean).join(' / ');
    addToast(`${product.name}${variantInfo ? ` (${variantInfo})` : ''} lisätty ostoskoriin!`);
  };
 
  return (
    <Section variant="white" className="min-h-screen pt-8 md:pt-12">
      <Link href="/kauppa" className="inline-flex items-center gap-2 text-sm font-bold text-gray-500 hover:text-black mb-8">
        <ArrowLeft size={18} strokeWidth={2} /> Takaisin kauppaan
      </Link>
 
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 lg:gap-24">
        {/* Gallery */}
        <div className="space-y-6">
          <div
            className="bg-[#f9f9f9] border border-gray-200 rounded-[2rem] overflow-hidden aspect-square shadow-sm relative group cursor-zoom-in"
            onClick={() => setIsLightboxOpen(true)}
          >
            <Image
                src={productImages[selectedImageIndex]}
                alt={product.name}
                fill
                sizes="(max-width: 1024px) 100vw, 50vw"
                className={`object-contain transition-all duration-300 p-8 ${isOutOfStock ? 'grayscale opacity-90' : ''}`}
                priority
                quality={90}
            />
 
            {/* Zoom hint */}
            <div className="absolute top-4 right-4 bg-white/90 p-2 rounded-full opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
              <ZoomIn size={20} className="text-gray-700" />
            </div>
            {isOutOfStock && availableStock > 0 && (
               <div className="absolute inset-0 bg-white/50 flex items-center justify-center z-10">
                 <span className="bg-black text-white px-6 py-3 rounded-full font-bold uppercase tracking-widest shadow-xl">Varasto täynnä ostoskorissa</span>
               </div>
            )}
 
            {/* Navigation Arrows - Only show if more than 1 image */}
            {productImages.length > 1 && (
              <>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    goToPrevious();
                  }}
                  className="absolute left-4 top-1/2 -translate-y-1/2 w-12 h-12 bg-white/90 hover:bg-black hover:text-white rounded-full flex items-center justify-center shadow-lg transition-all z-10 border border-gray-200"
                  aria-label="Previous image"
                >
                  <ArrowLeft size={20} strokeWidth={2.5} />
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    goToNext();
                  }}
                  className="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 bg-white/90 hover:bg-black hover:text-white rounded-full flex items-center justify-center shadow-lg transition-all z-10 border border-gray-200"
                  aria-label="Next image"
                >
                  <ArrowLeft size={20} strokeWidth={2.5} className="rotate-180" />
                </button>
 
                {/* Image counter */}
                <div className="absolute bottom-4 left-1/2 -translate-x-1/2 bg-black/70 text-white px-4 py-2 rounded-full text-sm font-bold z-10">
                  {selectedImageIndex + 1} / {productImages.length}
                </div>
              </>
            )}
          </div>
 
          {/* Thumbnails */}
          {productImages.length > 1 && (
            <div className="grid grid-cols-4 gap-4">
              {productImages.map((img, i) => (
                <button
                  key={i}
                  onClick={() => setSelectedImageIndex(i)}
                  className={`aspect-square rounded-2xl overflow-hidden cursor-pointer bg-white shadow-sm transition-all relative ${
                    i === selectedImageIndex
                      ? 'border-2 border-black ring-2 ring-offset-2 ring-black'
                      : 'border border-gray-200 hover:border-black'
                  }`}
                >
                   <Image
                     src={img}
                     alt={`${product.name} ${i + 1}`}
                     fill
                     sizes="(max-width: 768px) 25vw, 15vw"
                     className="object-contain p-2"
                     quality={85}
                   />
                </button>
              ))}
            </div>
          )}
        </div>
 
        {/* Info */}
        <div className="py-2">
          <div className="mb-4 flex items-center gap-3">
             <span className="text-xs font-black text-gray-400 uppercase tracking-widest px-2 py-1 bg-gray-50 rounded-md border border-gray-100">
               {product.category}
             </span>
             {availableStock > 0 ? (
               <span className="text-xs font-bold text-green-600 flex items-center gap-1">
                 <Check size={14} strokeWidth={3} /> Varastossa ({availableStock} kpl)
               </span>
             ) : (
               <span className="text-xs font-bold text-red-500">Loppu väliaikaisesti</span>
             )}
          </div>
          
          <h1 className="text-4xl md:text-6xl font-black mb-8 tracking-tighter leading-[0.95] text-black">{product.name}</h1>
          
          <div className="flex items-center gap-6 mb-10 pb-10 border-b border-gray-200">
             <div className="text-4xl font-black tracking-tight">
               {product.salePrice ? (
                 <span className="text-red-600">{product.salePrice} € <span className="text-gray-300 text-3xl line-through font-bold ml-3">{product.price} €</span></span>
               ) : (
                 <span>{product.price} €</span>
               )}
             </div>
             {product.isUsed && (
                <span className="bg-gray-100 text-black px-5 py-2 rounded-xl text-xs font-black uppercase tracking-wider border border-gray-200">
                  Kunto: {product.condition}
                </span>
             )}
          </div>
 
          <div className="prose prose-lg text-gray-700 leading-relaxed mb-10 font-medium">
            <p>{product.description}</p>
          </div>
 
          {/* Color Selector */}
          {product.colors && product.colors.length > 0 && (
            <div className="mb-8 pb-8 border-b border-gray-200">
              <div className="mb-4">
                <label className="block text-sm font-bold text-gray-900 mb-3">
                  Valitse väri {selectedColor && <span className="text-gray-500 font-medium">- {selectedColor}</span>}
                </label>
                <div className="flex flex-wrap gap-3">
                  {product.colors.map((color) => {
                    const isSelected = selectedColor === color.name;
                    // When both variants exist, get stock from the selected size's colorStocks
                    const colorStock = hasBothVariants && selectedSizeVariant?.colorStocks
                      ? (selectedSizeVariant.colorStocks.find(c => c.colorName === color.name)?.stock ?? 0)
                      : color.stock;
                    const isColorOutOfStock = colorStock <= 0;
                    return (
                      <button
                        key={color.name}
                        onClick={() => !isColorOutOfStock && setSelectedColor(color.name)}
                        disabled={isColorOutOfStock}
                        className={`relative flex items-center gap-3 px-4 py-3 rounded-xl border-2 transition-all ${
                          isSelected
                            ? 'border-black bg-gray-50 shadow-md'
                            : isColorOutOfStock
                            ? 'border-gray-200 bg-gray-100 cursor-not-allowed opacity-50'
                            : 'border-gray-200 hover:border-gray-400 hover:bg-gray-50'
                        }`}
                      >
                        <div
                          className={`w-8 h-8 rounded-full border-2 ${
                            isSelected ? 'border-black' : 'border-gray-300'
                          }`}
                          style={{ backgroundColor: color.hex }}
                        />
                        <div className="text-left">
                          <div className={`text-sm font-bold ${isColorOutOfStock ? 'text-gray-400' : 'text-gray-900'}`}>
                            {color.name}
                          </div>
                          <div className={`text-xs ${isColorOutOfStock ? 'text-red-500' : 'text-gray-500'}`}>
                            {isColorOutOfStock ? 'Loppu' : `${colorStock} kpl varastossa`}
                          </div>
                        </div>
                        {isSelected && (
                          <Check size={20} className="text-black absolute top-2 right-2" strokeWidth={3} />
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          )}
 
          {/* Size Selector */}
          {product.sizes && product.sizes.length > 0 && (
            <div className="mb-8 pb-8 border-b border-gray-200">
              <div className="mb-4">
                <label className="block text-sm font-bold text-gray-900 mb-3">
                  Valitse koko {selectedSize && <span className="text-gray-500 font-medium">- {selectedSize}</span>}
                </label>
                <div className="flex flex-wrap gap-3">
                  {product.sizes.map((size) => {
                    const isSelected = selectedSize === size.name;
                    // When both variants exist, compute total stock across all colors for this size
                    const sizeStock = hasBothVariants && size.colorStocks
                      ? size.colorStocks.reduce((sum, cs) => sum + cs.stock, 0)
                      : size.stock;
                    const isSizeOutOfStock = sizeStock <= 0;
                    return (
                      <button
                        key={size.name}
                        onClick={() => !isSizeOutOfStock && setSelectedSize(size.name)}
                        disabled={isSizeOutOfStock}
                        className={`relative px-6 py-3 rounded-xl border-2 transition-all ${
                          isSelected
                            ? 'border-black bg-gray-50 shadow-md'
                            : isSizeOutOfStock
                            ? 'border-gray-200 bg-gray-100 cursor-not-allowed opacity-50'
                            : 'border-gray-200 hover:border-gray-400 hover:bg-gray-50'
                        }`}
                      >
                        <div className="text-center">
                          <div className={`text-sm font-bold ${isSizeOutOfStock ? 'text-gray-400' : 'text-gray-900'}`}>
                            {size.name}
                          </div>
                          <div className={`text-xs ${isSizeOutOfStock ? 'text-red-500' : 'text-gray-500'}`}>
                            {isSizeOutOfStock ? 'Loppu' : `${sizeStock} kpl`}
                          </div>
                        </div>
                        {isSelected && (
                          <Check size={16} className="text-black absolute top-1 right-1" strokeWidth={3} />
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          )}
 
          {/* Primary Actions - Stacked on Mobile, Row on Desktop */}
          <div className="flex flex-col sm:flex-row gap-4 mb-8">
             <button
               onClick={handleAddToCart}
               disabled={isOutOfStock || availableStock <= 0}
               className={`flex-[2] py-5 rounded-2xl font-black text-lg md:text-xl transition-all shadow-2xl shadow-black/20 flex items-center justify-center gap-3 ${isOutOfStock || availableStock <= 0 ? 'bg-gray-100 text-gray-400 cursor-not-allowed shadow-none' : 'bg-black text-white hover:bg-gray-800 hover:-translate-y-1'}`}
             >
               {availableStock <= 0 ? 'LOPPU VÄLIAIKAISESTI' : isOutOfStock ? 'VARASTOSALDO TÄYNNÄ' : <><Plus size={24} strokeWidth={3} /> LISÄÄ KORIIN</>}
             </button>
             
             {/* Secondary Action: Reduce purchase anxiety */}
             <Link
               href="/yhteystiedot"
               className="flex-1 bg-white text-black border-2 border-gray-200 py-5 rounded-2xl font-bold text-lg hover:border-black hover:bg-gray-50 transition-all flex items-center justify-center gap-2"
             >
                <HelpCircle size={20} strokeWidth={2.5} /> Kysy
             </Link>
          </div>
 
          {/* Reassurance Note */}
          <div className="bg-blue-50/50 p-6 rounded-2xl border border-blue-100 mb-12 flex gap-4 items-start">
            <MessageCircle className="text-blue-600 flex-shrink-0 mt-1" size={24} />
            <div>
              <p className="text-sm font-bold text-gray-900 leading-relaxed">
                Epävarma sopivuudesta?
              </p>
              <p className="text-sm text-gray-600">
                Autamme mielellämme valitsemaan juuri sinulle sopivat varusteet. Asiantuntijamme ovat tavoitettavissa puhelimitse ja sähköpostilla.
              </p>
            </div>
          </div>
 
          {/* Specs */}
          {product.specs && (
            <div className="pt-8 border-t border-gray-100">
              <h3 className="font-black text-lg mb-6 uppercase tracking-widest text-black">Tekniset tiedot</h3>
              <dl className="grid grid-cols-1 gap-y-4 text-sm">
                {Object.entries(product.specs).map(([key, val]) => (
                  <div key={key} className="flex justify-between py-4 border-b border-gray-100 last:border-0 hover:bg-gray-50 transition-colors px-2 rounded-lg">
                    <dt className="text-gray-500 font-bold uppercase tracking-wide text-xs">{key}</dt>
                    <dd className="font-extrabold text-black text-base">{val}</dd>
                  </div>
                ))}
              </dl>
            </div>
          )}
        </div>
      </div>
 
      {/* Lightbox Modal */}
      {isLightboxOpen && (
        <div
          className="fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-4"
          onClick={() => setIsLightboxOpen(false)}
        >
          {/* Close button */}
          <button
            className="absolute top-6 right-6 w-12 h-12 bg-white/10 hover:bg-white/20 rounded-full flex items-center justify-center transition-all z-50 backdrop-blur-sm"
            onClick={() => setIsLightboxOpen(false)}
            aria-label="Close lightbox"
          >
            <X size={24} className="text-white" strokeWidth={2} />
          </button>
 
          {/* Image counter - positioned above thumbnails */}
          {productImages.length > 1 && (
            <div className="absolute bottom-28 left-1/2 -translate-x-1/2 bg-white/10 text-white px-6 py-3 rounded-full text-sm font-bold z-50 backdrop-blur-sm">
              {selectedImageIndex + 1} / {productImages.length}
            </div>
          )}
 
          {/* Navigation arrows - Only show if more than 1 image */}
          {productImages.length > 1 && (
            <>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  goToPrevious();
                }}
                className="absolute left-6 top-1/2 -translate-y-1/2 w-14 h-14 bg-white/10 hover:bg-white/20 rounded-full flex items-center justify-center transition-all z-50 backdrop-blur-sm"
                aria-label="Previous image"
              >
                <ArrowLeft size={24} className="text-white" strokeWidth={2.5} />
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  goToNext();
                }}
                className="absolute right-6 top-1/2 -translate-y-1/2 w-14 h-14 bg-white/10 hover:bg-white/20 rounded-full flex items-center justify-center transition-all z-50 backdrop-blur-sm"
                aria-label="Next image"
              >
                <ArrowLeft size={24} className="text-white rotate-180" strokeWidth={2.5} />
              </button>
            </>
          )}
 
          {/* Main image container */}
          <div
            className="relative max-w-7xl max-h-[90vh] w-full h-full flex items-center justify-center"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="relative w-full h-full">
              <Image
                src={productImages[selectedImageIndex]}
                alt={product.name}
                fill
                sizes="100vw"
                className="object-contain"
                quality={95}
                priority
              />
            </div>
          </div>
 
          {/* Thumbnails strip at bottom */}
          {productImages.length > 1 && (
            <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex gap-3 z-50 max-w-[90vw] overflow-x-auto px-4 py-2 bg-white/5 backdrop-blur-sm rounded-2xl">
              {productImages.map((img, i) => (
                <button
                  key={i}
                  onClick={(e) => {
                    e.stopPropagation();
                    setSelectedImageIndex(i);
                  }}
                  className={`w-16 h-16 rounded-lg overflow-hidden flex-shrink-0 transition-all relative ${
                    i === selectedImageIndex
                      ? 'ring-2 ring-white ring-offset-2 ring-offset-black/50'
                      : 'opacity-60 hover:opacity-100'
                  }`}
                >
                  <Image
                    src={img}
                    alt={`${product.name} ${i + 1}`}
                    fill
                    sizes="64px"
                    className="object-cover"
                    quality={75}
                  />
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </Section>
  );
};
 
export default ProductDetail;