// Reine Hilfsfunktionen — werden von Server und Client genutzt,
// deshalb bewusst ohne "server-only".

export type FileKind = "image" | "video" | "audio" | "pdf" | "text" | "archive" | "file";

export function kindOf(mime: string, name: string): FileKind {
  const m = (mime ?? "").toLowerCase();
  if (m.startsWith("image/")) return "image";
  if (m.startsWith("video/")) return "video";
  if (m.startsWith("audio/")) return "audio";
  if (m === "application/pdf") return "pdf";
  if (m.startsWith("text/") || m === "application/json") return "text";
  if (/\.(zip|rar|7z|tar|gz)$/i.test(name)) return "archive";
  return "file";
}

export const KIND_ICON: Record<FileKind, string> = {
  image: "image",
  video: "video",
  audio: "music",
  pdf: "document",
  text: "document",
  archive: "archive",
  file: "file",
};

export const KIND_COLOR: Record<FileKind, string> = {
  image: "#9ed7ff",
  video: "#ff9fd7",
  audio: "#c8bcff",
  pdf: "#ff7a9c",
  text: "#a0f0e0",
  archive: "#ffc36b",
  file: "#8aa0c8",
};

export function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
  return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
}

/** Anzeigename säubern: keine Pfadanteile, keine Steuerzeichen. */
export function cleanFileName(raw: string): string {
  // Steuerzeichen über den Zeichencode aussortieren — so steht kein
  // unsichtbares Zeichen im Quelltext.
  const base = [...raw]
    .filter((c) => {
      const code = c.charCodeAt(0);
      return code > 31 && code !== 127;
    })
    .join("")
    .replace(/[\\/]/g, "_")
    .trim();
  return (base || "Datei").slice(0, 255);
}
