All files / src/components/SearchPanel ProductDetailPanel.tsx

100% Statements 352/352
78.2% Branches 61/78
88.88% Functions 16/18
100% Lines 352/352

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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 6361x 1x                               1x 1x 1x             1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                   1x 1x                                         1x                       1x 14x 14x 14x 154x 154x   14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 14x 1x 1x 1x 1x 1x 1x 1x   1x     1x 1x   14x 14x   1x                   1x 14x 14x 14x   14x 1x 1x 1x 1x 1x 1x   1x     1x 14x 1x 1x 1x 1x 1x 1x   1x     1x 14x 1x 1x 1x 1x 1x 1x   1x     1x   14x 14x                         1x                           1x 1x 14x 14x 14x 14x 14x 14x 14x   14x 14x 14x   14x   14x 14x 14x 14x 14x   14x 6x 6x 6x 4x 2x 14x   14x   12x 12x 12x 12x 5x 5x 5x 5x   12x 12x 12x 12x 12x 12x 12x   12x 12x 14x 14x     14x 14x 14x 14x 14x 14x 14x   14x   14x 14x 14x 14x 14x   14x         14x 14x 14x 14x 14x 14x       14x   1x                     1x 3x 3x 2x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x   3x 3x     3x   1x                       1x 1x 1x 1x       1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x   1x     1x     1x 1x 3x 3x 3x   3x 3x   3x 3x       1x         1x   1x                       1x 14x 14x 14x       14x 14x 14x 1x 1x   13x 13x 13x 14x   14x 14x 1x 1x 1x   1x 1x 1x       14x 14x           14x   1x                             1x 1x 14x 14x 14x   14x 14x 14x 14x 14x 13x 13x 13x 13x 13x 13x 13x 13x 13x 14x 14x 14x 14x 14x   14x 14x 14x 14x   14x 14x 14x 4x 4x 4x   14x 14x 14x 14x   14x 14x 14x   14x 14x 14x 14x 14x 14x       14x 14x   14x 14x 14x       14x 14x 14x 14x 14x 14x     14x     14x 1x 1x 1x 1x 1x 1x           1x 14x 14x 14x 14x 14x 14x 14x   14x   14x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x   4x     4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x       4x 4x 4x 4x               4x                 14x   1x                   1x 4x 4x 4x 4x  
import { TruncatedDescription } from '@/components/SearchPanel/TruncatedDescription';
import {
  PriceHistoryTooltip,
  ProductDetailBody,
  ProductDetailContent,
  ProductDetailDescription,
  ProductDetailDocLinks,
  ProductDetailFieldRow,
  ProductDetailFieldsColumn,
  ProductDetailImageBox,
  ProductDetailImageColumn,
  ProductDetailPanelContainer,
  ProductDetailVariantsColumn,
  ProductDetailVariantsGrid,
  ProductImageNavButton,
  ProductImageTrigger,
} from '@/components/StyledComponents';
import { default as Link } from '@/components/TabLink';
import { ProductImageModal } from '@/components/SearchPanel/ProductImageModal';
import {
  formatUsd,
  PriceSparkline,
  PriceTrend,
  TREND_GLYPH,
  type PriceHistorySettings,
} from '@/components/SearchPanel/PriceTrendGraph';
import { SupplierStoreNotice } from '@/components/SearchPanel/SupplierStoreNotice';
import { omit } from '@/helpers/collectionUtils';
import { i18n } from '@/helpers/i18n';
import { formatDisplayPrice } from '@/helpers/price';
import {
  describeTrend,
  getProductPriceHistory,
  productSeriesKey,
  resolveRowTrendPoints,
  variantSeriesKey,
} from '@/helpers/priceHistory';
import { isPresent, resolveDisplayedVariants, resolveProductImages } from '@/helpers/product';
import { formatTimestamp, preloadImages } from '@/helpers/utils';
import COAIcon from '@/icons/COAIcon';
import SDSIcon from '@/icons/SDSIcon';
import TDSIcon from '@/icons/TDSIcon';
import { useCyclingIndex } from '@/shared/hooks/useCyclingIndex.hook';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import { Typography } from '@mui/material';
import type { Row, Table } from '@tanstack/react-table';
import {
  Fragment,
  useEffect,
  useRef,
  useState,
  type MouseEvent,
  type ReactElement,
  type ReactNode,
} from 'react';
 
