import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
    return twMerge(clsx(inputs))
}


export function relativeTime(dtString: string): string {
    /**
     * Convert a datetime string to a relative time string.
     *
     * Args:
     *   dtString (string): A datetime string in the format "YYYY-MM-DDTHH:MM:SS+HHMM"
     *
     * Returns:
     *   string: A relative time string, e.g. "1 Hour ago", "2 Weeks ago", etc.
     */
    const dt = new Date(dtString);
    const now = new Date();
    const diff = now.getTime() - dt.getTime();

    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    const weeks = Math.floor(days / 7);
    const months = Math.floor(days / 30);

    if (months >= 3) {
        return dt.toISOString().split('T')[0];
    } else if (months > 0) {
        return `${months} month${months > 1 ? 's' : ''} ago`;
    } else if (weeks > 0) {
        return `${weeks} week${weeks > 1 ? 's' : ''} ago`;
    } else if (days > 0) {
        return `${days} day${days > 1 ? 's' : ''} ago`;
    } else if (hours > 0) {
        return `${hours} hour${hours > 1 ? 's' : ''} ago`;
    } else if (minutes > 0) {
        return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
    } else {
        return `${seconds} second${seconds > 1 ? 's' : ''} ago`;
    }
}


export function getFirstGrapheme(text: string): string {
    // Get the first grapheme (visible character) from a string
    if (!text || text.length === 0) return '';

    // Use Intl.Segmenter for proper grapheme segmentation (modern browsers)
    if (typeof Intl !== 'undefined' && Intl.Segmenter) {
        const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
        const segments = segmenter.segment(text);
        const iterator = segments[Symbol.iterator]();
        const firstSegment = iterator.next();
        return firstSegment.done ? '' : firstSegment.value.segment;
    }

    // Fallback for environments without Intl.Segmenter
    // This handles many but not all cases correctly
    return Array.from(text)[0] || '';
};
