"use client";

import { useSafeIntl } from "@kopexa/i18n";
import { cn } from "@kopexa/shared-utils";
import {
	getScale,
	type ImpactLevel,
	type ImpactScaleConfig,
	type ImpactScalePreset,
} from "./scales";

export interface ImpactBadgeProps {
	/** Impact level 0-5 */
	level: ImpactLevel | number | null | undefined;
	/** Scale preset or custom scale config */
	scale?: ImpactScalePreset | ImpactScaleConfig;
	/** Show numeric value before label */
	showValue?: boolean;
	/** Additional class names */
	className?: string;
}

/**
 * ImpactBadge displays an impact level as a colored badge.
 *
 * @example
 * ```tsx
 * <ImpactBadge level={3} scale="risk" />
 * <ImpactBadge level={4} scale="asset" showValue />
 * ```
 */
export function ImpactBadge({
	level,
	scale = "risk",
	showValue = false,
	className,
}: ImpactBadgeProps) {
	const intl = useSafeIntl();

	// Normalize level to ImpactLevel
	const normalizedLevel: ImpactLevel =
		level === null || level === undefined
			? 0
			: ((Math.min(5, Math.max(0, Math.round(level))) as ImpactLevel) ?? 0);

	// Resolve scale config
	const scaleConfig: ImpactScaleConfig =
		typeof scale === "string" ? getScale(scale) : scale;

	const config = scaleConfig[normalizedLevel];
	const isUnrated = normalizedLevel === 0;

	// Get label from i18n or fallback
	const label = intl.formatMessage(config.message);

	return (
		<span
			className={cn(
				"inline-flex items-center gap-1.5 text-sm font-medium px-2 py-0.5 rounded",
				isUnrated
					? "text-muted-foreground bg-muted"
					: `${config.color} ${config.bgColor}`,
				className,
			)}
		>
			{showValue && !isUnrated && (
				<span className="text-xs font-mono opacity-70">{normalizedLevel}</span>
			)}
			{label}
		</span>
	);
}