/** How long each image is shown before cycling to the next, in milliseconds. */
const IMAGE_CYCLE_MS = 3000;
 
/**
 * Props for {@link ProductDetailPanel}.
 * @source
 */
interface ProductDetailPanelProps {
  /** The expanded top-level product row this panel details. */
  row: Row<Product>;
  /** The table instance, used to read `meta.userSettings` for price formatting. */
  table: Table<Product>;
}
 
/** A populated product-detail entry rendered as a label/value pair. */
interface DetailField {
  /** Column-style label shown in muted text. */
  label: string;
  /** Rendered value (text or a link/icon). */
  value: ReactNode;
}
 
/**
 * Builds the ordered list of populated detail fields for a product, skipping any
 * that are empty. Text identifiers render as-is; SDS/TDS/COA and PubChem render
 * as links so the user can open the underlying documents.
 * @param product - The product whose details to surface.
 * @returns The detail fields to render, in display order (empty when none apply).
 * @example
 * ```ts
 * buildDetailFields({ cas: "7647-14-5", formula: "NaCl" } as Product);
 * // => [{ label: "CAS", value: "7647-14-5" }, { label: "Formula", value: "NaCl" }]
 * ```
 * @source
 */
function buildDetailFields(product: Product): DetailField[] {
  const fields: DetailField[] = [];
  const pushText = (label: string, value: unknown) => {
    if (isPresent(value)) fields.push({ label, value: String(value) });
  };
 
  pushText(i18n('product_detail_cas'), product.cas);
  pushText(i18n('product_detail_formula'), product.formula);
  pushText(i18n('product_detail_molecular_weight'), product.moleweight);
  pushText(i18n('product_detail_iupac_name'), product.iupacName);
  pushText(i18n('product_detail_inchikey'), product.inchiKey);
  pushText(i18n('product_detail_inchi'), product.inchi);
  pushText(i18n('product_detail_smiles'), product.smiles);
  pushText(i18n('product_detail_purity'), product.purity);
  pushText(i18n('product_detail_grade'), product.grade);
  pushText(i18n('product_detail_concentration'), product.concentration);
  pushText(i18n('product_detail_manufacturer'), product.manufacturer);
  // Description is rendered in its own full-width band, not as a compact row.
 
  // PubChem link — truthy check narrows the optional id.
  const { pubchemId } = product;
  if (pubchemId) {
    fields.push({
      label: i18n('product_detail_pubchem'),
      value: (
        <Link
          href={`https://pubchem.ncbi.nlm.nih.gov/compound/${pubchemId}`}
          aria-label={i18n('product_detail_pubchem_cid', [String(pubchemId)])}
          title={i18n('product_detail_pubchem_view')}
        >
          {pubchemId}
        </Link>
      ),
    });
  }
 
  return fields;
}
 
/**
 * Builds the SDS / TDS / COA document icon links for a product, shown beneath
 * its image. Each link is included only when its URL is set.
 * @param product - The product whose document URLs to surface.
 * @returns The document links in display order (empty when the product has none).
 * @example
 * ```tsx
 * buildDocLinks({ sdsUrl: "https://s.pdf" } as Product); // => [<Link><SDSIcon/></Link>]
 * ```
 * @source
 */
function buildDocLinks(product: Product): ReactNode[] {
  const links: ReactNode[] = [];
  const { sdsUrl, specSheetUrl, coaUrl } = product;
 
  if (sdsUrl) {
    links.push(
      <Link
        key="sds"
        href={sdsUrl}
        aria-label={i18n('product_detail_sds')}
        title={i18n('product_detail_sds')}
      >
        <SDSIcon fontSize="small" />
      </Link>,
    );
  }
  if (specSheetUrl) {
    links.push(
      <Link
        key="tds"
        href={specSheetUrl}
        aria-label={i18n('product_detail_tds')}
        title={i18n('product_detail_tds')}
      >
        <TDSIcon fontSize="small" />
      </Link>,
    );
  }
  if (coaUrl) {
    links.push(
      <Link
        key="coa"
        href={coaUrl}
        aria-label={i18n('product_detail_coa')}
        title={i18n('product_detail_coa')}
      >
        <COAIcon fontSize="small" />
      </Link>,
    );
  }
 
  return links;
}
 
