<!-- CollapsibleText.svelte -->

<!-- The CollapsibleText component offers a collapsible text area with truncation functionality.
     It automatically shortens long texts up to a specified maximum length, ensuring the last 
     word before the limit is fully visible.
-->
<script lang="ts">
	import { cn } from '$lib/utils';
	import { Button } from '$lib/components/ui/button/index';
	import { fade } from 'svelte/transition';

	let { text, maxLength = 150, class: className = '' } = $props();
	let isExpanded = $state(false);

	// Derived values using runes
	const shouldCollapse = $derived(text.length > maxLength);

	function truncateText(text: string) {
		if (text.length <= maxLength) return text;

		// Find the last space before maxLength
		const lastSpace = text.slice(0, maxLength).lastIndexOf(' ');

		// If no space found, just use maxLength
		return lastSpace === -1 ? text.slice(0, maxLength) : text.slice(0, lastSpace);
	}

	// Find the last word boundary before maxLength
	let truncatedText = $derived(truncateText(text));

	const displayText = $derived(!shouldCollapse || isExpanded ? text : truncatedText + '...');

	function toggleExpand() {
		isExpanded = !isExpanded;
	}
</script>

<div class={cn('space-y-2', className)}>
	<p class="text-sm text-muted-foreground">
		{#if shouldCollapse}
			<span transition:fade>
				{@html displayText}
			</span>
		{:else}
			{@html text}
		{/if}
	</p>

	{#if shouldCollapse}
		<Button variant="link" class="h-auto p-0 text-sm" onclick={toggleExpand}>
			{isExpanded ? 'Read less' : 'Read more'}
		</Button>
	{/if}
</div>
