import { jsxs as i, Fragment as J, jsx as e } from "react/jsx-runtime";
import { useId as V, useRef as y, useState as d, useCallback as s } from "react";
import { u as q } from "./index-CkhZlaGj.js";
function Z({
  isOpen: U,
  onClose: w,
  onInsert: u,
  onImageUpload: v
}) {
  const N = V(), R = y(null), [p, L] = d(v ? "upload" : "url"), [r, D] = d(""), [g, C] = d(""), [B, h] = d(!1), [T, k] = d(!1), [f, c] = d(null), [P, l] = d(""), F = y(null), m = y(null), j = s(() => {
    m.current && (URL.revokeObjectURL(m.current), m.current = null), D(""), C(""), c(null), l(""), k(!1), h(!1);
  }, []), t = s(() => {
    j(), w();
  }, [w, j]);
  q({ isOpen: U, dialogRef: R, onClose: t });
  const A = async (a) => {
    if (!["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"].includes(a.type))
      return { valid: !1, error: "File harus berupa gambar (JPG, PNG, GIF, WebP)" };
    if (a.size > 10 * 1024 * 1024)
      return { valid: !1, error: "Ukuran file maksimal 10MB" };
    const _ = {
      "image/png": [[137, 80, 78, 71]],
      "image/jpeg": [[255, 216, 255]],
      "image/jpg": [[255, 216, 255]],
      "image/gif": [[71, 73, 70, 56]],
      "image/webp": [[82, 73, 70, 70]]
    };
    try {
      const o = await a.slice(0, 8).arrayBuffer(), x = new Uint8Array(o), S = _[a.type];
      if (!S)
        return { valid: !1, error: "Format gambar tidak dikenali" };
      if (!S.some(
        (W) => W.every(($, z) => x[z] === $)
      ))
        return { valid: !1, error: "File signature tidak valid. Kemungkinan file rusak atau mencurigakan." };
    } catch {
      return { valid: !1, error: "Gagal memvalidasi file" };
    }
    return { valid: !0 };
  }, b = s(
    async (a) => {
      const n = await A(a);
      if (!n.valid) {
        l(n.error);
        return;
      }
      l(""), m.current && URL.revokeObjectURL(m.current);
      const _ = URL.createObjectURL(a);
      if (m.current = _, c(_), v) {
        k(!0);
        try {
          const o = await v(a);
          if (!o)
            throw new Error("Upload gagal: URL tidak valid");
          u(o, g || a.name), t();
        } catch {
          l("Upload gagal. Silakan coba lagi."), c(null);
        } finally {
          k(!1);
        }
      } else {
        const o = new FileReader();
        o.onload = () => {
          const x = o.result;
          u(x, g || a.name), t();
        }, o.readAsDataURL(a);
      }
    },
    [v, u, g, t]
  ), M = s(
    (a) => {
      const n = a.target.files?.[0];
      n && b(n);
    },
    [b]
  ), I = s((a) => {
    a.preventDefault(), a.stopPropagation(), h(!0);
  }, []), E = s((a) => {
    a.preventDefault(), a.stopPropagation(), h(!1);
  }, []), O = s(
    (a) => {
      a.preventDefault(), a.stopPropagation(), h(!1);
      const n = a.dataTransfer.files?.[0];
      n && b(n);
    },
    [b]
  ), G = s(() => {
    if (!r.trim()) {
      l("Masukkan URL gambar");
      return;
    }
    try {
      new URL(r);
    } catch {
      l("URL tidak valid");
      return;
    }
    u(r.trim(), g || void 0), t();
  }, [r, g, u, t]), K = s(() => {
    if (r.trim())
      try {
        new URL(r), c(r.trim()), l("");
      } catch {
        l("URL tidak valid");
      }
  }, [r]);
  return U ? /* @__PURE__ */ i(J, { children: [
    /* @__PURE__ */ e("div", { className: "mtx-dialog-overlay", onClick: t }),
    /* @__PURE__ */ i("div", { className: "mtx-image-dialog", ref: R, role: "dialog", "aria-modal": "true", "aria-labelledby": N, tabIndex: -1, children: [
      /* @__PURE__ */ i("div", { className: "mtx-image-dialog__header", children: [
        /* @__PURE__ */ e("h3", { id: N, children: "Sisipkan Gambar" }),
        /* @__PURE__ */ e(
          "button",
          {
            className: "mtx-image-dialog__close",
            onClick: t,
            "aria-label": "Tutup",
            children: "✕"
          }
        )
      ] }),
      /* @__PURE__ */ i("div", { className: "mtx-image-dialog__tabs", children: [
        /* @__PURE__ */ e(
          "button",
          {
            className: `mtx-image-dialog__tab ${p === "upload" ? "is-active" : ""}`,
            onClick: () => {
              L("upload"), l(""), c(null);
            },
            children: "📁 Upload File"
          }
        ),
        /* @__PURE__ */ e(
          "button",
          {
            className: `mtx-image-dialog__tab ${p === "url" ? "is-active" : ""}`,
            onClick: () => {
              L("url"), l(""), c(null);
            },
            children: "🔗 URL"
          }
        )
      ] }),
      /* @__PURE__ */ i("div", { className: "mtx-image-dialog__body", children: [
        p === "upload" && /* @__PURE__ */ i(
          "div",
          {
            className: `mtx-image-dialog__dropzone ${B ? "is-dragging" : ""}`,
            onDragOver: I,
            onDragLeave: E,
            onDrop: O,
            onClick: () => F.current?.click(),
            children: [
              /* @__PURE__ */ e(
                "input",
                {
                  ref: F,
                  type: "file",
                  accept: "image/*",
                  onChange: M,
                  style: { display: "none" }
                }
              ),
              T ? /* @__PURE__ */ i("div", { className: "mtx-image-dialog__uploading", children: [
                /* @__PURE__ */ e("div", { className: "mtx-spinner" }),
                /* @__PURE__ */ e("p", { children: "Mengupload gambar..." })
              ] }) : f ? /* @__PURE__ */ e("div", { className: "mtx-image-dialog__preview", children: /* @__PURE__ */ e("img", { src: f, alt: "Preview" }) }) : /* @__PURE__ */ i("div", { className: "mtx-image-dialog__placeholder", children: [
                /* @__PURE__ */ i("svg", { width: "48", height: "48", viewBox: "0 0 48 48", fill: "none", stroke: "currentColor", strokeWidth: "1.5", children: [
                  /* @__PURE__ */ e("rect", { x: "4", y: "8", width: "40", height: "32", rx: "4" }),
                  /* @__PURE__ */ e("circle", { cx: "16", cy: "20", r: "4" }),
                  /* @__PURE__ */ e("path", { d: "M4 36l10-10 6 6 8-10 16 14" })
                ] }),
                /* @__PURE__ */ i("p", { children: [
                  /* @__PURE__ */ e("strong", { children: "Klik untuk pilih file" }),
                  " atau drag & drop ke sini"
                ] }),
                /* @__PURE__ */ e("span", { children: "JPG, PNG, GIF, WebP — Maks 10MB" })
              ] })
            ]
          }
        ),
        p === "url" && /* @__PURE__ */ i("div", { className: "mtx-image-dialog__url-form", children: [
          /* @__PURE__ */ e("label", { children: "URL Gambar" }),
          /* @__PURE__ */ e("div", { className: "mtx-image-dialog__url-row", children: /* @__PURE__ */ e(
            "input",
            {
              type: "url",
              value: r,
              onChange: (a) => D(a.target.value),
              placeholder: "https://example.com/gambar.jpg",
              onKeyDown: (a) => {
                a.key === "Enter" && G();
              },
              onBlur: K,
              autoFocus: !0
            }
          ) }),
          f && /* @__PURE__ */ e("div", { className: "mtx-image-dialog__url-preview", children: /* @__PURE__ */ e(
            "img",
            {
              src: f,
              alt: "Preview",
              onError: () => {
                c(null), l("Gambar tidak dapat dimuat dari URL ini");
              }
            }
          ) })
        ] }),
        /* @__PURE__ */ i("div", { className: "mtx-image-dialog__alt", children: [
          /* @__PURE__ */ e("label", { children: "Teks Alternatif (opsional)" }),
          /* @__PURE__ */ e(
            "input",
            {
              type: "text",
              value: g,
              onChange: (a) => C(a.target.value),
              placeholder: "Deskripsi gambar untuk aksesibilitas"
            }
          )
        ] }),
        P && /* @__PURE__ */ e("div", { className: "mtx-image-dialog__error", children: P })
      ] }),
      /* @__PURE__ */ i("div", { className: "mtx-image-dialog__footer", children: [
        /* @__PURE__ */ e("button", { className: "mtx-image-dialog__btn mtx-image-dialog__btn--cancel", onClick: t, children: "Batal" }),
        p === "url" && /* @__PURE__ */ e(
          "button",
          {
            className: "mtx-image-dialog__btn mtx-image-dialog__btn--insert",
            onClick: G,
            disabled: !r.trim(),
            children: "Sisipkan"
          }
        )
      ] })
    ] })
  ] }) : null;
}
export {
  Z as ImageInsertDialog
};