/**
 * Props for {@link ProductImageCarousel}.
 * @source
 */
interface ProductImageCarouselProps {
  /** The resolved images to display, in order. */
  images: ReturnType<typeof resolveProductImages>;
  /** Product title, used for the alt/aria fallback text. */
  title: string;
}
 
/**
 * Renders a product's image in the fixed-size detail box, cycling through the
 * images on a fixed interval (`IMAGE_CYCLE_MS`) when there is more than one. Hovering the
 * image reveals semi-transparent prev/next arrows for manual navigation; a click
 * anywhere else opens the full image in a new tab. Images that fail to load (e.g.
 * a CACTUS 404) are dropped from the rotation; the box disappears only once every
 * image has failed.
 * @param props - The images to show and the product title for fallback text.
 * @returns The image box, or `null` when there are no loadable images.
 * @example
 * ```tsx
 * <ProductImageCarousel images={resolveProductImages(product)} title={product.title} />
 * ```
 * @source
 */
export function ProductImageCarousel({
  images,
  title,
}: ProductImageCarouselProps): ReactElement | null {
  const [broken, setBroken] = useState<ReadonlySet<number>>(new Set());
  const [modalOpen, setModalOpen] = useState(false);
  // URLs already handed to the preloader, so we never fetch the same one twice.
  const preloadedRef = useRef<Set<string>>(new Set());
 
  const available = images
    .map((image, index) => ({ image, index }))
    .filter(({ index }) => !broken.has(index));
 
  const { index: position, next, prev } = useCyclingIndex(available.length, IMAGE_CYCLE_MS);
 
  // The thumbnails the carousel actually renders, in cycle order. The first is shown
  // immediately (loaded by the <img> below), so we preload only the rest — ahead of the
  // automatic rotation — and the key keeps the effect stable across value-equal renders.
  const thumbnails = available.map(({ image }) => image.thumbSrc).filter(Boolean);
  const thumbnailKey = thumbnails.join('\n');
 
  useEffect(() => {
    const urls = thumbnailKey.length > 0 ? thumbnailKey.split('\n') : [];
    const pending = urls.slice(1).filter((url) => !preloadedRef.current.has(url));
    if (pending.length === 0) return;
    for (const url of pending) preloadedRef.current.add(url);
    void preloadImages(pending);
  }, [thumbnailKey]);
 
  if (available.length === 0) return null;
 
  const current = available[Math.min(position, available.length - 1)];
  const hasMultiple = available.length > 1;
  // Cycle without letting the click bubble to the trigger that opens the modal.
  const navigate = (event: MouseEvent, step: () => void) => {
    event.preventDefault();
    event.stopPropagation();
    step();
  };
 
  return (
    <Fragment>
      <ProductDetailImageBox>
        <ProductImageTrigger
          type="button"
          aria-label={i18n('product_detail_view_images', [title])}
          onClick={() => setModalOpen(true)}
        >
          <img
            src={current.image.thumbSrc}
            alt={current.image.altText ?? title}
            onError={() => setBroken((brokenSet) => new Set(brokenSet).add(current.index))}
          />
        </ProductImageTrigger>
        {hasMultiple && (
          <>
            <ProductImageNavButton
              type="button"
              className="image-nav prev"
              aria-label={i18n('product_detail_prev_image')}
              onClick={(event) => navigate(event, prev)}
            >
              <ArrowBackIosNewIcon fontSize="small" />
            </ProductImageNavButton>
            <ProductImageNavButton
              type="button"
              className="image-nav next"
              aria-label={i18n('product_detail_next_image')}
              onClick={(event) => navigate(event, next)}
            >
              <ArrowForwardIosIcon fontSize="small" />
            </ProductImageNavButton>
          </>
        )}
      </ProductDetailImageBox>
      <ProductImageModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        images={available.map(({ image }) => image)}
        title={title}
        initialIndex={position}
      />
    </Fragment>
  );
}
 
