'use client';

import { precioProducto } from '@/lib/precioProducto';
import { useEffect, useMemo, useState } from 'react';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import Rating from '@mui/material/Rating';
import Skeleton from '@mui/material/Skeleton';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import CheckCircleRoundedIcon from '@mui/icons-material/CheckCircleRounded';
import CancelRoundedIcon from '@mui/icons-material/CancelRounded';
import FavoriteRoundedIcon from '@mui/icons-material/FavoriteRounded';
import FavoriteBorderRoundedIcon from '@mui/icons-material/FavoriteBorderRounded';
import ShareRoundedIcon from '@mui/icons-material/ShareRounded';
import HomeRoundedIcon from '@mui/icons-material/HomeRounded';
import LoginRoundedIcon from '@mui/icons-material/LoginRounded';
import RateReviewRoundedIcon from '@mui/icons-material/RateReviewRounded';
import ShoppingCartRoundedIcon from '@mui/icons-material/ShoppingCartRounded';
import StarRoundedIcon from '@mui/icons-material/StarRounded';
import type { InstallmentPlan, Product, ProductDetailSection as SectionItem, ProductReview } from '../../config/defaultStoreConfig';
import QuantitySelector from './QuantitySelector';
import StoreProductCard from './StoreProductCard';
import ZoomableProductImage from './ZoomableProductImage';
import {
	ProductDetailPage,
	ProductBreadcrumb,
	ProductDetailShell,
	ReviewCommentField,
	ProductGallery,
	ProductThumbs,
	ProductDetailInfo,
	ProductDetailMeta,
	ProductDetailRating,
	ProductAvailability,
	ProductDetailPrice,
	ProductInstallments,
	InstallmentsTitle,
	InstallmentOption,
	InstallmentRadio,
	InstallmentBody,
	InstallmentMain,
	InstallmentSub,
	InstallmentTag,
	ProductFactBox,
	ProductOptions,
	ProductSwatches,
	VariantChoiceRow,
	VariantChoice,
	ProductDetailActions,
	ProductDetailLower,
	ProductRelatedSidebar,
	ProductSideTitle,
	RelatedMiniList,
	RelatedMiniCard,
	RelatedMiniThumb,
	ProductTabbedArea,
	ProductTabBar,
	ProductTabPanel,
	RichDescription,
	ProductTextBlock,
	SpecTable,
	ReviewsGrid,
	ReviewCard,
	ReviewRating,
	ProductDetailSectionBlock,
	SectionTitle,
	ProductCarousel,
	IconAction
} from '../styles';
import { storeImageSrc } from '@/lib/storeImage';

interface StoreAuthMini {
	isLoggedIn: boolean;
	cliente: { nombre: string; email: string } | null;
	token: string | null;
}

interface Props {
	product: Product;
	relatedProducts: Product[];
	detailQuantity: number;
	detailSections: SectionItem[];
	detailMainDescription: string;
	detailReviews: ProductReview[];
	loading?: boolean;
	showBrand: boolean;
	showStock: boolean;
	showPromotionBadge: boolean;
	storeAuth: StoreAuthMini;
	formatPrice: (value: number) => string;
	onClose: () => void;
	onSetCategory: (category: string) => void;
	onSetDetailQuantity: (value: number) => void;
	onOpenDetail: (product: Product) => void;
	onAddToCart: (product: Product, quantity?: number, financingPlan?: InstallmentPlan) => void;
	onQuickView: (product: Product) => void;
	onSubmitReview: (rating: number, comment: string) => Promise<void>;
	onOpenCheckout: () => void;
	isFavorite?: boolean;
	onToggleWishlist?: (productId: string) => void;
}

/** Debajo de este umbral se muestra la cantidad exacta en vez de un genérico "En stock". */
const STOCK_BAJO = 5;

