---
/**
 * Portable Text Table block component
 *
 * Renders tables from WordPress imports.
 */
export interface Props {
	node: {
		_type: "table";
		_key: string;
		rows: Array<{
			_type: "tableRow";
			_key: string;
			cells: Array<{
				_type: "tableCell";
				_key: string;
				content: Array<{
					_type: "span";
					_key: string;
					text: string;
					marks?: string[];
				}>;
				markDefs?: Array<{
					_type: string;
					_key: string;
					[key: string]: unknown;
				}>;
				isHeader?: boolean;
			}>;
		}>;
		hasHeaderRow?: boolean;
	};
}

const { node } = Astro.props;
const rows = node?.rows ?? [];

if (!rows.length) {
	return null;
}

// Helper to render cell content as text (simplified - doesn't handle marks)
function renderCellText(
	content: Array<{ text: string; marks?: string[] }>,
): string {
	return content.map((span) => span.text).join("");
}
---

{() => {
	const hasHeader = node?.hasHeaderRow;
	const headerRow = hasHeader ? rows[0] : null;
	const bodyRows = hasHeader ? rows.slice(1) : rows;

	return (
		<div class="emdash-table-wrapper">
			<table class="emdash-table">
				{headerRow && (
					<thead>
						<tr>
							{headerRow.cells.map((cell) => (
								<th>{renderCellText(cell.content)}</th>
							))}
						</tr>
					</thead>
				)}
				<tbody>
					{bodyRows.map((row) => (
						<tr>
							{row.cells.map((cell) => {
								const CellTag = cell.isHeader ? "th" : "td";
								return <CellTag>{renderCellText(cell.content)}</CellTag>;
							})}
						</tr>
					))}
				</tbody>
			</table>
		</div>
	);
}}

<style>
	.emdash-table-wrapper {
		margin: 1.5rem 0;
		overflow-x: auto;
	}
	.emdash-table {
		width: 100%;
		border-collapse: collapse;
		font-size: 0.9rem;
	}
	.emdash-table th,
	.emdash-table td {
		border: 1px solid #ddd;
		padding: 0.75rem;
		text-align: left;
	}
	.emdash-table th {
		background: #f5f5f5;
		font-weight: 600;
	}
	.emdash-table tbody tr:nth-child(even) {
		background: #fafafa;
	}
	.emdash-table tbody tr:hover {
		background: #f0f0f0;
	}
</style>