/**
 * Per-entry trend badge for the price-history popover: a colored arrow and
 * signed percent comparing this point to the previous one (rising = red).
 * Renders nothing for the baseline point, which has no prior to compare to.
 * @param props - The previous point (if any) and the current point.
 * @returns The badge element, or `null` for the baseline point.
 * @example
 * ```tsx
 * <EntryTrend prev={{ t: 1, usd: 20 }} curr={{ t: 2, usd: 22 }} />; // ▲ +10.0%
 * ```
 * @source
 */
function EntryTrend({ prev, curr }: { prev?: PricePoint; curr: PricePoint }): ReactElement | null {
  if (prev === undefined) return null;
  const trend = describeTrend([prev, curr]);
  const sign = trend.deltaUsd > 0 ? '+' : trend.deltaUsd < 0 ? '−' : '';
  const paletteKey =
    trend.direction === 'up' ? 'error' : trend.direction === 'down' ? 'success' : undefined;
  return (
    <Typography
      component="span"
      variant="caption"
      sx={(theme) => ({
        whiteSpace: 'nowrap',
        fontWeight: 600,
        fontSize: 'inherit',
        // Brighten the arrows on the dark popover surface (green especially reads
        // dim there); keep the standard shade on the light surface.
        color:
          paletteKey === undefined
            ? theme.palette.text.secondary
            : theme.palette[paletteKey][theme.palette.mode === 'dark' ? 'light' : 'main'],
      })}
    >
      {TREND_GLYPH[trend.direction]}
      {trend.direction !== 'flat' && ` ${sign}${Math.abs(trend.pctChange).toFixed(1)}%`}
    </Typography>
  );
}
 
/**
 * Popover contents for a variant's price history: a sparkline on top (left to
 * right, oldest → newest) followed by a dated list of its recorded points
 * newest-first, each with its price and a trend badge comparing it to the
 * previous (older) entry, formatted in the user's currency.
 * @param props - The variant's series points and the user's currency settings.
 * @returns The card element, or `null` when there aren't two points to show.
 * @example
 * ```tsx
 * <VariantPriceHistoryCard points={variantSeries.points} userSettings={userSettings} />
 * ```
 * @source
 */
function VariantPriceHistoryCard({
  points,
  userSettings,
}: {
  points: readonly PricePoint[];
  userSettings?: PriceHistorySettings;
}): ReactElement | null {
  if (points.length < 2) return null;
  return (
    <div style={{ minWidth: 180 }}>
      <div style={{ color: 'inherit', marginBottom: 6 }}>
        <PriceSparkline points={points} />
      </div>
      <table style={{ borderCollapse: 'collapse', width: '100%', fontSize: '0.72rem' }}>
        <thead>
          <tr>
            <th style={{ textAlign: 'left', paddingRight: 12, opacity: 0.7, fontWeight: 600 }}>
              {i18n('product_detail_price_history_col_date')}
            </th>
            <th style={{ textAlign: 'right', opacity: 0.7, fontWeight: 600 }}>
              {i18n('product_detail_price_history_col_price')}
            </th>
            <th aria-hidden />
          </tr>
        </thead>
        <tbody>
          {/* Build rows oldest→newest so each trend compares to the prior (older)
              point, then reverse for display so the newest sits at the top. */}
          {points
            .map((point, index) => (
              <tr key={point.t}>
                <td style={{ textAlign: 'left', paddingRight: 12, whiteSpace: 'nowrap' }}>
                  {formatTimestamp(point.t)}
                </td>
                <td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
                  {formatUsd(point.usd, userSettings)}
                </td>
                <td style={{ textAlign: 'right', paddingLeft: 12, whiteSpace: 'nowrap' }}>
                  <EntryTrend prev={points[index - 1]} curr={point} />
                </td>
              </tr>
            ))
            .reverse()}
        </tbody>
      </table>
    </div>
  );
}
 
