import type { CSSProperties, ReactNode } from 'react';
import { cn } from '../../lib/cn';

/**
 * Indian-grouped rupee figure (lakh/crore). e.g. 20000000 → ₹2,00,00,000.
 */
export function formatINR(n: number | null | undefined): string {
  if (n == null || Number.isNaN(n)) return '—';
  const neg = n < 0;
  const s = Math.round(Math.abs(n)).toString();
  let last3 = s.slice(-3);
  let rest = s.slice(0, -3);
  if (rest) last3 = ',' + last3;
  rest = rest.replace(/\B(?=(\d{2})+(?!\d))/g, ',');
  return (neg ? '-' : '') + rest + last3;
}

export type RupeeSize = 'sm' | 'md' | 'lg' | 'xl' | 'hero';
export type RupeeTone = 'default' | 'accent' | 'navy' | 'muted' | 'onNavy';

export interface RupeeAmountProps {
  value: number;
  /** @default "md" */
  size?: RupeeSize;
  /** @default "default" */
  tone?: RupeeTone;
  sub?: ReactNode;
  className?: string;
  style?: CSSProperties;
}

const SIZES: Record<RupeeSize, number> = { sm: 16, md: 22, lg: 32, xl: 44, hero: 64 };
const TONES: Record<RupeeTone, string> = {
  default: 'var(--text-strong)',
  accent: 'var(--sunrise-600)',
  navy: 'var(--navy-900)',
  muted: 'var(--text-muted)',
  onNavy: 'var(--text-on-navy)',
};

/** Oversized confident rupee numeral via Inter Tight. */
export function RupeeAmount({ value, size = 'md', tone = 'default', sub, className, style }: RupeeAmountProps) {
  const fs = SIZES[size];
  return (
    <span className={cn('inline-flex flex-col leading-none font-numeric', className)} style={style}>
      <span
        className="font-extrabold tracking-[-0.02em] nums inline-flex items-baseline gap-0.5"
        style={{ fontSize: fs, color: TONES[tone] }}
      >
        <span className="font-bold" style={{ fontSize: fs * 0.62 }}>
          ₹
        </span>
        {formatINR(value)}
      </span>
      {sub && <span className="font-sans text-xs font-medium text-faint mt-1">{sub}</span>}
    </span>
  );
}
