<script lang="ts">
	import { formatPremierRating, getPremierRatingChange } from '$lib/utils/formatters';
	import { Trophy, TrendingUp, TrendingDown } from 'lucide-svelte';
	import RankIcon from './RankIcon.svelte';

	interface Props {
		rating: number | undefined | null;
		oldRating?: number | undefined | null;
		size?: 'sm' | 'md' | 'lg';
		showTier?: boolean;
		showChange?: boolean;
		showIcon?: boolean;
		class?: string;
	}

	let {
		rating,
		oldRating,
		size = 'md',
		showTier = false,
		showChange = false,
		showIcon = true,
		class: className = ''
	}: Props = $props();

	// Determine if this is a legacy CS:GO match (has old rank but no new rating)
	// CS:GO skill groups are 0-18, CS2 ratings are typically > 1000
	const isLegacyRank = $derived(
		oldRating !== undefined &&
			oldRating !== null &&
			oldRating >= 0 &&
			oldRating <= 18 &&
			(!rating || rating === 0 || rating > 30000)
	);

	// Debug logging (temporary)
	$effect(() => {
		if (oldRating !== undefined || rating !== undefined) {
			console.log('[PremierRatingBadge]', {
				oldRating,
				rating,
				isLegacyRank
			});
		}
	});

	const tierInfo = $derived(formatPremierRating(rating));
	const changeInfo = $derived(showChange ? getPremierRatingChange(oldRating, rating) : null);

	const baseClasses = 'inline-flex items-center gap-1.5 border rounded-lg font-medium';

	const sizeClasses = {
		sm: 'px-2 py-0.5 text-xs',
		md: 'px-3 py-1 text-sm',
		lg: 'px-4 py-2 text-base'
	};

	const iconSizes = {
		sm: 'h-3 w-3',
		md: 'h-4 w-4',
		lg: 'h-5 w-5'
	};

	const classes = $derived(
		`${baseClasses} ${tierInfo.cssClasses} ${sizeClasses[size]} ${className}`
	);
</script>

{#if isLegacyRank}
	<!-- Show CS:GO rank icon for legacy matches -->
	<RankIcon skillGroup={oldRating} {size} class={className} />
{:else if !rating || rating === 0}
	<!-- No rating available -->
	<span class="text-sm text-base-content/50">Unranked</span>
{:else}
	<!-- Show Premier rating for CS2 matches -->
	<div class={classes}>
		{#if showIcon}
			<Trophy class={iconSizes[size]} />
		{/if}

		<span>{tierInfo.formatted}</span>

		{#if showTier}
			<span class="opacity-75">({tierInfo.tier})</span>
		{/if}

		{#if showChange && changeInfo}
			<span class="ml-1 flex items-center gap-0.5 {changeInfo.cssClasses}">
				{#if changeInfo.isPositive}
					<TrendingUp class={iconSizes[size]} />
				{:else if changeInfo.change < 0}
					<TrendingDown class={iconSizes[size]} />
				{/if}
				{changeInfo.display}
			</span>
		{/if}
	</div>
{/if}
