import React, { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/router';
import Seo from '../../components/Seo';
import Breadcrumbs, { breadcrumbsJsonLd } from '../../components/Breadcrumbs';
import { productPath, toMetaDescription } from '../../lib/seo';
import { useSession } from 'next-auth/react';
import { useCart } from '../../context/CartContext';
import { isVariantAvailable, isVariantLowStock, type VariantKind } from '../../lib/variantStock';
import toast from 'react-hot-toast';
import ProductSchema from '../../components/ProductSchema';
import { getDefaultProductVariant } from '../../lib/productOffer';
import ProductImage from '../../components/ProductImage';
import Badge from '../../components/Badge';
import { CatalogProductGrid, formatProductCount } from '../../components/CatalogProductCard';
import { GetServerSideProps } from 'next';

interface ProductVariant {
  id: number;
  name: string;
  volume: string;
  volumeMl: number;
  currentPrice: number;
  kind?: VariantKind;
  sku?: string;
  stock?: number;
}

interface BadgeItem {
  name: string;
  color?: string | null;
}

interface ProductImage {
  url: string;
  isPrimary: boolean;
  alt: string | null;
}

interface RelatedProductVariant {
  id: number;
  name: string;
  volume: string;
  volumeMl: number;
  currentPrice: number;
  kind?: VariantKind;
  sku?: string;
  stock?: number;
}

interface RelatedProduct {
  id: number;
  slug: string;
  name: string;
  brandName: string;
  primaryImage: string;
  stock: number;
  badges?: BadgeItem[];
  variants: RelatedProductVariant[];
}

interface FragranceIngredient {
  id: number;
  name: string;
  slug: string;
  description: string;
  imageUrl: string;
}

interface Product {
  id: number;
  slug: string;
  name: string;
  description: string;
  characteristic: string;
  origin: string;
  categories: string[];
  perfumeType: string;
  brandName: string;
  brandSlug?: string;
  brandWebsite: string;
  topNotes: string;
  heartNotes: string;
  baseNotes: string;
  chemicals: string;
  primaryImage: string;
  compositionImage: string;
  allImages: ProductImage[];
  stock: number;
  badges?: BadgeItem[];
  variants: ProductVariant[];
  relatedProducts: RelatedProduct[];
  fragranceNotes?: {
    top: FragranceIngredient[];
    heart: FragranceIngredient[];
    base: FragranceIngredient[];
  };
}

interface ProductProps {
  initialProduct: Product | null;
  error?: string;
  id?: string;
  initialVariantSku?: string;
}

const formatVariantPrice = (price: number) => new Intl.NumberFormat('cs-CZ', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
}).format(price);

type FragranceLayerKey = 'top' | 'heart' | 'base';

interface FragranceLayer {
  key: FragranceLayerKey;
  title: string;
  hint: string;
  ingredients: FragranceIngredient[];
}

const legacyIngredientNames = (value: string, layer: FragranceLayerKey): FragranceIngredient[] =>
  value
    .split(/\s*[,;]\s*/u)
    .map((name) => name.trim())
    .filter(Boolean)
    .map((name, index) => ({
      id: -(index + 1),
      name,
      slug: `${layer}-${index}`,
      description: '',
      imageUrl: '',
    }));

const resolveLayerIngredients = (
  ingredients: FragranceIngredient[] | undefined,
  legacyNames: string,
  layer: FragranceLayerKey
) => ingredients && ingredients.length > 0
  ? ingredients
  : legacyIngredientNames(legacyNames, layer);

