"use client";
import { jsxs as z, jsx as i, Fragment as P } from "react/jsx-runtime";
import l from "react";
import { Button as _ } from "./button.js";
import { Card as U, CardHeader as W, CardTitle as H, CardContent as K } from "./card.js";
import { FilePreview as R } from "./file-preview/index.js";
import { Icon as O } from "./icon.js";
import { Input as V } from "./input.js";
const Z = {
  pdf: "application/pdf",
  doc: ".doc",
  docx: ".docx",
  xls: ".xls",
  xlsx: ".xlsx",
  ppt: ".ppt",
  pptx: ".pptx",
  txt: ".txt",
  csv: ".csv",
  jpg: ".jpg",
  jpeg: ".jpeg",
  png: ".png",
  gif: ".gif",
  image: "image/*",
  video: "video/*",
  audio: "audio/*",
  // Keep both extensions and MIME aliases because archive file types are
  // reported inconsistently across browsers and operating systems.
  zip: ".zip,application/zip,application/x-zip-compressed,multipart/x-zip",
  rar: ".rar,application/vnd.rar,application/x-rar-compressed",
  "7z": ".7z,application/x-7z-compressed",
  tar: ".tar,application/x-tar",
  gz: ".gz,application/gzip,application/x-gzip",
  tgz: ".tgz,.tar.gz,application/gzip,application/x-compressed-tar"
}, A = (f) => Math.ceil(f / (1024 * 1024)), re = ({
  extensions: f = ["pdf", "image", "video", "audio"],
  multiple: d = !1,
  onUpload: D,
  onRemove: b,
  description: w = "Trascina un file o clicca per selezionare",
  formatDescription: I = "Formato accettato: PDF, Immagini, Video, Audio",
  selectedLabel: u = "File selezionati",
  maxTotalSize: p,
  removeAllLabel: y = "rimuovi tutto",
  maxFiles: o,
  id: N,
  "data-testid": g
}) => {
  const x = f.map((e) => Z[e]).join(","), [t, m] = l.useState([]), [j, n] = l.useState(""), C = (e) => {
    const s = Array.from(e).filter(
      (r) => x.split(",").some((a) => (a = a.trim(), r.type.startsWith(a.replace("/*", "")) || r.name.toLowerCase().endsWith(a.replace("*", ""))))
    );
    let c = [];
    const h = [];
    if (d) {
      let r = s;
      if (typeof o == "number") {
        const a = Math.max(o - t.length, 0);
        a < s.length && (r = s.slice(0, a), h.push(`Max ${o} file`));
      }
      if (typeof p == "number") {
        const a = p;
        let F = t.reduce((v, S) => v + (S.size || 0), 0);
        const $ = [];
        let k = !1;
        for (const v of r)
          F + (v.size || 0) <= a ? ($.push(v), F += v.size || 0) : k || (h.push(`Max ${A(a)} MB`), k = !0);
        r = $;
      }
      c = [...t, ...r];
    } else {
      const r = s[0] ? [s[0]] : [];
      if (typeof p == "number" && r[0]) {
        const a = p;
        (r[0].size || 0) > a ? (h.push(`Max ${A(a)} MB`), c = t) : c = r;
      } else
        c = r;
    }
    m(c), n(h.join(" • ")), D?.(c);
  }, E = (e) => {
    e.target.files && C(e.target.files), e.target.value = "";
  }, L = (e) => {
    e.preventDefault(), C(e.dataTransfer.files);
  }, M = (e) => {
    const s = t[e], c = t.filter((h, r) => r !== e);
    m(c), n(""), b?.(s ? [s] : [], c);
  }, B = () => {
    const e = t;
    m([]), n(""), b?.(e, []);
  };
  return /* @__PURE__ */ z("div", { className: "mx-auto w-full space-y-4", children: [
    (d || t.length === 0) && /* @__PURE__ */ i(
      q,
      {
        accept: x,
        multiple: d,
        onDrop: L,
        onChange: E,
        description: w,
        formatDescription: I,
        errorCaption: j,
        id: N,
        "data-testid": g
      }
    ),
    t.length > 0 && /* @__PURE__ */ i(P, { children: /* @__PURE__ */ z(U, { size: "sm", className: "shadow-none", children: [
      /* @__PURE__ */ z(W, { className: "flex justify-between", children: [
        /* @__PURE__ */ i(H, { children: u }),
        /* @__PURE__ */ i(
          _,
          {
            size: "sm",
            variant: "ghost",
            className: "text-xs",
            onClick: B,
            children: y
          }
        )
      ] }),
      /* @__PURE__ */ i(K, { children: d ? /* @__PURE__ */ i("div", { className: "flex flex-nowrap gap-2 overflow-x-auto py-2", children: t.map((e, s) => /* @__PURE__ */ i(
        R,
        {
          file: e,
          onRemove: () => M(s)
        },
        e.name + s
      )) }) : /* @__PURE__ */ i(R, { file: t[0], onRemove: () => M(0) }) })
    ] }) })
  ] });
}, q = ({
  accept: f,
  multiple: d,
  onDrop: D,
  onChange: b,
  description: w,
  formatDescription: I,
  errorCaption: u,
  id: p,
  "data-testid": y
}) => {
  const o = l.useRef(null), [N, g] = l.useState(!1), x = l.useId(), t = l.useId(), m = l.useId(), j = l.useId();
  return /* @__PURE__ */ z(
    "div",
    {
      id: p,
      "data-testid": y,
      role: "button",
      tabIndex: 0,
      "aria-label": w || "Seleziona file",
      "aria-describedby": `${x} ${t}${u ? ` ${m}` : ""}`,
      onKeyDown: (n) => {
        (n.key === "Enter" || n.key === " ") && (n.preventDefault(), o.current && (o.current.value = "", o.current.click()));
      },
      onClick: () => {
        o.current && (o.current.value = "", o.current.click());
      },
      onDragEnter: () => g(!0),
      onDragOver: (n) => n.preventDefault(),
      onDragLeave: () => g(!1),
      onDrop: (n) => {
        g(!1), D(n);
      },
      className: `border-d-border flex w-full cursor-pointer flex-col items-center gap-3 rounded-lg border-2 border-dashed px-4 py-8 ${N ? "bg-muted/40" : ""}`,
      children: [
        /* @__PURE__ */ i(
          O,
          {
            name: "ArrowUpFromLine",
            className: "text-d-muted-foreground h-10 w-10"
          }
        ),
        /* @__PURE__ */ z("div", { className: "max-w-xs text-center", children: [
          /* @__PURE__ */ i("p", { id: x, className: "text-d-muted-foreground text-sm font-medium", children: w }),
          /* @__PURE__ */ i(
            "p",
            {
              id: t,
              className: "text-d-muted-foreground text-muted-foreground mt-1 text-xs",
              children: I
            }
          ),
          u ? /* @__PURE__ */ i("p", { id: m, className: "mt-2 text-xs font-medium text-red-600", children: u }) : null
        ] }),
        /* @__PURE__ */ i(
          V,
          {
            ref: o,
            id: j,
            type: "file",
            className: "hidden",
            accept: f,
            multiple: d,
            onChange: b
          }
        )
      ]
    }
  );
};
export {
  re as FileUploader
};
