<script lang="ts">
	import { getButtonStyle, parseColorText, getSegmentStyle } from "./utils";
	import { themeColors } from "$lib/stores/theme";
	import type { TableLine } from "./types";
	import "$lib/assets/css/tui-table.css";

	interface Props {
		line: TableLine;
		inline?: boolean;
	}

	let { line, inline = false }: Props = $props();

	const headers = $derived(line.tableHeaders || []);
	const rows = $derived(line.tableRows || []);
</script>

<div
	class="tui-table-wrapper"
	class:inline
	style="--table-accent: {getButtonStyle(line.style)}"
>
	{#if line.content}
		<div class="table-title">{line.content}</div>
	{/if}
	<table class="tui-table">
		{#if headers.length > 0}
			<thead>
				<tr>
					{#each headers as header}
						<th>{header}</th>
					{/each}
				</tr>
			</thead>
		{/if}
		<tbody>
			{#each rows as row, i}
				<tr class:alt={i % 2 === 1}>
					{#each row as cell}
						{@const cellSegments = parseColorText(
							cell,
							$themeColors.colorMap,
						)}
						<td>
							{#each cellSegments as segment}
								{#if getSegmentStyle(segment)}
									<span style={getSegmentStyle(segment)}
										>{segment.text}</span
									>
								{:else}
									{segment.text}
								{/if}
							{/each}
						</td>
					{/each}
				</tr>
			{/each}
		</tbody>
	</table>
</div>

<style>
	.tui-table-wrapper {
		margin: 0.5rem 0;
		border: 1px solid var(--terminal-border);
		border-radius: 6px;
		overflow: hidden;
	}

	.table-title {
		padding: 0.5rem 0.75rem;
		font-weight: 600;
		font-size: 0.85rem;
		color: var(--terminal-text);
		background: rgba(0, 0, 0, 0.1);
		border-bottom: 1px solid var(--terminal-border);
	}

	.tui-table {
		width: 100%;
		border-collapse: collapse;
		font-size: 0.8rem;
	}

	th {
		padding: 0.5rem 0.75rem;
		text-align: left;
		font-weight: 600;
		color: var(--table-accent);
		background: rgba(0, 0, 0, 0.15);
		border-bottom: 1px solid var(--terminal-border);
		white-space: nowrap;
	}

	td {
		padding: 0.4rem 0.75rem;
		color: var(--terminal-text);
		border-bottom: 1px solid var(--terminal-border);
	}

	tr:last-child td {
		border-bottom: none;
	}

	tr.alt {
		background: rgba(0, 0, 0, 0.03);
	}

	tr:hover {
		background: color-mix(in srgb, var(--table-accent) 5%, transparent);
	}
</style>