const ProductDetail: React.FC<ProductProps> = ({ initialProduct, error: initialError, id: ssrId, initialVariantSku }) => {
  const router = useRouter();
  const { id: queryId, variant: queryVariant } = router.query;
  const id = (Array.isArray(queryId) ? queryId[0] : queryId) || ssrId;
  const variantSku = (Array.isArray(queryVariant) ? queryVariant[0] : queryVariant) || initialVariantSku;
  const { addItem } = useCart();
  const { status: authStatus } = useSession();

  const [product, setProduct] = useState<Product | null>(initialProduct);
  const [loading, setLoading] = useState(!initialProduct);
  const [error, setError] = useState<string | null>(initialError || null);

  // Helper to calculate initial variant
  const calculateInitialVariant = (p: Product | null, slug: string | undefined, requestedSku?: string) => {
    if (!p) return null;
    const idStr = slug || p.slug;
    const volumeMatch = idStr.match(/-(\d+)ml$/);
    const volumeFromSlug = volumeMatch ? Number(volumeMatch[1]) : null;

    const variantBySku = requestedSku
      ? p.variants.find((variant) => variant.sku?.toLowerCase() === requestedSku.toLowerCase())
      : null;
    const variantByVolume = volumeFromSlug
      ? p.variants.find((v) => v.volumeMl === volumeFromSlug)
      : null;
    return variantBySku?.id ?? variantByVolume?.id ?? getDefaultProductVariant(p.variants, p.stock)?.id ?? null;
  };

  const [selectedVariantId, setSelectedVariantId] = useState<number | null>(() =>
    calculateInitialVariant(initialProduct, ssrId, initialVariantSku)
  );

  const [addedToCart, setAddedToCart] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);
  const [isInWishlist, setIsInWishlist] = useState(false);
  const [isWishlistLoading, setIsWishlistLoading] = useState(false);
  const relatedScrollerRef = useRef<HTMLDivElement>(null);
  const [relatedScrollState, setRelatedScrollState] = useState({ left: false, right: false });

  useEffect(() => {
    const scroller = relatedScrollerRef.current;
    if (!scroller) return;
    let dragging = false;
    let dragged = false;
    let pointerId: number | null = null;
    let startX = 0;
    let startScrollLeft = 0;
    let resetDraggedTimer: number | undefined;
    const update = () => setRelatedScrollState({
      left: scroller.scrollLeft > 4,
      right: scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 4,
    });
    const finishDrag = () => {
      if (!dragging) return;
      dragging = false;
      pointerId = null;
      scroller.style.scrollBehavior = '';
      scroller.classList.remove('cursor-grabbing', 'select-none');
      scroller.classList.add('cursor-grab');
      resetDraggedTimer = window.setTimeout(() => { dragged = false; }, 0);
    };
    const handlePointerDown = (event: PointerEvent) => {
      if (event.pointerType !== 'mouse' || event.button !== 0) return;
      if (resetDraggedTimer) window.clearTimeout(resetDraggedTimer);
      dragging = true;
      dragged = false;
      pointerId = event.pointerId;
      startX = event.clientX;
      startScrollLeft = scroller.scrollLeft;
      scroller.style.scrollBehavior = 'auto';
      scroller.classList.remove('cursor-grab');
      scroller.classList.add('cursor-grabbing', 'select-none');
    };
    const handlePointerMove = (event: PointerEvent) => {
      if (!dragging || event.pointerId !== pointerId) return;
      const distance = event.clientX - startX;
      if (Math.abs(distance) > 5) dragged = true;
      if (!dragged) return;
      event.preventDefault();
      scroller.scrollLeft = startScrollLeft - distance;
    };
    const handleClickCapture = (event: MouseEvent) => {
      if (!dragged) return;
      event.preventDefault();
      event.stopPropagation();
      dragged = false;
    };
    update();
    scroller.addEventListener('scroll', update, { passive: true });
    scroller.addEventListener('pointerdown', handlePointerDown);
    scroller.addEventListener('click', handleClickCapture, true);
    window.addEventListener('pointermove', handlePointerMove, { passive: false });
    window.addEventListener('pointerup', finishDrag);
    window.addEventListener('pointercancel', finishDrag);
    window.addEventListener('resize', update);
    return () => {
      scroller.removeEventListener('scroll', update);
      scroller.removeEventListener('pointerdown', handlePointerDown);
      scroller.removeEventListener('click', handleClickCapture, true);
      window.removeEventListener('pointermove', handlePointerMove);
      window.removeEventListener('pointerup', finishDrag);
      window.removeEventListener('pointercancel', finishDrag);
      window.removeEventListener('resize', update);
      if (resetDraggedTimer) window.clearTimeout(resetDraggedTimer);
    };
  }, [product?.id, product?.relatedProducts.length]);

  const scrollRelated = (direction: -1 | 1) => {
    const scroller = relatedScrollerRef.current;
    if (!scroller) return;
    const card = scroller.querySelector<HTMLElement>('article');
    const cardsPerStep = window.innerWidth >= 1024 ? 2 : 1;
    const distance = card ? (card.offsetWidth + 18) * cardsPerStep : scroller.clientWidth * 0.8;
    scroller.scrollBy({ left: direction * distance, behavior: 'smooth' });
  };
  useEffect(() => {
    if (initialProduct) {
      setProduct(initialProduct);
      setLoading(false);
      setError(initialError || null);

      // Calculate initial variant based on slug or default
      const initialVarId = calculateInitialVariant(initialProduct, id as string, variantSku);

      setSelectedVariantId(initialVarId);
      setSelectedImageIndex(0);
      setQuantity(1);
      setAddedToCart(false);
      setIsInWishlist(false);
    } else if (initialError) {
      setProduct(null);
      setError(initialError);
      setLoading(false);
    }
  }, [initialProduct, initialError, id]);

  useEffect(() => {
    if (!product || !variantSku) return;

    const variantIdFromUrl = calculateInitialVariant(product, id as string, variantSku);
    if (variantIdFromUrl !== null) {
      setSelectedVariantId((currentVariantId) => (
        currentVariantId === variantIdFromUrl ? currentVariantId : variantIdFromUrl
      ));
    }
  }, [product, id, variantSku]);

  useEffect(() => {
    // Only fetch if we don't have initial data and we have an ID
    if (!id || initialProduct) {
      return;
    }

    const fetchProduct = async () => {
      try {
        setLoading(true);

        // Extract slug from ID (e.g., "dior-sauvage-30ml" -> "dior-sauvage")
        const idStr = id as string;
        const productSlug = idStr.replace(/-\d+ml$/, '');

        const response = await fetch(`/api/products/${productSlug}`);
        if (!response.ok) {
          throw new Error('Failed to fetch product');
        }
        const data: Product = await response.json();
        setProduct(data);

        const initialVariantId = calculateInitialVariant(data, id as string, variantSku);
        setSelectedVariantId(initialVariantId);

        setSelectedImageIndex(0);
        setError(null);
      } catch (err) {
        setError('Nepodařilo se načíst produkt');
      } finally {
        setLoading(false);
      }
    };

    fetchProduct();
  }, [id, initialProduct, variantSku]);

  const selectVariant = (variantId: number) => {
    setSelectedVariantId(variantId);
    setQuantity(1);
    const nextVariant = product?.variants.find((variant) => variant.id === variantId);
    if (product && nextVariant?.sku) {
      const scrollPosition = { left: window.scrollX, top: window.scrollY };
      void router.replace(
        { pathname: `/product/${product.slug}`, query: { variant: nextVariant.sku } },
        undefined,
        { shallow: true, scroll: false },
      ).finally(() => {
        window.requestAnimationFrame(() => {
          window.requestAnimationFrame(() => {
            window.scrollTo({ ...scrollPosition, behavior: 'auto' });
          });
        });
      });
    }
  };

  const handleAddToCart = async () => {
    if (!product || !selectedVariantId) return;

    const variant = product.variants.find((v) => v.id === selectedVariantId);
    if (!variant) return;

    const displayImage = product.allImages[selectedImageIndex]?.url || product.primaryImage;

    for (let i = 0; i < quantity; i++) {
      await addItem({
        variantId: variant.id,
        productId: product.id,
        productName: product.name,
        productSlug: product.slug,
        brandName: product.brandName,
        volume: variant.volume,
        price: variant.currentPrice,
        image: displayImage,
      });
    }

    setAddedToCart(true);
    setTimeout(() => {
      setAddedToCart(false);
    }, 2000);
  };

  const handleWishlistToggle = async () => {
    if (authStatus === 'unauthenticated') {
      toast.error('Přihlaste se pro přidání do oblíbených');
      router.push('/login');
      return;
    }

    if (!product || !selectedVariantId || isWishlistLoading) return;

    try {
      setIsWishlistLoading(true);

      if (isInWishlist) {
        // TODO: Remove from wishlist (need to store item ID or call API differently)
        // For now, we'll just toggle the state
        setIsInWishlist(false);
        toast.success('Odebráno z oblíbených');
      } else {
        const response = await fetch('/api/wishlist', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ productId: product.id, variantId: selectedVariantId }),
        });

        if (response.status === 401) {
          toast.error('Přihlaste se pro přidání do oblíbených');
          router.push('/login');
        } else if (response.status === 409) {
          toast.error('Produkt je již v oblíbených');
          setIsInWishlist(true);
        } else if (response.ok) {
          setIsInWishlist(true);
          toast.success('Přidáno do oblíbených');
        } else {
          toast.error('Chyba při přidávání do oblíbených');
        }
      }
    } catch (error) {
      toast.error('Chyba při správě oblíbených');
    } finally {
      setIsWishlistLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="w-full bg-luxury-dark min-h-screen flex items-center justify-center pt-20 md:pt-48">
        <div className="text-center">
          <p className="text-luxury-gold text-lg">Načítání produktu...</p>
        </div>
      </div>
    );
  }

  if (error || !product) {
    return (
      <div className="w-full bg-luxury-dark min-h-screen flex items-center justify-center pt-20 md:pt-48">
        <div className="text-center">
          <p className="text-red-500 text-lg mb-4">{error || 'Produkt nenalezen'}</p>
          <button
            onClick={() => router.push('/')}
            className="px-6 py-2 bg-luxury-gold text-luxury-dark font-bold rounded-lg hover:bg-yellow-300 transition-all duration-300"
          >
            Zpět na hlavní stránku
          </button>
        </div>
      </div>
    );
  }

  const selectedVariant = product.variants.find((v) => v.id === selectedVariantId);
  const isSoldOut = !selectedVariant || !isVariantAvailable(selectedVariant, product.stock);
  const bottleVariants = product.variants.filter((variant) => variant.kind === 'BOTTLE');
  const otherVariants = product.variants.filter((variant) => variant.kind === 'OTHER');
  const fragranceLayers: FragranceLayer[] = [
    {
      key: 'top',
      title: 'Hlava',
      hint: 'První dojem',
      ingredients: resolveLayerIngredients(product.fragranceNotes?.top, product.topNotes, 'top'),
    },
    {
      key: 'heart',
      title: 'Srdce',
      hint: 'Charakter vůně',
      ingredients: resolveLayerIngredients(product.fragranceNotes?.heart, product.heartNotes, 'heart'),
    },
    {
      key: 'base',
      title: 'Základ',
      hint: 'Dlouhý dozvuk',
      ingredients: resolveLayerIngredients(product.fragranceNotes?.base, product.baseNotes, 'base'),
    },
  ];
  const visibleFragranceLayers = fragranceLayers.filter((layer) => layer.ingredients.length > 0);

  return (
    <>
      <Seo
        title={`${product.name} – celý parfém | ${product.brandName}`}
        description={toMetaDescription(
          product.description ||
            `Parfém ${product.name} od značky ${product.brandName}. Vyberte si celý flakon své oblíbené vůně.`
        )}
        canonical={productPath(product.slug)}
        ogImage={product.primaryImage}
        jsonLd={breadcrumbsJsonLd([
          { name: 'Domů', href: '/' },
          ...(product.brandSlug
            ? [{ name: product.brandName, href: `/brands/${product.brandSlug}` }]
            : [{ name: product.brandName }]),
          { name: product.name },
        ])}
      />
      <ProductSchema product={product} selectedVariant={selectedVariant} />
      <div className="w-full bg-luxury-dark min-h-screen pb-12 pt-20 md:pb-16 md:pt-24">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="md:hidden">
          <Breadcrumbs
            items={[
              { name: 'Domů', href: '/' },
              ...(product.brandSlug
                ? [{ name: product.brandName, href: `/brands/${product.brandSlug}` }]
                : [{ name: product.brandName }]),
              { name: product.name },
            ]}
          />
        </div>
        {/* Main Product Content */}
        <div className="flex flex-col gap-6 md:grid md:grid-cols-[0.88fr_1.12fr] lg:gap-8">
          {/* Product Image */}
          <div className="order-2 flex flex-col items-center justify-start gap-3 md:order-1">
            {/* Mobile Layout: Main image with thumbnails to the right */}
            <div className="flex w-full flex-row gap-3 md:flex-col">
              {/* Left side: Main Image and Brand/Name */}
              <div className="flex flex-1 flex-col gap-3 md:w-full md:flex-none">
                {/* Main Image */}
                <div className="relative flex w-full max-w-lg items-center justify-center rounded-lg bg-gradient-to-b from-luxury-dark to-luxury-dark/80 p-5 sm:p-6 md:p-5 min-h-80 sm:min-h-80 md:min-h-[400px] lg:min-h-[420px]">
                  <ProductImage
                    src={product.allImages[selectedImageIndex]?.url || product.primaryImage}
                    alt={product.name}
                    priority
                    className="h-full w-full object-contain max-h-80 sm:max-h-80 md:max-h-[410px]"
                  />
                </div>

                {/* Brand and Product Name - Mobile Only, below main image */}
                <div className="md:hidden w-full">
                  <p className="text-luxury-gold text-base sm:text-lg font-semibold uppercase tracking-widest mb-2">
                    {product.brandName}
                  </p>
                  <div className="mb-2 flex flex-wrap items-center gap-x-3 gap-y-2">
                    <p className="min-w-0 text-3xl font-black text-luxury-light font-aptos sm:text-4xl">
                      {product.name}
                    </p>
                    {product.badges && product.badges.length > 0 && (
                      <Badge badges={product.badges} placement="inline" />
                    )}
                  </div>
                  <div className="w-16 h-1 bg-luxury-gold rounded-full" />
                </div>
              </div>

              {/* Right side: Image Thumbnails - Vertical scroll on mobile, wrapped below on desktop */}
              {product.allImages.length > 1 && (
                <div className="w-auto md:w-full flex items-center md:items-stretch md:justify-center">
                  <div className="flex max-h-80 flex-col gap-2 overflow-y-auto md:max-h-none md:flex-row md:flex-wrap md:items-center md:justify-center md:overflow-visible">
                    {product.allImages.map((image, index) => (
                      selectedImageIndex !== index && (
                        <button
                          key={index}
                          onClick={() => setSelectedImageIndex(index)}
                          className="h-20 w-20 flex-shrink-0 overflow-hidden rounded-lg border border-luxury-gold/30 transition-all duration-300 hover:border-luxury-gold/60 md:h-20 md:w-20"
                        >
                          <ProductImage
                            src={image.url}
                            alt={`${product.name} - obrázek ${index + 1}`}
                            className="w-full h-full object-contain bg-luxury-dark/50"
                          />
                        </button>
                      )
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Product Details */}
          <div className="order-3 flex flex-col gap-4 md:order-2 md:gap-2">
            {/* Brand - Hidden on mobile */}
            <div className="hidden md:block">
              <p className="text-sm font-semibold uppercase tracking-widest text-luxury-gold lg:text-base">
                {product.brandName}
              </p>
            </div>

            {/* Product Name - Hidden on mobile */}
            <div className="hidden md:block">
              <h1 className="mb-1 text-3xl font-black text-luxury-light font-aptos lg:text-4xl">
                {product.name}
              </h1>
              <div className="h-0.5 w-12 rounded-full bg-luxury-gold" />
              {product.badges && product.badges.length > 0 && (
                <div className="mt-2">
                  <Badge badges={product.badges} placement="inline" />
                </div>
              )}
              {selectedVariant && (
                <p className={`mt-2 whitespace-nowrap text-2xl font-black font-aptos lg:text-3xl ${isSoldOut ? 'text-red-400' : 'text-luxury-gold'}`}>
                  {`${formatVariantPrice(Number(selectedVariant.currentPrice))} Kč`}
                </p>
              )}
            </div>

            {/* Description */}
            {product.description && (
              <div className="order-3 border-t border-luxury-gold/20 pt-3 md:order-none">
                <p className="text-base leading-relaxed text-luxury-light/75">
                  {product.description}
                </p>
              </div>
            )}

            {/* Variant Selection */}
            <div className="order-1 grid gap-2 border-t border-luxury-gold/20 pt-3 md:order-none">
              {bottleVariants.length > 0 && (
                <ProductVariantGroup
                  title="Celé parfémy"
                  hint="Pro vaši sbírku"
                  variants={bottleVariants}
                  productStock={product.stock}
                  selectedVariantId={selectedVariantId}
                  onSelect={selectVariant}
                />
              )}
              {otherVariants.length > 0 && (
                <ProductVariantGroup
                  title="Další varianty"
                  hint="Vyberte provedení"
                  variants={otherVariants}
                  productStock={product.stock}
                  selectedVariantId={selectedVariantId}
                  onSelect={selectVariant}
                />
              )}
            </div>

            {/* Quantity and Add to Cart */}
            {!isSoldOut && (
              <div className="order-2 flex flex-col gap-2 md:order-none">
                <div className="flex items-stretch gap-2">
                  <div className="flex min-h-[52px] items-center rounded-lg border border-luxury-gold/40">
                    <button
                      onClick={() => setQuantity(Math.max(1, quantity - 1))}
                      className="h-full px-3 text-luxury-gold transition-colors hover:bg-luxury-gold/10"
                      aria-label="Snížit počet kusů"
                    >
                      −
                    </button>
                    <span className="flex min-w-12 flex-col items-center px-3 text-center font-bold text-luxury-light">
                      <small className="text-[9px] font-semibold uppercase tracking-wider text-luxury-light/45">Počet</small>{quantity}
                    </span>
                    <button
                      onClick={() => setQuantity(quantity + 1)}
                      className="h-full px-3 text-luxury-gold transition-colors hover:bg-luxury-gold/10"
                      aria-label="Zvýšit počet kusů"
                    >
                      +
                    </button>
                  </div>

                  <button
                    onClick={handleAddToCart}
                    className={`min-h-[52px] flex-1 rounded-lg px-4 py-3 text-base font-bold transition-all duration-300 font-aptos ${
                      addedToCart
                        ? 'bg-green-500 text-white'
                        : 'bg-luxury-gold text-luxury-dark hover:bg-yellow-300 shadow-lg shadow-luxury-gold/20'
                    }`}
                  >
                    {addedToCart ? '✓ Přidáno do košíku' : 'Přidat do košíku'}
                  </button>
                  <button
                    onClick={handleWishlistToggle}
                    disabled={isWishlistLoading}
                    className="flex min-h-[52px] w-[52px] flex-none items-center justify-center rounded-lg bg-red-600 text-white transition-all duration-300 hover:bg-red-700"
                    title={isInWishlist ? 'Odebrat z oblíbených' : 'Přidat do oblíbených'}
                    aria-label={isInWishlist ? 'Odebrat z oblíbených' : 'Přidat do oblíbených'}
                  >
                    <svg className={`h-5 w-5 transition-transform duration-300 ${isInWishlist ? 'fill-current' : ''}`} fill={isInWishlist ? 'currentColor' : 'none'} stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" /></svg>
                  </button>
                </div>
                <p className="text-sm text-luxury-light/55">Skladem · standardní doručení do 2 pracovních dnů.</p>
              </div>
            )}

            {/* Sold Out Message */}
            {isSoldOut && (
              <div className="order-2 border-t border-luxury-gold/20 pt-6 md:order-none">
                <div className="w-full px-6 py-4 bg-red-500/20 border border-red-500/40 rounded-lg text-center">
                  <p className="text-red-400 font-bold">VYPRODÁNO</p>
                </div>
              </div>
            )}

          </div>
        </div>

        {/* Product Information Section */}
        <div className="mt-12 sm:mt-16 lg:mt-20 pt-10 sm:pt-12 lg:pt-16 border-t border-luxury-gold/40">
          <div className="mb-6 sm:mb-8">
            <h2 className="text-3xl sm:text-4xl md:text-5xl font-aptos font-black text-luxury-light mb-2">Informace o produktu</h2>
            <div className="w-16 h-1 bg-luxury-gold rounded-full" />
          </div>

          <div className="mb-8 grid grid-cols-1 items-start gap-5 lg:grid-cols-3">
            {(product.categories.length > 0 || product.perfumeType || product.characteristic || product.origin || product.brandName || product.brandWebsite) && (
              <div className="rounded-2xl border border-luxury-gold/40 bg-luxury-dark/50 p-4 transition-all duration-300 hover:border-luxury-gold/60 sm:p-5 lg:col-span-1 lg:p-6">
                <div className="space-y-4">
                  {product.categories.length > 0 && (
                    <div>
                      <p className="mb-1 text-[13px] font-bold uppercase tracking-widest text-luxury-gold/80">Kategorie</p>
                      <p className="text-base font-medium text-luxury-light">{product.categories.join(', ')}</p>
                    </div>
                  )}

                  {product.perfumeType && (
                    <div className={product.categories.length > 0 ? "border-t border-luxury-gold/20 pt-4" : ""}>
                      <p className="mb-1 text-[13px] font-bold uppercase tracking-widest text-luxury-gold/80">Typ Vůně</p>
                      <p className="text-base font-medium text-luxury-light">{product.perfumeType}</p>
                    </div>
                  )}

                  {product.characteristic && (
                    <div className={product.categories.length > 0 || product.perfumeType ? "border-t border-luxury-gold/20 pt-4" : ""}>
                      <p className="mb-1 text-[13px] font-bold uppercase tracking-widest text-luxury-gold/80">Charakteristika</p>
                      <p className="text-base leading-relaxed text-luxury-light">{product.characteristic}</p>
                    </div>
                  )}

                  {product.origin && (
                    <div className="border-t border-luxury-gold/20 pt-4">
                      <p className="mb-1 text-[13px] font-bold uppercase tracking-widest text-luxury-gold/80">Země původu</p>
                      <p className="text-base font-medium text-luxury-light">{product.origin}</p>
                    </div>
                  )}

                  {product.brandName && (
                    <div className="border-t border-luxury-gold/20 pt-4">
                      <p className="mb-1 text-[13px] font-bold uppercase tracking-widest text-luxury-gold/80">Výrobce</p>
                      <p className="text-base font-medium text-luxury-light">{product.brandName}</p>
                    </div>
                  )}

                  {product.brandWebsite && (
                    <div className="border-t border-luxury-gold/20 pt-4">
                      <p className="mb-1 text-[13px] font-bold uppercase tracking-widest text-luxury-gold/80">Stránka výrobce</p>
                      <a href={product.brandWebsite} target="_blank" rel="noopener noreferrer" className="text-base font-medium text-luxury-gold underline decoration-luxury-gold/50 transition-colors hover:text-yellow-300 hover:decoration-luxury-gold">
                        {product.brandWebsite}
                      </a>
                    </div>
                  )}
                </div>
              </div>
            )}

            {(visibleFragranceLayers.length > 0 || product.chemicals) && (
              <div className="rounded-2xl border border-luxury-gold/40 bg-luxury-dark/50 p-4 transition-all duration-300 hover:border-luxury-gold/60 sm:p-5 lg:col-span-2 lg:p-6">
                <div className="space-y-5">
                  {visibleFragranceLayers.length > 0 && (
                    <div>
                      <div className="mb-4">
                        <h3 className="text-2xl font-black text-luxury-light font-aptos sm:text-3xl">Ingredience vůně</h3>
                      </div>

                      <div className="grid items-start gap-2">
                        <div className="grid min-w-0 gap-2">
                          {visibleFragranceLayers.map((layer) => (
                            <FragranceLayerGrid key={layer.key} layer={layer} />
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {product.chemicals && (
                    <details className="group border-t border-luxury-gold/20 pt-4">
                      <summary className="flex cursor-pointer list-none items-center justify-between gap-4 marker:hidden [&::-webkit-details-marker]:hidden">
                        <span>
                          <span className="block text-base font-black text-luxury-light font-aptos">Chemické složení</span>
                        </span>
                        <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full border border-luxury-gold/30 text-luxury-gold transition-transform duration-300 group-open:rotate-45" aria-hidden="true">
                          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeWidth={1.7} d="M12 5v14M5 12h14" /></svg>
                        </span>
                      </summary>
                      <div className="mt-4 border-t border-luxury-light/10 pt-4">
                        <p className="whitespace-pre-wrap text-sm leading-relaxed text-luxury-light/80">{product.chemicals}</p>
                        <p className="mt-4 text-sm leading-relaxed text-luxury-light/50">
                          Za složení odpovídá výrobce. Doporučujeme kontrolovat složení výrobku přímo na stránkách výrobce kvůli případným změnám.
                        </p>
                      </div>
                    </details>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Related Products Section */}
          {product.relatedProducts && product.relatedProducts.length > 0 && (
            <div className="mt-20 border-t border-luxury-light/15 pt-16">
              <header className="mb-10 flex items-end justify-between gap-6">
                <div>
                  <p className="mb-2 text-sm font-bold uppercase tracking-[0.18em] text-luxury-gold">Od stejné značky</p>
                  <h2 className="text-4xl font-black tracking-[-0.035em] text-luxury-light sm:text-5xl lg:text-6xl">Další vůně</h2>
                </div>
                <div className="flex shrink-0 items-center gap-3">
                  <span className="hidden text-sm text-luxury-light/45 sm:block">{formatProductCount(product.relatedProducts.length)}</span>
                  <div className="flex gap-2" aria-label="Posouvání parfémů stejné značky">
                    <button
                      type="button"
                      onClick={() => scrollRelated(-1)}
                      disabled={!relatedScrollState.left}
                      className="grid h-11 w-11 place-items-center border border-luxury-light/20 text-luxury-light transition-colors hover:border-luxury-gold hover:text-luxury-gold disabled:cursor-default disabled:opacity-25"
                      aria-label="Předchozí parfémy"
                    >
                      <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="m15 18-6-6 6-6" /></svg>
                    </button>
                    <button
                      type="button"
                      onClick={() => scrollRelated(1)}
                      disabled={!relatedScrollState.right}
                      className="grid h-11 w-11 place-items-center border border-luxury-light/20 text-luxury-light transition-colors hover:border-luxury-gold hover:text-luxury-gold disabled:cursor-default disabled:opacity-25"
                      aria-label="Další parfémy"
                    >
                      <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="m9 18 6-6-6-6" /></svg>
                    </button>
                  </div>
                </div>
              </header>
              <CatalogProductGrid
                products={product.relatedProducts}
                containerRef={relatedScrollerRef}
                className="flex cursor-grab snap-x snap-mandatory gap-[18px] overflow-x-auto scroll-smooth pb-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden [&>article]:w-[72vw] [&>article]:max-w-[300px] [&>article]:shrink-0 [&>article]:snap-start sm:[&>article]:w-[42vw] lg:[&>article]:w-[calc((100%_-_54px)/4)] lg:[&>article]:max-w-none xl:[&>article]:w-[calc((100%_-_72px)/5)]"
              />
            </div>
          )}
        </div>
      </div>
    </div>
    </>
  );
};

function FragranceLayerGrid({ layer }: { layer: FragranceLayer }) {
  const ingredientColumnCount = Math.min(layer.ingredients.length, 5);
  const ingredientLayoutClass = {
    1: 'grid-cols-1 max-w-[160px]',
    2: 'grid-cols-2 max-w-[328px]',
    3: 'grid-cols-3 sm:max-w-[496px]',
    4: 'grid-cols-3 sm:grid-cols-4 sm:max-w-[664px]',
    5: 'grid-cols-3 sm:grid-cols-5 sm:max-w-none',
  }[ingredientColumnCount];

  return (
    <section
      className="grid gap-2 px-2 py-1.5"
      aria-labelledby={`fragrance-layer-${layer.key}`}
      data-fragrance-layer={layer.key}
    >
      <header className="text-center">
        <h4 id={`fragrance-layer-${layer.key}`} className="text-base font-black uppercase tracking-[0.12em] text-luxury-gold font-aptos">
          {layer.title}
        </h4>
      </header>

      <div className="min-w-0">
        <div className={`mx-auto grid w-full min-w-0 gap-2 ${ingredientLayoutClass}`}>
          {layer.ingredients.map((ingredient, ingredientIndex) => (
            <div
              key={`${layer.key}-${ingredient.id}-${ingredientIndex}`}
              className={`group flex min-w-0 flex-col items-center justify-center px-2 py-2 text-center ${ingredient.imageUrl ? 'min-h-[88px]' : 'min-h-10'}`}
              title={ingredient.description || ingredient.name}
            >
              {ingredient.imageUrl && (
                <ProductImage
                  src={ingredient.imageUrl}
                  alt={ingredient.name}
                  className="mb-2 h-14 w-14 object-contain drop-shadow-[0_8px_10px_rgba(0,0,0,0.4)] transition-transform duration-300 group-hover:scale-105 sm:h-16 sm:w-16"
                />
              )}
              <span className="line-clamp-2 text-[11px] font-bold uppercase leading-[1.3] tracking-[0.04em] text-luxury-light/85 sm:text-xs">
                {ingredient.name}
              </span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProductVariantGroup({
  title,
  hint,
  variants,
  productStock,
  selectedVariantId,
  onSelect,
}: {
  title: string;
  hint: string;
  variants: ProductVariant[];
  productStock: number;
  selectedVariantId: number | null;
  onSelect: (variantId: number) => void;
}) {
  return (
    <div className="grid gap-[clamp(4px,1.2vw,8px)] border-b border-luxury-gold/15 py-[clamp(5px,1.2vw,8px)]">
      <div className="flex items-center justify-between gap-3 px-0.5">
        <div className="flex min-w-0 items-baseline gap-[clamp(6px,1.2vw,10px)]">
          <p className="shrink-0 text-[clamp(13px,1.25vw,16px)] font-bold uppercase tracking-[0.14em] text-luxury-gold">{title}</p>
          <p className="truncate text-[clamp(10px,0.95vw,12px)] leading-tight text-luxury-light/50">{hint}</p>
        </div>
        <span className="shrink-0 text-[10px] font-semibold uppercase tracking-wider text-luxury-light/40">
          {variants.length} {variants.length === 1 ? 'varianta' : variants.length < 5 ? 'varianty' : 'variant'}
        </span>
      </div>
      <div className="flex items-center gap-[clamp(8px,1.5vw,18px)] overflow-x-auto pb-0.5 pt-2">
        {variants.map((variant) => {
          const soldOut = !isVariantAvailable(variant, productStock);
          const selected = selectedVariantId === variant.id;
          const lastPiece = !soldOut && isVariantLowStock(variant, productStock);
          const label = variant.name || variant.volume;
          const price = formatVariantPrice(Number(variant.currentPrice));

          return (
            <button
              type="button"
              key={variant.id}
              disabled={soldOut}
              aria-pressed={selected}
              aria-label={`${title}, ${label}, ${price} Kč${soldOut ? ', vyprodáno' : lastPiece ? ', poslední kus' : ''}`}
              onClick={() => onSelect(variant.id)}
              className={`relative flex min-h-[54px] min-w-max flex-1 flex-col items-center justify-center gap-0.5 whitespace-nowrap rounded-md border px-[clamp(7px,1vw,12px)] py-2 text-center transition-all duration-200 ${
                soldOut
                  ? 'cursor-not-allowed border-red-500/30 bg-red-500/5 text-red-300/45'
                  : selected
                  ? 'border-luxury-gold bg-luxury-gold text-luxury-dark shadow-md shadow-luxury-gold/15'
                  : 'border-luxury-gold/35 bg-transparent text-luxury-light hover:border-luxury-gold/75 hover:bg-luxury-gold/5'
              }`}
            >
              {lastPiece && (
                <span className="absolute right-1 top-0 z-10 -translate-y-1/2 rounded-full bg-red-500 px-1.5 py-0.5 text-[8px] font-black uppercase leading-none tracking-wide text-white shadow-sm shadow-black/40">
                  Poslední kus
                </span>
              )}
              <span className={`text-[clamp(12px,calc(1vw+1px),14px)] font-semibold ${selected ? 'text-luxury-dark/65' : soldOut ? 'text-red-300/55' : 'text-luxury-light/55'}`}>
                {label}
              </span>
              <b className={`text-[clamp(15px,1.4vw,19px)] ${selected ? 'text-luxury-dark' : soldOut ? 'text-red-300/55' : 'text-luxury-light'}`}>
                {soldOut ? 'Vyprodáno' : `${price} Kč`}
              </b>
            </button>
          );
        })}
      </div>
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { id } = context.query;
  const requestedVariant = Array.isArray(context.query.variant) ? context.query.variant[0] : context.query.variant;
  const protocol = context.req.headers['x-forwarded-proto'] || 'http';
  const host = context.req.headers.host;

  try {
    const idStr = id as string;
    if (!idStr) {
      return { notFound: true };
    }

    const volumeMatch = idStr.match(/-(\d+)ml$/);
    if (volumeMatch) {
      const productSlug = idStr.replace(/-\d+ml$/, '');
      return {
        redirect: {
          destination: `/product/${productSlug}`,
          permanent: true,
        },
      };
    }
    const productSlug = idStr;

    // Use internal fetch to avoid external network overhead if possible,
    // but using full URL is safer for SSR consistency
    const response = await fetch(`${protocol}://${host}/api/products/${productSlug}`);

    if (!response.ok) {
      return {
        props: {
          initialProduct: null,
          error: 'Produkt nebyl nalezen'
        }
      };
    }

    const data = await response.json();

    return {
      props: {
        initialProduct: data,
        id: idStr,
        initialVariantSku: typeof requestedVariant === 'string' ? requestedVariant : ''
      }
    };
  } catch (error) {
    console.error('SSR Error:', error);
    return {
      props: {
        initialProduct: null,
        error: 'Nepodařilo se načíst produkt',
        id: id as string
      }
    };
  }
};

export default ProductDetail;
