import { j as t } from "../../../../../../../_virtual/jsx-runtime.js";
import { DragDropContext as W, Droppable as X, Draggable as Y } from "../../../../../../../node_modules/.pnpm/@hello-pangea_dnd@18.0.1_@types_react@18.3.3_react-dom@18.3.0-canary-3d9b20132-20240124_f84299e6e55021d5dd75941266a1f9fa/node_modules/@hello-pangea/dnd/dist/dnd.esm.js";
import { resolveSchema as S } from "../../../../../../sdk/dist/shared/utils/schema-resolver.js";
import { useState as Z, useRef as V, useEffect as ee } from "react";
import "../../../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import "../../../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@18.3.0-canary-3d9b20132-20240124_react@18.3.0-canary-3d_c02c1e17bf76c343fd22d1f22394ecf5/node_modules/react-hot-toast/dist/index.js";
import { tx as D } from "../../../../../../style-system/dist/twind.js";
import { MdDragIndicator as z } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/md/index.js";
import { RxCross2 as H } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/rx/index.js";
import { TbPlus as re } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/tb/index.js";
import k, { FieldTitle as te } from "../field-factory.js";
import { usePageQueries as se } from "../../../../../../../use-page-data.js";
import { merge as ne } from "lodash-es";
import { Button as ae } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/button.js";
import { IconButton as O } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/icon-button.js";
import { Root as oe } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/text-field.js";
function _(n) {
  if (!n) return "";
  const l = document.createElement("div");
  return l.innerHTML = n, l.textContent || l.innerText || "";
}
function Ie({
  currentValue: n = [],
  onChange: l,
  formData: q,
  itemSchema: R,
  formSchema: A,
  title: B,
  description: M,
  brickId: g,
  fieldName: f,
  id: F,
  parents: $ = [],
  schema: h
}) {
  const Q = se(), [u, p] = Z(null), m = V([]);
  console.log("ArrayField, currentValue:", n, "itemSchema:", R, "fieldName:", f);
  const b = q.loop?.over ? "dynamic" : "static", y = h["ui:options"], E = h.maxItems, P = y?.addable ?? !0, j = y?.removable ?? !0, x = y?.orderable ?? !0, N = h["ui:displayField"], c = S(R);
  ee(() => {
    u !== null && m.current[u] && setTimeout(() => {
      m.current[u]?.scrollIntoView({
        behavior: "smooth",
        block: "start"
      });
    }, 100);
  }, [u]);
  const K = (s) => {
    p((r) => r === s ? null : s);
  }, L = () => {
    if (!P || E !== void 0 && n.length >= E)
      return;
    let s;
    if (c.type === "object") {
      if (s = {}, c.properties) {
        const a = new Set(c.required || []);
        Object.entries(c.properties).forEach(([i, o]) => {
          const w = S(o);
          a.has(i) && (s[i] = w.default);
        });
      }
    } else
      s = c.default ?? ie(c.type);
    const r = [...n, s];
    l(r), m.current = [...m.current, null];
    const e = r.length - 1;
    p(e);
  }, T = (s) => {
    if (!j) return;
    const r = n.filter((e, a) => a !== s);
    l(r), m.current = m.current.filter((e, a) => a !== s), p((e) => e === null || e === s ? null : e > s ? e - 1 : e);
  }, G = (s) => {
    if (!x || !s.destination) return;
    const { source: r, destination: e } = s;
    if (r.index === e.index) return;
    const a = Array.from(n), [i] = a.splice(r.index, 1);
    a.splice(e.index, 0, i), l(a), p((o) => {
      if (o === null) return null;
      if (o === r.index)
        return e.index;
      if (r.index < e.index) {
        if (o > r.index && o <= e.index)
          return o - 1;
      } else if (o >= e.index && o < r.index)
        return o + 1;
      return o;
    });
  }, J = (s, r) => {
    const e = s;
    if (N && e[N])
      return _(String(e[N]));
    const a = ["name", "title", "label", "text", "author"];
    for (const i of a)
      if (e[i])
        return _(String(e[i]));
    return `Item ${r + 1}`;
  }, C = (s, r, e, a) => {
    const i = s, o = u === r, w = J(s, r);
    return c.type === "object" ? /* @__PURE__ */ t.jsxs(
      "div",
      {
        ref: (d) => {
          e?.innerRef && e.innerRef(d), m.current[r] = d;
        },
        ...e?.draggableProps,
        className: D("border rounded", o ? "border-gray-300" : "border-gray-200"),
        children: [
          /* @__PURE__ */ t.jsxs(
            "div",
            {
              className: D(
                "flex items-center cursor-pointer justify-between p-2 bg-gray-100 hover:bg-upstart-50 rounded-t",
                !o && "rounded-b"
              ),
              onClick: () => K(r),
              children: [
                /* @__PURE__ */ t.jsxs("div", { className: "flex items-center gap-2 min-w-0 flex-1 rounded-[inherit]", children: [
                  x && /* @__PURE__ */ t.jsx(
                    "div",
                    {
                      ...e?.dragHandleProps,
                      className: "cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600",
                      children: /* @__PURE__ */ t.jsx(z, { className: "w-4 h-4" })
                    }
                  ),
                  /* @__PURE__ */ t.jsx("span", { className: "text-xs font-normal text-gray-700 truncate whitespace-nowrap", children: w })
                ] }),
                j && /* @__PURE__ */ t.jsx(
                  O,
                  {
                    type: "button",
                    size: "1",
                    variant: "ghost",
                    color: "red",
                    onClick: () => T(r),
                    title: "Remove item",
                    children: /* @__PURE__ */ t.jsx(H, { className: "w-3 h-3" })
                  }
                )
              ]
            }
          ),
          o && /* @__PURE__ */ t.jsx("div", { className: "p-2 bg-gray-50 rounded-b-[inherit]", children: /* @__PURE__ */ t.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ t.jsx(
            k,
            {
              schema: c,
              formData: i || {},
              noDynamic: a,
              formSchema: A,
              onChange: (d, v) => {
                const I = [...n], U = I[r] || {};
                I[r] = { ...U, ...d }, l(I);
              },
              options: {
                brickId: g,
                parents: [...$, `${f}[${r}]`]
              }
            }
          ) }) })
        ]
      }
    ) : /* @__PURE__ */ t.jsxs(
      "div",
      {
        ref: (d) => {
          e?.innerRef && e.innerRef(d), m.current[r] = d;
        },
        ...e?.draggableProps,
        className: "flex items-center gap-2 p-2 border rounded border-gray-200",
        children: [
          x && /* @__PURE__ */ t.jsx(
            "div",
            {
              ...e?.dragHandleProps,
              className: "cursor-grab hover:cursor-grabbing text-gray-400 hover:text-gray-600",
              children: /* @__PURE__ */ t.jsx(z, { className: "w-4 h-4" })
            }
          ),
          /* @__PURE__ */ t.jsx(
            oe,
            {
              size: "2",
              className: "flex-1",
              defaultValue: `${s || ""}`,
              onChange: (d) => {
                const v = [...n];
                v[r] = d.target.value, l(v);
              }
            }
          ),
          j && /* @__PURE__ */ t.jsx(
            O,
            {
              type: "button",
              size: "1",
              variant: "ghost",
              color: "red",
              onClick: () => T(r),
              title: "Remove item",
              className: "group",
              children: /* @__PURE__ */ t.jsx(H, { className: "w-3 h-3 text-gray-400 group-hover:text-red-800" })
            }
          )
        ]
      }
    );
  };
  return /* @__PURE__ */ t.jsxs("div", { className: "space-y-3 flex-1 min-w-0", children: [
    /* @__PURE__ */ t.jsxs("div", { className: "flex w-full items-center justify-between", children: [
      /* @__PURE__ */ t.jsx(
        te,
        {
          title: B,
          description: M,
          className: D(b === "dynamic" && "font-medium")
        }
      ),
      P && b === "static" && /* @__PURE__ */ t.jsxs(ae, { type: "button", onClick: L, variant: "soft", size: "1", radius: "full", children: [
        /* @__PURE__ */ t.jsx(re, { className: "w-3 h-3" }),
        " Add item"
      ] })
    ] }),
    b === "dynamic" ? /* @__PURE__ */ t.jsx("div", { className: "space-y-1 -mx-1", children: /* @__PURE__ */ t.jsx("div", { className: "px-1", children: /* @__PURE__ */ t.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ t.jsx(
      k,
      {
        schema: c,
        formData: n[0],
        formSchema: A,
        onChange: (s, r) => {
          console.log("Dynamic parent item data change", {
            itemData: s,
            itemFieldId: r,
            fieldName: f,
            brickId: g
          });
          const e = structuredClone(n ?? []).slice(0, 1);
          e[0] = ne({}, e[0], s), l(e);
        },
        options: {
          brickId: g,
          parents: [...$, `${f}[0]`]
        }
      }
    ) }) }) }) : x ? /* @__PURE__ */ t.jsx(W, { onDragEnd: G, children: /* @__PURE__ */ t.jsx(X, { droppableId: `array-${F}`, direction: "vertical", children: (s, r) => /* @__PURE__ */ t.jsxs("div", { ...s.droppableProps, ref: s.innerRef, className: "space-y-1 rounded", children: [
      n.map((e, a) => {
        const i = `item-${a}`;
        return /* @__PURE__ */ t.jsx(Y, { draggableId: i, index: a, children: (o) => C(e, a, o, !0) }, i);
      }),
      s.placeholder
    ] }) }) }) : /* @__PURE__ */ t.jsx("div", { className: "space-y-1 -mx-1", children: n.map((s, r) => /* @__PURE__ */ t.jsx("div", { children: C(s, r, null, !0) }, `${F}-${r}`)) }),
    Q.length === 0 && n.length === 0 && /* @__PURE__ */ t.jsx("div", { className: "text-center py-6 text-gray-400 text-sm border-2 border-dashed border-gray-200 rounded", children: "No items added yet." })
  ] });
}
function ie(n) {
  switch (n) {
    case "string":
      return "";
    case "number":
    case "integer":
      return 0;
    case "boolean":
      return !1;
    case "array":
      return [];
    case "object":
      return {};
    default:
      return "";
  }
}
export {
  Ie as default
};
//# sourceMappingURL=array.js.map
