/**
 * Class-name and number helpers shared by the admin screens.
 */

import { clsx, type ClassValue } from 'clsx';
import { extendTailwindMerge } from 'tailwind-merge';

/**
 * tailwind-merge has to know our `kl-` prefix, or it treats every utility as
 * an unknown class and never dedupes conflicting ones.
 */
const twMerge = extendTailwindMerge( { prefix: 'kl-' } );

/**
 * Join class names, letting later Tailwind utilities override earlier ones.
 *
 * @param inputs Class values, as accepted by `clsx`.
 */
export function cn( ...inputs: ClassValue[] ): string {
	return twMerge( clsx( inputs ) );
}

/**
 * The site's locale in BCP 47 form, for `Intl` formatters.
 */
function locale(): string {
	return window.helpora?.locale || document.documentElement.lang || 'en-US';
}

/**
 * Format a whole number with locale grouping: 12438 → "12,438".
 *
 * @param value Number to format.
 */
export function formatNumber( value: number ): string {
	return new Intl.NumberFormat( locale() ).format( value );
}

/**
 * Format a number compactly for tight columns: 2800 → "2.8K".
 *
 * @param value Number to format.
 */
export function formatCompact( value: number ): string {
	return new Intl.NumberFormat( locale(), {
		notation: 'compact',
		maximumFractionDigits: 1,
	} ).format( value );
}

/**
 * Format an ISO date as a short day label: "2026-09-10" → "Sep 10".
 *
 * @param iso     ISO date, `YYYY-MM-DD`.
 * @param options Extra `Intl.DateTimeFormat` options.
 */
export function formatDay(
	iso: string,
	options: Intl.DateTimeFormatOptions = {}
): string {
	// Noon UTC keeps the calendar day stable in every timezone.
	return new Intl.DateTimeFormat( locale(), {
		month: 'short',
		day: 'numeric',
		timeZone: 'UTC',
		...options,
	} ).format( new Date( `${ iso }T12:00:00Z` ) );
}
