import { j as jsxRuntimeExports } from "../../../../../../../_virtual/jsx-runtime.js";
import { DragDropContext, Droppable as ConnectedDroppable, Draggable as PublicDraggable } from "../../../../../../../node_modules/.pnpm/@hello-pangea_dnd@18.0.1_@types_react@19.1.13_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/@hello-pangea/dnd/dist/dnd.esm.js";
import { d as b } from "../../../../../../sdk/dist/shared/chunk-QGYZ7CG5.js";
import "../../../../../../sdk/dist/shared/chunk-AFVJZPLS.js";
import "@sinclair/typebox";
import "../../../../../../sdk/dist/shared/chunk-A3GF4PYW.js";
import "../../../../../../sdk/dist/shared/chunk-W33JMRRN.js";
import { useState, useRef, useEffect } 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@19.1.1_react@19.1.1__react@19.1.1/node_modules/react-hot-toast/dist/index.js";
import { tx as D } from "../../../../../../style-system/dist/twind.js";
import { MdDragIndicator } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/md/index.js";
import { RxCross2 } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/rx/index.js";
import { TbPlus } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/tb/index.js";
import ObjectFields, { FieldTitle } from "../field-factory.js";
import { usePageQueries } from "../../../../../../../use-page-data.js";
import { merge } from "lodash-es";
import { Button as o } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/button.js";
import { IconButton as o$1 } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/icon-button.js";
import { Root as u } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/text-field.js";
function stripHtml(html) {
  if (!html) return "";
  const div = document.createElement("div");
  div.innerHTML = html;
  return div.textContent || div.innerText || "";
}
function ArrayField({
  currentValue = [],
  onChange,
  formData,
  itemSchema,
  formSchema,
  title,
  description,
  brickId,
  fieldName,
  id,
  parents = [],
  schema
}) {
  const pageQueries = usePageQueries();
  const [expandedItem, setExpandedItem] = useState(null);
  const itemRefs = useRef([]);
  const mode = formData.loop?.over ? "dynamic" : "static";
  const uiOptions = schema["ui:options"];
  const maxItems = schema.maxItems;
  const addable = uiOptions?.addable ?? true;
  const removable = uiOptions?.removable ?? true;
  const orderable = uiOptions?.orderable ?? true;
  const displayField = schema["ui:displayField"];
  const resolvedItemSchema = b(itemSchema);
  useEffect(() => {
    if (expandedItem !== null && itemRefs.current[expandedItem]) {
      setTimeout(() => {
        itemRefs.current[expandedItem]?.scrollIntoView({
          behavior: "smooth",
          block: "start"
        });
      }, 100);
    }
  }, [expandedItem]);
  const toggleExpanded = (index) => {
    setExpandedItem((prev) => {
      if (prev === index) {
        return null;
      }
      return index;
    });
  };
  const handleAddItem = () => {
    if (!addable) return;
    if (maxItems !== void 0 && currentValue.length >= maxItems) {
      return;
    }
    let defaultItem;
    if (resolvedItemSchema.type === "object") {
      defaultItem = {};
      if (resolvedItemSchema.properties) {
        const requiredFields = new Set(resolvedItemSchema.required || []);
        Object.entries(resolvedItemSchema.properties).forEach(([key, prop]) => {
          const propSchema = b(prop);
          if (requiredFields.has(key)) {
            defaultItem[key] = propSchema.default;
          }
        });
      }
    } else {
      defaultItem = resolvedItemSchema.default ?? getDefaultForType(resolvedItemSchema.type);
    }
    const newArray = [...currentValue, defaultItem];
    onChange(newArray);
    itemRefs.current = [...itemRefs.current, null];
    const newIndex = newArray.length - 1;
    setExpandedItem(newIndex);
  };
  const handleRemoveItem = (index) => {
    if (!removable) return;
    const newArray = currentValue.filter((_, i) => i !== index);
    onChange(newArray);
    itemRefs.current = itemRefs.current.filter((_, i) => i !== index);
    setExpandedItem((prev) => {
      if (prev === null) return null;
      if (prev === index) {
        return null;
      } else if (prev > index) {
        return prev - 1;
      }
      return prev;
    });
  };
  const handleDragEnd = (result) => {
    if (!orderable || !result.destination) return;
    const { source, destination } = result;
    if (source.index === destination.index) return;
    const newArray = Array.from(currentValue);
    const [reorderedItem] = newArray.splice(source.index, 1);
    newArray.splice(destination.index, 0, reorderedItem);
    onChange(newArray);
    setExpandedItem((prev) => {
      if (prev === null) return null;
      if (prev === source.index) {
        return destination.index;
      } else if (source.index < destination.index) {
        if (prev > source.index && prev <= destination.index) {
          return prev - 1;
        }
      } else {
        if (prev >= destination.index && prev < source.index) {
          return prev + 1;
        }
      }
      return prev;
    });
  };
  const getDisplayText = (item, index) => {
    const typedItem = item;
    if (displayField && typedItem[displayField]) {
      return stripHtml(String(typedItem[displayField]));
    }
    const fallbackFields = ["name", "title", "label", "text", "author"];
    for (const field of fallbackFields) {
      if (typedItem[field]) {
        return stripHtml(String(typedItem[field]));
      }
    }
    return `Item ${index + 1}`;
  };
  const renderArrayItem = (item, index, provided, noDynamic) => {
    const typedItem = item;
    const isExpanded = expandedItem === index;
    const displayText = getDisplayText(item, index);
    if (resolvedItemSchema.type === "object") {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          ref: (el) => {
            if (provided?.innerRef) {
              provided.innerRef(el);
            }
            itemRefs.current[index] = el;
          },
          ...provided?.draggableProps,
          className: D("border rounded", isExpanded ? "border-gray-300" : "border-gray-200"),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: D(
                  "flex items-center cursor-pointer justify-between p-2 bg-gray-100 hover:bg-upstart-50 rounded-t",
                  !isExpanded && "rounded-b"
                ),
                onClick: () => toggleExpanded(index),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 min-w-0 flex-1 rounded-[inherit]", children: [
                    orderable && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        ...provided?.dragHandleProps,
                        className: "cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600",
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(MdDragIndicator, { className: "w-4 h-4" })
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-normal text-gray-700 truncate whitespace-nowrap", children: displayText })
                  ] }),
                  removable && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    o$1,
                    {
                      type: "button",
                      size: "1",
                      variant: "ghost",
                      color: "red",
                      onClick: () => handleRemoveItem(index),
                      title: "Remove item",
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(RxCross2, { className: "w-3 h-3" })
                    }
                  )
                ]
              }
            ),
            isExpanded && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-gray-50 rounded-b-[inherit]", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              ObjectFields,
              {
                schema: resolvedItemSchema,
                formData: typedItem || {},
                noDynamic,
                formSchema,
                onChange: (itemData, itemFieldId) => {
                  const newArray = [...currentValue];
                  const currentItem = newArray[index] || {};
                  newArray[index] = { ...currentItem, ...itemData };
                  onChange(newArray);
                },
                options: {
                  brickId,
                  parents: [...parents, `${fieldName}[${index}]`]
                }
              }
            ) }) })
          ]
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        ref: (el) => {
          if (provided?.innerRef) {
            provided.innerRef(el);
          }
          itemRefs.current[index] = el;
        },
        ...provided?.draggableProps,
        className: `flex items-center gap-2 p-2 border rounded border-gray-200`,
        children: [
          orderable && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              ...provided?.dragHandleProps,
              className: "cursor-grab hover:cursor-grabbing text-gray-400 hover:text-gray-600",
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(MdDragIndicator, { className: "w-4 h-4" })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            u,
            {
              size: "2",
              className: "flex-1",
              defaultValue: `${item || ""}`,
              onChange: (e) => {
                const newArray = [...currentValue];
                newArray[index] = e.target.value;
                onChange(newArray);
              }
            }
          ),
          removable && /* @__PURE__ */ jsxRuntimeExports.jsx(
            o$1,
            {
              type: "button",
              size: "1",
              variant: "ghost",
              color: "red",
              onClick: () => handleRemoveItem(index),
              title: "Remove item",
              className: "group",
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(RxCross2, { className: "w-3 h-3 text-gray-400 group-hover:text-red-800" })
            }
          )
        ]
      }
    );
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3 flex-1 min-w-0", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex w-full items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        FieldTitle,
        {
          title,
          description,
          className: D(mode === "dynamic" && "font-medium")
        }
      ),
      addable && mode === "static" && /* @__PURE__ */ jsxRuntimeExports.jsxs(o, { type: "button", onClick: handleAddItem, variant: "soft", size: "1", radius: "full", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(TbPlus, { className: "w-3 h-3" }),
        " Add item"
      ] })
    ] }),
    mode === "dynamic" ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-1 -mx-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      ObjectFields,
      {
        schema: resolvedItemSchema,
        formData: currentValue[0],
        formSchema,
        onChange: (itemData, itemFieldId) => {
          console.log("Dynamic parent item data change", {
            itemData,
            itemFieldId,
            fieldName,
            brickId
          });
          const newData = structuredClone(currentValue ?? []).slice(0, 1);
          newData[0] = merge({}, newData[0], itemData);
          onChange(newData);
        },
        options: {
          brickId,
          parents: [...parents, `${fieldName}[0]`]
        }
      }
    ) }) }) }) : orderable ? /* @__PURE__ */ jsxRuntimeExports.jsx(DragDropContext, { onDragEnd: handleDragEnd, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ConnectedDroppable, { droppableId: `array-${id}`, direction: "vertical", children: (provided, snapshot) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        ...provided.droppableProps,
        ref: provided.innerRef,
        className: `space-y-1 rounded empty:hidden`,
        children: [
          currentValue.map((item, index) => {
            const stableKey = `item-${index}`;
            return /* @__PURE__ */ jsxRuntimeExports.jsx(PublicDraggable, { draggableId: stableKey, index, children: (provided2) => renderArrayItem(item, index, provided2, true) }, stableKey);
          }),
          provided.placeholder
        ]
      }
    ) }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-1 -mx-1", children: currentValue.map((item, index) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: renderArrayItem(item, index, null, true) }, `${id}-${index}`)) }),
    pageQueries.length === 0 && currentValue.length === 0 && /* @__PURE__ */ jsxRuntimeExports.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 getDefaultForType(type) {
  switch (type) {
    case "string":
      return "";
    case "number":
    case "integer":
      return 0;
    case "boolean":
      return false;
    case "array":
      return [];
    case "object":
      return {};
    default:
      return "";
  }
}
export {
  ArrayField as default
};
//# sourceMappingURL=array.js.map
