export const MAX_PHOTO_BYTES = 2 * 1024 * 1024;
export const PHOTO_BUCKET = 'customer-avatars';
export const photoTypes = ['image/jpeg', 'image/png', 'image/webp'] as const;

export function photoType(bytes: Uint8Array): typeof photoTypes[number] | null {
  if (bytes.length < 12) return null;
  if ([137,80,78,71,13,10,26,10].every((byte, i) => bytes[i] === byte)) return 'image/png';
  if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return 'image/jpeg';
  const ascii = (start: number, end: number) => String.fromCharCode(...bytes.slice(start, end));
  if (ascii(0,4) === 'RIFF' && ascii(8,12) === 'WEBP') return 'image/webp';
  return null;
}

export function ownPhotoPath(path: unknown, userId: string): path is string {
  return typeof path === 'string' && path.startsWith(userId + '/') &&
    /^[0-9a-f-]{36}\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(png|jpg|webp)$/.test(path);
}

export function profileInitial(name: string) {
  const clean = name.trim().replace(/[\u200b\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
  return Array.from(new Intl.Segmenter(undefined, {granularity: 'grapheme'}).segment(clean))[0]?.segment.toLocaleUpperCase() || '';
}

export function profilePhotoUrl(userId: string, path?: string | null) {
  return path ? `/api/avatar?user=${encodeURIComponent(userId)}&v=${encodeURIComponent(path.split('/').pop() || '')}` : undefined;
}
