<script lang="ts">
	import Icon from '@iconify/svelte';
	import { getButtonStyle, parseColorText, getSegmentStyle } from './utils';
	import { themeColors } from '$lib/stores/theme';
	import type { ButtonLine } from './types';
	import '$lib/assets/css/tui-button.css';

	interface Props {
		line: ButtonLine;
		index: number;
		selected: boolean;
		onClick: (idx: number) => void;
		onHover: (idx: number) => void;
		inline?: boolean;
	}

	let {
		line,
		index,
		selected,
		onClick,
		onHover,
		inline = false
	}: Props = $props();

	// Determine if this is an external link
	const isExternal = $derived(line.external || (line.href && (line.href.startsWith('http://') || line.href.startsWith('https://'))));
	
	// Parse color formatting in content using theme colorMap
	const segments = $derived(parseColorText(line.content, $themeColors.colorMap));
</script>

<button
	class="tui-button"
	class:selected={selected}
	class:inline={inline}
	style="--btn-color: {getButtonStyle(line.style)}"
	onclick={() => onClick(index)}
	onmouseenter={() => onHover(index)}
	data-href={line.href || ''}
	data-external={isExternal ? 'true' : 'false'}
>
	<span class="btn-indicator">{selected ? '▶' : ' '}</span>
	{#if line.icon}
		<Icon icon={line.icon} width="16" />
	{/if}
	<span class="btn-text">
		{#each segments as segment}
			{#if segment.icon}
				<Icon icon={segment.icon} width="14" class="inline-icon" />
			{:else if getSegmentStyle(segment)}
				<span style={getSegmentStyle(segment)}>{segment.text}</span>
			{:else}
				{segment.text}
			{/if}
		{/each}
	</span>
	{#if line.href}
		{#if isExternal}
			<Icon icon="mdi:open-in-new" width="14" class="btn-arrow" />
		{:else}
			<Icon icon="mdi:chevron-right" width="16" class="btn-arrow" />
		{/if}
	{/if}
</button>