export default function ProductDetailSection({
	product,
	relatedProducts,
	detailQuantity,
	detailSections,
	detailMainDescription,
	detailReviews,
	loading = false,
	showBrand,
	showStock,
	showPromotionBadge,
	storeAuth,
	formatPrice,
	onClose,
	onSetCategory,
	onSetDetailQuantity,
	onOpenDetail,
	onAddToCart,
	onQuickView,
	onSubmitReview,
	onOpenCheckout,
	isFavorite = false,
	onToggleWishlist,
}: Props) {
	const [linkCopiado, setLinkCopiado] = useState(false);
	const compartir = async () => {
		const url = `${window.location.origin}/producto/${product.slug || product.id}`;
		try {
			if (navigator.share) {
				await navigator.share({ title: product.name, url });
				return;
			}
			await navigator.clipboard.writeText(url);
			setLinkCopiado(true);
			setTimeout(() => setLinkCopiado(false), 2500);
		} catch {
			/* el comprador canceló el diálogo de compartir */
		}
	};
	const [activeImage, setActiveImage] = useState(product.image);
	const [activeTab, setActiveTab] = useState<'description' | 'reviews' | 'specs'>('description');
	const [reviewRating, setReviewRating] = useState<number | null>(null);
	const [reviewComment, setReviewComment] = useState('');
	const [reviewSubmitting, setReviewSubmitting] = useState(false);
	const [reviewError, setReviewError] = useState('');
	const [reviewSuccess, setReviewSuccess] = useState(false);
	// null = paga al contado (opción por defecto).
	const [selectedPlanId, setSelectedPlanId] = useState<string | null>(null);
	// Combinación de variante elegida: atributoId -> valorId.
	const [selectedValueIds, setSelectedValueIds] = useState<Record<string, string>>({});

	// Reset when product changes (e.g. opening related product)
	useEffect(() => {
		setActiveImage(product.image);
		setActiveTab('description');
		setReviewRating(null);
		setReviewComment('');
		setReviewError('');
		setReviewSuccess(false);
		setSelectedPlanId(null);
	}, [product.id, product.image]);

	const installmentPlans = product.installments ?? [];
	const selectedPlan = selectedPlanId
		? (installmentPlans.find((p) => p.planId === selectedPlanId) ?? null)
		: null;

	const handleSubmitReview = async () => {
		if (!reviewRating) { setReviewError('Seleccioná una calificación'); return; }
		setReviewSubmitting(true);
		setReviewError('');
		try {
			await onSubmitReview(reviewRating, reviewComment);
			setReviewSuccess(true);
			setReviewRating(null);
			setReviewComment('');
		} catch (e: unknown) {
			setReviewError(e instanceof Error ? e.message : 'Error al publicar la reseña');
		} finally {
			setReviewSubmitting(false);
		}
	};

	// --- Variantes (color, talle, …) ------------------------------------------
	// El backend manda el padre con sus hijas reales del ERP. La ficha es una
	// sola; lo que cambia con la selección es precio/stock/imagen/SKU, y al
	// carrito se agrega la hija elegida.
	const variantAttributes = useMemo(() => product.variantAttributes ?? [], [product.variantAttributes]);
	const variants = useMemo(() => product.variants ?? [], [product.variants]);
	const hasVariants = variantAttributes.length > 0 && variants.length > 0;

	// Autoselección de la primera combinación con stock: así precio y stock nunca
	// quedan en blanco y "Agregar al carrito" funciona sin pasos extra.
	useEffect(() => {
		if (!hasVariants) {
			setSelectedValueIds({});
			return;
		}

		const preferida = variants.find((v) => v.stock > 0) ?? variants[0];
		const next: Record<string, string> = {};
		variantAttributes.forEach((attr) => {
			const match = attr.values.find((val) => preferida.optionValueIds.includes(val.id));

			if (match) next[attr.id] = match.id;
		});
		setSelectedValueIds(next);
	}, [hasVariants, variants, variantAttributes]);

	const selectedVariant = useMemo(() => {
		if (!hasVariants) return null;

		const elegidos = variantAttributes.map((attr) => selectedValueIds[attr.id]);

		if (elegidos.some((valueId) => !valueId)) return null;

		return variants.find((v) => elegidos.every((valueId) => v.optionValueIds.includes(valueId))) ?? null;
	}, [hasVariants, variantAttributes, variants, selectedValueIds]);

	/** Hay alguna variante con stock para este valor, respetando lo ya elegido en los demás atributos. */
	const isValueAvailable = (attrId: string, valueId: string) =>
		variants.some(
			(v) =>
				v.stock > 0 &&
				v.optionValueIds.includes(valueId) &&
				variantAttributes.every(
					(attr) =>
						attr.id === attrId ||
						!selectedValueIds[attr.id] ||
						v.optionValueIds.includes(selectedValueIds[attr.id])
				)
		);

	const handleSelectValue = (attrId: string, valueId: string) => {
		setSelectedValueIds((current) => {
			const next = { ...current, [attrId]: valueId };
			const existe = variants.some((v) =>
				variantAttributes.every((attr) => !next[attr.id] || v.optionValueIds.includes(next[attr.id]))
			);

			if (existe) return next;

			// La combinación resultante no existe (ej: ese color no viene en ese
			// talle): se reacomodan los otros atributos a una variante que sí exista.
			const fallback =
				variants.find((v) => v.stock > 0 && v.optionValueIds.includes(valueId)) ??
				variants.find((v) => v.optionValueIds.includes(valueId));

			if (!fallback) return next;

			const rebuilt: Record<string, string> = {};
			variantAttributes.forEach((attr) => {
				const match = attr.values.find((val) => fallback.optionValueIds.includes(val.id));

				if (match) rebuilt[attr.id] = match.id;
			});
			return rebuilt;
		});
	};

	// La variante manda sobre el padre en todo lo que el cliente ve y compra.
	const displayPrice = selectedVariant ? selectedVariant.price : product.price;
	const displayOldPrice = selectedVariant ? selectedVariant.oldPrice : product.oldPrice;
	const displayStock = selectedVariant ? selectedVariant.stock : product.stock;
	const displaySku = selectedVariant ? selectedVariant.sku : product.sku;

	// La foto propia de la variante se antepone a la galería del padre.
	const displayGallery = useMemo(() => {
		const base = product.gallery.length > 0 ? product.gallery : [product.image].filter(Boolean);
		const propia = selectedVariant?.image;

		return propia && !base.includes(propia) ? [propia, ...base] : base;
	}, [product.gallery, product.image, selectedVariant]);

	// Sincronizar imagen activa cuando llega la galería del backend
	useEffect(() => {
		if (displayGallery.length > 0 && !displayGallery.includes(activeImage)) {
			setActiveImage(displayGallery[0]);
		}
	}, [displayGallery]);

	useEffect(() => {
		if (selectedVariant?.image) setActiveImage(selectedVariant.image);
	}, [selectedVariant]);

	const inStock = displayStock > 0;

	/**
	 * Lo que realmente entra al carrito: el producto hijo del ERP, nunca el padre
	 * (que no es vendible). Mismo patrón que el plan de cuotas — lo elegido en la
	 * ficha viaja pegado al item.
	 */
	const productToAdd: Product = selectedVariant
		? {
				...product,
				id: selectedVariant.id,
				sku: selectedVariant.sku,
				name: selectedVariant.name,
				price: selectedVariant.price,
				oldPrice: selectedVariant.oldPrice,
				stock: selectedVariant.stock,
				image: selectedVariant.image || product.image,
				hasVariants: false,
				variants: undefined,
				variantAttributes: undefined
			}
		: product;

	// El backend arma `specifications` combinando las fijas del maestro (Marca, Categoría,
	// Unidad, Código, Código de barra) con las especificaciones libres que el comercio
	// cargó en el ERP (Potencia, Material, Dimensiones, …), ya en su orden. Si todavía no
	// llegó el detalle, se muestra el mínimo que trae la tarjeta del catálogo.
	const specRows = useMemo(() => {
		const fromSpecs = (product.specifications ?? []).filter((spec) => spec?.label && spec?.value);

		if (fromSpecs.length > 0) return fromSpecs;

		return [
			product.brand    ? { label: 'Marca',     value: product.brand }    : null,
			product.category ? { label: 'Categoría', value: product.category } : null,
			product.sku      ? { label: 'Código',    value: product.sku }      : null,
		].filter(Boolean) as { label: string; value: string }[];
	}, [product.specifications, product.brand, product.category, product.sku]);

	return (
		<ProductDetailPage>
			<ProductBreadcrumb aria-label="Ruta del producto">
				<button
					type="button"
					onClick={onClose}
				>
					<HomeRoundedIcon fontSize="small" />
				</button>
				<ArrowForwardIosIcon fontSize="inherit" />
				<button
					type="button"
					onClick={() => {
						onClose();
						onSetCategory(product.category);
					}}
				>
					{product.category}
				</button>
				<ArrowForwardIosIcon fontSize="inherit" />
				<strong>{product.name}</strong>
			</ProductBreadcrumb>
			<ProductDetailShell>
				<ProductGallery>
					{loading ? (
						<>
							<ProductThumbs>
								{[0, 1, 2].map((i) => <Skeleton key={i} variant="rectangular" width={64} height={64} sx={{ borderRadius: 1 }} />)}
							</ProductThumbs>
							<Skeleton variant="rectangular" sx={{ width: '100%', aspectRatio: '1', borderRadius: 2 }} />
						</>
					) : (
						<>
							<ProductThumbs>
								{displayGallery.map((image) => (
									<button
										key={image}
										type="button"
										data-active={image === activeImage}
										onClick={() => setActiveImage(image)}
										style={{ borderColor: image === activeImage ? 'var(--store-primary)' : 'transparent' }}
									>
										<img src={storeImageSrc(image, product.name)} alt={product.name} />
									</button>
								))}
							</ProductThumbs>
							<ZoomableProductImage
								src={storeImageSrc(activeImage || product.image, product.name)}
								alt={product.name}
								gallery={displayGallery}
								onNavigate={setActiveImage}
							/>
						</>
					)}
				</ProductGallery>
				<ProductDetailInfo>
					<ProductDetailMeta>
						<strong>{product.brand}</strong>
						{displaySku && <span>SKU: {displaySku}</span>}
					</ProductDetailMeta>
					<Typography
						component="h1"
						variant="h4"
					>
						{product.name}
					</Typography>
					{detailReviews.length > 0 && (
						<ProductDetailRating>
							<StarRoundedIcon fontSize="small" />
							{product.rating}
							<span>{detailReviews.length} reseña{detailReviews.length === 1 ? '' : 's'}</span>
						</ProductDetailRating>
					)}
					<ProductAvailability>
						<span>Disponibilidad:</span>
						{inStock ? (
							// El stock que llega ya tiene descontadas las reservas de otros pedidos.
							// Mostrar solo "En stock" escondía eso: el comprador se enteraba recién
							// al toparse con el límite en el carrito.
							<>
								<CheckCircleRoundedIcon fontSize="small" />
								<strong>
									{displayStock <= STOCK_BAJO
										? `Últimas ${displayStock} unidad${displayStock === 1 ? '' : 'es'}`
										: 'En stock'}
								</strong>
							</>
						) : (
							<><CancelRoundedIcon fontSize="small" style={{ color: 'var(--store-danger)' }} /><strong style={{ color: 'var(--store-danger)' }}>Sin stock</strong></>
						)}
					</ProductAvailability>
					<ProductDetailPrice>
						<strong>{precioProducto(displayPrice, formatPrice)}</strong>
						{displayOldPrice && <del>{formatPrice(displayOldPrice)}</del>}
					</ProductDetailPrice>
					{hasVariants &&
						variantAttributes.map((attr) => {
							const esColor = attr.values.some((val) => Boolean(val.colorHex));
							const elegido = selectedValueIds[attr.id];
							const elegidoLabel = attr.values.find((val) => val.id === elegido)?.value ?? '';
							return (
								<ProductOptions key={attr.id}>
									<strong>{attr.name}</strong>
									{elegidoLabel && <span>{elegidoLabel}</span>}
									{esColor ? (
										<ProductSwatches>
											{attr.values.map((val) => {
												const disponible = isValueAvailable(attr.id, val.id);
												return (
													<button
														key={val.id}
														type="button"
														aria-label={val.value}
														aria-pressed={elegido === val.id}
														title={disponible ? val.value : `${val.value} — sin stock`}
														data-active={elegido === val.id}
														onClick={() => handleSelectValue(attr.id, val.id)}
														style={{
															background: val.colorHex ?? 'var(--store-surface)',
															borderRadius: '50%',
															opacity: disponible ? 1 : 0.35
														}}
													/>
												);
											})}
										</ProductSwatches>
									) : (
										<VariantChoiceRow>
											{attr.values.map((val) => {
												const disponible = isValueAvailable(attr.id, val.id);
												return (
													<VariantChoice
														key={val.id}
														type="button"
														$selected={elegido === val.id}
														$unavailable={!disponible}
														aria-pressed={elegido === val.id}
														title={disponible ? val.value : `${val.value} — sin stock`}
														onClick={() => handleSelectValue(attr.id, val.id)}
													>
														{val.value}
													</VariantChoice>
												);
											})}
										</VariantChoiceRow>
									)}
								</ProductOptions>
							);
						})}
					{installmentPlans.length > 0 && (
						<ProductInstallments>
							<InstallmentsTitle>Elegí cómo pagar</InstallmentsTitle>

							<InstallmentOption
								type="button"
								$selected={!selectedPlan}
								onClick={() => setSelectedPlanId(null)}
								aria-pressed={!selectedPlan}
							>
								<InstallmentRadio $selected={!selectedPlan} />
								<InstallmentBody>
									<InstallmentMain>
										<span>Precio contado</span>
										<strong>{formatPrice(displayPrice)}</strong>
									</InstallmentMain>
									<InstallmentSub>Pago único al confirmar el pedido</InstallmentSub>
								</InstallmentBody>
							</InstallmentOption>

							{installmentPlans.map((cuota) => {
								const isSelected = selectedPlan?.planId === cuota.planId;
								const finalTotal =
									cuota.discountPercent > 0
										? Math.round(cuota.totalAmount * (1 - cuota.discountPercent / 100))
										: cuota.totalAmount;
								return (
									<InstallmentOption
										key={cuota.planId}
										type="button"
										$selected={isSelected}
										onClick={() => setSelectedPlanId(cuota.planId)}
										aria-pressed={isSelected}
									>
										<InstallmentRadio $selected={isSelected} />
										<InstallmentBody>
											<InstallmentMain>
												<span>{cuota.label}</span>
												<strong>
													{cuota.installmentsCount}x {formatPrice(cuota.installmentAmount)}
												</strong>
											</InstallmentMain>
											<InstallmentSub>
												<span>Total a crédito {formatPrice(finalTotal)}</span>
												{cuota.interestFree && <InstallmentTag $tone="free">Sin interés</InstallmentTag>}
												{cuota.discountPercent > 0 && (
													<InstallmentTag $tone="discount">-{cuota.discountPercent}%</InstallmentTag>
												)}
												{!cuota.interestFree && cuota.interestAmount > 0 && (
													<InstallmentTag $tone="interest">
														+{formatPrice(cuota.interestAmount)} vs contado
													</InstallmentTag>
												)}
												{cuota.downPayment ? <span>· Entrega {formatPrice(cuota.downPayment)}</span> : null}
											</InstallmentSub>
										</InstallmentBody>
									</InstallmentOption>
								);
							})}
						</ProductInstallments>
					)}
					<ProductFactBox>
						<li>
							<strong>Marca:</strong>
							<span>{product.brand}</span>
						</li>
						{displaySku && (
							<li>
								<strong>Código:</strong>
								<span>{displaySku}</span>
							</li>
						)}
						<li>
							<strong>Categoria:</strong>
							<span>{product.category}</span>
						</li>
						<li>
							<strong>Stock reservado:</strong>
							<span>Al confirmar el checkout</span>
						</li>
					</ProductFactBox>
					<QuantitySelector
						value={detailQuantity}
						max={displayStock}
						label="Cantidad"
						onChange={onSetDetailQuantity}
					/>
					<ProductDetailActions>
						<Button
							variant="contained"
							size="large"
							startIcon={<ShoppingCartRoundedIcon />}
							disabled={!inStock || (hasVariants && !selectedVariant)}
							onClick={() => onAddToCart(productToAdd, detailQuantity, selectedPlan ?? undefined)}
						>
							Agregar al carrito
						</Button>
						{/* El corazón de la ficha no tenía onClick: no hacía nada. */}
						<Tooltip
							title={isFavorite ? 'Quitar de favoritos' : 'Agregar a favoritos'}
							arrow
						>
							<IconAction
								aria-label={isFavorite ? `Quitar ${product.name} de favoritos` : `Agregar ${product.name} a favoritos`}
								aria-pressed={isFavorite}
								data-action="favorite"
								onClick={() => onToggleWishlist?.(product.id)}
								style={isFavorite ? { color: 'var(--store-danger)' } : undefined}
							>
								{isFavorite ? <FavoriteRoundedIcon fontSize="small" /> : <FavoriteBorderRoundedIcon fontSize="small" />}
							</IconAction>
						</Tooltip>
						{/* Link propio de la ficha (/producto/slug): al compartirlo trae título e
						    imagen. La dirección de la barra usa la navegación interna (#/producto). */}
						<Tooltip
							title={linkCopiado ? 'Link copiado' : 'Compartir'}
							arrow
						>
							<IconAction
								aria-label={`Compartir ${product.name}`}
								onClick={compartir}
							>
								<ShareRoundedIcon fontSize="small" />
							</IconAction>
						</Tooltip>
					</ProductDetailActions>
				</ProductDetailInfo>
			</ProductDetailShell>
			<ProductDetailLower data-has-sidebar={relatedProducts.length > 0 ? 'true' : 'false'}>
				{relatedProducts.length > 0 && (
					<ProductRelatedSidebar>
						<ProductSideTitle>Productos relacionados</ProductSideTitle>
						<RelatedMiniList>
							{relatedProducts.slice(0, 4).map((related) => (
								<RelatedMiniCard
									key={related.id}
									type="button"
									onClick={() => onOpenDetail(related)}
								>
									<RelatedMiniThumb>
										<img src={storeImageSrc(related.image, related.name)} alt={related.name} />
									</RelatedMiniThumb>
									<div>
										{(related.reviewCount ?? 0) > 0 && (
											<ReviewRating>
												<StarRoundedIcon fontSize="small" />
												{related.rating} ({related.reviewCount})
											</ReviewRating>
										)}
										<strong>{related.name}</strong>
										<span>{precioProducto(related.price, formatPrice)}</span>
									</div>
								</RelatedMiniCard>
							))}
						</RelatedMiniList>
					</ProductRelatedSidebar>
				)}

				<ProductTabbedArea>
					<ProductTabBar>
						<button
							type="button"
							data-active={activeTab === 'description' ? 'true' : undefined}
							onClick={() => setActiveTab('description')}
						>
							Descripción
						</button>
						<button
							type="button"
							data-active={activeTab === 'specs' ? 'true' : undefined}
							onClick={() => setActiveTab('specs')}
						>
							Especificaciones
						</button>
						<button
							type="button"
							data-active={activeTab === 'reviews' ? 'true' : undefined}
							onClick={() => setActiveTab('reviews')}
						>
							Reseñas{detailReviews.length > 0 ? ` (${detailReviews.length})` : ''}
						</button>
					</ProductTabBar>
					<ProductTabPanel>
						{activeTab === 'description' && (
							<>
								<RichDescription>{detailMainDescription || product.name}</RichDescription>
								{detailSections.map((section) =>
									section.type === 'text' ? (
										<ProductTextBlock key={section.title}>
											<strong>{section.title}</strong>
											<p>{section.content}</p>
										</ProductTextBlock>
									) : null
								)}
							</>
						)}
						{activeTab === 'specs' &&
							(specRows.length > 0 ? (
								<SpecTable>
									{specRows.map((row, index) => (
										// La clave sola no alcanza: las especificaciones libres las escribe
										// el comercio y pueden repetir un nombre.
										<li key={`${row.label}-${index}`}>
											<strong>{row.label}</strong>
											<span>{row.value}</span>
										</li>
									))}
								</SpecTable>
							) : (
								<Typography variant="body2" color="text.secondary">
									Este producto todavía no tiene especificaciones cargadas.
								</Typography>
							))}
						{activeTab === 'reviews' && (
							<div style={{ display: 'grid', gap: 24 }}>
								{/* Lista de reseñas */}
								{detailReviews.length > 0 ? (
									<ReviewsGrid>
										{detailReviews.map((review) => (
											<ReviewCard key={review.id}>
												<div>
													<strong>{review.author}</strong>
													<span>{review.date}</span>
												</div>
												<ReviewRating>
													<StarRoundedIcon fontSize="small" />
													{review.rating.toFixed(1)}
												</ReviewRating>
												{review.comment && <p>{review.comment}</p>}
											</ReviewCard>
										))}
									</ReviewsGrid>
								) : (
									<Typography variant="body2" color="text.secondary">
										Todavía no hay reseñas para este producto. ¡Sé el primero!
									</Typography>
								)}

								{/* Formulario de nueva reseña */}
								{storeAuth.isLoggedIn ? (
									reviewSuccess ? (
										<div style={{ display: 'grid', gap: 8, padding: '16px', background: 'var(--store-surface)', borderRadius: 8 }}>
											<Typography variant="body2" sx={{ color: 'var(--store-success)', fontWeight: 600 }}>
												¡Gracias por tu reseña! Fue publicada correctamente.
											</Typography>
											<Button size="small" variant="text" onClick={() => setReviewSuccess(false)}>
												Escribir otra reseña
											</Button>
										</div>
									) : (
										<div style={{ display: 'grid', gap: 12, padding: '16px', background: 'var(--store-surface)', borderRadius: 8 }}>
											<Typography variant="subtitle2" sx={{ fontWeight: 600, display: 'flex', alignItems: 'center', gap: 1 }}>
												<RateReviewRoundedIcon fontSize="small" />
												Escribir una reseña
											</Typography>
											<div>
												<Typography variant="caption" color="text.secondary" sx={{ mb: 0.5, display: 'block' }}>
													Tu calificación *
												</Typography>
												<Rating
													value={reviewRating}
													onChange={(_, val) => { setReviewRating(val); setReviewError(''); }}
													size="large"
												/>
											</div>
											{/* Textarea nativo, no TextField de MUI: ver ReviewCommentField en styles.ts. */}
											<ReviewCommentField>
												<span>Comentario (opcional)</span>
												<textarea
													rows={3}
													value={reviewComment}
													onChange={(e) => setReviewComment(e.target.value)}
													disabled={reviewSubmitting}
													placeholder="Contá tu experiencia con este producto..."
												/>
											</ReviewCommentField>
											{reviewError && (
												<Typography variant="caption" sx={{ color: 'var(--store-danger)' }}>{reviewError}</Typography>
											)}
											<Button
												variant="contained"
												size="small"
												onClick={handleSubmitReview}
												disabled={reviewSubmitting || !reviewRating}
												startIcon={reviewSubmitting ? <CircularProgress size={14} color="inherit" /> : <RateReviewRoundedIcon />}
												sx={{ justifySelf: 'start' }}
											>
												{reviewSubmitting ? 'Publicando...' : 'Publicar reseña'}
											</Button>
										</div>
									)
								) : (
									<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', background: 'var(--store-surface)', borderRadius: 8 }}>
										<Typography variant="body2" color="text.secondary" sx={{ flex: 1 }}>
											Iniciá sesión para escribir una reseña.
										</Typography>
										<Button
											size="small"
											variant="outlined"
											startIcon={<LoginRoundedIcon />}
											onClick={onOpenCheckout}
										>
											Iniciar sesión
										</Button>
									</div>
								)}
							</div>
						)}
					</ProductTabPanel>
				</ProductTabbedArea>
			</ProductDetailLower>
			{relatedProducts.length > 0 && (
				<ProductDetailSectionBlock>
					<SectionTitle>Tambien podria interesarte</SectionTitle>
					<ProductCarousel>
						{relatedProducts.map((related) => (
							<StoreProductCard
								key={related.id}
								product={related}
								showBrand={showBrand}
								showStock={showStock}
								showPromotionBadge={showPromotionBadge}
								formatPrice={formatPrice}
								onOpenDetail={onOpenDetail}
								onAddToCart={onAddToCart}
								onQuickView={onQuickView}
							/>
						))}
					</ProductCarousel>
				</ProductDetailSectionBlock>
			)}
		</ProductDetailPage>
	);
}