/**
 * The base product's price-history block: current price, trend, and a sparkline
 * with the recorded-point count. Falls back to a "No history yet" note while
 * tracking is enabled but fewer than two points exist; renders nothing when
 * tracking is disabled and no history was ever recorded.
 * @param props - The aggregated price points to summarize and the user's settings.
 * @returns The history block, or `null` when there's nothing to show.
 * @example
 * ```tsx
 * <ProductPriceHistory points={aggregatePoints} userSettings={userSettings} />
 * ```
 * @source
 */
function ProductPriceHistory({
  points,
  userSettings,
}: {
  points?: readonly PricePoint[];
  userSettings?: PriceHistorySettings;
}): ReactElement | null {
  const hasTrend = points !== undefined && points.length >= 2;
  if (!hasTrend && userSettings?.priceTracking?.enabled === false) {
    return null;
  }
 
  return (
    <ProductDetailFieldRow>
      <span className="detail-label">
        {i18n('product_detail_price_history_currency', [userSettings?.currency ?? 'USD'])}
      </span>
      <span className="detail-value">
        {hasTrend ? (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ color: 'inherit' }}>
              <PriceSparkline points={points} colorByTrend />
            </span>
            <PriceTrend points={points} userSettings={userSettings} />
            <Typography component="span" variant="caption" color="text.secondary">
              {i18n('product_detail_points', [String(points.length)])}
            </Typography>
          </span>
        ) : (
          <Typography component="span" variant="caption" color="text.secondary">
            {i18n('product_detail_no_history')}
          </Typography>
        )}
      </span>
    </ProductDetailFieldRow>
  );
}
 
/**
 * Expanded detail panel rendered beneath a product row in place of variant
 * sub-rows. Shows (left) the product image or a derived structure depiction,
 * (middle) every populated detail field, and (right) the product's variants as
 * links with their price and quantity.
 *
 * Variants are sourced from the row's filtered `subRows` so an active filter
 * narrows the list; when no filter is applied this equals the full variant set.
 * @param props - The row to detail and the table instance for user settings.
 * @returns The rendered detail panel.
 * @example
 * ```tsx
 * <ProductDetailPanel row={row} table={table} />
 * ```
 * @source
 */
