import type { VehicleRealtimeRow } from '../../api/types';
import { formatZhNumber } from './formatters';

export type FleetStatus = 'online' | 'offline' | 'driving' | 'idle' | 'alert' | 'unknown';

export function vehicleStatus(vehicle: VehicleRealtimeRow): FleetStatus {
  if (!vehicle.lastSeen) return 'unknown';
  if (!vehicle.online) return 'offline';
  if (vehicle.speedKmh > 3) return 'driving';
  return 'idle';
}

export function statusLabel(status: FleetStatus) {
  return {
    online: '在线',
    offline: '离线',
    driving: '行驶',
    idle: '静止',
    alert: '告警',
    unknown: '未知'
  }[status];
}

export function relativeFreshness(value: string) {
  const time = Date.parse(value);
  if (!Number.isFinite(time)) return '时间未知';
  const seconds = Math.max(0, Math.round((Date.now() - time) / 1000));
  if (seconds < 60) return `${seconds} 秒前`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟前`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)} 小时前`;
  return `${Math.floor(seconds / 86400)} 天前`;
}

export function formatNumber(value: number, maximumFractionDigits = 0) {
  return formatZhNumber(value, maximumFractionDigits);
}
