import {
	NESTED_CHILD_FOCUS_BOX_STYLE,
	useNestedElementChromeState,
} from '@pdfdraft/core/lib/elementSelection';
import type { Element } from '@pdfdraft/core/stores/editor.store.types';
import React, { memo, useMemo, useState } from 'react';
import { ElementToolbar } from '@pdfdraft/core/extensions';
import { __ } from '@wordpress/i18n';
import { ElementControls } from '../../../../../../pdfdraft/resources/editor/core/components/editor/slot-fill/ElementControls';
import { useEditorActions } from '@pdfdraft/core/stores/editor.store';
import { ColorControl } from '../../../../../../pdfdraft/resources/editor/core/components/rich-text/ColorPicker';
import { TypographyControl, TypographyFamilyControl, TypographyWeightControl } from '@pdfdraft/core/components';
import { QueryClientProvider } from '@tanstack/react-query';
import { queryClient } from '../../data-field/query-client';
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from '@pdfdraft/ui/components/select';
import { Switch } from '@pdfdraft/ui/components/switch';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@pdfdraft/ui/components/tooltip';

import { ProGate } from '@pdfdraft/core/components';
import { featureGate } from '@pdfdraft/core/lib/feature-gate';
import type { ProductTableTemplateKey, ProductTableTemplateSettings } from '../constants/types';
import {
	DEFAULT_PRODUCT_TABLE_TEMPLATE_SETTINGS,
	PRODUCT_TABLE_NAMESPACE,
} from '../constants/types';
import { getTemplateSpec } from '../constants/templates';
import { PRODUCT_THUMB_PLACEHOLDER_DATA_URL } from '../../../../constants/product-thumb-placeholder';

type ProductTableFakeItem = {
	productDisplayName: string;
	quantity: number;
	unitPrice: string;
	lineTotal: string;
	sku?: string;
	thumbnailSrc?: string;
};

export type ProductTableProps = {
	data: Element;
	isSelected: boolean;
} & React.HTMLAttributes<HTMLDivElement>;

function getOrderItemsFromWindow(maxRows: number): ProductTableFakeItem[] | null {
	const order = (window as any)?._PDFDRAFT_PDF_INVOICES_FOR_WOOCOMMERCE_ORDER_DATA_ as
		| {
				currency_symbol?: string;
				line_items?: Array<{
					name?: string;
					parent_name?: string;
					quantity?: number;
					price?: number;
					total?: string;
					sku?: string;
					image?: { src?: string };
					meta_data?: Array<{ key?: string; value?: unknown }>;
				}>;
			}
		| undefined;

	if (!order?.line_items || !Array.isArray(order.line_items)) return null;

	const currencySymbol = String(order.currency_symbol ?? '').trim();

	const mapped = order.line_items
		.filter((li) => li && typeof li.quantity === 'number')
		.map((li) => {
			const baseName = String(li.parent_name ?? li.name ?? '').trim();
			const metaNormalized = Array.isArray(li.meta_data)
				? li.meta_data
						.map((m) => {
							const rawKey = String(m.key ?? '').trim();
							if (!rawKey) return '';
							let label = rawKey.replace(/^attribute_/, '').replace(/^pa_/, '');
							label = label.replace(/_/g, ' ');
							const v = String(m.value ?? '').trim();
							return v ? `${label}: ${v}` : '';
						})
						.filter(Boolean)
						.join(', ')
				: '';

			const productDisplayName = metaNormalized
				? `${baseName}${baseName ? ' - ' : ''}${metaNormalized}`
				: baseName || String(li.name ?? '').trim();

			const unitPriceNum =
				typeof li.price === 'number' && Number.isFinite(li.price) ? li.price : 0;
			const unitPrice = `${currencySymbol}${unitPriceNum.toFixed(2)}`.trim();

			return {
				productDisplayName,
				quantity: li.quantity ?? 0,
				unitPrice: unitPrice || '0',
				lineTotal: String(li.total ?? ''),
				sku: li.sku ? String(li.sku) : '',
				thumbnailSrc: li.image?.src ? String(li.image.src) : undefined,
			} satisfies ProductTableFakeItem;
		});

	return mapped.length ? mapped.slice(0, maxRows) : null;
}

