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 { d as C } from "../../../../../../sdk/dist/shared/chunk-LEWKHCRI.js";
import "../../../../../../sdk/dist/shared/chunk-F4JNKU7J.js";
import "@sinclair/typebox";
import "../../../../../../sdk/dist/shared/chunk-7UBMXMNJ.js";
import "../../../../../../sdk/dist/shared/chunk-JRCVYDCD.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 S } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/md/index.js";
import { RxCross2 as z } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.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.5.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/tb/index.js";
import H, { 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 k } 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 O(o) {
  if (!o) return "";
  const l = document.createElement("div");
  return l.innerHTML = o, l.textContent || l.innerText || "";
}
function $e({
  currentValue: o = [],
  onChange: l,
  formData: q,
  itemSchema: B,
  formSchema: R,
  title: M,
  description: Q,
  brickId: x,
  fieldName: g,
  id: A,
  parents: $ = [],
  schema: h
}) {
  const _ = se(), [u, f] = Z(null), m = V([]), b = q.loop?.over ? "dynamic" : "static", y = h["ui:options"], E = h.maxItems, F = y?.addable ?? !0, j = y?.removable ?? !0, p = y?.orderable ?? !0, N = h["ui:displayField"], c = C(B);
  ee(() => {
    u !== null && m.current[u] && setTimeout(() => {
      m.current[u]?.scrollIntoView({
        behavior: "smooth",
        block: "start"
      });
    }, 100);
  }, [u]);
  const K = (s) => {
    f((r) => r === s ? null : s);
  }, L = () => {
    if (!F || E !== void 0 && o.length >= E)
      return;
    let s;
    if (c.type === "object") {
      if (s = {}, c.properties) {
        const n = new Set(c.required || []);
        Object.entries(c.properties).forEach(([i, a]) => {
          const w = C(a);
          n.has(i) && (s[i] = w.default);
        });
      }
    } else
      s = c.default ?? ie(c.type);
    const r = [...o, s];
    l(r), m.current = [...m.current, null];
    const e = r.length - 1;
    f(e);
  }, P = (s) => {
    if (!j) return;
    const r = o.filter((e, n) => n !== s);
    l(r), m.current = m.current.filter((e, n) => n !== s), f((e) => e === null || e === s ? null : e > s ? e - 1 : e);
  }, G = (s) => {
    if (!p || !s.destination) return;
    const { source: r, destination: e } = s;
    if (r.index === e.index) return;
    const n = Array.from(o), [i] = n.splice(r.index, 1);
    n.splice(e.index, 0, i), l(n), f((a) => {
      if (a === null) return null;
      if (a === r.index)
        return e.index;
      if (r.index < e.index) {
        if (a > r.index && a <= e.index)
          return a - 1;
      } else if (a >= e.index && a < r.index)
        return a + 1;
      return a;
    });
  }, J = (s, r) => {
    const e = s;
    if (N && e[N])
      return O(String(e[N]));
    const n = ["name", "title", "label", "text", "author"];
    for (const i of n)
      if (e[i])
        return O(String(e[i]));
    return `Item ${r + 1}`;
  }, T = (s, r, e, n) => {
    const i = s, a = 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", a ? "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",
                !a && "rounded-b"
              ),
              onClick: () => K(r),
              children: [
                /* @__PURE__ */ t.jsxs("div", { className: "flex items-center gap-2 min-w-0 flex-1 rounded-[inherit]", children: [
                  p && /* @__PURE__ */ t.jsx(
                    "div",
                    {
                      ...e?.dragHandleProps,
                      className: "cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600",
                      children: /* @__PURE__ */ t.jsx(S, { 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(
                  k,
                  {
                    type: "button",
                    size: "1",
                    variant: "ghost",
                    color: "red",
                    onClick: () => P(r),
                    title: "Remove item",
                    children: /* @__PURE__ */ t.jsx(z, { className: "w-3 h-3" })
                  }
                )
              ]
            }
          ),
          a && /* @__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(
            H,
            {
              schema: c,
              formData: i || {},
              noDynamic: n,
              formSchema: R,
              onChange: (d, I) => {
                const v = [...o], U = v[r] || {};
                v[r] = { ...U, ...d }, l(v);
              },
              options: {
                brickId: x,
                parents: [...$, `${g}[${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: [
          p && /* @__PURE__ */ t.jsx(
            "div",
            {
              ...e?.dragHandleProps,
              className: "cursor-grab hover:cursor-grabbing text-gray-400 hover:text-gray-600",
              children: /* @__PURE__ */ t.jsx(S, { className: "w-4 h-4" })
            }
          ),
          /* @__PURE__ */ t.jsx(
            oe,
            {
              size: "2",
              className: "flex-1",
              defaultValue: `${s || ""}`,
              onChange: (d) => {
                const I = [...o];
                I[r] = d.target.value, l(I);
              }
            }
          ),
          j && /* @__PURE__ */ t.jsx(
            k,
            {
              type: "button",
              size: "1",
              variant: "ghost",
              color: "red",
              onClick: () => P(r),
              title: "Remove item",
              className: "group",
              children: /* @__PURE__ */ t.jsx(z, { 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: M,
          description: Q,
          className: D(b === "dynamic" && "font-medium")
        }
      ),
      F && 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(
      H,
      {
        schema: c,
        formData: o[0],
        formSchema: R,
        onChange: (s, r) => {
          console.log("Dynamic parent item data change", {
            itemData: s,
            itemFieldId: r,
            fieldName: g,
            brickId: x
          });
          const e = structuredClone(o ?? []).slice(0, 1);
          e[0] = ne({}, e[0], s), l(e);
        },
        options: {
          brickId: x,
          parents: [...$, `${g}[0]`]
        }
      }
    ) }) }) }) : p ? /* @__PURE__ */ t.jsx(W, { onDragEnd: G, children: /* @__PURE__ */ t.jsx(X, { droppableId: `array-${A}`, direction: "vertical", children: (s, r) => /* @__PURE__ */ t.jsxs(
      "div",
      {
        ...s.droppableProps,
        ref: s.innerRef,
        className: "space-y-1 rounded empty:hidden",
        children: [
          o.map((e, n) => {
            const i = `item-${n}`;
            return /* @__PURE__ */ t.jsx(Y, { draggableId: i, index: n, children: (a) => T(e, n, a, !0) }, i);
          }),
          s.placeholder
        ]
      }
    ) }) }) : /* @__PURE__ */ t.jsx("div", { className: "space-y-1 -mx-1", children: o.map((s, r) => /* @__PURE__ */ t.jsx("div", { children: T(s, r, null, !0) }, `${A}-${r}`)) }),
    _.length === 0 && o.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(o) {
  switch (o) {
    case "string":
      return "";
    case "number":
    case "integer":
      return 0;
    case "boolean":
      return !1;
    case "array":
      return [];
    case "object":
      return {};
    default:
      return "";
  }
}
export {
  $e as default
};
//# sourceMappingURL=array.js.map
