export function formatBytes(n) {
  if (!Number.isFinite(n) || n <= 0) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  let i = 0;
  let v = n;
  while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }
  return `${v.toFixed(v >= 10 || i === 0 ? 0 : 1)} ${units[i]}`;
}

export function when(value) {
  if (!value) return '';
  try {
    return new Intl.DateTimeFormat('en', {
      month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
    }).format(new Date(value));
  } catch { return value; }
}

export function itemKey(item) {
  return `${item.source_type}-${item.id}`;
}

export function itemName(item) {
  return item.source_type === 'artifact' ? (item.title || item.path || item.id) : item.name;
}

export function itemKindLabel(item) {
  if (item.source_type === 'artifact') return item.kind || 'artifact';
  if (item.local_only) return 'local';
  return item.kind || 'file';
}

export function itemAuthorLabel(item) {
  if (item.source_type === 'artifact') {
    const id = item.agent_id || '';
    if (!id) return 'Agent';
    if (id === 'main-orchestrator') return 'Main agent';
    if (id === 'ops-agent') return 'Caretaker';
    return id;
  }
  return 'You';
}
