<script lang="ts">
    type Props = {
        text: string;
        maxChars?: number;
        threshold?: number;  // when to start showing counter
    };
    let { text, maxChars = 1000000, threshold = 750000 }: Props = $props();
    
    const graphemeCount = $derived.by(() => {
        const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
        return [...segmenter.segment(text)].length;
    });
    
    const shouldShow = $derived(graphemeCount > threshold);
    const remaining = $derived(maxChars - graphemeCount);
    const color = $derived(
        graphemeCount > 950000 ? 'text-red-600' :
        graphemeCount > 800000 ? 'text-yellow-600' :
        'text-green-600'
    );
</script>

{#if shouldShow}
    <p class="text-xs {color}">
        {remaining.toLocaleString()} characters remaining ({graphemeCount.toLocaleString()} / {maxChars.toLocaleString()})
    </p>
{/if}
