import { crudFormat, crudLabel } from "../crud/style";
import { extname, getFileType } from "./upload";
const TEXT_EXTS = new Set([
  "txt",
  "md",
  "markdown",
  "json",
  "log",
  "csv",
  "xml",
  "html",
  "htm",
  "css",
  "js",
  "ts",
  "jsx",
  "tsx",
  "vue",
  "yaml",
  "yml",
  "ini",
  "conf",
  "sql"
]);
export function getMediaPreviewKind(path = "") {
  const type = getFileType(path);
  if (type === "image")
    return "image";
  if (type === "video")
    return "video";
  if (type === "audio")
    return "audio";
  return getFilePreviewKind(path);
}
function getFilePreviewKind(path = "") {
  const type = getFileType(path);
  if (type === "pdf")
    return "pdf";
  if (type === "excel")
    return "excel";
  const ext = extname(path);
  if (TEXT_EXTS.has(ext))
    return "text";
  if (type === "word" || type === "ppt")
    return "office";
  return "unsupported";
}
export function fileDisplayName(path = "", fallback) {
  const fb = fallback ?? crudLabel("typeFile");
  const base = String(path).split("?")[0]?.split("/").pop() || "";
  return base || fb;
}
export async function fetchFileText(url) {
  const res = await fetch(url, { credentials: "include" });
  if (!res.ok)
    throw new Error(crudFormat(crudLabel("loadFailedStatus"), res.status));
  return res.text();
}
async function fetchFileArrayBuffer(url) {
  const res = await fetch(url, { credentials: "include" });
  if (!res.ok)
    throw new Error(crudFormat(crudLabel("loadFailedStatus"), res.status));
  return res.arrayBuffer();
}
export async function loadExcelPreviewHtml(url) {
  const mod = await import("xlsx");
  const XLSX = mod.utils != null ? mod : mod.default ?? mod;
  const buf = await fetchFileArrayBuffer(url);
  const wb = XLSX.read(buf, { type: "array" });
  const name = wb.SheetNames[0];
  if (!name)
    return `<p>${crudLabel("emptyWorkbook")}</p>`;
  const sheet = wb.Sheets[name];
  if (!sheet)
    return `<p>${crudLabel("emptySheet")}</p>`;
  return XLSX.utils.sheet_to_html(sheet, {
    id: "vm-file-preview-sheet",
    editable: false
  });
}
