'use client';

import {HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {Icon} from '@astryxdesign/core/Icon';
import {ICONS} from '@/shared/utils/icons';
import {formatDelta} from '@/shared/utils/format';

/**
 * Period-over-period change.
 *
 * Direction and goodness are separate ideas: a rise in refunds is bad, a rise
 * in revenue is good. The arrow shows direction, the colour shows whether that
 * direction is good — which is why `isRiseGood` is a required part of the KPI
 * contract rather than an assumption baked in here.
 *
 * This is one of the few places semantic colour is allowed, because the colour
 * IS the information.
 */
export function MetricDelta({
  value,
  isRiseGood = true,
  size = 'sm',
}: {
  value: number;
  isRiseGood?: boolean;
  size?: 'xsm' | 'sm';
}) {
  const isFlat = Math.abs(value) < 0.05;
  const isGood = value > 0 === isRiseGood;

  // Icon exposes semantic colours as props; Text does not (its union stops at
  // primary/secondary/disabled/accent). For the label we go through the
  // Tailwind bridge instead, which maps --color-success/--color-error into
  // utilities — still a token, never a literal.
  const textClass = isFlat
    ? 'text-secondary'
    : isGood
      ? 'text-success'
      : 'text-error';

  return (
    <HStack gap={0.5} vAlign="center">
      {isFlat ? null : (
        <Icon
          icon={value > 0 ? ICONS.up : ICONS.down}
          size="xsm"
          color={isGood ? 'success' : 'error'}
        />
      )}
      <Text size={size} weight="medium" color="inherit" className={textClass}>
        {isFlat ? '—' : formatDelta(value)}
      </Text>
    </HStack>
  );
}