function getTwoRowFakeItems(): ProductTableFakeItem[] {
	return [
		{
			productDisplayName: 'T-shirt - Color: Blue, Size: Large',
			quantity: 1,
			unitPrice: '$20.00',
			lineTotal: '$20.00',
			sku: 'SKU-1',
		},
		{
			productDisplayName: 'T-shirt - Color: Black, Size: Medium',
			quantity: 2,
			unitPrice: '$20.00',
			lineTotal: '$40.00',
			sku: 'SKU-2',
		},
	];
}

/** Preview rows aligned with the modern zebra reference (5 alternating bands). */
function getModernZebraFakeItems(): ProductTableFakeItem[] {
	return [
		{
			productDisplayName: 'Linen Set - Color: White - Size: Medium',
			quantity: 2,
			unitPrice: '$15.00',
			lineTotal: '$30.00',
		},
		{
			productDisplayName: 'Cotton Tee - Color: Navy - Size: Large',
			quantity: 1,
			unitPrice: '$22.50',
			lineTotal: '$22.50',
		},
	];
}

export const ProductTable = memo(
	({ data, isSelected: _isSelected, style: divStyle, ...divProps }: ProductTableProps) => {
		const { updateElement } = useEditorActions(['updateElement']);
		const { showChrome, showNestedChildFocus } =
			useNestedElementChromeState(data.id);
		const [alignSelectOpen, setAlignSelectOpen] = useState(false);
		const [templateSelectOpen, setTemplateSelectOpen] = useState(false);

		const templateSettings = {
			...DEFAULT_PRODUCT_TABLE_TEMPLATE_SETTINGS,
			...(data.props ?? {}),
			columns: {
				...DEFAULT_PRODUCT_TABLE_TEMPLATE_SETTINGS.columns,
				...(data.props as any)?.columns,
			},
			textStyle: {
				...(DEFAULT_PRODUCT_TABLE_TEMPLATE_SETTINGS.textStyle ?? {}),
				...((data.props as any)?.textStyle ?? {}),
			},
		} as ProductTableTemplateSettings;
		const templateKey = (templateSettings.template ?? 'minimal') as ProductTableTemplateKey;
		const spec = getTemplateSpec({ template: templateKey, columns: templateSettings.columns });
		const isModernZebra = Boolean(spec.modernZebra);
		const headerBgOverride = templateSettings.headerBackgroundColor?.trim();
		const effectiveHeaderBg = headerBgOverride ? templateSettings.headerBackgroundColor! : spec.headerBg;
		const headerTextOverride = templateSettings.headerTextColor?.trim();
		const modernHeaderText = headerTextOverride
			? templateSettings.headerTextColor!
			: (spec.headerTextColor ?? '#ffffff');
		const zebraEvenBg = spec.zebraEvenBg ?? '#f5f5f5';
		const modernRowRadius = spec.rowBorderRadiusPx ?? 8;
		const modernRowGap = spec.rowGapPx ?? 8;

		const textStyle = templateSettings.textStyle ?? {};
		const modernBodyColor = textStyle.color ?? spec.bodyMutedColor ?? '#6b7280';
		const textAlign = textStyle.textAlign ?? 'left';
		const textColor = textStyle.color;
		const effectiveHeaderTextColor = headerTextOverride
			? templateSettings.headerTextColor!
			: textColor;
		const textFontFamily = textStyle.fontFamily;
		const textFontWeight = textStyle.fontWeight;

		const showProductName = Boolean(templateSettings.columns?.showProductName);
		const showQuantity = Boolean(templateSettings.columns?.showQuantity);
		const showUnitPrice = Boolean(templateSettings.columns?.showUnitPrice);
		const showLineTotal = Boolean(templateSettings.columns?.showLineTotal);
		const showSku = Boolean(templateSettings.columns?.showSku);
		const showThumbnail = Boolean(templateSettings.columns?.showThumbnail);

		const elementWidthPx = useMemo(() => {
			const raw = data.style?.width ?? data.props?.style?.width;
			if (typeof raw === 'number') return Math.max(180, raw);
			if (typeof raw === 'string') {
				const n = parseFloat(raw.replace('px', ''));
				return Number.isFinite(n) ? Math.max(180, n) : 280;
			}
			return 280;
		}, [data.style?.width, data.props?.style]);

		const colWidthsPx = useMemo(() => {
			// Distribute a fixed width into weighted columns.
			const weights: number[] = [
				// thumbnail (first)
				showThumbnail ? 1.25 : 0,
				// product name
				showProductName ? 2.0 : 0,
				// quantity
				showQuantity ? 1.0 : 0,
				// unit price
				showUnitPrice ? 1.0 : 0,
				// line total
				showLineTotal ? 1.0 : 0,
				// sku (optional)
				showSku ? 1.0 : 0,
			];
			const sum = weights.reduce((a, b) => a + b, 0) || 1;
			return weights.map((w) => Math.round((w / sum) * elementWidthPx));
		}, [
			elementWidthPx,
			showProductName,
			showQuantity,
			showUnitPrice,
			showLineTotal,
			showSku,
			showThumbnail,
		]);

		const border = `${spec.borderWidthPx}px solid ${spec.borderColor}`;
		const tableStyle: React.CSSProperties = {
			width: `${elementWidthPx}px`,
			height: '100%',
			borderCollapse: 'collapse',
			tableLayout: 'fixed',
			fontSize: `${spec.fontSizePx}px`,
			lineHeight: spec.lineHeight,
			background: 'transparent',
			fontFamily: textFontFamily,
		};

		const cellStyle: React.CSSProperties = {
			border,
			padding: `${spec.cellPaddingPx}px`,
			verticalAlign: 'top',
			wordWrap: 'break-word',
			overflow: 'hidden',
			textAlign,
			color: textColor,
			fontWeight: textFontWeight,
		};

		const headerCellStyle: React.CSSProperties = {
			...cellStyle,
			background: effectiveHeaderBg,
			color: effectiveHeaderTextColor,
			fontWeight: textFontWeight ?? spec.headerFontWeight,
		};

		const imgStyle: React.CSSProperties = {
			width: `${spec.thumbnailSizePx}px`,
			height: `${spec.thumbnailSizePx}px`,
			objectFit: 'cover',
			display: 'block',
		};

		const modernTableStyle: React.CSSProperties = {
			width: `${elementWidthPx}px`,
			height: '100%',
			borderCollapse: 'separate',
			borderSpacing: `0 ${modernRowGap}px`,
			marginTop: `-${modernRowGap}px`,
			tableLayout: 'fixed',
			fontSize: `${spec.fontSizePx}px`,
			lineHeight: spec.lineHeight,
			background: 'transparent',
			fontFamily: textFontFamily,
		};

		const modernTh = (
			align: React.CSSProperties['textAlign'],
			isFirst: boolean,
			isLast: boolean,
		): React.CSSProperties => ({
			border: 'none',
			padding: `${spec.cellPaddingPx}px`,
			verticalAlign: 'middle',
			background: effectiveHeaderBg,
			color: modernHeaderText,
			fontWeight: spec.headerFontWeight,
			textAlign: align,
			height: `${spec.headerHeightPx}px`,
			borderTopLeftRadius: isFirst ? modernRowRadius : 0,
			borderTopRightRadius: isLast ? modernRowRadius : 0,
			fontFamily: textFontFamily,
		});

		const modernTd = (
			align: React.CSSProperties['textAlign'],
			rowIndex: number,
			isFirst: boolean,
			isLast: boolean,
		): React.CSSProperties => {
			const isGray = rowIndex % 2 === 1;
			return {
				border: 'none',
				padding: `${spec.cellPaddingPx}px`,
				verticalAlign: 'top',
				wordWrap: 'break-word',
				overflow: 'hidden',
				textAlign: align,
				color: modernBodyColor,
				fontWeight: textFontWeight ?? 400,
				fontFamily: textFontFamily,
				background: isGray ? zebraEvenBg : '#ffffff',
				height: `${spec.rowHeightPx}px`,
				borderTopLeftRadius: isGray && isFirst ? modernRowRadius : 0,
				borderBottomLeftRadius: isGray && isFirst ? modernRowRadius : 0,
				borderTopRightRadius: isGray && isLast ? modernRowRadius : 0,
				borderBottomRightRadius: isGray && isLast ? modernRowRadius : 0,
			};
		};

		// Editor preview: classic =2 rows; modern zebra = 2 rows (or live order data).
		const items = useMemo(() => {
			if (!isModernZebra) return getTwoRowFakeItems();
			const fromOrder = getOrderItemsFromWindow(2);
			if (fromOrder?.length) {
				const fallback = getModernZebraFakeItems();
				return [...fromOrder, ...fallback].slice(0, 2);
			}
			return getModernZebraFakeItems();
		}, [isModernZebra]);

		const patchTemplate = (nextTemplate: ProductTableTemplateKey) => {
			updateElement(data.id, (prev: any) => ({
				...prev,
				props: {
					...(prev.props ?? {}),
					template: nextTemplate,
				},
			}));
		};

		const patchColumnToggle = (
			key:
				| 'showProductName'
				| 'showQuantity'
				| 'showUnitPrice'
				| 'showLineTotal'
				| 'showSku'
				| 'showThumbnail',
			value: boolean,
		) => {
			updateElement(data.id, (prev: any) => ({
				...prev,
				props: {
					...(prev.props ?? {}),
					columns: {
						...(prev.props?.columns ?? {}),
						[key]: value,
					},
				},
			}));
		};

		const patchTextStyle = (patch: Partial<NonNullable<ProductTableTemplateSettings['textStyle']>>) => {
			updateElement(data.id, (prev: any) => ({
				...prev,
				props: {
					...(prev.props ?? {}),
					textStyle: {
						...(prev.props?.textStyle ?? {}),
						...patch,
					},
				},
			}));
		};

		const patchHeaderBackground = (value?: string) => {
			const trimmed = value?.trim();
			updateElement(data.id, (prev: any) => ({
				...prev,
				props: {
					...(prev.props ?? {}),
					...(trimmed ? { headerBackgroundColor: trimmed } : { headerBackgroundColor: undefined }),
				},
			}));
		};

		const patchHeaderTextColor = (value?: string) => {
			const trimmed = value?.trim();
			updateElement(data.id, (prev: any) => ({
				...prev,
				props: {
					...(prev.props ?? {}),
					...(trimmed ? { headerTextColor: trimmed } : { headerTextColor: undefined }),
				},
			}));
		};

		type VisCol = {
			id: 'thumb' | 'product' | 'qty' | 'unit' | 'total' | 'sku';
			label: string;
			align: React.CSSProperties['textAlign'];
		};
		const visCols: VisCol[] = [
			showThumbnail ? { id: 'thumb', label: 'Thumbnail', align: 'center' } : null,
			showProductName ? { id: 'product', label: 'Product Name', align: 'left' } : null,
			showQuantity ? { id: 'qty', label: 'Quantity', align: 'center' } : null,
			showUnitPrice ? { id: 'unit', label: 'Price (Unit Price)', align: 'right' } : null,
			showLineTotal ? { id: 'total', label: 'Total (line total)', align: 'right' } : null,
			showSku ? { id: 'sku', label: 'SKU', align: 'left' } : null,
		].filter(Boolean) as VisCol[];

		return (
			<div
				{...divProps}
				style={{
					position: 'absolute',
					...(divStyle || {}),
					...(showNestedChildFocus ? NESTED_CHILD_FOCUS_BOX_STYLE : {}),
					overflow: isModernZebra ? 'visible' : undefined,
				}}
				data-id={data.id}
				data-type={PRODUCT_TABLE_NAMESPACE}
			>
				{showChrome && (
					<ElementToolbar>
						<div className="flex flex-nowrap items-center gap-2 rounded-md bg-white px-3 py-[9px] shadow-[0px_6px_24px_0px_rgba(10,10,10,0.08)]">
							<QueryClientProvider client={queryClient}>
								<TypographyControl
									currentFontFamily={textFontFamily}
									currentFontWeight={textFontWeight?.toString()}
									onFamilyChange={(font) => {
										const currentWeight = textFontWeight?.toString() ?? '400';
										const hasCurrentWeight = font.variants.find(
											(x) => x.toString() === currentWeight,
										);
										const newWeight = hasCurrentWeight
											? currentWeight
											: font.defVariant === 'regular'
												? '400'
												: (font.defVariant ?? '400');
										patchTextStyle({ fontFamily: font.family, fontWeight: newWeight });
									}}
									onWeightChange={(weight) => patchTextStyle({ fontWeight: weight })}
								>
									<TypographyFamilyControl />
									<TypographyWeightControl />
								</TypographyControl>
							</QueryClientProvider>
							<TooltipProvider delayDuration={0}>
								<Tooltip open={alignSelectOpen ? false : undefined}>
									<TooltipTrigger asChild>
										<span>
											<Select
												value={textAlign}
												open={alignSelectOpen}
												onOpenChange={setAlignSelectOpen}
												onValueChange={(v: string) =>
													patchTextStyle({ textAlign: v as any })
												}
											>
												<SelectTrigger className="h-auto w-auto gap-1 rounded border-input p-1 text-sm leading-[20px]">
													<SelectValue />
												</SelectTrigger>
												<SelectContent className="shadow-none">
													<SelectItem value="left">Left</SelectItem>
													<SelectItem value="center">Center</SelectItem>
													<SelectItem value="right">Right</SelectItem>
												</SelectContent>
											</Select>
										</span>
									</TooltipTrigger>
									<TooltipContent align="center" side="bottom" sideOffset={10}>
										{__('Text Align', 'pdfdraft-pdf-invoices-for-woocommerce')}
									</TooltipContent>
								</Tooltip>
							</TooltipProvider>
							<ProGate locked={!featureGate.canChangeColors()}>
								<div className="flex flex-nowrap items-center gap-2">
									<ColorControl
										tooltipLabel={__(
											'Text Color',
											'pdfdraft-pdf-invoices-for-woocommerce',
										)}
										currentColor={textColor}
										onColorChange={(v?: string) => patchTextStyle({ color: v })}
									/>
									<ColorControl
										tooltipLabel={__(
											'Header background',
											'pdfdraft-pdf-invoices-for-woocommerce',
										)}
										currentColor={effectiveHeaderBg}
										onColorChange={(v?: string) => patchHeaderBackground(v)}
									/>
									<ColorControl
										tooltipLabel={__(
											'Header text color',
											'pdfdraft-pdf-invoices-for-woocommerce',
										)}
										currentColor={
											effectiveHeaderTextColor ??
											(isModernZebra ? modernHeaderText : undefined)
										}
										onColorChange={(v?: string) => patchHeaderTextColor(v)}
									/>
								</div>
							</ProGate>
							<TooltipProvider delayDuration={0}>
								<Tooltip open={templateSelectOpen ? false : undefined}>
									<TooltipTrigger asChild>
										<span>
											<Select
												value={templateKey}
												open={templateSelectOpen}
												onOpenChange={setTemplateSelectOpen}
												onValueChange={(v: string) =>
													patchTemplate(v as ProductTableTemplateKey)
												}
											>
												<SelectTrigger className="h-auto w-auto gap-1 rounded border-input p-1 text-sm leading-[20px]">
													<SelectValue />
												</SelectTrigger>
												<SelectContent className="shadow-none">
													<SelectItem value="minimal">
														{__('Minimal', 'pdfdraft-pdf-invoices-for-woocommerce')}
													</SelectItem>
													<SelectItem value="classic">
														{__('Classic', 'pdfdraft-pdf-invoices-for-woocommerce')}
													</SelectItem>
													<SelectItem value="compact">
														{__('Compact', 'pdfdraft-pdf-invoices-for-woocommerce')}
													</SelectItem>
													<SelectItem value="invoice_bold">
														{__('Invoice Bold', 'pdfdraft-pdf-invoices-for-woocommerce')}
													</SelectItem>
													<SelectItem value="modern_zebra">
														{__('Modern', 'pdfdraft-pdf-invoices-for-woocommerce')}
													</SelectItem>
												</SelectContent>
											</Select>
										</span>
									</TooltipTrigger>
									<TooltipContent align="center" side="bottom" sideOffset={10}>
										{__('Template', 'pdfdraft-pdf-invoices-for-woocommerce')}
									</TooltipContent>
								</Tooltip>
							</TooltipProvider>
						</div>
					</ElementToolbar>
				)}
				{showChrome && (
					<ElementControls>
						<div>
							<p className="mb-3 text-xs font-semibold uppercase tracking-widest text-[#888]">
								{__('Table Columns', 'pdfdraft-pdf-invoices-for-woocommerce')}
							</p>
							<div className="space-y-2">
								{[
									{ id: 'pdfdraft-product-table-col-name',       label: __('Product Name', 'pdfdraft-pdf-invoices-for-woocommerce'),      checked: showProductName, key: 'showProductName' as const },
									{ id: 'pdfdraft-product-table-col-qty',        label: __('Quantity', 'pdfdraft-pdf-invoices-for-woocommerce'),           checked: showQuantity,    key: 'showQuantity' as const },
									{ id: 'pdfdraft-product-table-col-unit-price', label: __('Price (Unit Price)', 'pdfdraft-pdf-invoices-for-woocommerce'), checked: showUnitPrice,   key: 'showUnitPrice' as const },
									{ id: 'pdfdraft-product-table-col-line-total', label: __('Total (Line Total)', 'pdfdraft-pdf-invoices-for-woocommerce'), checked: showLineTotal,   key: 'showLineTotal' as const },
									{ id: 'pdfdraft-product-table-col-sku',        label: __('SKU', 'pdfdraft-pdf-invoices-for-woocommerce'),                checked: showSku,         key: 'showSku' as const },
									{ id: 'pdfdraft-product-table-col-thumbnail',  label: __('Thumbnail', 'pdfdraft-pdf-invoices-for-woocommerce'),          checked: showThumbnail,   key: 'showThumbnail' as const },
								].map((col) => (
									<div
										key={col.id}
										className="flex items-center justify-between rounded-xl border border-border/70 bg-white px-4 py-3"
									>
										<span className="text-sm font-medium text-[#1d2327]">{col.label}</span>
										<div style={{ transform: 'scale(0.9)', transformOrigin: 'right center', flexShrink: 0 }}>
											<Switch
												id={col.id}
												checked={col.checked}
												onCheckedChange={(checked) => patchColumnToggle(col.key, checked)}
											/>
										</div>
									</div>
								))}
							</div>
						</div>
					</ElementControls>
				)}
				{isModernZebra ? (
					<table style={modernTableStyle}>
						<colgroup>
							{showThumbnail ? (
								<col style={{ width: `${colWidthsPx[0]}px` }} />
							) : null}
							{showProductName ? (
								<col style={{ width: `${colWidthsPx[1]}px` }} />
							) : null}
							{showQuantity ? (
								<col style={{ width: `${colWidthsPx[2]}px` }} />
							) : null}
							{showUnitPrice ? (
								<col style={{ width: `${colWidthsPx[3]}px` }} />
							) : null}
							{showLineTotal ? (
								<col style={{ width: `${colWidthsPx[4]}px` }} />
							) : null}
							{showSku ? <col style={{ width: `${colWidthsPx[5]}px` }} /> : null}
						</colgroup>
						<thead>
							<tr>
								{visCols.map((c, i) => (
									<th key={c.id} style={modernTh(c.align, i === 0, i === visCols.length - 1)}>
										{c.label}
									</th>
								))}
							</tr>
						</thead>
						<tbody>
							{items.map((item, rowIdx) => (
								<tr key={rowIdx}>
									{visCols.map((c, i) => {
										const st = modernTd(c.align, rowIdx, i === 0, i === visCols.length - 1);
										const cellKey = `${rowIdx}-${c.id}`;
										if (c.id === 'thumb') {
											return (
												<td key={cellKey} style={st}>
													<img
														alt=""
														src={item.thumbnailSrc ?? PRODUCT_THUMB_PLACEHOLDER_DATA_URL}
														style={imgStyle}
													/>
												</td>
											);
										}
										if (c.id === 'product') {
											return (
												<td key={cellKey} style={st}>
													<div>{item.productDisplayName}</div>
												</td>
											);
										}
										if (c.id === 'qty') {
											return (
												<td key={cellKey} style={st}>
													<div>{item.quantity}</div>
												</td>
											);
										}
										if (c.id === 'unit') {
											return (
												<td key={cellKey} style={st}>
													<div>{item.unitPrice}</div>
												</td>
											);
										}
										if (c.id === 'total') {
											return (
												<td key={cellKey} style={st}>
													<div>{item.lineTotal}</div>
												</td>
											);
										}
										return (
											<td key={cellKey} style={st}>
												<div>{item.sku ?? ''}</div>
											</td>
										);
									})}
								</tr>
							))}
						</tbody>
					</table>
				) : (
					<table style={tableStyle}>
						<colgroup>
							{showThumbnail ? (
								<col style={{ width: `${colWidthsPx[0]}px` }} />
							) : null}
							{showProductName ? (
								<col style={{ width: `${colWidthsPx[1]}px` }} />
							) : null}
							{showQuantity ? (
								<col style={{ width: `${colWidthsPx[2]}px` }} />
							) : null}
							{showUnitPrice ? (
								<col style={{ width: `${colWidthsPx[3]}px` }} />
							) : null}
							{showLineTotal ? (
								<col style={{ width: `${colWidthsPx[4]}px` }} />
							) : null}
							{showSku ? <col style={{ width: `${colWidthsPx[5]}px` }} /> : null}
						</colgroup>
						<thead>
							<tr>
								{showThumbnail ? (
									<th
										style={{
											...headerCellStyle,
											height: `${spec.headerHeightPx}px`,
										}}
									>
										Thumbnail
									</th>
								) : null}
								{showProductName ? (
									<th
										style={{
											...headerCellStyle,
											height: `${spec.headerHeightPx}px`,
										}}
									>
										Product Name
									</th>
								) : null}
								{showQuantity ? (
									<th
										style={{
											...headerCellStyle,
											height: `${spec.headerHeightPx}px`,
										}}
									>
										Quantity
									</th>
								) : null}
								{showUnitPrice ? (
									<th
										style={{
											...headerCellStyle,
											height: `${spec.headerHeightPx}px`,
										}}
									>
										Price (Unit Price)
									</th>
								) : null}
								{showLineTotal ? (
									<th
										style={{
											...headerCellStyle,
											height: `${spec.headerHeightPx}px`,
										}}
									>
										Total (line total)
									</th>
								) : null}
								{showSku ? (
									<th
										style={{
											...headerCellStyle,
											height: `${spec.headerHeightPx}px`,
										}}
									>
										SKU
									</th>
								) : null}
							</tr>
						</thead>
						<tbody>
							{items.map((item, idx) => (
								<tr key={idx} style={{ height: `${spec.rowHeightPx}px` }}>
									{showThumbnail ? (
										<td style={cellStyle}>
											<img
												alt=""
												src={item.thumbnailSrc ?? PRODUCT_THUMB_PLACEHOLDER_DATA_URL}
												style={imgStyle}
											/>
										</td>
									) : null}
									{showProductName ? (
										<td style={cellStyle}>
											<div>{item.productDisplayName}</div>
										</td>
									) : null}
									{showQuantity ? (
										<td style={cellStyle}>
											<div>{item.quantity}</div>
										</td>
									) : null}
									{showUnitPrice ? (
										<td style={cellStyle}>
											<div>{item.unitPrice}</div>
										</td>
									) : null}
									{showLineTotal ? (
										<td style={cellStyle}>
											<div>{item.lineTotal}</div>
										</td>
									) : null}
									{showSku ? (
										<td style={cellStyle}>
											<div>{item.sku ?? ''}</div>
										</td>
									) : null}
								</tr>
							))}
						</tbody>
					</table>
				)}
			</div>
		);
	},
);

