type WindDirectionIndicatorProps = {
    degrees: number;
    size?: 'sm' | 'md';
    showLabel?: boolean;
};

const CARDINAL_DIRECTIONS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];

function normalizeDegrees(degrees: number): number {
    return ((degrees % 360) + 360) % 360;
}

function cardinalDirection(degrees: number): string {
    const normalizedDirection = normalizeDegrees(degrees);
    const index = Math.round(normalizedDirection / 45) % CARDINAL_DIRECTIONS.length;

    return CARDINAL_DIRECTIONS[index];
}

export default function WindDirectionIndicator({
    degrees,
    size = 'md',
    showLabel = true,
}: WindDirectionIndicatorProps) {
    const normalizedDirection = normalizeDegrees(degrees);
    const dimensionClass = size === 'sm' ? 'size-9' : 'size-12';
    const iconSize = size === 'sm' ? 36 : 48;

    return (
        <div className="flex items-center gap-3">
            <div
                className={`relative flex items-center justify-center rounded-full border border-border bg-background/80 ${dimensionClass}`}
            >
                <span className="absolute top-1 text-[9px] font-semibold tracking-[0.25em] text-muted-foreground">
                    N
                </span>
                <svg
                    viewBox="0 0 48 48"
                    width={iconSize}
                    height={iconSize}
                    className="text-primary"
                    aria-hidden="true"
                >
                    <circle
                        cx="24"
                        cy="24"
                        r="18"
                        fill="none"
                        stroke="currentColor"
                        strokeOpacity="0.18"
                        strokeWidth="2"
                    />
                    <g transform={`rotate(${normalizedDirection} 24 24)`}>
                        <path d="M24 8 L29 24 L24 20 L19 24 Z" fill="currentColor" />
                        <path
                            d="M24 39 L21 24 L24 27 L27 24 Z"
                            fill="currentColor"
                            fillOpacity="0.28"
                        />
                    </g>
                </svg>
            </div>

            {showLabel ? (
                <div className="min-w-0">
                    <div className="font-semibold text-foreground">
                        {normalizedDirection.toFixed(0)}°
                    </div>
                    <div className="text-xs text-muted-foreground">
                        {cardinalDirection(normalizedDirection)}
                    </div>
                </div>
            ) : null}
        </div>
    );
}
