import { formatUnits } from 'viem';

export function getAddressShortName(address: string) {
  if (!address) {
    return '';
  }
  const addressBegin = address.substring(0, 6);
  const addressEnd = address.substring(address.length - 4, address.length);
  return addressBegin + '...' + addressEnd;
}

export function relativeTime(timestamp: string | number): string {
  try {
    const sec = typeof timestamp === 'string' ? Number(timestamp) : timestamp;
    const nowSec = Math.floor(Date.now() / 1000);
    const diff = nowSec - sec;
    if (diff < 60) return 'just now';
    if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
    return `${Math.floor(diff / 86400)}d ago`;
  } catch {
    return '';
  }
}

export function parseTokenAmount(rawWei: string, decimals = 18): number {
  try {
    return Number(formatUnits(BigInt(rawWei), decimals));
  } catch {
    return 0;
  }
}