export function ProductDetailPanel({ row, table }: ProductDetailPanelProps): ReactElement {
  const product = row.original;
  const userSettings = table.options.meta?.userSettings;
  const images = resolveProductImages(product);
 
  // Load recorded price history for this product (base + variant series), keyed
  // by series id for direct lookup below. Re-runs if the product identity changes.
  const productKey = productSeriesKey(product);
  const [priceHistory, setPriceHistory] = useState<Map<string, PriceHistoryEntry>>(new Map());
  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      const map = await getProductPriceHistory(product);
      if (!cancelled) setPriceHistory(map);
    };
    void load();
    return () => {
      cancelled = true;
    };
  }, [product, productKey]);
  // Prefer the filtered sub-rows (respecting active filters); fall back to the
  // raw variants. Product[] is assignable to Variant[] since Product extends it.
  const variants: Variant[] =
    row.subRows.length > 0 ? row.subRows.map((sub) => sub.original) : (product.variants ?? []);
 
  // Include the parent product itself as a row unless a supplier already lists it
  // as a variant. Shared with the table's ungrouped display mode so the two never
  // drift; see resolveDisplayedVariants for the identity/purchasable-unit dedup.
  const displayedVariants = resolveDisplayedVariants(product, variants);
 
  // Resolve a row's recorded series: the parent's history lives under the base
  // productKey, every other variant under its own variant key.
  const seriesFor = (variant: Variant): PriceHistoryEntry | undefined => {
    const key = variant === product ? productKey : variantSeriesKey(product, variant);
    return key !== undefined ? priceHistory.get(key) : undefined;
  };
 
  // The product-level summary aggregates the *displayed* rows into one mean-price
  // series (shared with the results table's trend column), so it can never
  // contradict the rows below it.
  const aggregatePoints = resolveRowTrendPoints(product, displayedVariants, priceHistory);
 
  const detailFields = buildDetailFields(product);
  const docLinks = buildDocLinks(product);
  const hasVariants = displayedVariants.length > 0;
 
  return (
    <ProductDetailPanelContainer>
      {(images.length > 0 || docLinks.length > 0) && (
        <ProductDetailImageColumn>
          <ProductImageCarousel images={images} title={product.title} />
          {docLinks.length > 0 && <ProductDetailDocLinks>{docLinks}</ProductDetailDocLinks>}
        </ProductDetailImageColumn>
      )}
 
      <ProductDetailContent>
        <SupplierStoreNotice product={product} />
 
        {isPresent(product.description) && (
          <ProductDetailDescription>
            <TruncatedDescription text={product.description} />
          </ProductDetailDescription>
        )}
 
        <ProductDetailBody>
          <ProductDetailFieldsColumn>
            {detailFields.map((field) => (
              <ProductDetailFieldRow key={field.label}>
                <span className="detail-label">{field.label}</span>
                <span className="detail-value">{field.value}</span>
              </ProductDetailFieldRow>
            ))}
            <ProductPriceHistory points={aggregatePoints} userSettings={userSettings} />
          </ProductDetailFieldsColumn>
 
          {product.parentProduct ? (
            <ProductDetailVariantsColumn>
              <ProductDetailFieldRow>
                <span className="detail-label">{i18n('product_detail_parent_product')}</span>
                <span className="detail-value">
                  <Link href={product.parentProduct.permalink ?? product.parentProduct.url}>
                    {product.parentProduct.title}
                  </Link>
                </span>
              </ProductDetailFieldRow>
            </ProductDetailVariantsColumn>
          ) : (
            hasVariants && (
              <ProductDetailVariantsColumn>
                <ProductDetailVariantsGrid>
                  <Typography
                    className="variant-header"
                    variant="caption"
                    color="text.secondary"
                    fontWeight={600}
                  >
                    {i18n('product_detail_variants_currency', [userSettings?.currency ?? 'USD'])}
                  </Typography>
                  {displayedVariants.map((variant, index) => {
                    const variantId = variantSeriesKey(product, variant);
                    const variantSeries = seriesFor(variant);
                    return (
                      <Fragment key={`${variantId ?? variant.title ?? 'variant'}-${index}`}>
                        <span className="variant-name">
                          <Link
                            href={
                              variant.permalink ?? variant.url ?? product.permalink ?? product.url
                            }
                            history={{
                              type: 'product',
                              data: omit({ ...product, ...variant }, 'variants'),
                            }}
                          >
                            {variant.title ?? product.title}
                          </Link>
                        </span>
                        <span className="variant-price">
                          {formatDisplayPrice(variant, userSettings)}
                        </span>
                        <span className="variant-qty">{variantQuantity(variant)}</span>
                        <span className="variant-trend">
                          {variantSeries && variantSeries.points.length >= 2 && (
                            <PriceHistoryTooltip
                              arrow
                              title={
                                <VariantPriceHistoryCard
                                  points={variantSeries.points}
                                  userSettings={userSettings}
                                />
                              }
                            >
                              <span style={{ display: 'inline-flex' }}>
                                <PriceTrend
                                  points={variantSeries.points}
                                  userSettings={userSettings}
                                />
                              </span>
                            </PriceHistoryTooltip>
                          )}
                        </span>
                      </Fragment>
                    );
                  })}
                </ProductDetailVariantsGrid>
              </ProductDetailVariantsColumn>
            )
          )}
        </ProductDetailBody>
      </ProductDetailContent>
    </ProductDetailPanelContainer>
  );
}
 
/**
 * Formats a variant's quantity and unit for the variants list, e.g. `"500 g"`.
 * @param variant - The variant to format.
 * @returns The `"<quantity> <uom>"` string, or `""` when no quantity is set.
 * @example
 * ```ts
 * variantQuantity({ quantity: 500, uom: "g" }); // => "500 g"
 * variantQuantity({}); // => ""
 * ```
 * @source
 */
function variantQuantity(variant: Variant): string {
  if (!isPresent(variant.quantity)) return '';
  return `${variant.quantity} ${variant.uom ?? ''}`.trim();
}