/**
 * 백엔드 FileType 과 1:1 매칭되는 5종 분류.
 *   image    — jpg, png, gif, webp, heic
 *   video    — mp4, mov, avi, webm
 *   audio    — mp3, wav, m4a, ogg
 *   document — pdf, docx, xlsx, pptx, txt, csv, hwp
 *   file     — 그 외/분류 애매 (zip, json 등)
 */
export type AssetCategory = 'image' | 'video' | 'audio' | 'document' | 'file';
export type UploadCategory = 'all' | AssetCategory;

export const categoryConfig: Record<UploadCategory, { label: string }> = {
  all: { label: '전체' },
  image: { label: 'Image' },
  video: { label: 'Video' },
  audio: { label: 'Audio' },
  document: { label: 'Document' },
  file: { label: 'File' },
};

export const categoryBadge: Record<AssetCategory, string> = {
  image: 'bg-brand-tint-purple text-brand-purple-muted shadow-[2px_3px_6px_rgba(155,138,212,0.12)]',
  video: 'bg-brand-rose-bg text-brand-rose shadow-[2px_3px_6px_rgba(212,136,154,0.12)]',
  audio: 'bg-sky-50 text-sky-700 shadow-[2px_3px_6px_rgba(56,189,248,0.12)]',
  document: 'bg-brand-earth-bg text-brand-earth shadow-[2px_3px_6px_rgba(212,168,114,0.12)]',
  file: 'bg-slate-100 text-slate-600 shadow-[2px_3px_6px_rgba(100,116,139,0.10)]',
};

// 확장자 → 카테고리. 백엔드 분류 규칙과 동일.
const EXT_BY_CATEGORY: Record<AssetCategory, string[]> = {
  image: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'heic'],
  video: ['mp4', 'mov', 'avi', 'webm'],
  audio: ['mp3', 'wav', 'm4a', 'ogg'],
  document: ['pdf', 'docx', 'xlsx', 'pptx', 'txt', 'csv', 'hwp'],
  file: [], // 폴백
};

export const ALL_ACCEPT = (Object.entries(EXT_BY_CATEGORY) as [AssetCategory, string[]][])
  .flatMap(([, exts]) => exts.map((e) => `.${e}`))
  .join(',');

export function categorize(file: File): AssetCategory {
  const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
  for (const [cat, exts] of Object.entries(EXT_BY_CATEGORY) as [AssetCategory, string[]][]) {
    if (exts.includes(ext)) return cat;
  }
  // MIME 폴백 — 확장자 누락된 케이스 보완.
  if (file.type.startsWith('image/')) return 'image';
  if (file.type.startsWith('video/')) return 'video';
  if (file.type.startsWith('audio/')) return 'audio';
  return 'file';
}

export function formatSize(bytes: number): string {
  if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`;
  if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
  return `${bytes} B`;
}

export function uid() {
  return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
