const DIGITS = '0123456789';
const H = 1.15; // digit slot height in em

function Digit({ char, delay, active }: { char: string; delay: number; active: boolean }) {
  const idx = DIGITS.indexOf(char);
  if (idx === -1)
    return (
      <span
        aria-hidden="true"
        className="inline-block"
        style={{
          height: `${H}em`,
          lineHeight: `${H}em`,
          overflow: 'hidden',
          verticalAlign: 'top',
        }}
      >
        {char}
      </span>
    );

  const offset = active ? -idx * H : 0;

  return (
    <span
      aria-hidden="true"
      className="inline-block overflow-hidden"
      style={{
        height: `${H}em`,
        lineHeight: `${H}em`,
        overflow: 'hidden',
        verticalAlign: 'top',
      }}
    >
      <span
        className="block"
        style={{
          transform: `translateY(${offset}em)`,
          transition: `transform 0.5s cubic-bezier(0.22, 1, 0.36, 1) ${delay}ms`,
        }}
      >
        {DIGITS.split('').map((d) => (
          <span
            key={d}
            className="block text-center"
            style={{ height: `${H}em`, lineHeight: `${H}em` }}
          >
            {d}
          </span>
        ))}
      </span>
    </span>
  );
}

export function TickerValue({ text, active = true }: { text: string; active?: boolean }) {
  const chars = text.split('');
  const len = chars.length;
  return (
    <span
      aria-label={text}
      className="inline-flex whitespace-nowrap leading-none"
      role="text"
      style={{ fontVariantNumeric: 'tabular-nums' }}
    >
      {chars.map((ch, i) => (
        <Digit key={i} char={ch} delay={(len - 1 - i) * 30} active={active} />
      ))}
    </span>
  );
}
